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

1.203   ! brouard     1: /* $Id: imach.c,v 1.202 2015/09/22 19:45:16 brouard Exp $
1.126     brouard     2:   $State: Exp $
1.163     brouard     3:   $Log: imach.c,v $
1.203   ! brouard     4:   Revision 1.202  2015/09/22 19:45:16  brouard
        !             5:   Summary: Adding some overall graph on contribution to likelihood. Might change
        !             6: 
1.202     brouard     7:   Revision 1.201  2015/09/15 17:34:58  brouard
                      8:   Summary: 0.98r0
                      9: 
                     10:   - Some new graphs like suvival functions
                     11:   - Some bugs fixed like model=1+age+V2.
                     12: 
1.201     brouard    13:   Revision 1.200  2015/09/09 16:53:55  brouard
                     14:   Summary: Big bug thanks to Flavia
                     15: 
                     16:   Even model=1+age+V2. did not work anymore
                     17: 
1.200     brouard    18:   Revision 1.199  2015/09/07 14:09:23  brouard
                     19:   Summary: 0.98q6 changing default small png format for graph to vectorized svg.
                     20: 
1.199     brouard    21:   Revision 1.198  2015/09/03 07:14:39  brouard
                     22:   Summary: 0.98q5 Flavia
                     23: 
1.198     brouard    24:   Revision 1.197  2015/09/01 18:24:39  brouard
                     25:   *** empty log message ***
                     26: 
1.197     brouard    27:   Revision 1.196  2015/08/18 23:17:52  brouard
                     28:   Summary: 0.98q5
                     29: 
1.196     brouard    30:   Revision 1.195  2015/08/18 16:28:39  brouard
                     31:   Summary: Adding a hack for testing purpose
                     32: 
                     33:   After reading the title, ftol and model lines, if the comment line has
                     34:   a q, starting with #q, the answer at the end of the run is quit. It
                     35:   permits to run test files in batch with ctest. The former workaround was
                     36:   $ echo q | imach foo.imach
                     37: 
1.195     brouard    38:   Revision 1.194  2015/08/18 13:32:00  brouard
                     39:   Summary:  Adding error when the covariance matrix doesn't contain the exact number of lines required by the model line.
                     40: 
1.194     brouard    41:   Revision 1.193  2015/08/04 07:17:42  brouard
                     42:   Summary: 0.98q4
                     43: 
1.193     brouard    44:   Revision 1.192  2015/07/16 16:49:02  brouard
                     45:   Summary: Fixing some outputs
                     46: 
1.192     brouard    47:   Revision 1.191  2015/07/14 10:00:33  brouard
                     48:   Summary: Some fixes
                     49: 
1.191     brouard    50:   Revision 1.190  2015/05/05 08:51:13  brouard
                     51:   Summary: Adding digits in output parameters (7 digits instead of 6)
                     52: 
                     53:   Fix 1+age+.
                     54: 
1.190     brouard    55:   Revision 1.189  2015/04/30 14:45:16  brouard
                     56:   Summary: 0.98q2
                     57: 
1.189     brouard    58:   Revision 1.188  2015/04/30 08:27:53  brouard
                     59:   *** empty log message ***
                     60: 
1.188     brouard    61:   Revision 1.187  2015/04/29 09:11:15  brouard
                     62:   *** empty log message ***
                     63: 
1.187     brouard    64:   Revision 1.186  2015/04/23 12:01:52  brouard
                     65:   Summary: V1*age is working now, version 0.98q1
                     66: 
                     67:   Some codes had been disabled in order to simplify and Vn*age was
                     68:   working in the optimization phase, ie, giving correct MLE parameters,
                     69:   but, as usual, outputs were not correct and program core dumped.
                     70: 
1.186     brouard    71:   Revision 1.185  2015/03/11 13:26:42  brouard
                     72:   Summary: Inclusion of compile and links command line for Intel Compiler
                     73: 
1.185     brouard    74:   Revision 1.184  2015/03/11 11:52:39  brouard
                     75:   Summary: Back from Windows 8. Intel Compiler
                     76: 
1.184     brouard    77:   Revision 1.183  2015/03/10 20:34:32  brouard
                     78:   Summary: 0.98q0, trying with directest, mnbrak fixed
                     79: 
                     80:   We use directest instead of original Powell test; probably no
                     81:   incidence on the results, but better justifications;
                     82:   We fixed Numerical Recipes mnbrak routine which was wrong and gave
                     83:   wrong results.
                     84: 
1.183     brouard    85:   Revision 1.182  2015/02/12 08:19:57  brouard
                     86:   Summary: Trying to keep directest which seems simpler and more general
                     87:   Author: Nicolas Brouard
                     88: 
1.182     brouard    89:   Revision 1.181  2015/02/11 23:22:24  brouard
                     90:   Summary: Comments on Powell added
                     91: 
                     92:   Author:
                     93: 
1.181     brouard    94:   Revision 1.180  2015/02/11 17:33:45  brouard
                     95:   Summary: Finishing move from main to function (hpijx and prevalence_limit)
                     96: 
1.180     brouard    97:   Revision 1.179  2015/01/04 09:57:06  brouard
                     98:   Summary: back to OS/X
                     99: 
1.179     brouard   100:   Revision 1.178  2015/01/04 09:35:48  brouard
                    101:   *** empty log message ***
                    102: 
1.178     brouard   103:   Revision 1.177  2015/01/03 18:40:56  brouard
                    104:   Summary: Still testing ilc32 on OSX
                    105: 
1.177     brouard   106:   Revision 1.176  2015/01/03 16:45:04  brouard
                    107:   *** empty log message ***
                    108: 
1.176     brouard   109:   Revision 1.175  2015/01/03 16:33:42  brouard
                    110:   *** empty log message ***
                    111: 
1.175     brouard   112:   Revision 1.174  2015/01/03 16:15:49  brouard
                    113:   Summary: Still in cross-compilation
                    114: 
1.174     brouard   115:   Revision 1.173  2015/01/03 12:06:26  brouard
                    116:   Summary: trying to detect cross-compilation
                    117: 
1.173     brouard   118:   Revision 1.172  2014/12/27 12:07:47  brouard
                    119:   Summary: Back from Visual Studio and Intel, options for compiling for Windows XP
                    120: 
1.172     brouard   121:   Revision 1.171  2014/12/23 13:26:59  brouard
                    122:   Summary: Back from Visual C
                    123: 
                    124:   Still problem with utsname.h on Windows
                    125: 
1.171     brouard   126:   Revision 1.170  2014/12/23 11:17:12  brouard
                    127:   Summary: Cleaning some \%% back to %%
                    128: 
                    129:   The escape was mandatory for a specific compiler (which one?), but too many warnings.
                    130: 
1.170     brouard   131:   Revision 1.169  2014/12/22 23:08:31  brouard
                    132:   Summary: 0.98p
                    133: 
                    134:   Outputs some informations on compiler used, OS etc. Testing on different platforms.
                    135: 
1.169     brouard   136:   Revision 1.168  2014/12/22 15:17:42  brouard
1.170     brouard   137:   Summary: update
1.169     brouard   138: 
1.168     brouard   139:   Revision 1.167  2014/12/22 13:50:56  brouard
                    140:   Summary: Testing uname and compiler version and if compiled 32 or 64
                    141: 
                    142:   Testing on Linux 64
                    143: 
1.167     brouard   144:   Revision 1.166  2014/12/22 11:40:47  brouard
                    145:   *** empty log message ***
                    146: 
1.166     brouard   147:   Revision 1.165  2014/12/16 11:20:36  brouard
                    148:   Summary: After compiling on Visual C
                    149: 
                    150:   * imach.c (Module): Merging 1.61 to 1.162
                    151: 
1.165     brouard   152:   Revision 1.164  2014/12/16 10:52:11  brouard
                    153:   Summary: Merging with Visual C after suppressing some warnings for unused variables. Also fixing Saito's bug 0.98Xn
                    154: 
                    155:   * imach.c (Module): Merging 1.61 to 1.162
                    156: 
1.164     brouard   157:   Revision 1.163  2014/12/16 10:30:11  brouard
                    158:   * imach.c (Module): Merging 1.61 to 1.162
                    159: 
1.163     brouard   160:   Revision 1.162  2014/09/25 11:43:39  brouard
                    161:   Summary: temporary backup 0.99!
                    162: 
1.162     brouard   163:   Revision 1.1  2014/09/16 11:06:58  brouard
                    164:   Summary: With some code (wrong) for nlopt
                    165: 
                    166:   Author:
                    167: 
                    168:   Revision 1.161  2014/09/15 20:41:41  brouard
                    169:   Summary: Problem with macro SQR on Intel compiler
                    170: 
1.161     brouard   171:   Revision 1.160  2014/09/02 09:24:05  brouard
                    172:   *** empty log message ***
                    173: 
1.160     brouard   174:   Revision 1.159  2014/09/01 10:34:10  brouard
                    175:   Summary: WIN32
                    176:   Author: Brouard
                    177: 
1.159     brouard   178:   Revision 1.158  2014/08/27 17:11:51  brouard
                    179:   *** empty log message ***
                    180: 
1.158     brouard   181:   Revision 1.157  2014/08/27 16:26:55  brouard
                    182:   Summary: Preparing windows Visual studio version
                    183:   Author: Brouard
                    184: 
                    185:   In order to compile on Visual studio, time.h is now correct and time_t
                    186:   and tm struct should be used. difftime should be used but sometimes I
                    187:   just make the differences in raw time format (time(&now).
                    188:   Trying to suppress #ifdef LINUX
                    189:   Add xdg-open for __linux in order to open default browser.
                    190: 
1.157     brouard   191:   Revision 1.156  2014/08/25 20:10:10  brouard
                    192:   *** empty log message ***
                    193: 
1.156     brouard   194:   Revision 1.155  2014/08/25 18:32:34  brouard
                    195:   Summary: New compile, minor changes
                    196:   Author: Brouard
                    197: 
1.155     brouard   198:   Revision 1.154  2014/06/20 17:32:08  brouard
                    199:   Summary: Outputs now all graphs of convergence to period prevalence
                    200: 
1.154     brouard   201:   Revision 1.153  2014/06/20 16:45:46  brouard
                    202:   Summary: If 3 live state, convergence to period prevalence on same graph
                    203:   Author: Brouard
                    204: 
1.153     brouard   205:   Revision 1.152  2014/06/18 17:54:09  brouard
                    206:   Summary: open browser, use gnuplot on same dir than imach if not found in the path
                    207: 
1.152     brouard   208:   Revision 1.151  2014/06/18 16:43:30  brouard
                    209:   *** empty log message ***
                    210: 
1.151     brouard   211:   Revision 1.150  2014/06/18 16:42:35  brouard
                    212:   Summary: If gnuplot is not in the path try on same directory than imach binary (OSX)
                    213:   Author: brouard
                    214: 
1.150     brouard   215:   Revision 1.149  2014/06/18 15:51:14  brouard
                    216:   Summary: Some fixes in parameter files errors
                    217:   Author: Nicolas Brouard
                    218: 
1.149     brouard   219:   Revision 1.148  2014/06/17 17:38:48  brouard
                    220:   Summary: Nothing new
                    221:   Author: Brouard
                    222: 
                    223:   Just a new packaging for OS/X version 0.98nS
                    224: 
1.148     brouard   225:   Revision 1.147  2014/06/16 10:33:11  brouard
                    226:   *** empty log message ***
                    227: 
1.147     brouard   228:   Revision 1.146  2014/06/16 10:20:28  brouard
                    229:   Summary: Merge
                    230:   Author: Brouard
                    231: 
                    232:   Merge, before building revised version.
                    233: 
1.146     brouard   234:   Revision 1.145  2014/06/10 21:23:15  brouard
                    235:   Summary: Debugging with valgrind
                    236:   Author: Nicolas Brouard
                    237: 
                    238:   Lot of changes in order to output the results with some covariates
                    239:   After the Edimburgh REVES conference 2014, it seems mandatory to
                    240:   improve the code.
                    241:   No more memory valgrind error but a lot has to be done in order to
                    242:   continue the work of splitting the code into subroutines.
                    243:   Also, decodemodel has been improved. Tricode is still not
                    244:   optimal. nbcode should be improved. Documentation has been added in
                    245:   the source code.
                    246: 
1.144     brouard   247:   Revision 1.143  2014/01/26 09:45:38  brouard
                    248:   Summary: Version 0.98nR (to be improved, but gives same optimization results as 0.98k. Nice, promising
                    249: 
                    250:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    251:   (Module): Version 0.98nR Running ok, but output format still only works for three covariates.
                    252: 
1.143     brouard   253:   Revision 1.142  2014/01/26 03:57:36  brouard
                    254:   Summary: gnuplot changed plot w l 1 has to be changed to plot w l lt 2
                    255: 
                    256:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    257: 
1.142     brouard   258:   Revision 1.141  2014/01/26 02:42:01  brouard
                    259:   * imach.c (Module): Trying to merge old staffs together while being at Tokyo. Not tested...
                    260: 
1.141     brouard   261:   Revision 1.140  2011/09/02 10:37:54  brouard
                    262:   Summary: times.h is ok with mingw32 now.
                    263: 
1.140     brouard   264:   Revision 1.139  2010/06/14 07:50:17  brouard
                    265:   After the theft of my laptop, I probably lost some lines of codes which were not uploaded to the CVS tree.
                    266:   I remember having already fixed agemin agemax which are pointers now but not cvs saved.
                    267: 
1.139     brouard   268:   Revision 1.138  2010/04/30 18:19:40  brouard
                    269:   *** empty log message ***
                    270: 
1.138     brouard   271:   Revision 1.137  2010/04/29 18:11:38  brouard
                    272:   (Module): Checking covariates for more complex models
                    273:   than V1+V2. A lot of change to be done. Unstable.
                    274: 
1.137     brouard   275:   Revision 1.136  2010/04/26 20:30:53  brouard
                    276:   (Module): merging some libgsl code. Fixing computation
                    277:   of likelione (using inter/intrapolation if mle = 0) in order to
                    278:   get same likelihood as if mle=1.
                    279:   Some cleaning of code and comments added.
                    280: 
1.136     brouard   281:   Revision 1.135  2009/10/29 15:33:14  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.135     brouard   284:   Revision 1.134  2009/10/29 13:18:53  brouard
                    285:   (Module): Now imach stops if date of birth, at least year of birth, is not given. Some cleaning of the code.
                    286: 
1.134     brouard   287:   Revision 1.133  2009/07/06 10:21:25  brouard
                    288:   just nforces
                    289: 
1.133     brouard   290:   Revision 1.132  2009/07/06 08:22:05  brouard
                    291:   Many tings
                    292: 
1.132     brouard   293:   Revision 1.131  2009/06/20 16:22:47  brouard
                    294:   Some dimensions resccaled
                    295: 
1.131     brouard   296:   Revision 1.130  2009/05/26 06:44:34  brouard
                    297:   (Module): Max Covariate is now set to 20 instead of 8. A
                    298:   lot of cleaning with variables initialized to 0. Trying to make
                    299:   V2+V3*age+V1+V4 strb=V3*age+V1+V4 working better.
                    300: 
1.130     brouard   301:   Revision 1.129  2007/08/31 13:49:27  lievre
                    302:   Modification of the way of exiting when the covariate is not binary in order to see on the window the error message before exiting
                    303: 
1.129     lievre    304:   Revision 1.128  2006/06/30 13:02:05  brouard
                    305:   (Module): Clarifications on computing e.j
                    306: 
1.128     brouard   307:   Revision 1.127  2006/04/28 18:11:50  brouard
                    308:   (Module): Yes the sum of survivors was wrong since
                    309:   imach-114 because nhstepm was no more computed in the age
                    310:   loop. Now we define nhstepma in the age loop.
                    311:   (Module): In order to speed up (in case of numerous covariates) we
                    312:   compute health expectancies (without variances) in a first step
                    313:   and then all the health expectancies with variances or standard
                    314:   deviation (needs data from the Hessian matrices) which slows the
                    315:   computation.
                    316:   In the future we should be able to stop the program is only health
                    317:   expectancies and graph are needed without standard deviations.
                    318: 
1.127     brouard   319:   Revision 1.126  2006/04/28 17:23:28  brouard
                    320:   (Module): Yes the sum of survivors was wrong since
                    321:   imach-114 because nhstepm was no more computed in the age
                    322:   loop. Now we define nhstepma in the age loop.
                    323:   Version 0.98h
                    324: 
1.126     brouard   325:   Revision 1.125  2006/04/04 15:20:31  lievre
                    326:   Errors in calculation of health expectancies. Age was not initialized.
                    327:   Forecasting file added.
                    328: 
                    329:   Revision 1.124  2006/03/22 17:13:53  lievre
                    330:   Parameters are printed with %lf instead of %f (more numbers after the comma).
                    331:   The log-likelihood is printed in the log file
                    332: 
                    333:   Revision 1.123  2006/03/20 10:52:43  brouard
                    334:   * imach.c (Module): <title> changed, corresponds to .htm file
                    335:   name. <head> headers where missing.
                    336: 
                    337:   * imach.c (Module): Weights can have a decimal point as for
                    338:   English (a comma might work with a correct LC_NUMERIC environment,
                    339:   otherwise the weight is truncated).
                    340:   Modification of warning when the covariates values are not 0 or
                    341:   1.
                    342:   Version 0.98g
                    343: 
                    344:   Revision 1.122  2006/03/20 09:45:41  brouard
                    345:   (Module): Weights can have a decimal point as for
                    346:   English (a comma might work with a correct LC_NUMERIC environment,
                    347:   otherwise the weight is truncated).
                    348:   Modification of warning when the covariates values are not 0 or
                    349:   1.
                    350:   Version 0.98g
                    351: 
                    352:   Revision 1.121  2006/03/16 17:45:01  lievre
                    353:   * imach.c (Module): Comments concerning covariates added
                    354: 
                    355:   * imach.c (Module): refinements in the computation of lli if
                    356:   status=-2 in order to have more reliable computation if stepm is
                    357:   not 1 month. Version 0.98f
                    358: 
                    359:   Revision 1.120  2006/03/16 15:10:38  lievre
                    360:   (Module): refinements in the computation of lli if
                    361:   status=-2 in order to have more reliable computation if stepm is
                    362:   not 1 month. Version 0.98f
                    363: 
                    364:   Revision 1.119  2006/03/15 17:42:26  brouard
                    365:   (Module): Bug if status = -2, the loglikelihood was
                    366:   computed as likelihood omitting the logarithm. Version O.98e
                    367: 
                    368:   Revision 1.118  2006/03/14 18:20:07  brouard
                    369:   (Module): varevsij Comments added explaining the second
                    370:   table of variances if popbased=1 .
                    371:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    372:   (Module): Function pstamp added
                    373:   (Module): Version 0.98d
                    374: 
                    375:   Revision 1.117  2006/03/14 17:16:22  brouard
                    376:   (Module): varevsij Comments added explaining the second
                    377:   table of variances if popbased=1 .
                    378:   (Module): Covariances of eij, ekl added, graphs fixed, new html link.
                    379:   (Module): Function pstamp added
                    380:   (Module): Version 0.98d
                    381: 
                    382:   Revision 1.116  2006/03/06 10:29:27  brouard
                    383:   (Module): Variance-covariance wrong links and
                    384:   varian-covariance of ej. is needed (Saito).
                    385: 
                    386:   Revision 1.115  2006/02/27 12:17:45  brouard
                    387:   (Module): One freematrix added in mlikeli! 0.98c
                    388: 
                    389:   Revision 1.114  2006/02/26 12:57:58  brouard
                    390:   (Module): Some improvements in processing parameter
                    391:   filename with strsep.
                    392: 
                    393:   Revision 1.113  2006/02/24 14:20:24  brouard
                    394:   (Module): Memory leaks checks with valgrind and:
                    395:   datafile was not closed, some imatrix were not freed and on matrix
                    396:   allocation too.
                    397: 
                    398:   Revision 1.112  2006/01/30 09:55:26  brouard
                    399:   (Module): Back to gnuplot.exe instead of wgnuplot.exe
                    400: 
                    401:   Revision 1.111  2006/01/25 20:38:18  brouard
                    402:   (Module): Lots of cleaning and bugs added (Gompertz)
                    403:   (Module): Comments can be added in data file. Missing date values
                    404:   can be a simple dot '.'.
                    405: 
                    406:   Revision 1.110  2006/01/25 00:51:50  brouard
                    407:   (Module): Lots of cleaning and bugs added (Gompertz)
                    408: 
                    409:   Revision 1.109  2006/01/24 19:37:15  brouard
                    410:   (Module): Comments (lines starting with a #) are allowed in data.
                    411: 
                    412:   Revision 1.108  2006/01/19 18:05:42  lievre
                    413:   Gnuplot problem appeared...
                    414:   To be fixed
                    415: 
                    416:   Revision 1.107  2006/01/19 16:20:37  brouard
                    417:   Test existence of gnuplot in imach path
                    418: 
                    419:   Revision 1.106  2006/01/19 13:24:36  brouard
                    420:   Some cleaning and links added in html output
                    421: 
                    422:   Revision 1.105  2006/01/05 20:23:19  lievre
                    423:   *** empty log message ***
                    424: 
                    425:   Revision 1.104  2005/09/30 16:11:43  lievre
                    426:   (Module): sump fixed, loop imx fixed, and simplifications.
                    427:   (Module): If the status is missing at the last wave but we know
                    428:   that the person is alive, then we can code his/her status as -2
                    429:   (instead of missing=-1 in earlier versions) and his/her
                    430:   contributions to the likelihood is 1 - Prob of dying from last
                    431:   health status (= 1-p13= p11+p12 in the easiest case of somebody in
                    432:   the healthy state at last known wave). Version is 0.98
                    433: 
                    434:   Revision 1.103  2005/09/30 15:54:49  lievre
                    435:   (Module): sump fixed, loop imx fixed, and simplifications.
                    436: 
                    437:   Revision 1.102  2004/09/15 17:31:30  brouard
                    438:   Add the possibility to read data file including tab characters.
                    439: 
                    440:   Revision 1.101  2004/09/15 10:38:38  brouard
                    441:   Fix on curr_time
                    442: 
                    443:   Revision 1.100  2004/07/12 18:29:06  brouard
                    444:   Add version for Mac OS X. Just define UNIX in Makefile
                    445: 
                    446:   Revision 1.99  2004/06/05 08:57:40  brouard
                    447:   *** empty log message ***
                    448: 
                    449:   Revision 1.98  2004/05/16 15:05:56  brouard
                    450:   New version 0.97 . First attempt to estimate force of mortality
                    451:   directly from the data i.e. without the need of knowing the health
                    452:   state at each age, but using a Gompertz model: log u =a + b*age .
                    453:   This is the basic analysis of mortality and should be done before any
                    454:   other analysis, in order to test if the mortality estimated from the
                    455:   cross-longitudinal survey is different from the mortality estimated
                    456:   from other sources like vital statistic data.
                    457: 
                    458:   The same imach parameter file can be used but the option for mle should be -3.
                    459: 
1.133     brouard   460:   Agnès, who wrote this part of the code, tried to keep most of the
1.126     brouard   461:   former routines in order to include the new code within the former code.
                    462: 
                    463:   The output is very simple: only an estimate of the intercept and of
                    464:   the slope with 95% confident intervals.
                    465: 
                    466:   Current limitations:
                    467:   A) Even if you enter covariates, i.e. with the
                    468:   model= V1+V2 equation for example, the programm does only estimate a unique global model without covariates.
                    469:   B) There is no computation of Life Expectancy nor Life Table.
                    470: 
                    471:   Revision 1.97  2004/02/20 13:25:42  lievre
                    472:   Version 0.96d. Population forecasting command line is (temporarily)
                    473:   suppressed.
                    474: 
                    475:   Revision 1.96  2003/07/15 15:38:55  brouard
                    476:   * imach.c (Repository): Errors in subdirf, 2, 3 while printing tmpout is
                    477:   rewritten within the same printf. Workaround: many printfs.
                    478: 
                    479:   Revision 1.95  2003/07/08 07:54:34  brouard
                    480:   * imach.c (Repository):
                    481:   (Repository): Using imachwizard code to output a more meaningful covariance
                    482:   matrix (cov(a12,c31) instead of numbers.
                    483: 
                    484:   Revision 1.94  2003/06/27 13:00:02  brouard
                    485:   Just cleaning
                    486: 
                    487:   Revision 1.93  2003/06/25 16:33:55  brouard
                    488:   (Module): On windows (cygwin) function asctime_r doesn't
                    489:   exist so I changed back to asctime which exists.
                    490:   (Module): Version 0.96b
                    491: 
                    492:   Revision 1.92  2003/06/25 16:30:45  brouard
                    493:   (Module): On windows (cygwin) function asctime_r doesn't
                    494:   exist so I changed back to asctime which exists.
                    495: 
                    496:   Revision 1.91  2003/06/25 15:30:29  brouard
                    497:   * imach.c (Repository): Duplicated warning errors corrected.
                    498:   (Repository): Elapsed time after each iteration is now output. It
                    499:   helps to forecast when convergence will be reached. Elapsed time
                    500:   is stamped in powell.  We created a new html file for the graphs
                    501:   concerning matrix of covariance. It has extension -cov.htm.
                    502: 
                    503:   Revision 1.90  2003/06/24 12:34:15  brouard
                    504:   (Module): Some bugs corrected for windows. Also, when
                    505:   mle=-1 a template is output in file "or"mypar.txt with the design
                    506:   of the covariance matrix to be input.
                    507: 
                    508:   Revision 1.89  2003/06/24 12:30:52  brouard
                    509:   (Module): Some bugs corrected for windows. Also, when
                    510:   mle=-1 a template is output in file "or"mypar.txt with the design
                    511:   of the covariance matrix to be input.
                    512: 
                    513:   Revision 1.88  2003/06/23 17:54:56  brouard
                    514:   * 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.
                    515: 
                    516:   Revision 1.87  2003/06/18 12:26:01  brouard
                    517:   Version 0.96
                    518: 
                    519:   Revision 1.86  2003/06/17 20:04:08  brouard
                    520:   (Module): Change position of html and gnuplot routines and added
                    521:   routine fileappend.
                    522: 
                    523:   Revision 1.85  2003/06/17 13:12:43  brouard
                    524:   * imach.c (Repository): Check when date of death was earlier that
                    525:   current date of interview. It may happen when the death was just
                    526:   prior to the death. In this case, dh was negative and likelihood
                    527:   was wrong (infinity). We still send an "Error" but patch by
                    528:   assuming that the date of death was just one stepm after the
                    529:   interview.
                    530:   (Repository): Because some people have very long ID (first column)
                    531:   we changed int to long in num[] and we added a new lvector for
                    532:   memory allocation. But we also truncated to 8 characters (left
                    533:   truncation)
                    534:   (Repository): No more line truncation errors.
                    535: 
                    536:   Revision 1.84  2003/06/13 21:44:43  brouard
                    537:   * imach.c (Repository): Replace "freqsummary" at a correct
                    538:   place. It differs from routine "prevalence" which may be called
                    539:   many times. Probs is memory consuming and must be used with
                    540:   parcimony.
                    541:   Version 0.95a3 (should output exactly the same maximization than 0.8a2)
                    542: 
                    543:   Revision 1.83  2003/06/10 13:39:11  lievre
                    544:   *** empty log message ***
                    545: 
                    546:   Revision 1.82  2003/06/05 15:57:20  brouard
                    547:   Add log in  imach.c and  fullversion number is now printed.
                    548: 
                    549: */
                    550: /*
                    551:    Interpolated Markov Chain
                    552: 
                    553:   Short summary of the programme:
                    554:   
                    555:   This program computes Healthy Life Expectancies from
                    556:   cross-longitudinal data. Cross-longitudinal data consist in: -1- a
                    557:   first survey ("cross") where individuals from different ages are
                    558:   interviewed on their health status or degree of disability (in the
                    559:   case of a health survey which is our main interest) -2- at least a
                    560:   second wave of interviews ("longitudinal") which measure each change
                    561:   (if any) in individual health status.  Health expectancies are
                    562:   computed from the time spent in each health state according to a
                    563:   model. More health states you consider, more time is necessary to reach the
                    564:   Maximum Likelihood of the parameters involved in the model.  The
                    565:   simplest model is the multinomial logistic model where pij is the
                    566:   probability to be observed in state j at the second wave
                    567:   conditional to be observed in state i at the first wave. Therefore
                    568:   the model is: log(pij/pii)= aij + bij*age+ cij*sex + etc , where
                    569:   'age' is age and 'sex' is a covariate. If you want to have a more
                    570:   complex model than "constant and age", you should modify the program
                    571:   where the markup *Covariates have to be included here again* invites
                    572:   you to do it.  More covariates you add, slower the
                    573:   convergence.
                    574: 
                    575:   The advantage of this computer programme, compared to a simple
                    576:   multinomial logistic model, is clear when the delay between waves is not
                    577:   identical for each individual. Also, if a individual missed an
                    578:   intermediate interview, the information is lost, but taken into
                    579:   account using an interpolation or extrapolation.  
                    580: 
                    581:   hPijx is the probability to be observed in state i at age x+h
                    582:   conditional to the observed state i at age x. The delay 'h' can be
                    583:   split into an exact number (nh*stepm) of unobserved intermediate
                    584:   states. This elementary transition (by month, quarter,
                    585:   semester or year) is modelled as a multinomial logistic.  The hPx
                    586:   matrix is simply the matrix product of nh*stepm elementary matrices
                    587:   and the contribution of each individual to the likelihood is simply
                    588:   hPijx.
                    589: 
                    590:   Also this programme outputs the covariance matrix of the parameters but also
                    591:   of the life expectancies. It also computes the period (stable) prevalence. 
                    592:   
1.133     brouard   593:   Authors: Nicolas Brouard (brouard@ined.fr) and Agnès Lièvre (lievre@ined.fr).
                    594:            Institut national d'études démographiques, Paris.
1.126     brouard   595:   This software have been partly granted by Euro-REVES, a concerted action
                    596:   from the European Union.
                    597:   It is copyrighted identically to a GNU software product, ie programme and
                    598:   software can be distributed freely for non commercial use. Latest version
                    599:   can be accessed at http://euroreves.ined.fr/imach .
                    600: 
                    601:   Help to debug: LD_PRELOAD=/usr/local/lib/libnjamd.so ./imach foo.imach
                    602:   or better on gdb : set env LD_PRELOAD=/usr/local/lib/libnjamd.so
                    603:   
                    604:   **********************************************************************/
                    605: /*
                    606:   main
                    607:   read parameterfile
                    608:   read datafile
                    609:   concatwav
                    610:   freqsummary
                    611:   if (mle >= 1)
                    612:     mlikeli
                    613:   print results files
                    614:   if mle==1 
                    615:      computes hessian
                    616:   read end of parameter file: agemin, agemax, bage, fage, estepm
                    617:       begin-prev-date,...
                    618:   open gnuplot file
                    619:   open html file
1.145     brouard   620:   period (stable) prevalence      | pl_nom    1-1 2-2 etc by covariate
                    621:    for age prevalim()             | #****** V1=0  V2=1  V3=1  V4=0 ******
                    622:                                   | 65 1 0 2 1 3 1 4 0  0.96326 0.03674
                    623:     freexexit2 possible for memory heap.
                    624: 
                    625:   h Pij x                         | pij_nom  ficrestpij
                    626:    # Cov Agex agex+h hpijx with i,j= 1-1 1-2     1-3     2-1     2-2     2-3
                    627:        1  85   85    1.00000             0.00000 0.00000 0.00000 1.00000 0.00000
                    628:        1  85   86    0.68299             0.22291 0.09410 0.71093 0.00000 0.28907
                    629: 
                    630:        1  65   99    0.00364             0.00322 0.99314 0.00350 0.00310 0.99340
                    631:        1  65  100    0.00214             0.00204 0.99581 0.00206 0.00196 0.99597
                    632:   variance of p one-step probabilities varprob  | prob_nom   ficresprob #One-step probabilities and stand. devi in ()
                    633:    Standard deviation of one-step probabilities | probcor_nom   ficresprobcor #One-step probabilities and correlation matrix
                    634:    Matrix of variance covariance of one-step probabilities |  probcov_nom ficresprobcov #One-step probabilities and covariance matrix
                    635: 
1.126     brouard   636:   forecasting if prevfcast==1 prevforecast call prevalence()
                    637:   health expectancies
                    638:   Variance-covariance of DFLE
                    639:   prevalence()
                    640:    movingaverage()
                    641:   varevsij() 
                    642:   if popbased==1 varevsij(,popbased)
                    643:   total life expectancies
                    644:   Variance of period (stable) prevalence
                    645:  end
                    646: */
                    647: 
1.187     brouard   648: /* #define DEBUG */
                    649: /* #define DEBUGBRENT */
1.203   ! brouard   650: /* #define DEBUGLINMIN */
        !           651: /* #define DEBUGHESS */
        !           652: #define DEBUGHESSIJ
        !           653: /* #define LINMINORIGINAL  /\* Don't use loop on scale in linmin (accepting nan)*\/ */
1.165     brouard   654: #define POWELL /* Instead of NLOPT */
1.192     brouard   655: #define POWELLF1F3 /* Skip test */
1.186     brouard   656: /* #define POWELLORIGINAL /\* Don't use Directest to decide new direction but original Powell test *\/ */
                    657: /* #define MNBRAKORIGINAL /\* Don't use mnbrak fix *\/ */
1.126     brouard   658: 
                    659: #include <math.h>
                    660: #include <stdio.h>
                    661: #include <stdlib.h>
                    662: #include <string.h>
1.159     brouard   663: 
                    664: #ifdef _WIN32
                    665: #include <io.h>
1.172     brouard   666: #include <windows.h>
                    667: #include <tchar.h>
1.159     brouard   668: #else
1.126     brouard   669: #include <unistd.h>
1.159     brouard   670: #endif
1.126     brouard   671: 
                    672: #include <limits.h>
                    673: #include <sys/types.h>
1.171     brouard   674: 
                    675: #if defined(__GNUC__)
                    676: #include <sys/utsname.h> /* Doesn't work on Windows */
                    677: #endif
                    678: 
1.126     brouard   679: #include <sys/stat.h>
                    680: #include <errno.h>
1.159     brouard   681: /* extern int errno; */
1.126     brouard   682: 
1.157     brouard   683: /* #ifdef LINUX */
                    684: /* #include <time.h> */
                    685: /* #include "timeval.h" */
                    686: /* #else */
                    687: /* #include <sys/time.h> */
                    688: /* #endif */
                    689: 
1.126     brouard   690: #include <time.h>
                    691: 
1.136     brouard   692: #ifdef GSL
                    693: #include <gsl/gsl_errno.h>
                    694: #include <gsl/gsl_multimin.h>
                    695: #endif
                    696: 
1.167     brouard   697: 
1.162     brouard   698: #ifdef NLOPT
                    699: #include <nlopt.h>
                    700: typedef struct {
                    701:   double (* function)(double [] );
                    702: } myfunc_data ;
                    703: #endif
                    704: 
1.126     brouard   705: /* #include <libintl.h> */
                    706: /* #define _(String) gettext (String) */
                    707: 
1.141     brouard   708: #define MAXLINE 1024 /* Was 256. Overflow with 312 with 2 states and 4 covariates. Should be ok */
1.126     brouard   709: 
                    710: #define GNUPLOTPROGRAM "gnuplot"
                    711: /*#define GNUPLOTPROGRAM "..\\gp37mgw\\wgnuplot"*/
                    712: #define FILENAMELENGTH 132
                    713: 
                    714: #define        GLOCK_ERROR_NOPATH              -1      /* empty path */
                    715: #define        GLOCK_ERROR_GETCWD              -2      /* cannot get cwd */
                    716: 
1.144     brouard   717: #define MAXPARM 128 /**< Maximum number of parameters for the optimization */
                    718: #define NPARMAX 64 /**< (nlstate+ndeath-1)*nlstate*ncovmodel */
1.126     brouard   719: 
                    720: #define NINTERVMAX 8
1.144     brouard   721: #define NLSTATEMAX 8 /**< Maximum number of live states (for func) */
                    722: #define NDEATHMAX 8 /**< Maximum number of dead states (for func) */
                    723: #define NCOVMAX 20 /**< Maximum number of covariates, including generated covariates V1*V2 */
1.197     brouard   724: #define codtabm(h,k)  (1 & (h-1) >> (k-1))+1
1.126     brouard   725: #define MAXN 20000
1.144     brouard   726: #define YEARM 12. /**< Number of months per year */
1.126     brouard   727: #define AGESUP 130
                    728: #define AGEBASE 40
1.194     brouard   729: #define AGEOVERFLOW 1.e20
1.164     brouard   730: #define AGEGOMP 10 /**< Minimal age for Gompertz adjustment */
1.157     brouard   731: #ifdef _WIN32
                    732: #define DIRSEPARATOR '\\'
                    733: #define CHARSEPARATOR "\\"
                    734: #define ODIRSEPARATOR '/'
                    735: #else
1.126     brouard   736: #define DIRSEPARATOR '/'
                    737: #define CHARSEPARATOR "/"
                    738: #define ODIRSEPARATOR '\\'
                    739: #endif
                    740: 
1.203   ! brouard   741: /* $Id: imach.c,v 1.202 2015/09/22 19:45:16 brouard Exp $ */
1.126     brouard   742: /* $State: Exp $ */
1.196     brouard   743: #include "version.h"
                    744: char version[]=__IMACH_VERSION__;
1.197     brouard   745: 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.203   ! brouard   746: char fullversion[]="$Revision: 1.202 $ $Date: 2015/09/22 19:45:16 $"; 
1.126     brouard   747: char strstart[80];
                    748: char optionfilext[10], optionfilefiname[FILENAMELENGTH];
1.130     brouard   749: int erreur=0, nberr=0, nbwarn=0; /* Error number, number of errors number of warnings  */
1.187     brouard   750: int nagesqr=0, nforce=0; /* nagesqr=1 if model is including age*age, number of forces */
1.145     brouard   751: /* Number of covariates model=V2+V1+ V3*age+V2*V4 */
                    752: int cptcovn=0; /**< cptcovn number of covariates added in the model (excepting constant and age and age*product) */
                    753: int cptcovt=0; /**< cptcovt number of covariates added in the model (excepting constant and age) */
                    754: int cptcovs=0; /**< cptcovs number of simple covariates V2+V1 =2 */
                    755: int cptcovage=0; /**< Number of covariates with age: V3*age only =1 */
                    756: int cptcovprodnoage=0; /**< Number of covariate products without age */   
                    757: int cptcoveff=0; /* Total number of covariates to vary for printing results */
                    758: int cptcov=0; /* Working variable */
1.126     brouard   759: int npar=NPARMAX;
                    760: int nlstate=2; /* Number of live states */
                    761: int ndeath=1; /* Number of dead states */
1.130     brouard   762: int ncovmodel=0, ncovcol=0;     /* Total number of covariables including constant a12*1 +b12*x ncovmodel=2 */
1.126     brouard   763: int popbased=0;
                    764: 
                    765: int *wav; /* Number of waves for this individuual 0 is possible */
1.130     brouard   766: int maxwav=0; /* Maxim number of waves */
                    767: int jmin=0, jmax=0; /* min, max spacing between 2 waves */
                    768: int ijmin=0, ijmax=0; /* Individuals having jmin and jmax */ 
                    769: int gipmx=0, gsw=0; /* Global variables on the number of contributions 
1.126     brouard   770:                   to the likelihood and the sum of weights (done by funcone)*/
1.130     brouard   771: int mle=1, weightopt=0;
1.126     brouard   772: int **mw; /* mw[mi][i] is number of the mi wave for this individual */
                    773: int **dh; /* dh[mi][i] is number of steps between mi,mi+1 for this individual */
                    774: int **bh; /* bh[mi][i] is the bias (+ or -) for this individual if the delay between
                    775:           * wave mi and wave mi+1 is not an exact multiple of stepm. */
1.162     brouard   776: int countcallfunc=0;  /* Count the number of calls to func */
1.130     brouard   777: double jmean=1; /* Mean space between 2 waves */
1.145     brouard   778: double **matprod2(); /* test */
1.126     brouard   779: double **oldm, **newm, **savm; /* Working pointers to matrices */
                    780: double **oldms, **newms, **savms; /* Fixed working pointers to matrices */
1.136     brouard   781: /*FILE *fic ; */ /* Used in readdata only */
                    782: FILE *ficpar, *ficparo,*ficres, *ficresp, *ficrespl, *ficrespij, *ficrest,*ficresf,*ficrespop;
1.126     brouard   783: FILE *ficlog, *ficrespow;
1.130     brouard   784: int globpr=0; /* Global variable for printing or not */
1.126     brouard   785: double fretone; /* Only one call to likelihood */
1.130     brouard   786: long ipmx=0; /* Number of contributions */
1.126     brouard   787: double sw; /* Sum of weights */
                    788: char filerespow[FILENAMELENGTH];
                    789: char fileresilk[FILENAMELENGTH]; /* File of individual contributions to the likelihood */
                    790: FILE *ficresilk;
                    791: FILE *ficgp,*ficresprob,*ficpop, *ficresprobcov, *ficresprobcor;
                    792: FILE *ficresprobmorprev;
                    793: FILE *fichtm, *fichtmcov; /* Html File */
                    794: FILE *ficreseij;
                    795: char filerese[FILENAMELENGTH];
                    796: FILE *ficresstdeij;
                    797: char fileresstde[FILENAMELENGTH];
                    798: FILE *ficrescveij;
                    799: char filerescve[FILENAMELENGTH];
                    800: FILE  *ficresvij;
                    801: char fileresv[FILENAMELENGTH];
                    802: FILE  *ficresvpl;
                    803: char fileresvpl[FILENAMELENGTH];
                    804: char title[MAXLINE];
                    805: char optionfile[FILENAMELENGTH], datafile[FILENAMELENGTH],  filerespl[FILENAMELENGTH];
                    806: char plotcmd[FILENAMELENGTH], pplotcmd[FILENAMELENGTH];
                    807: char tmpout[FILENAMELENGTH],  tmpout2[FILENAMELENGTH]; 
                    808: char command[FILENAMELENGTH];
                    809: int  outcmd=0;
                    810: 
                    811: char fileres[FILENAMELENGTH], filerespij[FILENAMELENGTH], filereso[FILENAMELENGTH], rfileres[FILENAMELENGTH];
1.202     brouard   812: char fileresu[FILENAMELENGTH]; /* fileres without r in front */
1.126     brouard   813: char filelog[FILENAMELENGTH]; /* Log file */
                    814: char filerest[FILENAMELENGTH];
                    815: char fileregp[FILENAMELENGTH];
                    816: char popfile[FILENAMELENGTH];
                    817: 
                    818: char optionfilegnuplot[FILENAMELENGTH], optionfilehtm[FILENAMELENGTH], optionfilehtmcov[FILENAMELENGTH] ;
                    819: 
1.157     brouard   820: /* struct timeval start_time, end_time, curr_time, last_time, forecast_time; */
                    821: /* struct timezone tzp; */
                    822: /* extern int gettimeofday(); */
                    823: struct tm tml, *gmtime(), *localtime();
                    824: 
                    825: extern time_t time();
                    826: 
                    827: struct tm start_time, end_time, curr_time, last_time, forecast_time;
                    828: time_t  rstart_time, rend_time, rcurr_time, rlast_time, rforecast_time; /* raw time */
                    829: struct tm tm;
                    830: 
1.126     brouard   831: char strcurr[80], strfor[80];
                    832: 
                    833: char *endptr;
                    834: long lval;
                    835: double dval;
                    836: 
                    837: #define NR_END 1
                    838: #define FREE_ARG char*
                    839: #define FTOL 1.0e-10
                    840: 
                    841: #define NRANSI 
                    842: #define ITMAX 200 
                    843: 
                    844: #define TOL 2.0e-4 
                    845: 
                    846: #define CGOLD 0.3819660 
                    847: #define ZEPS 1.0e-10 
                    848: #define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d); 
                    849: 
                    850: #define GOLD 1.618034 
                    851: #define GLIMIT 100.0 
                    852: #define TINY 1.0e-20 
                    853: 
                    854: static double maxarg1,maxarg2;
                    855: #define FMAX(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)>(maxarg2)? (maxarg1):(maxarg2))
                    856: #define FMIN(a,b) (maxarg1=(a),maxarg2=(b),(maxarg1)<(maxarg2)? (maxarg1):(maxarg2))
                    857:   
                    858: #define SIGN(a,b) ((b)>0.0 ? fabs(a) : -fabs(a))
                    859: #define rint(a) floor(a+0.5)
1.166     brouard   860: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/myutils_8h-source.html */
1.183     brouard   861: #define mytinydouble 1.0e-16
1.166     brouard   862: /* #define DEQUAL(a,b) (fabs((a)-(b))<mytinydouble) */
                    863: /* http://www.thphys.uni-heidelberg.de/~robbers/cmbeasy/doc/html/mynrutils_8h-source.html */
                    864: /* static double dsqrarg; */
                    865: /* #define DSQR(a) (DEQUAL((dsqrarg=(a)),0.0) ? 0.0 : dsqrarg*dsqrarg) */
1.126     brouard   866: static double sqrarg;
                    867: #define SQR(a) ((sqrarg=(a)) == 0.0 ? 0.0 :sqrarg*sqrarg)
                    868: #define SWAP(a,b) {temp=(a);(a)=(b);(b)=temp;} 
                    869: int agegomp= AGEGOMP;
                    870: 
                    871: int imx; 
                    872: int stepm=1;
                    873: /* Stepm, step in month: minimum step interpolation*/
                    874: 
                    875: int estepm;
                    876: /* Estepm, step in month to interpolate survival function in order to approximate Life Expectancy*/
                    877: 
                    878: int m,nb;
                    879: long *num;
1.197     brouard   880: int firstpass=0, lastpass=4,*cod, *cens;
1.192     brouard   881: int *ncodemax;  /* ncodemax[j]= Number of modalities of the j th
                    882:                   covariate for which somebody answered excluding 
                    883:                   undefined. Usually 2: 0 and 1. */
                    884: int *ncodemaxwundef;  /* ncodemax[j]= Number of modalities of the j th
                    885:                             covariate for which somebody answered including 
                    886:                             undefined. Usually 3: -1, 0 and 1. */
1.126     brouard   887: double **agev,*moisnais, *annais, *moisdc, *andc,**mint, **anint;
                    888: double **pmmij, ***probs;
                    889: double *ageexmed,*agecens;
                    890: double dateintmean=0;
                    891: 
                    892: double *weight;
                    893: int **s; /* Status */
1.141     brouard   894: double *agedc;
1.145     brouard   895: double  **covar; /**< covar[j,i], value of jth covariate for individual i,
1.141     brouard   896:                  * covar=matrix(0,NCOVMAX,1,n); 
1.187     brouard   897:                  * cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*age; */
1.141     brouard   898: double  idx; 
                    899: int **nbcode, *Tvar; /**< model=V2 => Tvar[1]= 2 */
1.197     brouard   900: int *Tage;
1.145     brouard   901: int *Ndum; /** Freq of modality (tricode */
1.200     brouard   902: /* int **codtab;*/ /**< codtab=imatrix(1,100,1,10); */
1.141     brouard   903: int **Tvard, *Tprod, cptcovprod, *Tvaraff;
1.126     brouard   904: double *lsurv, *lpop, *tpop;
                    905: 
1.143     brouard   906: double ftol=FTOL; /**< Tolerance for computing Max Likelihood */
                    907: double ftolhess; /**< Tolerance for computing hessian */
1.126     brouard   908: 
                    909: /**************** split *************************/
                    910: static int split( char *path, char *dirc, char *name, char *ext, char *finame )
                    911: {
                    912:   /* From a file name with (full) path (either Unix or Windows) we extract the directory (dirc)
                    913:      the name of the file (name), its extension only (ext) and its first part of the name (finame)
                    914:   */ 
                    915:   char *ss;                            /* pointer */
1.186     brouard   916:   int  l1=0, l2=0;                             /* length counters */
1.126     brouard   917: 
                    918:   l1 = strlen(path );                  /* length of path */
                    919:   if ( l1 == 0 ) return( GLOCK_ERROR_NOPATH );
                    920:   ss= strrchr( path, DIRSEPARATOR );           /* find last / */
                    921:   if ( ss == NULL ) {                  /* no directory, so determine current directory */
                    922:     strcpy( name, path );              /* we got the fullname name because no directory */
                    923:     /*if(strrchr(path, ODIRSEPARATOR )==NULL)
                    924:       printf("Warning you should use %s as a separator\n",DIRSEPARATOR);*/
                    925:     /* get current working directory */
                    926:     /*    extern  char* getcwd ( char *buf , int len);*/
1.184     brouard   927: #ifdef WIN32
                    928:     if (_getcwd( dirc, FILENAME_MAX ) == NULL ) {
                    929: #else
                    930:        if (getcwd(dirc, FILENAME_MAX) == NULL) {
                    931: #endif
1.126     brouard   932:       return( GLOCK_ERROR_GETCWD );
                    933:     }
                    934:     /* got dirc from getcwd*/
                    935:     printf(" DIRC = %s \n",dirc);
                    936:   } else {                             /* strip direcotry from path */
                    937:     ss++;                              /* after this, the filename */
                    938:     l2 = strlen( ss );                 /* length of filename */
                    939:     if ( l2 == 0 ) return( GLOCK_ERROR_NOPATH );
                    940:     strcpy( name, ss );                /* save file name */
                    941:     strncpy( dirc, path, l1 - l2 );    /* now the directory */
1.186     brouard   942:     dirc[l1-l2] = '\0';                        /* add zero */
1.126     brouard   943:     printf(" DIRC2 = %s \n",dirc);
                    944:   }
                    945:   /* We add a separator at the end of dirc if not exists */
                    946:   l1 = strlen( dirc );                 /* length of directory */
                    947:   if( dirc[l1-1] != DIRSEPARATOR ){
                    948:     dirc[l1] =  DIRSEPARATOR;
                    949:     dirc[l1+1] = 0; 
                    950:     printf(" DIRC3 = %s \n",dirc);
                    951:   }
                    952:   ss = strrchr( name, '.' );           /* find last / */
                    953:   if (ss >0){
                    954:     ss++;
                    955:     strcpy(ext,ss);                    /* save extension */
                    956:     l1= strlen( name);
                    957:     l2= strlen(ss)+1;
                    958:     strncpy( finame, name, l1-l2);
                    959:     finame[l1-l2]= 0;
                    960:   }
                    961: 
                    962:   return( 0 );                         /* we're done */
                    963: }
                    964: 
                    965: 
                    966: /******************************************/
                    967: 
                    968: void replace_back_to_slash(char *s, char*t)
                    969: {
                    970:   int i;
                    971:   int lg=0;
                    972:   i=0;
                    973:   lg=strlen(t);
                    974:   for(i=0; i<= lg; i++) {
                    975:     (s[i] = t[i]);
                    976:     if (t[i]== '\\') s[i]='/';
                    977:   }
                    978: }
                    979: 
1.132     brouard   980: char *trimbb(char *out, char *in)
1.137     brouard   981: { /* Trim multiple blanks in line but keeps first blanks if line starts with blanks */
1.132     brouard   982:   char *s;
                    983:   s=out;
                    984:   while (*in != '\0'){
1.137     brouard   985:     while( *in == ' ' && *(in+1) == ' '){ /* && *(in+1) != '\0'){*/
1.132     brouard   986:       in++;
                    987:     }
                    988:     *out++ = *in++;
                    989:   }
                    990:   *out='\0';
                    991:   return s;
                    992: }
                    993: 
1.187     brouard   994: /* char *substrchaine(char *out, char *in, char *chain) */
                    995: /* { */
                    996: /*   /\* Substract chain 'chain' from 'in', return and output 'out' *\/ */
                    997: /*   char *s, *t; */
                    998: /*   t=in;s=out; */
                    999: /*   while ((*in != *chain) && (*in != '\0')){ */
                   1000: /*     *out++ = *in++; */
                   1001: /*   } */
                   1002: 
                   1003: /*   /\* *in matches *chain *\/ */
                   1004: /*   while ((*in++ == *chain++) && (*in != '\0')){ */
                   1005: /*     printf("*in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1006: /*   } */
                   1007: /*   in--; chain--; */
                   1008: /*   while ( (*in != '\0')){ */
                   1009: /*     printf("Bef *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1010: /*     *out++ = *in++; */
                   1011: /*     printf("Aft *in = %c, *out= %c *chain= %c \n", *in, *out, *chain);  */
                   1012: /*   } */
                   1013: /*   *out='\0'; */
                   1014: /*   out=s; */
                   1015: /*   return out; */
                   1016: /* } */
                   1017: char *substrchaine(char *out, char *in, char *chain)
                   1018: {
                   1019:   /* Substract chain 'chain' from 'in', return and output 'out' */
                   1020:   /* in="V1+V1*age+age*age+V2", chain="age*age" */
                   1021: 
                   1022:   char *strloc;
                   1023: 
                   1024:   strcpy (out, in); 
                   1025:   strloc = strstr(out, chain); /* strloc points to out at age*age+V2 */
                   1026:   printf("Bef strloc=%s chain=%s out=%s \n", strloc, chain, out);
                   1027:   if(strloc != NULL){ 
                   1028:     /* will affect out */ /* strloc+strlenc(chain)=+V2 */ /* Will also work in Unicode */
                   1029:     memmove(strloc,strloc+strlen(chain), strlen(strloc+strlen(chain))+1);
                   1030:     /* strcpy (strloc, strloc +strlen(chain));*/
                   1031:   }
                   1032:   printf("Aft strloc=%s chain=%s in=%s out=%s \n", strloc, chain, in, out);
                   1033:   return out;
                   1034: }
                   1035: 
                   1036: 
1.145     brouard  1037: char *cutl(char *blocc, char *alocc, char *in, char occ)
                   1038: {
1.187     brouard  1039:   /* cuts string in into blocc and alocc where blocc ends before FIRST occurence of char 'occ' 
1.145     brouard  1040:      and alocc starts after first occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
1.187     brouard  1041:      gives blocc="abcdef" and alocc="ghi2j".
1.145     brouard  1042:      If occ is not found blocc is null and alocc is equal to in. Returns blocc
                   1043:   */
1.160     brouard  1044:   char *s, *t;
1.145     brouard  1045:   t=in;s=in;
                   1046:   while ((*in != occ) && (*in != '\0')){
                   1047:     *alocc++ = *in++;
                   1048:   }
                   1049:   if( *in == occ){
                   1050:     *(alocc)='\0';
                   1051:     s=++in;
                   1052:   }
                   1053:  
                   1054:   if (s == t) {/* occ not found */
                   1055:     *(alocc-(in-s))='\0';
                   1056:     in=s;
                   1057:   }
                   1058:   while ( *in != '\0'){
                   1059:     *blocc++ = *in++;
                   1060:   }
                   1061: 
                   1062:   *blocc='\0';
                   1063:   return t;
                   1064: }
1.137     brouard  1065: char *cutv(char *blocc, char *alocc, char *in, char occ)
                   1066: {
1.187     brouard  1067:   /* cuts string in into blocc and alocc where blocc ends before LAST occurence of char 'occ' 
1.137     brouard  1068:      and alocc starts after last occurence of char 'occ' : ex cutv(blocc,alocc,"abcdef2ghi2j",'2')
                   1069:      gives blocc="abcdef2ghi" and alocc="j".
                   1070:      If occ is not found blocc is null and alocc is equal to in. Returns alocc
                   1071:   */
                   1072:   char *s, *t;
                   1073:   t=in;s=in;
                   1074:   while (*in != '\0'){
                   1075:     while( *in == occ){
                   1076:       *blocc++ = *in++;
                   1077:       s=in;
                   1078:     }
                   1079:     *blocc++ = *in++;
                   1080:   }
                   1081:   if (s == t) /* occ not found */
                   1082:     *(blocc-(in-s))='\0';
                   1083:   else
                   1084:     *(blocc-(in-s)-1)='\0';
                   1085:   in=s;
                   1086:   while ( *in != '\0'){
                   1087:     *alocc++ = *in++;
                   1088:   }
                   1089: 
                   1090:   *alocc='\0';
                   1091:   return s;
                   1092: }
                   1093: 
1.126     brouard  1094: int nbocc(char *s, char occ)
                   1095: {
                   1096:   int i,j=0;
                   1097:   int lg=20;
                   1098:   i=0;
                   1099:   lg=strlen(s);
                   1100:   for(i=0; i<= lg; i++) {
                   1101:   if  (s[i] == occ ) j++;
                   1102:   }
                   1103:   return j;
                   1104: }
                   1105: 
1.137     brouard  1106: /* void cutv(char *u,char *v, char*t, char occ) */
                   1107: /* { */
                   1108: /*   /\* cuts string t into u and v where u ends before last occurence of char 'occ'  */
                   1109: /*      and v starts after last occurence of char 'occ' : ex cutv(u,v,"abcdef2ghi2j",'2') */
                   1110: /*      gives u="abcdef2ghi" and v="j" *\/ */
                   1111: /*   int i,lg,j,p=0; */
                   1112: /*   i=0; */
                   1113: /*   lg=strlen(t); */
                   1114: /*   for(j=0; j<=lg-1; j++) { */
                   1115: /*     if((t[j]!= occ) && (t[j+1]== occ)) p=j+1; */
                   1116: /*   } */
1.126     brouard  1117: 
1.137     brouard  1118: /*   for(j=0; j<p; j++) { */
                   1119: /*     (u[j] = t[j]); */
                   1120: /*   } */
                   1121: /*      u[p]='\0'; */
1.126     brouard  1122: 
1.137     brouard  1123: /*    for(j=0; j<= lg; j++) { */
                   1124: /*     if (j>=(p+1))(v[j-p-1] = t[j]); */
                   1125: /*   } */
                   1126: /* } */
1.126     brouard  1127: 
1.160     brouard  1128: #ifdef _WIN32
                   1129: char * strsep(char **pp, const char *delim)
                   1130: {
                   1131:   char *p, *q;
                   1132:          
                   1133:   if ((p = *pp) == NULL)
                   1134:     return 0;
                   1135:   if ((q = strpbrk (p, delim)) != NULL)
                   1136:   {
                   1137:     *pp = q + 1;
                   1138:     *q = '\0';
                   1139:   }
                   1140:   else
                   1141:     *pp = 0;
                   1142:   return p;
                   1143: }
                   1144: #endif
                   1145: 
1.126     brouard  1146: /********************** nrerror ********************/
                   1147: 
                   1148: void nrerror(char error_text[])
                   1149: {
                   1150:   fprintf(stderr,"ERREUR ...\n");
                   1151:   fprintf(stderr,"%s\n",error_text);
                   1152:   exit(EXIT_FAILURE);
                   1153: }
                   1154: /*********************** vector *******************/
                   1155: double *vector(int nl, int nh)
                   1156: {
                   1157:   double *v;
                   1158:   v=(double *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(double)));
                   1159:   if (!v) nrerror("allocation failure in vector");
                   1160:   return v-nl+NR_END;
                   1161: }
                   1162: 
                   1163: /************************ free vector ******************/
                   1164: void free_vector(double*v, int nl, int nh)
                   1165: {
                   1166:   free((FREE_ARG)(v+nl-NR_END));
                   1167: }
                   1168: 
                   1169: /************************ivector *******************************/
                   1170: int *ivector(long nl,long nh)
                   1171: {
                   1172:   int *v;
                   1173:   v=(int *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(int)));
                   1174:   if (!v) nrerror("allocation failure in ivector");
                   1175:   return v-nl+NR_END;
                   1176: }
                   1177: 
                   1178: /******************free ivector **************************/
                   1179: void free_ivector(int *v, long nl, long nh)
                   1180: {
                   1181:   free((FREE_ARG)(v+nl-NR_END));
                   1182: }
                   1183: 
                   1184: /************************lvector *******************************/
                   1185: long *lvector(long nl,long nh)
                   1186: {
                   1187:   long *v;
                   1188:   v=(long *) malloc((size_t)((nh-nl+1+NR_END)*sizeof(long)));
                   1189:   if (!v) nrerror("allocation failure in ivector");
                   1190:   return v-nl+NR_END;
                   1191: }
                   1192: 
                   1193: /******************free lvector **************************/
                   1194: void free_lvector(long *v, long nl, long nh)
                   1195: {
                   1196:   free((FREE_ARG)(v+nl-NR_END));
                   1197: }
                   1198: 
                   1199: /******************* imatrix *******************************/
                   1200: int **imatrix(long nrl, long nrh, long ncl, long nch) 
                   1201:      /* allocate a int matrix with subscript range m[nrl..nrh][ncl..nch] */ 
                   1202: { 
                   1203:   long i, nrow=nrh-nrl+1,ncol=nch-ncl+1; 
                   1204:   int **m; 
                   1205:   
                   1206:   /* allocate pointers to rows */ 
                   1207:   m=(int **) malloc((size_t)((nrow+NR_END)*sizeof(int*))); 
                   1208:   if (!m) nrerror("allocation failure 1 in matrix()"); 
                   1209:   m += NR_END; 
                   1210:   m -= nrl; 
                   1211:   
                   1212:   
                   1213:   /* allocate rows and set pointers to them */ 
                   1214:   m[nrl]=(int *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(int))); 
                   1215:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()"); 
                   1216:   m[nrl] += NR_END; 
                   1217:   m[nrl] -= ncl; 
                   1218:   
                   1219:   for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol; 
                   1220:   
                   1221:   /* return pointer to array of pointers to rows */ 
                   1222:   return m; 
                   1223: } 
                   1224: 
                   1225: /****************** free_imatrix *************************/
                   1226: void free_imatrix(m,nrl,nrh,ncl,nch)
                   1227:       int **m;
                   1228:       long nch,ncl,nrh,nrl; 
                   1229:      /* free an int matrix allocated by imatrix() */ 
                   1230: { 
                   1231:   free((FREE_ARG) (m[nrl]+ncl-NR_END)); 
                   1232:   free((FREE_ARG) (m+nrl-NR_END)); 
                   1233: } 
                   1234: 
                   1235: /******************* matrix *******************************/
                   1236: double **matrix(long nrl, long nrh, long ncl, long nch)
                   1237: {
                   1238:   long i, nrow=nrh-nrl+1, ncol=nch-ncl+1;
                   1239:   double **m;
                   1240: 
                   1241:   m=(double **) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1242:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1243:   m += NR_END;
                   1244:   m -= nrl;
                   1245: 
                   1246:   m[nrl]=(double *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1247:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1248:   m[nrl] += NR_END;
                   1249:   m[nrl] -= ncl;
                   1250: 
                   1251:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1252:   return m;
1.145     brouard  1253:   /* print *(*(m+1)+70) or print m[1][70]; print m+1 or print &(m[1]) or &(m[1][0])
                   1254: m[i] = address of ith row of the table. &(m[i]) is its value which is another adress
                   1255: that of m[i][0]. In order to get the value p m[i][0] but it is unitialized.
1.126     brouard  1256:    */
                   1257: }
                   1258: 
                   1259: /*************************free matrix ************************/
                   1260: void free_matrix(double **m, long nrl, long nrh, long ncl, long nch)
                   1261: {
                   1262:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1263:   free((FREE_ARG)(m+nrl-NR_END));
                   1264: }
                   1265: 
                   1266: /******************* ma3x *******************************/
                   1267: double ***ma3x(long nrl, long nrh, long ncl, long nch, long nll, long nlh)
                   1268: {
                   1269:   long i, j, nrow=nrh-nrl+1, ncol=nch-ncl+1, nlay=nlh-nll+1;
                   1270:   double ***m;
                   1271: 
                   1272:   m=(double ***) malloc((size_t)((nrow+NR_END)*sizeof(double*)));
                   1273:   if (!m) nrerror("allocation failure 1 in matrix()");
                   1274:   m += NR_END;
                   1275:   m -= nrl;
                   1276: 
                   1277:   m[nrl]=(double **) malloc((size_t)((nrow*ncol+NR_END)*sizeof(double)));
                   1278:   if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
                   1279:   m[nrl] += NR_END;
                   1280:   m[nrl] -= ncl;
                   1281: 
                   1282:   for (i=nrl+1; i<=nrh; i++) m[i]=m[i-1]+ncol;
                   1283: 
                   1284:   m[nrl][ncl]=(double *) malloc((size_t)((nrow*ncol*nlay+NR_END)*sizeof(double)));
                   1285:   if (!m[nrl][ncl]) nrerror("allocation failure 3 in matrix()");
                   1286:   m[nrl][ncl] += NR_END;
                   1287:   m[nrl][ncl] -= nll;
                   1288:   for (j=ncl+1; j<=nch; j++) 
                   1289:     m[nrl][j]=m[nrl][j-1]+nlay;
                   1290:   
                   1291:   for (i=nrl+1; i<=nrh; i++) {
                   1292:     m[i][ncl]=m[i-1l][ncl]+ncol*nlay;
                   1293:     for (j=ncl+1; j<=nch; j++) 
                   1294:       m[i][j]=m[i][j-1]+nlay;
                   1295:   }
                   1296:   return m; 
                   1297:   /*  gdb: p *(m+1) <=> p m[1] and p (m+1) <=> p (m+1) <=> p &(m[1])
                   1298:            &(m[i][j][k]) <=> *((*(m+i) + j)+k)
                   1299:   */
                   1300: }
                   1301: 
                   1302: /*************************free ma3x ************************/
                   1303: void free_ma3x(double ***m, long nrl, long nrh, long ncl, long nch,long nll, long nlh)
                   1304: {
                   1305:   free((FREE_ARG)(m[nrl][ncl]+ nll-NR_END));
                   1306:   free((FREE_ARG)(m[nrl]+ncl-NR_END));
                   1307:   free((FREE_ARG)(m+nrl-NR_END));
                   1308: }
                   1309: 
                   1310: /*************** function subdirf ***********/
                   1311: char *subdirf(char fileres[])
                   1312: {
                   1313:   /* Caution optionfilefiname is hidden */
                   1314:   strcpy(tmpout,optionfilefiname);
                   1315:   strcat(tmpout,"/"); /* Add to the right */
                   1316:   strcat(tmpout,fileres);
                   1317:   return tmpout;
                   1318: }
                   1319: 
                   1320: /*************** function subdirf2 ***********/
                   1321: char *subdirf2(char fileres[], char *preop)
                   1322: {
                   1323:   
                   1324:   /* Caution optionfilefiname is hidden */
                   1325:   strcpy(tmpout,optionfilefiname);
                   1326:   strcat(tmpout,"/");
                   1327:   strcat(tmpout,preop);
                   1328:   strcat(tmpout,fileres);
                   1329:   return tmpout;
                   1330: }
                   1331: 
                   1332: /*************** function subdirf3 ***********/
                   1333: char *subdirf3(char fileres[], char *preop, char *preop2)
                   1334: {
                   1335:   
                   1336:   /* Caution optionfilefiname is hidden */
                   1337:   strcpy(tmpout,optionfilefiname);
                   1338:   strcat(tmpout,"/");
                   1339:   strcat(tmpout,preop);
                   1340:   strcat(tmpout,preop2);
                   1341:   strcat(tmpout,fileres);
                   1342:   return tmpout;
                   1343: }
                   1344: 
1.162     brouard  1345: char *asc_diff_time(long time_sec, char ascdiff[])
                   1346: {
                   1347:   long sec_left, days, hours, minutes;
                   1348:   days = (time_sec) / (60*60*24);
                   1349:   sec_left = (time_sec) % (60*60*24);
                   1350:   hours = (sec_left) / (60*60) ;
                   1351:   sec_left = (sec_left) %(60*60);
                   1352:   minutes = (sec_left) /60;
                   1353:   sec_left = (sec_left) % (60);
                   1354:   sprintf(ascdiff,"%ld day(s) %ld hour(s) %ld minute(s) %ld second(s)",days, hours, minutes, sec_left);  
                   1355:   return ascdiff;
                   1356: }
                   1357: 
1.126     brouard  1358: /***************** f1dim *************************/
                   1359: extern int ncom; 
                   1360: extern double *pcom,*xicom;
                   1361: extern double (*nrfunc)(double []); 
                   1362:  
                   1363: double f1dim(double x) 
                   1364: { 
                   1365:   int j; 
                   1366:   double f;
                   1367:   double *xt; 
                   1368:  
                   1369:   xt=vector(1,ncom); 
                   1370:   for (j=1;j<=ncom;j++) xt[j]=pcom[j]+x*xicom[j]; 
                   1371:   f=(*nrfunc)(xt); 
                   1372:   free_vector(xt,1,ncom); 
                   1373:   return f; 
                   1374: } 
                   1375: 
                   1376: /*****************brent *************************/
                   1377: double brent(double ax, double bx, double cx, double (*f)(double), double tol,         double *xmin) 
1.187     brouard  1378: {
                   1379:   /* Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx is
                   1380:    * between ax and cx, and f(bx) is less than both f(ax) and f(cx) ), this routine isolates
                   1381:    * the minimum to a fractional precision of about tol using Brent’s method. The abscissa of
                   1382:    * the minimum is returned as xmin, and the minimum function value is returned as brent , the
                   1383:    * returned function value. 
                   1384:   */
1.126     brouard  1385:   int iter; 
                   1386:   double a,b,d,etemp;
1.159     brouard  1387:   double fu=0,fv,fw,fx;
1.164     brouard  1388:   double ftemp=0.;
1.126     brouard  1389:   double p,q,r,tol1,tol2,u,v,w,x,xm; 
                   1390:   double e=0.0; 
                   1391:  
                   1392:   a=(ax < cx ? ax : cx); 
                   1393:   b=(ax > cx ? ax : cx); 
                   1394:   x=w=v=bx; 
                   1395:   fw=fv=fx=(*f)(x); 
                   1396:   for (iter=1;iter<=ITMAX;iter++) { 
                   1397:     xm=0.5*(a+b); 
                   1398:     tol2=2.0*(tol1=tol*fabs(x)+ZEPS); 
                   1399:     /*         if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret)))*/
                   1400:     printf(".");fflush(stdout);
                   1401:     fprintf(ficlog,".");fflush(ficlog);
1.162     brouard  1402: #ifdef DEBUGBRENT
1.126     brouard  1403:     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);
                   1404:     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);
                   1405:     /*         if ((fabs(x-xm) <= (tol2-0.5*(b-a)))||(2.0*fabs(fu-ftemp) <= ftol*1.e-2*(fabs(fu)+fabs(ftemp)))) { */
                   1406: #endif
                   1407:     if (fabs(x-xm) <= (tol2-0.5*(b-a))){ 
                   1408:       *xmin=x; 
                   1409:       return fx; 
                   1410:     } 
                   1411:     ftemp=fu;
                   1412:     if (fabs(e) > tol1) { 
                   1413:       r=(x-w)*(fx-fv); 
                   1414:       q=(x-v)*(fx-fw); 
                   1415:       p=(x-v)*q-(x-w)*r; 
                   1416:       q=2.0*(q-r); 
                   1417:       if (q > 0.0) p = -p; 
                   1418:       q=fabs(q); 
                   1419:       etemp=e; 
                   1420:       e=d; 
                   1421:       if (fabs(p) >= fabs(0.5*q*etemp) || p <= q*(a-x) || p >= q*(b-x)) 
                   1422:        d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1423:       else { 
                   1424:        d=p/q; 
                   1425:        u=x+d; 
                   1426:        if (u-a < tol2 || b-u < tol2) 
                   1427:          d=SIGN(tol1,xm-x); 
                   1428:       } 
                   1429:     } else { 
                   1430:       d=CGOLD*(e=(x >= xm ? a-x : b-x)); 
                   1431:     } 
                   1432:     u=(fabs(d) >= tol1 ? x+d : x+SIGN(tol1,d)); 
                   1433:     fu=(*f)(u); 
                   1434:     if (fu <= fx) { 
                   1435:       if (u >= x) a=x; else b=x; 
                   1436:       SHFT(v,w,x,u) 
1.183     brouard  1437:       SHFT(fv,fw,fx,fu) 
                   1438:     } else { 
                   1439:       if (u < x) a=u; else b=u; 
                   1440:       if (fu <= fw || w == x) { 
                   1441:        v=w; 
                   1442:        w=u; 
                   1443:        fv=fw; 
                   1444:        fw=fu; 
                   1445:       } else if (fu <= fv || v == x || v == w) { 
                   1446:        v=u; 
                   1447:        fv=fu; 
                   1448:       } 
                   1449:     } 
1.126     brouard  1450:   } 
                   1451:   nrerror("Too many iterations in brent"); 
                   1452:   *xmin=x; 
                   1453:   return fx; 
                   1454: } 
                   1455: 
                   1456: /****************** mnbrak ***********************/
                   1457: 
                   1458: void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, double *fc, 
                   1459:            double (*func)(double)) 
1.183     brouard  1460: { /* Given a function func , and given distinct initial points ax and bx , this routine searches in
                   1461: the downhill direction (defined by the function as evaluated at the initial points) and returns
                   1462: new points ax , bx , cx that bracket a minimum of the function. Also returned are the function
                   1463: values at the three points, fa, fb , and fc such that fa > fb and fb < fc.
                   1464:    */
1.126     brouard  1465:   double ulim,u,r,q, dum;
                   1466:   double fu; 
1.187     brouard  1467: 
                   1468:   double scale=10.;
                   1469:   int iterscale=0;
                   1470: 
                   1471:   *fa=(*func)(*ax); /*  xta[j]=pcom[j]+(*ax)*xicom[j]; fa=f(xta[j])*/
                   1472:   *fb=(*func)(*bx); /*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) */
                   1473: 
                   1474: 
                   1475:   /* while(*fb != *fb){ /\* *ax should be ok, reducing distance to *ax *\/ */
                   1476:   /*   printf("Warning mnbrak *fb = %lf, *bx=%lf *ax=%lf *fa==%lf iter=%d\n",*fb, *bx, *ax, *fa, iterscale++); */
                   1477:   /*   *bx = *ax - (*ax - *bx)/scale; */
                   1478:   /*   *fb=(*func)(*bx);  /\*  xtb[j]=pcom[j]+(*bx)*xicom[j]; fb=f(xtb[j]) *\/ */
                   1479:   /* } */
                   1480: 
1.126     brouard  1481:   if (*fb > *fa) { 
                   1482:     SHFT(dum,*ax,*bx,dum) 
1.183     brouard  1483:     SHFT(dum,*fb,*fa,dum) 
                   1484:   } 
1.126     brouard  1485:   *cx=(*bx)+GOLD*(*bx-*ax); 
                   1486:   *fc=(*func)(*cx); 
1.183     brouard  1487: #ifdef DEBUG
                   1488:   printf("mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1489:   fprintf(ficlog,"mnbrak0 *fb=%.12e *fc=%.12e\n",*fb,*fc);
                   1490: #endif
                   1491:   while (*fb > *fc) { /* Declining a,b,c with fa> fb > fc */
1.126     brouard  1492:     r=(*bx-*ax)*(*fb-*fc); 
                   1493:     q=(*bx-*cx)*(*fb-*fa); 
                   1494:     u=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/ 
1.183     brouard  1495:       (2.0*SIGN(FMAX(fabs(q-r),TINY),q-r)); /* Minimum abscissa of a parabolic estimated from (a,fa), (b,fb) and (c,fc). */
                   1496:     ulim=(*bx)+GLIMIT*(*cx-*bx); /* Maximum abscissa where function should be evaluated */
                   1497:     if ((*bx-u)*(u-*cx) > 0.0) { /* if u_p is between b and c */
1.126     brouard  1498:       fu=(*func)(u); 
1.163     brouard  1499: #ifdef DEBUG
                   1500:       /* f(x)=A(x-u)**2+f(u) */
                   1501:       double A, fparabu; 
                   1502:       A= (*fb - *fa)/(*bx-*ax)/(*bx+*ax-2*u);
                   1503:       fparabu= *fa - A*(*ax-u)*(*ax-u);
                   1504:       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);
                   1505:       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  1506:       /* And thus,it can be that fu > *fc even if fparabu < *fc */
                   1507:       /* mnbrak (*ax=7.666299858533, *fa=299039.693133272231), (*bx=8.595447774979, *fb=298976.598289369489),
                   1508:         (*cx=10.098840694817, *fc=298946.631474258087),  (*u=9.852501168332, fu=298948.773013752128, fparabu=298945.434711494134) */
                   1509:       /* In that case, there is no bracket in the output! Routine is wrong with many consequences.*/
1.163     brouard  1510: #endif 
1.184     brouard  1511: #ifdef MNBRAKORIGINAL
1.183     brouard  1512: #else
1.191     brouard  1513: /*       if (fu > *fc) { */
                   1514: /* #ifdef DEBUG */
                   1515: /*       printf("mnbrak4  fu > fc \n"); */
                   1516: /*       fprintf(ficlog, "mnbrak4 fu > fc\n"); */
                   1517: /* #endif */
                   1518: /*     /\* 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 *\\/  *\/ */
                   1519: /*     /\* SHFT(*fa,*fc,fu,*fc) /\\* (b, u, c) is a bracket while test fb > fc will be fu > fc  will exit *\\/ *\/ */
                   1520: /*     dum=u; /\* Shifting c and u *\/ */
                   1521: /*     u = *cx; */
                   1522: /*     *cx = dum; */
                   1523: /*     dum = fu; */
                   1524: /*     fu = *fc; */
                   1525: /*     *fc =dum; */
                   1526: /*       } else { /\* end *\/ */
                   1527: /* #ifdef DEBUG */
                   1528: /*       printf("mnbrak3  fu < fc \n"); */
                   1529: /*       fprintf(ficlog, "mnbrak3 fu < fc\n"); */
                   1530: /* #endif */
                   1531: /*     dum=u; /\* Shifting c and u *\/ */
                   1532: /*     u = *cx; */
                   1533: /*     *cx = dum; */
                   1534: /*     dum = fu; */
                   1535: /*     fu = *fc; */
                   1536: /*     *fc =dum; */
                   1537: /*       } */
1.183     brouard  1538: #ifdef DEBUG
1.191     brouard  1539:       printf("mnbrak34  fu < or >= fc \n");
                   1540:       fprintf(ficlog, "mnbrak34 fu < fc\n");
1.183     brouard  1541: #endif
1.191     brouard  1542:       dum=u; /* Shifting c and u */
                   1543:       u = *cx;
                   1544:       *cx = dum;
                   1545:       dum = fu;
                   1546:       fu = *fc;
                   1547:       *fc =dum;
1.183     brouard  1548: #endif
1.162     brouard  1549:     } else if ((*cx-u)*(u-ulim) > 0.0) { /* u is after c but before ulim */
1.183     brouard  1550: #ifdef DEBUG
                   1551:       printf("mnbrak2  u after c but before ulim\n");
                   1552:       fprintf(ficlog, "mnbrak2 u after c but before ulim\n");
                   1553: #endif
1.126     brouard  1554:       fu=(*func)(u); 
                   1555:       if (fu < *fc) { 
1.183     brouard  1556: #ifdef DEBUG
                   1557:       printf("mnbrak2  u after c but before ulim AND fu < fc\n");
                   1558:       fprintf(ficlog, "mnbrak2 u after c but before ulim AND fu <fc \n");
                   1559: #endif
1.126     brouard  1560:        SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx)) 
1.183     brouard  1561:        SHFT(*fb,*fc,fu,(*func)(u)) 
                   1562:       } 
1.162     brouard  1563:     } else if ((u-ulim)*(ulim-*cx) >= 0.0) { /* u outside ulim (verifying that ulim is beyond c) */
1.183     brouard  1564: #ifdef DEBUG
                   1565:       printf("mnbrak2  u outside ulim (verifying that ulim is beyond c)\n");
                   1566:       fprintf(ficlog, "mnbrak2 u outside ulim (verifying that ulim is beyond c)\n");
                   1567: #endif
1.126     brouard  1568:       u=ulim; 
                   1569:       fu=(*func)(u); 
1.183     brouard  1570:     } else { /* u could be left to b (if r > q parabola has a maximum) */
                   1571: #ifdef DEBUG
                   1572:       printf("mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1573:       fprintf(ficlog, "mnbrak2  u could be left to b (if r > q parabola has a maximum)\n");
                   1574: #endif
1.126     brouard  1575:       u=(*cx)+GOLD*(*cx-*bx); 
                   1576:       fu=(*func)(u); 
1.183     brouard  1577:     } /* end tests */
1.126     brouard  1578:     SHFT(*ax,*bx,*cx,u) 
1.183     brouard  1579:     SHFT(*fa,*fb,*fc,fu) 
                   1580: #ifdef DEBUG
                   1581:       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);
                   1582:       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);
                   1583: #endif
                   1584:   } /* 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  1585: } 
                   1586: 
                   1587: /*************** linmin ************************/
1.162     brouard  1588: /* Given an n -dimensional point p[1..n] and an n -dimensional direction xi[1..n] , moves and
                   1589: resets p to where the function func(p) takes on a minimum along the direction xi from p ,
                   1590: and replaces xi by the actual vector displacement that p was moved. Also returns as fret
                   1591: the value of func at the returned location p . This is actually all accomplished by calling the
                   1592: routines mnbrak and brent .*/
1.126     brouard  1593: int ncom; 
                   1594: double *pcom,*xicom;
                   1595: double (*nrfunc)(double []); 
                   1596:  
                   1597: void linmin(double p[], double xi[], int n, double *fret,double (*func)(double [])) 
                   1598: { 
                   1599:   double brent(double ax, double bx, double cx, 
                   1600:               double (*f)(double), double tol, double *xmin); 
                   1601:   double f1dim(double x); 
                   1602:   void mnbrak(double *ax, double *bx, double *cx, double *fa, double *fb, 
                   1603:              double *fc, double (*func)(double)); 
                   1604:   int j; 
                   1605:   double xx,xmin,bx,ax; 
                   1606:   double fx,fb,fa;
1.187     brouard  1607: 
1.203   ! brouard  1608: #ifdef LINMINORIGINAL
        !          1609: #else
        !          1610:   double scale=10., axs, xxs; /* Scale added for infinity */
        !          1611: #endif
        !          1612:   
1.126     brouard  1613:   ncom=n; 
                   1614:   pcom=vector(1,n); 
                   1615:   xicom=vector(1,n); 
                   1616:   nrfunc=func; 
                   1617:   for (j=1;j<=n;j++) { 
                   1618:     pcom[j]=p[j]; 
1.202     brouard  1619:     xicom[j]=xi[j]; /* Former scale xi[j] of currrent direction i */
1.126     brouard  1620:   } 
1.187     brouard  1621: 
1.203   ! brouard  1622: #ifdef LINMINORIGINAL
        !          1623:   xx=1.;
        !          1624: #else
        !          1625:   axs=0.0;
        !          1626:   xxs=1.;
        !          1627:   do{
        !          1628:     xx= xxs;
        !          1629: #endif
1.187     brouard  1630:     ax=0.;
                   1631:     mnbrak(&ax,&xx,&bx,&fa,&fx,&fb,f1dim);  /* Outputs: xtx[j]=pcom[j]+(*xx)*xicom[j]; fx=f(xtx[j]) */
                   1632:     /* brackets with inputs ax=0 and xx=1, but points, pcom=p, and directions values, xicom=xi, are sent via f1dim(x) */
                   1633:     /* 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))   */
                   1634:     /* Outputs: fa=f(p(j)) and fx=f(p(j) + xxs * xi(j) ) and f(bx)= f(p(j)+ bx* xi(j)) */
                   1635:     /* Given input ax=axs and xx=xxs, xx might be too far from ax to get a finite f(xx) */
                   1636:     /* Searches on line, outputs (ax, xx, bx) such that fx < min(fa and fb) */
                   1637:     /* 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.203   ! brouard  1638: #ifdef LINMINORIGINAL
        !          1639: #else
        !          1640:     if (fx != fx){
        !          1641:        xxs=xxs/scale; /* Trying a smaller xx, closer to initial ax=0 */
        !          1642:        printf("|");
        !          1643:        fprintf(ficlog,"|");
        !          1644: #ifdef DEBUGLINMIN
        !          1645:        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);
        !          1646: #endif
        !          1647:     }
        !          1648:   }while(fx != fx);
        !          1649: #endif
        !          1650:   
1.191     brouard  1651: #ifdef DEBUGLINMIN
                   1652:   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  1653:   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  1654: #endif
1.187     brouard  1655:   *fret=brent(ax,xx,bx,f1dim,TOL,&xmin); /* Giving a bracketting triplet (ax, xx, bx), find a minimum, xmin, according to f1dim, *fret(xmin),*/
                   1656:   /* fa = f(p[j] + ax * xi[j]), fx = f(p[j] + xx * xi[j]), fb = f(p[j] + bx * xi[j]) */
                   1657:   /* fmin = f(p[j] + xmin * xi[j]) */
                   1658:   /* P+lambda n in that direction (lambdamin), with TOL between abscisses */
                   1659:   /* f1dim(xmin): for (j=1;j<=ncom;j++) xt[j]=pcom[j]+xmin*xicom[j]; */
1.126     brouard  1660: #ifdef DEBUG
                   1661:   printf("retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1662:   fprintf(ficlog,"retour brent fret=%.12e xmin=%.12e\n",*fret,xmin);
                   1663: #endif
1.191     brouard  1664: #ifdef DEBUGLINMIN
                   1665:   printf("linmin end ");
1.202     brouard  1666:   fprintf(ficlog,"linmin end ");
1.191     brouard  1667: #endif
1.126     brouard  1668:   for (j=1;j<=n;j++) { 
1.203   ! brouard  1669: #ifdef LINMINORIGINAL
        !          1670:     xi[j] *= xmin; 
        !          1671: #else
        !          1672: #ifdef DEBUGLINMIN
        !          1673:     if(xxs <1.0)
        !          1674:       printf(" before xi[%d]=%12.8f", j,xi[j]);
        !          1675: #endif
        !          1676:     xi[j] *= xmin*xxs; /* xi rescaled by xmin and number of loops: if xmin=-1.237 and xi=(1,0,...,0) xi=(-1.237,0,...,0) */
        !          1677: #ifdef DEBUGLINMIN
        !          1678:     if(xxs <1.0)
        !          1679:       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 );
        !          1680: #endif
        !          1681: #endif
1.187     brouard  1682:     p[j] += xi[j]; /* Parameters values are updated accordingly */
1.126     brouard  1683:   } 
1.191     brouard  1684: #ifdef DEBUGLINMIN
1.203   ! brouard  1685:   printf("\n");
1.191     brouard  1686:   printf("Comparing last *frec(xmin=%12.8f)=%12.8f from Brent and frec(0.)=%12.8f \n", xmin, *fret, (*func)(p));
1.202     brouard  1687:   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  1688:   for (j=1;j<=n;j++) { 
1.202     brouard  1689:     printf(" xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1690:     fprintf(ficlog," xi[%d]= %14.10f p[%d]= %12.7f",j,xi[j],j,p[j]);
                   1691:     if(j % ncovmodel == 0){
1.191     brouard  1692:       printf("\n");
1.202     brouard  1693:       fprintf(ficlog,"\n");
                   1694:     }
1.191     brouard  1695:   }
1.203   ! brouard  1696: #else
1.191     brouard  1697: #endif
1.126     brouard  1698:   free_vector(xicom,1,n); 
                   1699:   free_vector(pcom,1,n); 
                   1700: } 
                   1701: 
                   1702: 
                   1703: /*************** powell ************************/
1.162     brouard  1704: /*
                   1705: Minimization of a function func of n variables. Input consists of an initial starting point
                   1706: p[1..n] ; an initial matrix xi[1..n][1..n] , whose columns contain the initial set of di-
                   1707: rections (usually the n unit vectors); and ftol , the fractional tolerance in the function value
                   1708: such that failure to decrease by more than this amount on one iteration signals doneness. On
                   1709: output, p is set to the best point found, xi is the then-current direction set, fret is the returned
                   1710: function value at p , and iter is the number of iterations taken. The routine linmin is used.
                   1711:  */
1.126     brouard  1712: void powell(double p[], double **xi, int n, double ftol, int *iter, double *fret, 
                   1713:            double (*func)(double [])) 
                   1714: { 
                   1715:   void linmin(double p[], double xi[], int n, double *fret, 
                   1716:              double (*func)(double [])); 
                   1717:   int i,ibig,j; 
                   1718:   double del,t,*pt,*ptt,*xit;
1.181     brouard  1719:   double directest;
1.126     brouard  1720:   double fp,fptt;
                   1721:   double *xits;
                   1722:   int niterf, itmp;
                   1723: 
                   1724:   pt=vector(1,n); 
                   1725:   ptt=vector(1,n); 
                   1726:   xit=vector(1,n); 
                   1727:   xits=vector(1,n); 
                   1728:   *fret=(*func)(p); 
                   1729:   for (j=1;j<=n;j++) pt[j]=p[j]; 
1.202     brouard  1730:   rcurr_time = time(NULL);  
1.126     brouard  1731:   for (*iter=1;;++(*iter)) { 
1.187     brouard  1732:     fp=(*fret); /* From former iteration or initial value */
1.126     brouard  1733:     ibig=0; 
                   1734:     del=0.0; 
1.157     brouard  1735:     rlast_time=rcurr_time;
                   1736:     /* (void) gettimeofday(&curr_time,&tzp); */
                   1737:     rcurr_time = time(NULL);  
                   1738:     curr_time = *localtime(&rcurr_time);
                   1739:     printf("\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret, rcurr_time-rlast_time, rcurr_time-rstart_time);fflush(stdout);
                   1740:     fprintf(ficlog,"\nPowell iter=%d -2*LL=%.12f %ld sec. %ld sec.",*iter,*fret,rcurr_time-rlast_time, rcurr_time-rstart_time); fflush(ficlog);
                   1741: /*     fprintf(ficrespow,"%d %.12f %ld",*iter,*fret,curr_time.tm_sec-start_time.tm_sec); */
1.192     brouard  1742:     for (i=1;i<=n;i++) {
1.126     brouard  1743:       printf(" %d %.12f",i, p[i]);
                   1744:       fprintf(ficlog," %d %.12lf",i, p[i]);
                   1745:       fprintf(ficrespow," %.12lf", p[i]);
                   1746:     }
                   1747:     printf("\n");
                   1748:     fprintf(ficlog,"\n");
                   1749:     fprintf(ficrespow,"\n");fflush(ficrespow);
                   1750:     if(*iter <=3){
1.157     brouard  1751:       tml = *localtime(&rcurr_time);
                   1752:       strcpy(strcurr,asctime(&tml));
                   1753:       rforecast_time=rcurr_time; 
1.126     brouard  1754:       itmp = strlen(strcurr);
                   1755:       if(strcurr[itmp-1]=='\n')  /* Windows outputs with a new line */
                   1756:        strcurr[itmp-1]='\0';
1.162     brouard  1757:       printf("\nConsidering the time needed for the last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.157     brouard  1758:       fprintf(ficlog,"\nConsidering the time needed for this last iteration #%d: %ld seconds,\n",*iter,rcurr_time-rlast_time);
1.126     brouard  1759:       for(niterf=10;niterf<=30;niterf+=10){
1.157     brouard  1760:        rforecast_time=rcurr_time+(niterf-*iter)*(rcurr_time-rlast_time);
                   1761:        forecast_time = *localtime(&rforecast_time);
                   1762:        strcpy(strfor,asctime(&forecast_time));
1.126     brouard  1763:        itmp = strlen(strfor);
                   1764:        if(strfor[itmp-1]=='\n')
                   1765:        strfor[itmp-1]='\0';
1.157     brouard  1766:        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);
                   1767:        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  1768:       }
                   1769:     }
1.187     brouard  1770:     for (i=1;i<=n;i++) { /* For each direction i */
                   1771:       for (j=1;j<=n;j++) xit[j]=xi[j][i]; /* Directions stored from previous iteration with previous scales */
1.126     brouard  1772:       fptt=(*fret); 
                   1773: #ifdef DEBUG
1.203   ! brouard  1774:       printf("fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
        !          1775:       fprintf(ficlog, "fret=%lf, %lf, %lf \n", *fret, *fret, *fret);
1.126     brouard  1776: #endif
1.203   ! brouard  1777:       printf("%d",i);fflush(stdout); /* print direction (parameter) i */
1.126     brouard  1778:       fprintf(ficlog,"%d",i);fflush(ficlog);
1.188     brouard  1779:       linmin(p,xit,n,fret,func); /* Point p[n]. xit[n] has been loaded for direction i as input.*/
                   1780:                                    /* Outputs are fret(new point p) p is updated and xit rescaled */
                   1781:       if (fabs(fptt-(*fret)) > del) { /* We are keeping the max gain on each of the n directions */
                   1782:        /* because that direction will be replaced unless the gain del is small */
                   1783:        /* in comparison with the 'probable' gain, mu^2, with the last average direction. */
                   1784:        /* Unless the n directions are conjugate some gain in the determinant may be obtained */
                   1785:        /* with the new direction. */
1.126     brouard  1786:        del=fabs(fptt-(*fret)); 
                   1787:        ibig=i; 
                   1788:       } 
                   1789: #ifdef DEBUG
                   1790:       printf("%d %.12e",i,(*fret));
                   1791:       fprintf(ficlog,"%d %.12e",i,(*fret));
                   1792:       for (j=1;j<=n;j++) {
                   1793:        xits[j]=FMAX(fabs(p[j]-pt[j]),1.e-5);
                   1794:        printf(" x(%d)=%.12e",j,xit[j]);
                   1795:        fprintf(ficlog," x(%d)=%.12e",j,xit[j]);
                   1796:       }
                   1797:       for(j=1;j<=n;j++) {
1.162     brouard  1798:        printf(" p(%d)=%.12e",j,p[j]);
                   1799:        fprintf(ficlog," p(%d)=%.12e",j,p[j]);
1.126     brouard  1800:       }
                   1801:       printf("\n");
                   1802:       fprintf(ficlog,"\n");
                   1803: #endif
1.187     brouard  1804:     } /* end loop on each direction i */
                   1805:     /* Convergence test will use last linmin estimation (fret) and compare former iteration (fp) */ 
1.188     brouard  1806:     /* But p and xit have been updated at the end of linmin, *fret corresponds to new p, xit  */
1.187     brouard  1807:     /* New value of last point Pn is not computed, P(n-1) */
1.182     brouard  1808:     if (2.0*fabs(fp-(*fret)) <= ftol*(fabs(fp)+fabs(*fret))) { /* Did we reach enough precision? */
1.188     brouard  1809:       /* We could compare with a chi^2. chisquare(0.95,ddl=1)=3.84 */
                   1810:       /* By adding age*age in a model, the new -2LL should be lower and the difference follows a */
                   1811:       /* a chisquare statistics with 1 degree. To be significant at the 95% level, it should have */
                   1812:       /* decreased of more than 3.84  */
                   1813:       /* By adding age*age and V1*age the gain (-2LL) should be more than 5.99 (ddl=2) */
                   1814:       /* By using V1+V2+V3, the gain should be  7.82, compared with basic 1+age. */
                   1815:       /* By adding 10 parameters more the gain should be 18.31 */
                   1816: 
                   1817:       /* Starting the program with initial values given by a former maximization will simply change */
                   1818:       /* the scales of the directions and the directions, because the are reset to canonical directions */
                   1819:       /* Thus the first calls to linmin will give new points and better maximizations until fp-(*fret) is */
                   1820:       /* under the tolerance value. If the tolerance is very small 1.e-9, it could last long.  */
1.126     brouard  1821: #ifdef DEBUG
                   1822:       int k[2],l;
                   1823:       k[0]=1;
                   1824:       k[1]=-1;
                   1825:       printf("Max: %.12e",(*func)(p));
                   1826:       fprintf(ficlog,"Max: %.12e",(*func)(p));
                   1827:       for (j=1;j<=n;j++) {
                   1828:        printf(" %.12e",p[j]);
                   1829:        fprintf(ficlog," %.12e",p[j]);
                   1830:       }
                   1831:       printf("\n");
                   1832:       fprintf(ficlog,"\n");
                   1833:       for(l=0;l<=1;l++) {
                   1834:        for (j=1;j<=n;j++) {
                   1835:          ptt[j]=p[j]+(p[j]-pt[j])*k[l];
                   1836:          printf("l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1837:          fprintf(ficlog,"l=%d j=%d ptt=%.12e, xits=%.12e, p=%.12e, xit=%.12e", l,j,ptt[j],xits[j],p[j],xit[j]);
                   1838:        }
                   1839:        printf("func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1840:        fprintf(ficlog,"func(ptt)=%.12e, deriv=%.12e\n",(*func)(ptt),(ptt[j]-p[j])/((*func)(ptt)-(*func)(p)));
                   1841:       }
                   1842: #endif
                   1843: 
                   1844: 
                   1845:       free_vector(xit,1,n); 
                   1846:       free_vector(xits,1,n); 
                   1847:       free_vector(ptt,1,n); 
                   1848:       free_vector(pt,1,n); 
                   1849:       return; 
1.192     brouard  1850:     } /* enough precision */ 
1.126     brouard  1851:     if (*iter == ITMAX) nrerror("powell exceeding maximum iterations."); 
1.181     brouard  1852:     for (j=1;j<=n;j++) { /* Computes the extrapolated point P_0 + 2 (P_n-P_0) */
1.126     brouard  1853:       ptt[j]=2.0*p[j]-pt[j]; 
                   1854:       xit[j]=p[j]-pt[j]; 
                   1855:       pt[j]=p[j]; 
                   1856:     } 
1.181     brouard  1857:     fptt=(*func)(ptt); /* f_3 */
1.192     brouard  1858: #ifdef POWELLF1F3
                   1859: #else
1.161     brouard  1860:     if (fptt < fp) { /* If extrapolated point is better, decide if we keep that new direction or not */
1.192     brouard  1861: #endif
1.162     brouard  1862:       /* (x1 f1=fp), (x2 f2=*fret), (x3 f3=fptt), (xm fm) */
1.161     brouard  1863:       /* From x1 (P0) distance of x2 is at h and x3 is 2h */
1.162     brouard  1864:       /* Let f"(x2) be the 2nd derivative equal everywhere.  */
                   1865:       /* Then the parabolic through (x1,f1), (x2,f2) and (x3,f3) */
                   1866:       /* will reach at f3 = fm + h^2/2 f"m  ; f" = (f1 -2f2 +f3 ) / h**2 */
1.181     brouard  1867:       /* Conditional for using this new direction is that mu^2 = (f1-2f2+f3)^2 /2 < del */
1.161     brouard  1868:       /* t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)-del*SQR(fp-fptt); */
1.183     brouard  1869: #ifdef NRCORIGINAL
                   1870:       t=2.0*(fp-2.0*(*fret)+fptt)*SQR(fp-(*fret)-del)- del*SQR(fp-fptt); /* Original Numerical Recipes in C*/
                   1871: #else
                   1872:       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  1873:       t= t- del*SQR(fp-fptt);
1.183     brouard  1874: #endif
1.202     brouard  1875:       directest = fp-2.0*(*fret)+fptt - 2.0 * del; /* If delta was big enough we change it for a new direction */
1.161     brouard  1876: #ifdef DEBUG
1.181     brouard  1877:       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);
                   1878:       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  1879:       printf("t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1880:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1881:       fprintf(ficlog,"t3= %.12lf, t4= %.12lf, t3*= %.12lf, t4*= %.12lf\n",SQR(fp-(*fret)-del),SQR(fp-fptt),
                   1882:             (fp-(*fret)-del)*(fp-(*fret)-del),(fp-fptt)*(fp-fptt));
                   1883:       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);
                   1884:       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);
                   1885: #endif
1.183     brouard  1886: #ifdef POWELLORIGINAL
                   1887:       if (t < 0.0) { /* Then we use it for new direction */
                   1888: #else
1.182     brouard  1889:       if (directest*t < 0.0) { /* Contradiction between both tests */
1.202     brouard  1890:        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  1891:         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  1892:         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  1893:         fprintf(ficlog,"f1-2f2+f3= %.12lf, f1-f2-del= %.12lf, f1-f3= %.12lf\n",fp-2.0*(*fret)+fptt, fp -(*fret) -del, fp-fptt);
                   1894:       } 
1.181     brouard  1895:       if (directest < 0.0) { /* Then we use it for new direction */
                   1896: #endif
1.191     brouard  1897: #ifdef DEBUGLINMIN
                   1898:        printf("Before linmin in direction P%d-P0\n",n);
                   1899:        for (j=1;j<=n;j++) { 
1.202     brouard  1900:          printf(" Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1901:          fprintf(ficlog," Before xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1902:          if(j % ncovmodel == 0){
1.191     brouard  1903:            printf("\n");
1.202     brouard  1904:            fprintf(ficlog,"\n");
                   1905:          }
1.191     brouard  1906:        }
                   1907: #endif
1.187     brouard  1908:        linmin(p,xit,n,fret,func); /* computes minimum on the extrapolated direction: changes p and rescales xit.*/
1.191     brouard  1909: #ifdef DEBUGLINMIN
                   1910:        for (j=1;j<=n;j++) { 
                   1911:          printf("After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
1.202     brouard  1912:          fprintf(ficlog,"After xit[%d]= %12.7f p[%d]= %12.7f",j,xit[j],j,p[j]);
                   1913:          if(j % ncovmodel == 0){
1.191     brouard  1914:            printf("\n");
1.202     brouard  1915:            fprintf(ficlog,"\n");
                   1916:          }
1.191     brouard  1917:        }
                   1918: #endif
1.126     brouard  1919:        for (j=1;j<=n;j++) { 
1.181     brouard  1920:          xi[j][ibig]=xi[j][n]; /* Replace direction with biggest decrease by last direction n */
                   1921:          xi[j][n]=xit[j];      /* and this nth direction by the by the average p_0 p_n */
1.126     brouard  1922:        }
1.181     brouard  1923:        printf("Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
                   1924:        fprintf(ficlog,"Gaining to use new average direction of P0 P%d instead of biggest increase direction %d :\n",n,ibig);
1.161     brouard  1925: 
1.126     brouard  1926: #ifdef DEBUG
1.164     brouard  1927:        printf("Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
                   1928:        fprintf(ficlog,"Direction changed  last moved %d in place of ibig=%d, new last is the average:\n",n,ibig);
1.126     brouard  1929:        for(j=1;j<=n;j++){
                   1930:          printf(" %.12e",xit[j]);
                   1931:          fprintf(ficlog," %.12e",xit[j]);
                   1932:        }
                   1933:        printf("\n");
                   1934:        fprintf(ficlog,"\n");
                   1935: #endif
1.192     brouard  1936:       } /* end of t or directest negative */
                   1937: #ifdef POWELLF1F3
                   1938: #else
1.162     brouard  1939:     } /* end if (fptt < fp)  */
1.192     brouard  1940: #endif
                   1941:   } /* loop iteration */ 
1.126     brouard  1942: } 
                   1943: 
                   1944: /**** Prevalence limit (stable or period prevalence)  ****************/
                   1945: 
1.203   ! brouard  1946: double **prevalim(double **prlim, int nlstate, double x[], double age, double **oldm, double **savm, double ftolpl, int *ncvyear, int ij)
1.126     brouard  1947: {
                   1948:   /* Computes the prevalence limit in each live state at age x by left multiplying the unit
1.203   ! brouard  1949:      matrix by transitions matrix until convergence is reached with precision ftolpl */
1.169     brouard  1950:   
1.126     brouard  1951:   int i, ii,j,k;
                   1952:   double min, max, maxmin, maxmax,sumnew=0.;
1.145     brouard  1953:   /* double **matprod2(); */ /* test */
1.131     brouard  1954:   double **out, cov[NCOVMAX+1], **pmij();
1.126     brouard  1955:   double **newm;
1.202     brouard  1956:   double agefin, delaymax=100 ; /* Max number of years to converge */
1.203   ! brouard  1957:   int ncvloop=0;
1.169     brouard  1958:   
1.126     brouard  1959:   for (ii=1;ii<=nlstate+ndeath;ii++)
                   1960:     for (j=1;j<=nlstate+ndeath;j++){
                   1961:       oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   1962:     }
1.169     brouard  1963:   
                   1964:   cov[1]=1.;
                   1965:   
                   1966:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
1.202     brouard  1967:   /* Start at agefin= age, computes the matrix of passage and loops decreasing agefin until convergence is reached */
1.126     brouard  1968:   for(agefin=age-stepm/YEARM; agefin>=age-delaymax; agefin=agefin-stepm/YEARM){
1.202     brouard  1969:     ncvloop++;
1.126     brouard  1970:     newm=savm;
                   1971:     /* Covariates have to be included here again */
1.138     brouard  1972:     cov[2]=agefin;
1.187     brouard  1973:     if(nagesqr==1)
                   1974:       cov[3]= agefin*agefin;;
1.138     brouard  1975:     for (k=1; k<=cptcovn;k++) {
1.200     brouard  1976:       /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
                   1977:       cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
1.198     brouard  1978:       /* 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  1979:     }
1.186     brouard  1980:     /*wrong? for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  1981:     /* for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]*cov[2]; */
                   1982:     for (k=1; k<=cptcovage;k++) cov[2+nagesqr+Tage[k]]=nbcode[Tvar[k]][codtabm(ij,k)]*cov[2];
1.186     brouard  1983:     for (k=1; k<=cptcovprod;k++) /* Useless */
1.200     brouard  1984:       /* cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,Tvard[k][1])] * nbcode[Tvard[k][2]][codtabm(ij,Tvard[k][2])]; */
                   1985:       cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)] * nbcode[Tvard[k][2]][codtabm(ij,k)];
1.138     brouard  1986:     
                   1987:     /*printf("ij=%d cptcovprod=%d tvar=%d ", ij, cptcovprod, Tvar[1]);*/
                   1988:     /*printf("ij=%d cov[3]=%lf cov[4]=%lf \n",ij, cov[3],cov[4]);*/
                   1989:     /*printf("ij=%d cov[3]=%lf \n",ij, cov[3]);*/
1.145     brouard  1990:     /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
                   1991:     /* out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /\* Bug Valgrind *\/ */
1.142     brouard  1992:     out=matprod2(newm, pmij(pmmij,cov,ncovmodel,x,nlstate),1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, oldm); /* Bug Valgrind */
1.138     brouard  1993:     
1.126     brouard  1994:     savm=oldm;
                   1995:     oldm=newm;
                   1996:     maxmax=0.;
                   1997:     for(j=1;j<=nlstate;j++){
                   1998:       min=1.;
                   1999:       max=0.;
                   2000:       for(i=1; i<=nlstate; i++) {
                   2001:        sumnew=0;
                   2002:        for(k=1; k<=ndeath; k++) sumnew+=newm[i][nlstate+k];
                   2003:        prlim[i][j]= newm[i][j]/(1-sumnew);
                   2004:        max=FMAX(max,prlim[i][j]);
                   2005:        min=FMIN(min,prlim[i][j]);
1.202     brouard  2006:         /* 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  2007:       }
1.203   ! brouard  2008:       maxmin=(max-min)/(max+min)*2;
1.126     brouard  2009:       maxmax=FMAX(maxmax,maxmin);
1.169     brouard  2010:     } /* j loop */
1.203   ! brouard  2011:     *ncvyear= (int)age- (int)agefin;
        !          2012:     /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126     brouard  2013:     if(maxmax < ftolpl){
1.203   ! brouard  2014:       /* printf("maxmax=%lf maxmin=%lf ncvloop=%ld, age=%d, agefin=%d ncvyear=%d \n", maxmax, maxmin, ncvloop, (int)age, (int)agefin, *ncvyear); */
1.126     brouard  2015:       return prlim;
                   2016:     }
1.169     brouard  2017:   } /* age loop */
1.203   ! brouard  2018:   printf("Warning: the stable prevalence at age %d did not converge with the required precision %g > ftolpl=%g. \n\
        !          2019: Earliest age to start was %d-%d=%d, ncvloop=%d, ncvyear=%d\n", (int)age, maxmax, ftolpl, (int)age, (int)delaymax, (int)agefin, ncvloop, *ncvyear);
        !          2020: /* 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  2021:   return prlim; /* should not reach here */
1.126     brouard  2022: }
                   2023: 
                   2024: /*************** transition probabilities ***************/ 
                   2025: 
                   2026: double **pmij(double **ps, double *cov, int ncovmodel, double *x, int nlstate )
                   2027: {
1.138     brouard  2028:   /* According to parameters values stored in x and the covariate's values stored in cov,
                   2029:      computes the probability to be observed in state j being in state i by appying the
                   2030:      model to the ncovmodel covariates (including constant and age).
                   2031:      lnpijopii=ln(pij/pii)= aij+bij*age+cij*v1+dij*v2+... = sum_nc=1^ncovmodel xij(nc)*cov[nc]
                   2032:      and, according on how parameters are entered, the position of the coefficient xij(nc) of the
                   2033:      ncth covariate in the global vector x is given by the formula:
                   2034:      j<i nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel
                   2035:      j>=i nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel
                   2036:      Computes ln(pij/pii) (lnpijopii), deduces pij/pii by exponentiation,
                   2037:      sums on j different of i to get 1-pii/pii, deduces pii, and then all pij.
                   2038:      Outputs ps[i][j] the probability to be observed in j being in j according to
                   2039:      the values of the covariates cov[nc] and corresponding parameter values x[nc+shiftij]
                   2040:   */
                   2041:   double s1, lnpijopii;
1.126     brouard  2042:   /*double t34;*/
1.164     brouard  2043:   int i,j, nc, ii, jj;
1.126     brouard  2044: 
                   2045:     for(i=1; i<= nlstate; i++){
                   2046:       for(j=1; j<i;j++){
1.138     brouard  2047:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2048:          /*lnpijopii += param[i][j][nc]*cov[nc];*/
                   2049:          lnpijopii += x[nc+((i-1)*(nlstate+ndeath-1)+j-1)*ncovmodel]*cov[nc];
                   2050: /*      printf("Int j<i s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2051:        }
1.138     brouard  2052:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
                   2053: /*     printf("s1=%.17e, lnpijopii=%.17e\n",s1,lnpijopii); */
1.126     brouard  2054:       }
                   2055:       for(j=i+1; j<=nlstate+ndeath;j++){
1.138     brouard  2056:        for (nc=1, lnpijopii=0.;nc <=ncovmodel; nc++){
                   2057:          /*lnpijopii += x[(i-1)*nlstate*ncovmodel+(j-2)*ncovmodel+nc+(i-1)*(ndeath-1)*ncovmodel]*cov[nc];*/
                   2058:          lnpijopii += x[nc + ((i-1)*(nlstate+ndeath-1)+(j-2))*ncovmodel]*cov[nc];
                   2059: /*       printf("Int j>i s1=%.17e, lnpijopii=%.17e %lx %lx\n",s1,lnpijopii,s1,lnpijopii); */
1.126     brouard  2060:        }
1.138     brouard  2061:        ps[i][j]=lnpijopii; /* In fact ln(pij/pii) */
1.126     brouard  2062:       }
                   2063:     }
                   2064:     
                   2065:     for(i=1; i<= nlstate; i++){
                   2066:       s1=0;
1.131     brouard  2067:       for(j=1; j<i; j++){
1.138     brouard  2068:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2069:        /*printf("debug1 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2070:       }
                   2071:       for(j=i+1; j<=nlstate+ndeath; j++){
1.138     brouard  2072:        s1+=exp(ps[i][j]); /* In fact sums pij/pii */
1.131     brouard  2073:        /*printf("debug2 %d %d ps=%lf exp(ps)=%lf s1+=%lf\n",i,j,ps[i][j],exp(ps[i][j]),s1); */
                   2074:       }
1.138     brouard  2075:       /* s1= sum_{j<>i} pij/pii=(1-pii)/pii and thus pii is known from s1 */
1.126     brouard  2076:       ps[i][i]=1./(s1+1.);
1.138     brouard  2077:       /* Computing other pijs */
1.126     brouard  2078:       for(j=1; j<i; j++)
                   2079:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2080:       for(j=i+1; j<=nlstate+ndeath; j++)
                   2081:        ps[i][j]= exp(ps[i][j])*ps[i][i];
                   2082:       /* ps[i][nlstate+1]=1.-s1- ps[i][i];*/ /* Sum should be 1 */
                   2083:     } /* end i */
                   2084:     
                   2085:     for(ii=nlstate+1; ii<= nlstate+ndeath; ii++){
                   2086:       for(jj=1; jj<= nlstate+ndeath; jj++){
                   2087:        ps[ii][jj]=0;
                   2088:        ps[ii][ii]=1;
                   2089:       }
                   2090:     }
                   2091:     
1.145     brouard  2092:     
                   2093:     /* for(ii=1; ii<= nlstate+ndeath; ii++){ */
                   2094:     /*   for(jj=1; jj<= nlstate+ndeath; jj++){ */
                   2095:     /*         printf(" pmij  ps[%d][%d]=%lf ",ii,jj,ps[ii][jj]); */
                   2096:     /*   } */
                   2097:     /*   printf("\n "); */
                   2098:     /* } */
                   2099:     /* printf("\n ");printf("%lf ",cov[2]);*/
                   2100:     /*
1.126     brouard  2101:       for(i=1; i<= npar; i++) printf("%f ",x[i]);
                   2102:       goto end;*/
                   2103:     return ps;
                   2104: }
                   2105: 
                   2106: /**************** Product of 2 matrices ******************/
                   2107: 
1.145     brouard  2108: double **matprod2(double **out, double **in,int nrl, int nrh, int ncl, int nch, int ncolol, int ncoloh, double **b)
1.126     brouard  2109: {
                   2110:   /* Computes the matrix product of in(1,nrh-nrl+1)(1,nch-ncl+1) times
                   2111:      b(1,nch-ncl+1)(1,ncoloh-ncolol+1) into out(...) */
                   2112:   /* in, b, out are matrice of pointers which should have been initialized 
                   2113:      before: only the contents of out is modified. The function returns
                   2114:      a pointer to pointers identical to out */
1.145     brouard  2115:   int i, j, k;
1.126     brouard  2116:   for(i=nrl; i<= nrh; i++)
1.145     brouard  2117:     for(k=ncolol; k<=ncoloh; k++){
                   2118:       out[i][k]=0.;
                   2119:       for(j=ncl; j<=nch; j++)
                   2120:        out[i][k] +=in[i][j]*b[j][k];
                   2121:     }
1.126     brouard  2122:   return out;
                   2123: }
                   2124: 
                   2125: 
                   2126: /************* Higher Matrix Product ***************/
                   2127: 
                   2128: double ***hpxij(double ***po, int nhstepm, double age, int hstepm, double *x, int nlstate, int stepm, double **oldm, double **savm, int ij )
                   2129: {
                   2130:   /* Computes the transition matrix starting at age 'age' over 
                   2131:      'nhstepm*hstepm*stepm' months (i.e. until
                   2132:      age (in years)  age+nhstepm*hstepm*stepm/12) by multiplying 
                   2133:      nhstepm*hstepm matrices. 
                   2134:      Output is stored in matrix po[i][j][h] for h every 'hstepm' step 
                   2135:      (typically every 2 years instead of every month which is too big 
                   2136:      for the memory).
                   2137:      Model is determined by parameters x and covariates have to be 
                   2138:      included manually here. 
                   2139: 
                   2140:      */
                   2141: 
                   2142:   int i, j, d, h, k;
1.131     brouard  2143:   double **out, cov[NCOVMAX+1];
1.126     brouard  2144:   double **newm;
1.187     brouard  2145:   double agexact;
1.126     brouard  2146: 
                   2147:   /* Hstepm could be zero and should return the unit matrix */
                   2148:   for (i=1;i<=nlstate+ndeath;i++)
                   2149:     for (j=1;j<=nlstate+ndeath;j++){
                   2150:       oldm[i][j]=(i==j ? 1.0 : 0.0);
                   2151:       po[i][j][0]=(i==j ? 1.0 : 0.0);
                   2152:     }
                   2153:   /* Even if hstepm = 1, at least one multiplication by the unit matrix */
                   2154:   for(h=1; h <=nhstepm; h++){
                   2155:     for(d=1; d <=hstepm; d++){
                   2156:       newm=savm;
                   2157:       /* Covariates have to be included here again */
                   2158:       cov[1]=1.;
1.187     brouard  2159:       agexact=age+((h-1)*hstepm + (d-1))*stepm/YEARM;
                   2160:       cov[2]=agexact;
                   2161:       if(nagesqr==1)
                   2162:        cov[3]= agexact*agexact;
1.131     brouard  2163:       for (k=1; k<=cptcovn;k++) 
1.200     brouard  2164:        cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,k)];
                   2165:        /* cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.186     brouard  2166:       for (k=1; k<=cptcovage;k++) /* Should start at cptcovn+1 */
                   2167:        /* cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  2168:        cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
                   2169:        /* cov[2+nagesqr+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k]])]*cov[2]; */
1.145     brouard  2170:       for (k=1; k<=cptcovprod;k++) /* Useless because included in cptcovn */
1.200     brouard  2171:        cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
                   2172:        /* 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  2173: 
                   2174: 
                   2175:       /*printf("hxi cptcov=%d cptcode=%d\n",cptcov,cptcode);*/
                   2176:       /*printf("h=%d d=%d age=%f cov=%f\n",h,d,age,cov[2]);*/
                   2177:       out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,1,nlstate+ndeath, 
                   2178:                   pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2179:       savm=oldm;
                   2180:       oldm=newm;
                   2181:     }
                   2182:     for(i=1; i<=nlstate+ndeath; i++)
                   2183:       for(j=1;j<=nlstate+ndeath;j++) {
                   2184:        po[i][j][h]=newm[i][j];
1.128     brouard  2185:        /*if(h==nhstepm) printf("po[%d][%d][%d]=%f ",i,j,h,po[i][j][h]);*/
1.126     brouard  2186:       }
1.128     brouard  2187:     /*printf("h=%d ",h);*/
1.126     brouard  2188:   } /* end h */
1.128     brouard  2189: /*     printf("\n H=%d \n",h); */
1.126     brouard  2190:   return po;
                   2191: }
                   2192: 
1.162     brouard  2193: #ifdef NLOPT
                   2194:   double  myfunc(unsigned n, const double *p1, double *grad, void *pd){
                   2195:   double fret;
                   2196:   double *xt;
                   2197:   int j;
                   2198:   myfunc_data *d2 = (myfunc_data *) pd;
                   2199: /* xt = (p1-1); */
                   2200:   xt=vector(1,n); 
                   2201:   for (j=1;j<=n;j++)   xt[j]=p1[j-1]; /* xt[1]=p1[0] */
                   2202: 
                   2203:   fret=(d2->function)(xt); /*  p xt[1]@8 is fine */
                   2204:   /* fret=(*func)(xt); /\*  p xt[1]@8 is fine *\/ */
                   2205:   printf("Function = %.12lf ",fret);
                   2206:   for (j=1;j<=n;j++) printf(" %d %.8lf", j, xt[j]); 
                   2207:   printf("\n");
                   2208:  free_vector(xt,1,n);
                   2209:   return fret;
                   2210: }
                   2211: #endif
1.126     brouard  2212: 
                   2213: /*************** log-likelihood *************/
                   2214: double func( double *x)
                   2215: {
                   2216:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2217:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2218:   double **out;
                   2219:   double sw; /* Sum of weights */
                   2220:   double lli; /* Individual log likelihood */
                   2221:   int s1, s2;
                   2222:   double bbh, survp;
                   2223:   long ipmx;
1.187     brouard  2224:   double agexact;
1.126     brouard  2225:   /*extern weight */
                   2226:   /* We are differentiating ll according to initial status */
                   2227:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2228:   /*for(i=1;i<imx;i++) 
                   2229:     printf(" %d\n",s[4][i]);
                   2230:   */
1.162     brouard  2231: 
                   2232:   ++countcallfunc;
                   2233: 
1.126     brouard  2234:   cov[1]=1.;
                   2235: 
                   2236:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2237: 
                   2238:   if(mle==1){
                   2239:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.138     brouard  2240:       /* Computes the values of the ncovmodel covariates of the model
                   2241:         depending if the covariates are fixed or variying (age dependent) and stores them in cov[]
                   2242:         Then computes with function pmij which return a matrix p[i][j] giving the elementary probability
                   2243:         to be observed in j being in i according to the model.
                   2244:        */
1.145     brouard  2245:       for (k=1; k<=cptcovn;k++){ /* Simple and product covariates without age* products */
1.187     brouard  2246:          cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.145     brouard  2247:       }
1.137     brouard  2248:       /* In model V2+V1*V4+age*V3+V3*V2 Tvar[1] is V2, Tvar[2=V1*V4] 
1.138     brouard  2249:         is 6, Tvar[3=age*V3] should not be computed because of age Tvar[4=V3*V2] 
1.137     brouard  2250:         has been calculated etc */
1.126     brouard  2251:       for(mi=1; mi<= wav[i]-1; mi++){
                   2252:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2253:          for (j=1;j<=nlstate+ndeath;j++){
                   2254:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2255:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2256:          }
                   2257:        for(d=0; d<dh[mi][i]; d++){
                   2258:          newm=savm;
1.187     brouard  2259:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2260:          cov[2]=agexact;
                   2261:          if(nagesqr==1)
                   2262:            cov[3]= agexact*agexact;
1.126     brouard  2263:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2264:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact; /* Tage[kk] gives the data-covariate associated with age */
1.126     brouard  2265:          }
                   2266:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2267:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2268:          savm=oldm;
                   2269:          oldm=newm;
                   2270:        } /* end mult */
                   2271:       
                   2272:        /*lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]);*/ /* Original formula */
                   2273:        /* But now since version 0.9 we anticipate for bias at large stepm.
                   2274:         * If stepm is larger than one month (smallest stepm) and if the exact delay 
                   2275:         * (in months) between two waves is not a multiple of stepm, we rounded to 
                   2276:         * the nearest (and in case of equal distance, to the lowest) interval but now
                   2277:         * we keep into memory the bias bh[mi][i] and also the previous matrix product
                   2278:         * (i.e to dh[mi][i]-1) saved in 'savm'. Then we inter(extra)polate the
                   2279:         * probability in order to take into account the bias as a fraction of the way
                   2280:         * from savm to out if bh is negative or even beyond if bh is positive. bh varies
                   2281:         * -stepm/2 to stepm/2 .
                   2282:         * For stepm=1 the results are the same as for previous versions of Imach.
                   2283:         * For stepm > 1 the results are less biased than in previous versions. 
                   2284:         */
                   2285:        s1=s[mw[mi][i]][i];
                   2286:        s2=s[mw[mi+1][i]][i];
                   2287:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2288:        /* bias bh is positive if real duration
                   2289:         * is higher than the multiple of stepm and negative otherwise.
                   2290:         */
                   2291:        /* lli= (savm[s1][s2]>1.e-8 ?(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]):log((1.+bbh)*out[s1][s2]));*/
                   2292:        if( s2 > nlstate){ 
                   2293:          /* i.e. if s2 is a death state and if the date of death is known 
                   2294:             then the contribution to the likelihood is the probability to 
                   2295:             die between last step unit time and current  step unit time, 
                   2296:             which is also equal to probability to die before dh 
                   2297:             minus probability to die before dh-stepm . 
                   2298:             In version up to 0.92 likelihood was computed
                   2299:        as if date of death was unknown. Death was treated as any other
                   2300:        health state: the date of the interview describes the actual state
                   2301:        and not the date of a change in health state. The former idea was
                   2302:        to consider that at each interview the state was recorded
                   2303:        (healthy, disable or death) and IMaCh was corrected; but when we
                   2304:        introduced the exact date of death then we should have modified
                   2305:        the contribution of an exact death to the likelihood. This new
                   2306:        contribution is smaller and very dependent of the step unit
                   2307:        stepm. It is no more the probability to die between last interview
                   2308:        and month of death but the probability to survive from last
                   2309:        interview up to one month before death multiplied by the
                   2310:        probability to die within a month. Thanks to Chris
                   2311:        Jackson for correcting this bug.  Former versions increased
                   2312:        mortality artificially. The bad side is that we add another loop
                   2313:        which slows down the processing. The difference can be up to 10%
                   2314:        lower mortality.
                   2315:          */
1.183     brouard  2316:        /* If, at the beginning of the maximization mostly, the
                   2317:           cumulative probability or probability to be dead is
                   2318:           constant (ie = 1) over time d, the difference is equal to
                   2319:           0.  out[s1][3] = savm[s1][3]: probability, being at state
                   2320:           s1 at precedent wave, to be dead a month before current
                   2321:           wave is equal to probability, being at state s1 at
                   2322:           precedent wave, to be dead at mont of the current
                   2323:           wave. Then the observed probability (that this person died)
                   2324:           is null according to current estimated parameter. In fact,
                   2325:           it should be very low but not zero otherwise the log go to
                   2326:           infinity.
                   2327:        */
                   2328: /* #ifdef INFINITYORIGINAL */
                   2329: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2330: /* #else */
                   2331: /*       if ((out[s1][s2] - savm[s1][s2]) < mytinydouble)  */
                   2332: /*         lli=log(mytinydouble); */
                   2333: /*       else */
                   2334: /*         lli=log(out[s1][s2] - savm[s1][s2]); */
                   2335: /* #endif */
                   2336:            lli=log(out[s1][s2] - savm[s1][s2]);
1.126     brouard  2337: 
                   2338:        } else if  (s2==-2) {
                   2339:          for (j=1,survp=0. ; j<=nlstate; j++) 
                   2340:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2341:          /*survp += out[s1][j]; */
                   2342:          lli= log(survp);
                   2343:        }
                   2344:        
                   2345:        else if  (s2==-4) { 
                   2346:          for (j=3,survp=0. ; j<=nlstate; j++)  
                   2347:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2348:          lli= log(survp); 
                   2349:        } 
                   2350: 
                   2351:        else if  (s2==-5) { 
                   2352:          for (j=1,survp=0. ; j<=2; j++)  
                   2353:            survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2354:          lli= log(survp); 
                   2355:        } 
                   2356:        
                   2357:        else{
                   2358:          lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2359:          /*  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 */
                   2360:        } 
                   2361:        /*lli=(1.+bbh)*log(out[s1][s2])- bbh*log(savm[s1][s2]);*/
                   2362:        /*if(lli ==000.0)*/
                   2363:        /*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); */
                   2364:        ipmx +=1;
                   2365:        sw += weight[i];
                   2366:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.183     brouard  2367:        /* if (lli < log(mytinydouble)){ */
                   2368:        /*   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); */
                   2369:        /*   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]); */
                   2370:        /* } */
1.126     brouard  2371:       } /* end of wave */
                   2372:     } /* end of individual */
                   2373:   }  else if(mle==2){
                   2374:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2375:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2376:       for(mi=1; mi<= wav[i]-1; mi++){
                   2377:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2378:          for (j=1;j<=nlstate+ndeath;j++){
                   2379:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2380:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2381:          }
                   2382:        for(d=0; d<=dh[mi][i]; d++){
                   2383:          newm=savm;
1.187     brouard  2384:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2385:          cov[2]=agexact;
                   2386:          if(nagesqr==1)
                   2387:            cov[3]= agexact*agexact;
1.126     brouard  2388:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2389:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2390:          }
                   2391:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2392:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2393:          savm=oldm;
                   2394:          oldm=newm;
                   2395:        } /* end mult */
                   2396:       
                   2397:        s1=s[mw[mi][i]][i];
                   2398:        s2=s[mw[mi+1][i]][i];
                   2399:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2400:        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 */
                   2401:        ipmx +=1;
                   2402:        sw += weight[i];
                   2403:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2404:       } /* end of wave */
                   2405:     } /* end of individual */
                   2406:   }  else if(mle==3){  /* exponential inter-extrapolation */
                   2407:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2408:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2409:       for(mi=1; mi<= wav[i]-1; mi++){
                   2410:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2411:          for (j=1;j<=nlstate+ndeath;j++){
                   2412:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2413:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2414:          }
                   2415:        for(d=0; d<dh[mi][i]; d++){
                   2416:          newm=savm;
1.187     brouard  2417:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2418:          cov[2]=agexact;
                   2419:          if(nagesqr==1)
                   2420:            cov[3]= agexact*agexact;
1.126     brouard  2421:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2422:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2423:          }
                   2424:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2425:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2426:          savm=oldm;
                   2427:          oldm=newm;
                   2428:        } /* end mult */
                   2429:       
                   2430:        s1=s[mw[mi][i]][i];
                   2431:        s2=s[mw[mi+1][i]][i];
                   2432:        bbh=(double)bh[mi][i]/(double)stepm; 
                   2433:        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 */
                   2434:        ipmx +=1;
                   2435:        sw += weight[i];
                   2436:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2437:       } /* end of wave */
                   2438:     } /* end of individual */
                   2439:   }else if (mle==4){  /* ml=4 no inter-extrapolation */
                   2440:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2441:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2442:       for(mi=1; mi<= wav[i]-1; mi++){
                   2443:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2444:          for (j=1;j<=nlstate+ndeath;j++){
                   2445:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2446:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2447:          }
                   2448:        for(d=0; d<dh[mi][i]; d++){
                   2449:          newm=savm;
1.187     brouard  2450:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2451:          cov[2]=agexact;
                   2452:          if(nagesqr==1)
                   2453:            cov[3]= agexact*agexact;
1.126     brouard  2454:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2455:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2456:          }
                   2457:        
                   2458:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2459:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2460:          savm=oldm;
                   2461:          oldm=newm;
                   2462:        } /* end mult */
                   2463:       
                   2464:        s1=s[mw[mi][i]][i];
                   2465:        s2=s[mw[mi+1][i]][i];
                   2466:        if( s2 > nlstate){ 
                   2467:          lli=log(out[s1][s2] - savm[s1][s2]);
                   2468:        }else{
                   2469:          lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2470:        }
                   2471:        ipmx +=1;
                   2472:        sw += weight[i];
                   2473:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2474: /*     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]); */
                   2475:       } /* end of wave */
                   2476:     } /* end of individual */
                   2477:   }else{  /* ml=5 no inter-extrapolation no jackson =0.8a */
                   2478:     for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2479:       for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2480:       for(mi=1; mi<= wav[i]-1; mi++){
                   2481:        for (ii=1;ii<=nlstate+ndeath;ii++)
                   2482:          for (j=1;j<=nlstate+ndeath;j++){
                   2483:            oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2484:            savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2485:          }
                   2486:        for(d=0; d<dh[mi][i]; d++){
                   2487:          newm=savm;
1.187     brouard  2488:          agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2489:          cov[2]=agexact;
                   2490:          if(nagesqr==1)
                   2491:            cov[3]= agexact*agexact;
1.126     brouard  2492:          for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2493:            cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2494:          }
                   2495:        
                   2496:          out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2497:                       1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
                   2498:          savm=oldm;
                   2499:          oldm=newm;
                   2500:        } /* end mult */
                   2501:       
                   2502:        s1=s[mw[mi][i]][i];
                   2503:        s2=s[mw[mi+1][i]][i];
                   2504:        lli=log(out[s[mw[mi][i]][i]][s[mw[mi+1][i]][i]]); /* Original formula */
                   2505:        ipmx +=1;
                   2506:        sw += weight[i];
                   2507:        ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
                   2508:        /*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]);*/
                   2509:       } /* end of wave */
                   2510:     } /* end of individual */
                   2511:   } /* End of if */
                   2512:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2513:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2514:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2515:   return -l;
                   2516: }
                   2517: 
                   2518: /*************** log-likelihood *************/
                   2519: double funcone( double *x)
                   2520: {
                   2521:   /* Same as likeli but slower because of a lot of printf and if */
                   2522:   int i, ii, j, k, mi, d, kk;
1.131     brouard  2523:   double l, ll[NLSTATEMAX+1], cov[NCOVMAX+1];
1.126     brouard  2524:   double **out;
                   2525:   double lli; /* Individual log likelihood */
                   2526:   double llt;
                   2527:   int s1, s2;
                   2528:   double bbh, survp;
1.187     brouard  2529:   double agexact;
1.126     brouard  2530:   /*extern weight */
                   2531:   /* We are differentiating ll according to initial status */
                   2532:   /*  for (i=1;i<=npar;i++) printf("%f ", x[i]);*/
                   2533:   /*for(i=1;i<imx;i++) 
                   2534:     printf(" %d\n",s[4][i]);
                   2535:   */
                   2536:   cov[1]=1.;
                   2537: 
                   2538:   for(k=1; k<=nlstate; k++) ll[k]=0.;
                   2539: 
                   2540:   for (i=1,ipmx=0, sw=0.; i<=imx; i++){
1.187     brouard  2541:     for (k=1; k<=cptcovn;k++) cov[2+nagesqr+k]=covar[Tvar[k]][i];
1.126     brouard  2542:     for(mi=1; mi<= wav[i]-1; mi++){
                   2543:       for (ii=1;ii<=nlstate+ndeath;ii++)
                   2544:        for (j=1;j<=nlstate+ndeath;j++){
                   2545:          oldm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2546:          savm[ii][j]=(ii==j ? 1.0 : 0.0);
                   2547:        }
                   2548:       for(d=0; d<dh[mi][i]; d++){
                   2549:        newm=savm;
1.187     brouard  2550:        agexact=agev[mw[mi][i]][i]+d*stepm/YEARM;
                   2551:        cov[2]=agexact;
                   2552:        if(nagesqr==1)
                   2553:          cov[3]= agexact*agexact;
1.126     brouard  2554:        for (kk=1; kk<=cptcovage;kk++) {
1.187     brouard  2555:          cov[Tage[kk]+2+nagesqr]=covar[Tvar[Tage[kk]]][i]*agexact;
1.126     brouard  2556:        }
1.187     brouard  2557: 
1.145     brouard  2558:        /* savm=pmij(pmmij,cov,ncovmodel,x,nlstate); */
1.126     brouard  2559:        out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath,
                   2560:                     1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate));
1.145     brouard  2561:        /* out=matprod2(newm,oldm,1,nlstate+ndeath,1,nlstate+ndeath, */
                   2562:        /*           1,nlstate+ndeath,pmij(pmmij,cov,ncovmodel,x,nlstate)); */
1.126     brouard  2563:        savm=oldm;
                   2564:        oldm=newm;
                   2565:       } /* end mult */
                   2566:       
                   2567:       s1=s[mw[mi][i]][i];
                   2568:       s2=s[mw[mi+1][i]][i];
                   2569:       bbh=(double)bh[mi][i]/(double)stepm; 
                   2570:       /* bias is positive if real duration
                   2571:        * is higher than the multiple of stepm and negative otherwise.
                   2572:        */
                   2573:       if( s2 > nlstate && (mle <5) ){  /* Jackson */
                   2574:        lli=log(out[s1][s2] - savm[s1][s2]);
                   2575:       } else if  (s2==-2) {
                   2576:        for (j=1,survp=0. ; j<=nlstate; j++) 
                   2577:          survp += (1.+bbh)*out[s1][j]- bbh*savm[s1][j];
                   2578:        lli= log(survp);
                   2579:       }else if (mle==1){
                   2580:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2581:       } else if(mle==2){
                   2582:        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 */
                   2583:       } else if(mle==3){  /* exponential inter-extrapolation */
                   2584:        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 */
                   2585:       } else if (mle==4){  /* mle=4 no inter-extrapolation */
                   2586:        lli=log(out[s1][s2]); /* Original formula */
1.136     brouard  2587:       } else{  /* mle=0 back to 1 */
                   2588:        lli= log((1.+bbh)*out[s1][s2]- bbh*savm[s1][s2]); /* linear interpolation */
                   2589:        /*lli=log(out[s1][s2]); */ /* Original formula */
1.126     brouard  2590:       } /* End of if */
                   2591:       ipmx +=1;
                   2592:       sw += weight[i];
                   2593:       ll[s[mw[mi][i]][i]] += 2*weight[i]*lli;
1.132     brouard  2594:       /*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  2595:       if(globpr){
1.202     brouard  2596:        fprintf(ficresilk,"%9ld %6.1f %6d %2d %2d %2d %2d %3d %11.6f %8.4f\
1.126     brouard  2597:  %11.6f %11.6f %11.6f ", \
1.202     brouard  2598:                num[i], agexact, i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],
1.126     brouard  2599:                2*weight[i]*lli,out[s1][s2],savm[s1][s2]);
                   2600:        for(k=1,llt=0.,l=0.; k<=nlstate; k++){
                   2601:          llt +=ll[k]*gipmx/gsw;
                   2602:          fprintf(ficresilk," %10.6f",-ll[k]*gipmx/gsw);
                   2603:        }
                   2604:        fprintf(ficresilk," %10.6f\n", -llt);
                   2605:       }
                   2606:     } /* end of wave */
                   2607:   } /* end of individual */
                   2608:   for(k=1,l=0.; k<=nlstate; k++) l += ll[k];
                   2609:   /* printf("l1=%f l2=%f ",ll[1],ll[2]); */
                   2610:   l= l*ipmx/sw; /* To get the same order of magnitude as if weight=1 for every body */
                   2611:   if(globpr==0){ /* First time we count the contributions and weights */
                   2612:     gipmx=ipmx;
                   2613:     gsw=sw;
                   2614:   }
                   2615:   return -l;
                   2616: }
                   2617: 
                   2618: 
                   2619: /*************** function likelione ***********/
                   2620: void likelione(FILE *ficres,double p[], int npar, int nlstate, int *globpri, long *ipmx, double *sw, double *fretone, double (*funcone)(double []))
                   2621: {
                   2622:   /* This routine should help understanding what is done with 
                   2623:      the selection of individuals/waves and
                   2624:      to check the exact contribution to the likelihood.
                   2625:      Plotting could be done.
                   2626:    */
                   2627:   int k;
                   2628: 
                   2629:   if(*globpri !=0){ /* Just counts and sums, no printings */
1.201     brouard  2630:     strcpy(fileresilk,"ILK_"); 
1.202     brouard  2631:     strcat(fileresilk,fileresu);
1.126     brouard  2632:     if((ficresilk=fopen(fileresilk,"w"))==NULL) {
                   2633:       printf("Problem with resultfile: %s\n", fileresilk);
                   2634:       fprintf(ficlog,"Problem with resultfile: %s\n", fileresilk);
                   2635:     }
                   2636:     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  2637:     fprintf(ficresilk, "#num_i age i s1 s2 mi mw dh likeli weight 2wlli out sav ");
1.126     brouard  2638:     /*         i,s1,s2,mi,mw[mi][i],dh[mi][i],exp(lli),weight[i],2*weight[i]*lli,out[s1][s2],savm[s1][s2]); */
                   2639:     for(k=1; k<=nlstate; k++) 
                   2640:       fprintf(ficresilk," -2*gipw/gsw*weight*ll[%d]++",k);
                   2641:     fprintf(ficresilk," -2*gipw/gsw*weight*ll(total)\n");
                   2642:   }
                   2643: 
                   2644:   *fretone=(*funcone)(p);
                   2645:   if(*globpri !=0){
                   2646:     fclose(ficresilk);
1.202     brouard  2647:     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));
                   2648:     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> \
                   2649: <img src=\"%s.png\">",subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"),subdirf2(optionfilefiname,"ILK_"));
                   2650:     fflush(fichtm);
1.126     brouard  2651:   } 
                   2652:   return;
                   2653: }
                   2654: 
                   2655: 
                   2656: /*********** Maximum Likelihood Estimation ***************/
                   2657: 
                   2658: void mlikeli(FILE *ficres,double p[], int npar, int ncovmodel, int nlstate, double ftol, double (*func)(double []))
                   2659: {
1.165     brouard  2660:   int i,j, iter=0;
1.126     brouard  2661:   double **xi;
                   2662:   double fret;
                   2663:   double fretone; /* Only one call to likelihood */
                   2664:   /*  char filerespow[FILENAMELENGTH];*/
1.162     brouard  2665: 
                   2666: #ifdef NLOPT
                   2667:   int creturn;
                   2668:   nlopt_opt opt;
                   2669:   /* double lb[9] = { -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL, -HUGE_VAL }; /\* lower bounds *\/ */
                   2670:   double *lb;
                   2671:   double minf; /* the minimum objective value, upon return */
                   2672:   double * p1; /* Shifted parameters from 0 instead of 1 */
                   2673:   myfunc_data dinst, *d = &dinst;
                   2674: #endif
                   2675: 
                   2676: 
1.126     brouard  2677:   xi=matrix(1,npar,1,npar);
                   2678:   for (i=1;i<=npar;i++)
                   2679:     for (j=1;j<=npar;j++)
                   2680:       xi[i][j]=(i==j ? 1.0 : 0.0);
                   2681:   printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.201     brouard  2682:   strcpy(filerespow,"POW_"); 
1.126     brouard  2683:   strcat(filerespow,fileres);
                   2684:   if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   2685:     printf("Problem with resultfile: %s\n", filerespow);
                   2686:     fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   2687:   }
                   2688:   fprintf(ficrespow,"# Powell\n# iter -2*LL");
                   2689:   for (i=1;i<=nlstate;i++)
                   2690:     for(j=1;j<=nlstate+ndeath;j++)
                   2691:       if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   2692:   fprintf(ficrespow,"\n");
1.162     brouard  2693: #ifdef POWELL
1.126     brouard  2694:   powell(p,xi,npar,ftol,&iter,&fret,func);
1.162     brouard  2695: #endif
1.126     brouard  2696: 
1.162     brouard  2697: #ifdef NLOPT
                   2698: #ifdef NEWUOA
                   2699:   opt = nlopt_create(NLOPT_LN_NEWUOA,npar);
                   2700: #else
                   2701:   opt = nlopt_create(NLOPT_LN_BOBYQA,npar);
                   2702: #endif
                   2703:   lb=vector(0,npar-1);
                   2704:   for (i=0;i<npar;i++) lb[i]= -HUGE_VAL;
                   2705:   nlopt_set_lower_bounds(opt, lb);
                   2706:   nlopt_set_initial_step1(opt, 0.1);
                   2707:   
                   2708:   p1= (p+1); /*  p *(p+1)@8 and p *(p1)@8 are equal p1[0]=p[1] */
                   2709:   d->function = func;
                   2710:   printf(" Func %.12lf \n",myfunc(npar,p1,NULL,d));
                   2711:   nlopt_set_min_objective(opt, myfunc, d);
                   2712:   nlopt_set_xtol_rel(opt, ftol);
                   2713:   if ((creturn=nlopt_optimize(opt, p1, &minf)) < 0) {
                   2714:     printf("nlopt failed! %d\n",creturn); 
                   2715:   }
                   2716:   else {
                   2717:     printf("found minimum after %d evaluations (NLOPT=%d)\n", countcallfunc ,NLOPT);
                   2718:     printf("found minimum at f(%g,%g) = %0.10g\n", p[0], p[1], minf);
                   2719:     iter=1; /* not equal */
                   2720:   }
                   2721:   nlopt_destroy(opt);
                   2722: #endif
1.126     brouard  2723:   free_matrix(xi,1,npar,1,npar);
                   2724:   fclose(ficrespow);
1.203   ! brouard  2725:   printf("\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
        !          2726:   fprintf(ficlog,"\n#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.180     brouard  2727:   fprintf(ficres,"#Number of iterations & function calls = %d & %d, -2 Log likelihood = %.12f\n",iter, countcallfunc,func(p));
1.126     brouard  2728: 
                   2729: }
                   2730: 
                   2731: /**** Computes Hessian and covariance matrix ***/
1.203   ! brouard  2732: void hesscov(double **matcov, double **hess, double p[], int npar, double delti[], double ftolhess, double (*func)(double []))
1.126     brouard  2733: {
                   2734:   double  **a,**y,*x,pd;
1.203   ! brouard  2735:   /* double **hess; */
1.164     brouard  2736:   int i, j;
1.126     brouard  2737:   int *indx;
                   2738: 
                   2739:   double hessii(double p[], double delta, int theta, double delti[],double (*func)(double []),int npar);
1.203   ! brouard  2740:   double hessij(double p[], double **hess, double delti[], int i, int j,double (*func)(double []),int npar);
1.126     brouard  2741:   void lubksb(double **a, int npar, int *indx, double b[]) ;
                   2742:   void ludcmp(double **a, int npar, int *indx, double *d) ;
                   2743:   double gompertz(double p[]);
1.203   ! brouard  2744:   /* hess=matrix(1,npar,1,npar); */
1.126     brouard  2745: 
                   2746:   printf("\nCalculation of the hessian matrix. Wait...\n");
                   2747:   fprintf(ficlog,"\nCalculation of the hessian matrix. Wait...\n");
                   2748:   for (i=1;i<=npar;i++){
1.203   ! brouard  2749:     printf("%d-",i);fflush(stdout);
        !          2750:     fprintf(ficlog,"%d-",i);fflush(ficlog);
1.126     brouard  2751:    
                   2752:      hess[i][i]=hessii(p,ftolhess,i,delti,func,npar);
                   2753:     
                   2754:     /*  printf(" %f ",p[i]);
                   2755:        printf(" %lf %lf %lf",hess[i][i],ftolhess,delti[i]);*/
                   2756:   }
                   2757:   
                   2758:   for (i=1;i<=npar;i++) {
                   2759:     for (j=1;j<=npar;j++)  {
                   2760:       if (j>i) { 
1.203   ! brouard  2761:        printf(".%d-%d",i,j);fflush(stdout);
        !          2762:        fprintf(ficlog,".%d-%d",i,j);fflush(ficlog);
        !          2763:        hess[i][j]=hessij(p,hess, delti,i,j,func,npar);
1.126     brouard  2764:        
                   2765:        hess[j][i]=hess[i][j];    
                   2766:        /*printf(" %lf ",hess[i][j]);*/
                   2767:       }
                   2768:     }
                   2769:   }
                   2770:   printf("\n");
                   2771:   fprintf(ficlog,"\n");
                   2772: 
                   2773:   printf("\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2774:   fprintf(ficlog,"\nInverting the hessian to get the covariance matrix. Wait...\n");
                   2775:   
                   2776:   a=matrix(1,npar,1,npar);
                   2777:   y=matrix(1,npar,1,npar);
                   2778:   x=vector(1,npar);
                   2779:   indx=ivector(1,npar);
                   2780:   for (i=1;i<=npar;i++)
                   2781:     for (j=1;j<=npar;j++) a[i][j]=hess[i][j];
                   2782:   ludcmp(a,npar,indx,&pd);
                   2783: 
                   2784:   for (j=1;j<=npar;j++) {
                   2785:     for (i=1;i<=npar;i++) x[i]=0;
                   2786:     x[j]=1;
                   2787:     lubksb(a,npar,indx,x);
                   2788:     for (i=1;i<=npar;i++){ 
                   2789:       matcov[i][j]=x[i];
                   2790:     }
                   2791:   }
                   2792: 
                   2793:   printf("\n#Hessian matrix#\n");
                   2794:   fprintf(ficlog,"\n#Hessian matrix#\n");
                   2795:   for (i=1;i<=npar;i++) { 
                   2796:     for (j=1;j<=npar;j++) { 
1.203   ! brouard  2797:       printf("%.6e ",hess[i][j]);
        !          2798:       fprintf(ficlog,"%.6e ",hess[i][j]);
1.126     brouard  2799:     }
                   2800:     printf("\n");
                   2801:     fprintf(ficlog,"\n");
                   2802:   }
                   2803: 
1.203   ! brouard  2804:   /* printf("\n#Covariance matrix#\n"); */
        !          2805:   /* fprintf(ficlog,"\n#Covariance matrix#\n"); */
        !          2806:   /* for (i=1;i<=npar;i++) {  */
        !          2807:   /*   for (j=1;j<=npar;j++) {  */
        !          2808:   /*     printf("%.6e ",matcov[i][j]); */
        !          2809:   /*     fprintf(ficlog,"%.6e ",matcov[i][j]); */
        !          2810:   /*   } */
        !          2811:   /*   printf("\n"); */
        !          2812:   /*   fprintf(ficlog,"\n"); */
        !          2813:   /* } */
        !          2814: 
1.126     brouard  2815:   /* Recompute Inverse */
1.203   ! brouard  2816:   /* for (i=1;i<=npar;i++) */
        !          2817:   /*   for (j=1;j<=npar;j++) a[i][j]=matcov[i][j]; */
        !          2818:   /* ludcmp(a,npar,indx,&pd); */
        !          2819: 
        !          2820:   /*  printf("\n#Hessian matrix recomputed#\n"); */
        !          2821: 
        !          2822:   /* for (j=1;j<=npar;j++) { */
        !          2823:   /*   for (i=1;i<=npar;i++) x[i]=0; */
        !          2824:   /*   x[j]=1; */
        !          2825:   /*   lubksb(a,npar,indx,x); */
        !          2826:   /*   for (i=1;i<=npar;i++){  */
        !          2827:   /*     y[i][j]=x[i]; */
        !          2828:   /*     printf("%.3e ",y[i][j]); */
        !          2829:   /*     fprintf(ficlog,"%.3e ",y[i][j]); */
        !          2830:   /*   } */
        !          2831:   /*   printf("\n"); */
        !          2832:   /*   fprintf(ficlog,"\n"); */
        !          2833:   /* } */
        !          2834: 
        !          2835:   /* Verifying the inverse matrix */
        !          2836: #ifdef DEBUGHESS
        !          2837:   y=matprod2(y,hess,1,npar,1,npar,1,npar,matcov);
1.126     brouard  2838: 
1.203   ! brouard  2839:    printf("\n#Verification: multiplying the matrix of covariance by the Hessian matrix, should be unity:#\n");
        !          2840:    fprintf(ficlog,"\n#Verification: multiplying the matrix of covariance by the Hessian matrix. Should be unity:#\n");
1.126     brouard  2841: 
                   2842:   for (j=1;j<=npar;j++) {
                   2843:     for (i=1;i<=npar;i++){ 
1.203   ! brouard  2844:       printf("%.2f ",y[i][j]);
        !          2845:       fprintf(ficlog,"%.2f ",y[i][j]);
1.126     brouard  2846:     }
                   2847:     printf("\n");
                   2848:     fprintf(ficlog,"\n");
                   2849:   }
1.203   ! brouard  2850: #endif
1.126     brouard  2851: 
                   2852:   free_matrix(a,1,npar,1,npar);
                   2853:   free_matrix(y,1,npar,1,npar);
                   2854:   free_vector(x,1,npar);
                   2855:   free_ivector(indx,1,npar);
1.203   ! brouard  2856:   /* free_matrix(hess,1,npar,1,npar); */
1.126     brouard  2857: 
                   2858: 
                   2859: }
                   2860: 
                   2861: /*************** hessian matrix ****************/
                   2862: double hessii(double x[], double delta, int theta, double delti[], double (*func)(double []), int npar)
1.203   ! brouard  2863: { /* Around values of x, computes the function func and returns the scales delti and hessian */
1.126     brouard  2864:   int i;
                   2865:   int l=1, lmax=20;
1.203   ! brouard  2866:   double k1,k2, res, fx;
1.132     brouard  2867:   double p2[MAXPARM+1]; /* identical to x */
1.126     brouard  2868:   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4;
                   2869:   int k=0,kmax=10;
                   2870:   double l1;
                   2871: 
                   2872:   fx=func(x);
                   2873:   for (i=1;i<=npar;i++) p2[i]=x[i];
1.145     brouard  2874:   for(l=0 ; l <=lmax; l++){  /* Enlarging the zone around the Maximum */
1.126     brouard  2875:     l1=pow(10,l);
                   2876:     delts=delt;
                   2877:     for(k=1 ; k <kmax; k=k+1){
                   2878:       delt = delta*(l1*k);
                   2879:       p2[theta]=x[theta] +delt;
1.145     brouard  2880:       k1=func(p2)-fx;   /* Might be negative if too close to the theoretical maximum */
1.126     brouard  2881:       p2[theta]=x[theta]-delt;
                   2882:       k2=func(p2)-fx;
                   2883:       /*res= (k1-2.0*fx+k2)/delt/delt; */
1.203   ! brouard  2884:       res= (k1+k2)/delt/delt/2.; /* Divided by 2 because L and not 2*L */
1.126     brouard  2885:       
1.203   ! brouard  2886: #ifdef DEBUGHESSII
1.126     brouard  2887:       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);
                   2888:       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);
                   2889: #endif
                   2890:       /*if(fabs(k1-2.0*fx+k2) <1.e-13){ */
                   2891:       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)){
                   2892:        k=kmax;
                   2893:       }
                   2894:       else if((k1 >khi/nkhif) || (k2 >khi/nkhif)){ /* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. */
1.164     brouard  2895:        k=kmax; l=lmax*10;
1.126     brouard  2896:       }
                   2897:       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){ 
                   2898:        delts=delt;
                   2899:       }
1.203   ! brouard  2900:     } /* End loop k */
1.126     brouard  2901:   }
                   2902:   delti[theta]=delts;
                   2903:   return res; 
                   2904:   
                   2905: }
                   2906: 
1.203   ! brouard  2907: double hessij( double x[], double **hess, double delti[], int thetai,int thetaj,double (*func)(double []),int npar)
1.126     brouard  2908: {
                   2909:   int i;
1.164     brouard  2910:   int l=1, lmax=20;
1.126     brouard  2911:   double k1,k2,k3,k4,res,fx;
1.132     brouard  2912:   double p2[MAXPARM+1];
1.203   ! brouard  2913:   int k, kmax=1;
        !          2914:   double v1, v2, cv12, lc1, lc2;
        !          2915:   
1.126     brouard  2916:   fx=func(x);
1.203   ! brouard  2917:   for (k=1; k<=kmax; k=k+10) {
1.126     brouard  2918:     for (i=1;i<=npar;i++) p2[i]=x[i];
1.203   ! brouard  2919:     p2[thetai]=x[thetai]+delti[thetai]*k;
        !          2920:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  2921:     k1=func(p2)-fx;
                   2922:   
1.203   ! brouard  2923:     p2[thetai]=x[thetai]+delti[thetai]*k;
        !          2924:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  2925:     k2=func(p2)-fx;
                   2926:   
1.203   ! brouard  2927:     p2[thetai]=x[thetai]-delti[thetai]*k;
        !          2928:     p2[thetaj]=x[thetaj]+delti[thetaj]*k;
1.126     brouard  2929:     k3=func(p2)-fx;
                   2930:   
1.203   ! brouard  2931:     p2[thetai]=x[thetai]-delti[thetai]*k;
        !          2932:     p2[thetaj]=x[thetaj]-delti[thetaj]*k;
1.126     brouard  2933:     k4=func(p2)-fx;
1.203   ! brouard  2934:     res=(k1-k2-k3+k4)/4.0/delti[thetai]/k/delti[thetaj]/k/2.; /* Because of L not 2*L */
        !          2935:     if(k1*k2*k3*k4 <0.){
        !          2936:       kmax=kmax+10;
        !          2937:       if(kmax >=10){
        !          2938:       printf("Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
        !          2939:       fprintf(ficlog,"Warning: directions %d-%d, you are not estimating the Hessian at the exact maximum likelihood; increase ftol=%.2e\n",thetai,thetaj, ftol);
        !          2940:       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);
        !          2941:       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);
        !          2942:       }
        !          2943:     }
        !          2944: #ifdef DEBUGHESSIJ
        !          2945:     v1=hess[thetai][thetai];
        !          2946:     v2=hess[thetaj][thetaj];
        !          2947:     cv12=res;
        !          2948:     /* Computing eigen value of Hessian matrix */
        !          2949:     lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
        !          2950:     lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
        !          2951:     if ((lc2 <0) || (lc1 <0) ){
        !          2952:       printf("Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
        !          2953:       fprintf(ficlog, "Warning: sub Hessian matrix '%d%d' does not have positive eigen values \n",thetai,thetaj);
        !          2954:       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);
        !          2955:       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);
        !          2956:     }
1.126     brouard  2957: #endif
                   2958:   }
                   2959:   return res;
                   2960: }
                   2961: 
1.203   ! brouard  2962:     /* Not done yet: Was supposed to fix if not exactly at the maximum */
        !          2963: /* double hessij( double x[], double delti[], int thetai,int thetaj,double (*func)(double []),int npar) */
        !          2964: /* { */
        !          2965: /*   int i; */
        !          2966: /*   int l=1, lmax=20; */
        !          2967: /*   double k1,k2,k3,k4,res,fx; */
        !          2968: /*   double p2[MAXPARM+1]; */
        !          2969: /*   double delt=0.0001, delts, nkhi=10.,nkhif=1., khi=1.e-4; */
        !          2970: /*   int k=0,kmax=10; */
        !          2971: /*   double l1; */
        !          2972:   
        !          2973: /*   fx=func(x); */
        !          2974: /*   for(l=0 ; l <=lmax; l++){  /\* Enlarging the zone around the Maximum *\/ */
        !          2975: /*     l1=pow(10,l); */
        !          2976: /*     delts=delt; */
        !          2977: /*     for(k=1 ; k <kmax; k=k+1){ */
        !          2978: /*       delt = delti*(l1*k); */
        !          2979: /*       for (i=1;i<=npar;i++) p2[i]=x[i]; */
        !          2980: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
        !          2981: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
        !          2982: /*       k1=func(p2)-fx; */
        !          2983:       
        !          2984: /*       p2[thetai]=x[thetai]+delti[thetai]/k; */
        !          2985: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
        !          2986: /*       k2=func(p2)-fx; */
        !          2987:       
        !          2988: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
        !          2989: /*       p2[thetaj]=x[thetaj]+delti[thetaj]/k; */
        !          2990: /*       k3=func(p2)-fx; */
        !          2991:       
        !          2992: /*       p2[thetai]=x[thetai]-delti[thetai]/k; */
        !          2993: /*       p2[thetaj]=x[thetaj]-delti[thetaj]/k; */
        !          2994: /*       k4=func(p2)-fx; */
        !          2995: /*       res=(k1-k2-k3+k4)/4.0/delti[thetai]*k/delti[thetaj]*k/2.; /\* Because of L not 2*L *\/ */
        !          2996: /* #ifdef DEBUGHESSIJ */
        !          2997: /*       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); */
        !          2998: /*       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); */
        !          2999: /* #endif */
        !          3000: /*       if((k1 <khi/nkhi/2.) || (k2 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)|| (k4 <khi/nkhi/2.)){ */
        !          3001: /*     k=kmax; */
        !          3002: /*       } */
        !          3003: /*       else if((k1 >khi/nkhif) || (k2 >khi/nkhif) || (k4 >khi/nkhif) || (k4 >khi/nkhif)){ /\* Keeps lastvalue before 3.84/2 KHI2 5% 1d.f. *\/ */
        !          3004: /*     k=kmax; l=lmax*10; */
        !          3005: /*       } */
        !          3006: /*       else if((k1 >khi/nkhi) || (k2 >khi/nkhi)){  */
        !          3007: /*     delts=delt; */
        !          3008: /*       } */
        !          3009: /*     } /\* End loop k *\/ */
        !          3010: /*   } */
        !          3011: /*   delti[theta]=delts; */
        !          3012: /*   return res;  */
        !          3013: /* } */
        !          3014: 
        !          3015: 
1.126     brouard  3016: /************** Inverse of matrix **************/
                   3017: void ludcmp(double **a, int n, int *indx, double *d) 
                   3018: { 
                   3019:   int i,imax,j,k; 
                   3020:   double big,dum,sum,temp; 
                   3021:   double *vv; 
                   3022:  
                   3023:   vv=vector(1,n); 
                   3024:   *d=1.0; 
                   3025:   for (i=1;i<=n;i++) { 
                   3026:     big=0.0; 
                   3027:     for (j=1;j<=n;j++) 
                   3028:       if ((temp=fabs(a[i][j])) > big) big=temp; 
                   3029:     if (big == 0.0) nrerror("Singular matrix in routine ludcmp"); 
                   3030:     vv[i]=1.0/big; 
                   3031:   } 
                   3032:   for (j=1;j<=n;j++) { 
                   3033:     for (i=1;i<j;i++) { 
                   3034:       sum=a[i][j]; 
                   3035:       for (k=1;k<i;k++) sum -= a[i][k]*a[k][j]; 
                   3036:       a[i][j]=sum; 
                   3037:     } 
                   3038:     big=0.0; 
                   3039:     for (i=j;i<=n;i++) { 
                   3040:       sum=a[i][j]; 
                   3041:       for (k=1;k<j;k++) 
                   3042:        sum -= a[i][k]*a[k][j]; 
                   3043:       a[i][j]=sum; 
                   3044:       if ( (dum=vv[i]*fabs(sum)) >= big) { 
                   3045:        big=dum; 
                   3046:        imax=i; 
                   3047:       } 
                   3048:     } 
                   3049:     if (j != imax) { 
                   3050:       for (k=1;k<=n;k++) { 
                   3051:        dum=a[imax][k]; 
                   3052:        a[imax][k]=a[j][k]; 
                   3053:        a[j][k]=dum; 
                   3054:       } 
                   3055:       *d = -(*d); 
                   3056:       vv[imax]=vv[j]; 
                   3057:     } 
                   3058:     indx[j]=imax; 
                   3059:     if (a[j][j] == 0.0) a[j][j]=TINY; 
                   3060:     if (j != n) { 
                   3061:       dum=1.0/(a[j][j]); 
                   3062:       for (i=j+1;i<=n;i++) a[i][j] *= dum; 
                   3063:     } 
                   3064:   } 
                   3065:   free_vector(vv,1,n);  /* Doesn't work */
                   3066: ;
                   3067: } 
                   3068: 
                   3069: void lubksb(double **a, int n, int *indx, double b[]) 
                   3070: { 
                   3071:   int i,ii=0,ip,j; 
                   3072:   double sum; 
                   3073:  
                   3074:   for (i=1;i<=n;i++) { 
                   3075:     ip=indx[i]; 
                   3076:     sum=b[ip]; 
                   3077:     b[ip]=b[i]; 
                   3078:     if (ii) 
                   3079:       for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; 
                   3080:     else if (sum) ii=i; 
                   3081:     b[i]=sum; 
                   3082:   } 
                   3083:   for (i=n;i>=1;i--) { 
                   3084:     sum=b[i]; 
                   3085:     for (j=i+1;j<=n;j++) sum -= a[i][j]*b[j]; 
                   3086:     b[i]=sum/a[i][i]; 
                   3087:   } 
                   3088: } 
                   3089: 
                   3090: void pstamp(FILE *fichier)
                   3091: {
1.196     brouard  3092:   fprintf(fichier,"# %s.%s\n#IMaCh version %s, %s\n#%s\n# %s", optionfilefiname,optionfilext,version,copyright, fullversion, strstart);
1.126     brouard  3093: }
                   3094: 
                   3095: /************ Frequencies ********************/
                   3096: 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[])
                   3097: {  /* Some frequencies */
                   3098:   
1.164     brouard  3099:   int i, m, jk, j1, bool, z1,j;
1.126     brouard  3100:   int first;
                   3101:   double ***freq; /* Frequencies */
                   3102:   double *pp, **prop;
                   3103:   double pos,posprop, k2, dateintsum=0,k2cpt=0;
                   3104:   char fileresp[FILENAMELENGTH];
                   3105:   
                   3106:   pp=vector(1,nlstate);
                   3107:   prop=matrix(1,nlstate,iagemin,iagemax+3);
1.201     brouard  3108:   strcpy(fileresp,"P_");
                   3109:   strcat(fileresp,fileresu);
1.126     brouard  3110:   if((ficresp=fopen(fileresp,"w"))==NULL) {
                   3111:     printf("Problem with prevalence resultfile: %s\n", fileresp);
                   3112:     fprintf(ficlog,"Problem with prevalence resultfile: %s\n", fileresp);
                   3113:     exit(0);
                   3114:   }
                   3115:   freq= ma3x(-5,nlstate+ndeath,-5,nlstate+ndeath,iagemin,iagemax+3);
                   3116:   j1=0;
                   3117:   
                   3118:   j=cptcoveff;
                   3119:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3120: 
                   3121:   first=1;
                   3122: 
1.169     brouard  3123:   /* for(k1=1; k1<=j ; k1++){ */  /* Loop on covariates */
                   3124:   /*  for(i1=1; i1<=ncodemax[k1];i1++){ */ /* Now it is 2 */
                   3125:   /*    j1++; */
1.145     brouard  3126:   for (j1 = 1; j1 <= (int) pow(2,cptcoveff); j1++){
1.126     brouard  3127:       /*printf("cptcoveff=%d Tvaraff=%d", cptcoveff,Tvaraff[1]);
                   3128:        scanf("%d", i);*/
                   3129:       for (i=-5; i<=nlstate+ndeath; i++)  
                   3130:        for (jk=-5; jk<=nlstate+ndeath; jk++)  
                   3131:          for(m=iagemin; m <= iagemax+3; m++)
                   3132:            freq[i][jk][m]=0;
1.143     brouard  3133:       
                   3134:       for (i=1; i<=nlstate; i++)  
                   3135:        for(m=iagemin; m <= iagemax+3; m++)
                   3136:          prop[i][m]=0;
1.126     brouard  3137:       
                   3138:       dateintsum=0;
                   3139:       k2cpt=0;
                   3140:       for (i=1; i<=imx; i++) {
                   3141:        bool=1;
1.144     brouard  3142:        if  (cptcovn>0) { /* Filter is here: Must be looked at for model=V1+V2+V3+V4 */
                   3143:          for (z1=1; z1<=cptcoveff; z1++)       
1.198     brouard  3144:             if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]){
1.145     brouard  3145:                 /* Tests if the value of each of the covariates of i is equal to filter j1 */
1.144     brouard  3146:               bool=0;
1.198     brouard  3147:               /* 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", 
                   3148:                 bool,i,z1, z1, Tvaraff[z1],i,covar[Tvaraff[z1]][i],j1,z1,codtabm(j1,z1),
                   3149:                 j1,z1,nbcode[Tvaraff[z1]][codtabm(j1,z1)],j1);*/
                   3150:               /* For j1=7 in V1+V2+V3+V4 = 0 1 1 0 and codtabm(7,3)=1 and nbcde[3][?]=1*/
1.144     brouard  3151:             } 
1.126     brouard  3152:        }
1.144     brouard  3153:  
1.126     brouard  3154:        if (bool==1){
                   3155:          for(m=firstpass; m<=lastpass; m++){
                   3156:            k2=anint[m][i]+(mint[m][i]/12.);
                   3157:            /*if ((k2>=dateprev1) && (k2<=dateprev2)) {*/
                   3158:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3159:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3160:              if (s[m][i]>0 && s[m][i]<=nlstate) prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3161:              if (m<lastpass) {
                   3162:                freq[s[m][i]][s[m+1][i]][(int)agev[m][i]] += weight[i];
                   3163:                freq[s[m][i]][s[m+1][i]][iagemax+3] += weight[i];
                   3164:              }
                   3165:              
                   3166:              if ((agev[m][i]>1) && (agev[m][i]< (iagemax+3))) {
                   3167:                dateintsum=dateintsum+k2;
                   3168:                k2cpt++;
                   3169:              }
                   3170:              /*}*/
                   3171:          }
                   3172:        }
1.145     brouard  3173:       } /* end i */
1.126     brouard  3174:        
                   3175:       /*      fprintf(ficresp, "#Count between %.lf/%.lf/%.lf and %.lf/%.lf/%.lf\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2);*/
                   3176:       pstamp(ficresp);
                   3177:       if  (cptcovn>0) {
                   3178:        fprintf(ficresp, "\n#********** Variable "); 
1.198     brouard  3179:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresp, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  3180:        fprintf(ficresp, "**********\n#");
1.143     brouard  3181:        fprintf(ficlog, "\n#********** Variable "); 
1.198     brouard  3182:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficlog, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.143     brouard  3183:        fprintf(ficlog, "**********\n#");
1.126     brouard  3184:       }
                   3185:       for(i=1; i<=nlstate;i++) 
                   3186:        fprintf(ficresp, " Age Prev(%d) N(%d) N",i,i);
                   3187:       fprintf(ficresp, "\n");
                   3188:       
                   3189:       for(i=iagemin; i <= iagemax+3; i++){
                   3190:        if(i==iagemax+3){
                   3191:          fprintf(ficlog,"Total");
                   3192:        }else{
                   3193:          if(first==1){
                   3194:            first=0;
                   3195:            printf("See log file for details...\n");
                   3196:          }
                   3197:          fprintf(ficlog,"Age %d", i);
                   3198:        }
                   3199:        for(jk=1; jk <=nlstate ; jk++){
                   3200:          for(m=-1, pp[jk]=0; m <=nlstate+ndeath ; m++)
                   3201:            pp[jk] += freq[jk][m][i]; 
                   3202:        }
                   3203:        for(jk=1; jk <=nlstate ; jk++){
                   3204:          for(m=-1, pos=0; m <=0 ; m++)
                   3205:            pos += freq[jk][m][i];
                   3206:          if(pp[jk]>=1.e-10){
                   3207:            if(first==1){
1.132     brouard  3208:              printf(" %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
1.126     brouard  3209:            }
                   3210:            fprintf(ficlog," %d.=%.0f loss[%d]=%.1f%%",jk,pp[jk],jk,100*pos/pp[jk]);
                   3211:          }else{
                   3212:            if(first==1)
                   3213:              printf(" %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3214:            fprintf(ficlog," %d.=%.0f loss[%d]=NaNQ%%",jk,pp[jk],jk);
                   3215:          }
                   3216:        }
                   3217: 
                   3218:        for(jk=1; jk <=nlstate ; jk++){
                   3219:          for(m=0, pp[jk]=0; m <=nlstate+ndeath; m++)
                   3220:            pp[jk] += freq[jk][m][i];
                   3221:        }       
                   3222:        for(jk=1,pos=0,posprop=0; jk <=nlstate ; jk++){
                   3223:          pos += pp[jk];
                   3224:          posprop += prop[jk][i];
                   3225:        }
                   3226:        for(jk=1; jk <=nlstate ; jk++){
                   3227:          if(pos>=1.e-5){
                   3228:            if(first==1)
                   3229:              printf(" %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3230:            fprintf(ficlog," %d.=%.0f prev[%d]=%.1f%%",jk,pp[jk],jk,100*pp[jk]/pos);
                   3231:          }else{
                   3232:            if(first==1)
                   3233:              printf(" %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3234:            fprintf(ficlog," %d.=%.0f prev[%d]=NaNQ%%",jk,pp[jk],jk);
                   3235:          }
                   3236:          if( i <= iagemax){
                   3237:            if(pos>=1.e-5){
                   3238:              fprintf(ficresp," %d %.5f %.0f %.0f",i,prop[jk][i]/posprop, prop[jk][i],posprop);
                   3239:              /*probs[i][jk][j1]= pp[jk]/pos;*/
                   3240:              /*printf("\ni=%d jk=%d j1=%d %.5f %.0f %.0f %f",i,jk,j1,pp[jk]/pos, pp[jk],pos,probs[i][jk][j1]);*/
                   3241:            }
                   3242:            else
                   3243:              fprintf(ficresp," %d NaNq %.0f %.0f",i,prop[jk][i],posprop);
                   3244:          }
                   3245:        }
                   3246:        
                   3247:        for(jk=-1; jk <=nlstate+ndeath; jk++)
                   3248:          for(m=-1; m <=nlstate+ndeath; m++)
                   3249:            if(freq[jk][m][i] !=0 ) {
                   3250:            if(first==1)
                   3251:              printf(" %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3252:              fprintf(ficlog," %d%d=%.0f",jk,m,freq[jk][m][i]);
                   3253:            }
                   3254:        if(i <= iagemax)
                   3255:          fprintf(ficresp,"\n");
                   3256:        if(first==1)
                   3257:          printf("Others in log...\n");
                   3258:        fprintf(ficlog,"\n");
                   3259:       }
1.145     brouard  3260:       /*}*/
1.126     brouard  3261:   }
                   3262:   dateintmean=dateintsum/k2cpt; 
                   3263:  
                   3264:   fclose(ficresp);
                   3265:   free_ma3x(freq,-5,nlstate+ndeath,-5,nlstate+ndeath, iagemin, iagemax+3);
                   3266:   free_vector(pp,1,nlstate);
                   3267:   free_matrix(prop,1,nlstate,iagemin, iagemax+3);
                   3268:   /* End of Freq */
                   3269: }
                   3270: 
                   3271: /************ Prevalence ********************/
                   3272: 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)
                   3273: {  
                   3274:   /* Compute observed prevalence between dateprev1 and dateprev2 by counting the number of people
                   3275:      in each health status at the date of interview (if between dateprev1 and dateprev2).
                   3276:      We still use firstpass and lastpass as another selection.
                   3277:   */
                   3278:  
1.164     brouard  3279:   int i, m, jk, j1, bool, z1,j;
                   3280: 
                   3281:   double **prop;
                   3282:   double posprop; 
1.126     brouard  3283:   double  y2; /* in fractional years */
                   3284:   int iagemin, iagemax;
1.145     brouard  3285:   int first; /** to stop verbosity which is redirected to log file */
1.126     brouard  3286: 
                   3287:   iagemin= (int) agemin;
                   3288:   iagemax= (int) agemax;
                   3289:   /*pp=vector(1,nlstate);*/
                   3290:   prop=matrix(1,nlstate,iagemin,iagemax+3); 
                   3291:   /*  freq=ma3x(-1,nlstate+ndeath,-1,nlstate+ndeath,iagemin,iagemax+3);*/
                   3292:   j1=0;
                   3293:   
1.145     brouard  3294:   /*j=cptcoveff;*/
1.126     brouard  3295:   if (cptcovn<1) {j=1;ncodemax[1]=1;}
                   3296:   
1.145     brouard  3297:   first=1;
                   3298:   for(j1=1; j1<= (int) pow(2,cptcoveff);j1++){
                   3299:     /*for(i1=1; i1<=ncodemax[k1];i1++){
                   3300:       j1++;*/
1.126     brouard  3301:       
                   3302:       for (i=1; i<=nlstate; i++)  
                   3303:        for(m=iagemin; m <= iagemax+3; m++)
                   3304:          prop[i][m]=0.0;
                   3305:      
                   3306:       for (i=1; i<=imx; i++) { /* Each individual */
                   3307:        bool=1;
                   3308:        if  (cptcovn>0) {
                   3309:          for (z1=1; z1<=cptcoveff; z1++) 
1.198     brouard  3310:            if (covar[Tvaraff[z1]][i]!= nbcode[Tvaraff[z1]][codtabm(j1,z1)]) 
1.126     brouard  3311:              bool=0;
                   3312:        } 
                   3313:        if (bool==1) { 
                   3314:          for(m=firstpass; m<=lastpass; m++){/* Other selection (we can limit to certain interviews*/
                   3315:            y2=anint[m][i]+(mint[m][i]/12.); /* Fractional date in year */
                   3316:            if ((y2>=dateprev1) && (y2<=dateprev2)) { /* Here is the main selection (fractional years) */
                   3317:              if(agev[m][i]==0) agev[m][i]=iagemax+1;
                   3318:              if(agev[m][i]==1) agev[m][i]=iagemax+2;
                   3319:              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); 
                   3320:              if (s[m][i]>0 && s[m][i]<=nlstate) { 
                   3321:                /*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]]);*/
                   3322:                prop[s[m][i]][(int)agev[m][i]] += weight[i];
                   3323:                prop[s[m][i]][iagemax+3] += weight[i]; 
                   3324:              } 
                   3325:            }
                   3326:          } /* end selection of waves */
                   3327:        }
                   3328:       }
                   3329:       for(i=iagemin; i <= iagemax+3; i++){  
                   3330:        for(jk=1,posprop=0; jk <=nlstate ; jk++) { 
                   3331:          posprop += prop[jk][i]; 
                   3332:        } 
1.145     brouard  3333:        
1.126     brouard  3334:        for(jk=1; jk <=nlstate ; jk++){     
                   3335:          if( i <=  iagemax){ 
                   3336:            if(posprop>=1.e-5){ 
                   3337:              probs[i][jk][j1]= prop[jk][i]/posprop;
1.145     brouard  3338:            } else{
                   3339:              if(first==1){
                   3340:                first=0;
                   3341:                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]);
                   3342:              }
                   3343:            }
1.126     brouard  3344:          } 
                   3345:        }/* end jk */ 
                   3346:       }/* end i */ 
1.145     brouard  3347:     /*} *//* end i1 */
                   3348:   } /* end j1 */
1.126     brouard  3349:   
                   3350:   /*  free_ma3x(freq,-1,nlstate+ndeath,-1,nlstate+ndeath, iagemin, iagemax+3);*/
                   3351:   /*free_vector(pp,1,nlstate);*/
                   3352:   free_matrix(prop,1,nlstate, iagemin,iagemax+3);
                   3353: }  /* End of prevalence */
                   3354: 
                   3355: /************* Waves Concatenation ***************/
                   3356: 
                   3357: 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)
                   3358: {
                   3359:   /* Concatenates waves: wav[i] is the number of effective (useful waves) of individual i.
                   3360:      Death is a valid wave (if date is known).
                   3361:      mw[mi][i] is the mi (mi=1 to wav[i])  effective wave of individual i
                   3362:      dh[m][i] or dh[mw[mi][i]][i] is the delay between two effective waves m=mw[mi][i]
                   3363:      and mw[mi+1][i]. dh depends on stepm.
                   3364:      */
                   3365: 
                   3366:   int i, mi, m;
                   3367:   /* int j, k=0,jk, ju, jl,jmin=1e+5, jmax=-1;
                   3368:      double sum=0., jmean=0.;*/
                   3369:   int first;
                   3370:   int j, k=0,jk, ju, jl;
                   3371:   double sum=0.;
                   3372:   first=0;
1.164     brouard  3373:   jmin=100000;
1.126     brouard  3374:   jmax=-1;
                   3375:   jmean=0.;
                   3376:   for(i=1; i<=imx; i++){
                   3377:     mi=0;
                   3378:     m=firstpass;
                   3379:     while(s[m][i] <= nlstate){
                   3380:       if(s[m][i]>=1 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5)
                   3381:        mw[++mi][i]=m;
                   3382:       if(m >=lastpass)
                   3383:        break;
                   3384:       else
                   3385:        m++;
                   3386:     }/* end while */
                   3387:     if (s[m][i] > nlstate){
                   3388:       mi++;    /* Death is another wave */
                   3389:       /* if(mi==0)  never been interviewed correctly before death */
                   3390:         /* Only death is a correct wave */
                   3391:       mw[mi][i]=m;
                   3392:     }
                   3393: 
                   3394:     wav[i]=mi;
                   3395:     if(mi==0){
                   3396:       nbwarn++;
                   3397:       if(first==0){
                   3398:        printf("Warning! No valid information for individual %ld line=%d (skipped) and may be others, see log file\n",num[i],i);
                   3399:        first=1;
                   3400:       }
                   3401:       if(first==1){
                   3402:        fprintf(ficlog,"Warning! No valid information for individual %ld line=%d (skipped)\n",num[i],i);
                   3403:       }
                   3404:     } /* end mi==0 */
                   3405:   } /* End individuals */
                   3406: 
                   3407:   for(i=1; i<=imx; i++){
                   3408:     for(mi=1; mi<wav[i];mi++){
                   3409:       if (stepm <=0)
                   3410:        dh[mi][i]=1;
                   3411:       else{
                   3412:        if (s[mw[mi+1][i]][i] > nlstate) { /* A death */
                   3413:          if (agedc[i] < 2*AGESUP) {
                   3414:            j= rint(agedc[i]*12-agev[mw[mi][i]][i]*12); 
                   3415:            if(j==0) j=1;  /* Survives at least one month after exam */
                   3416:            else if(j<0){
                   3417:              nberr++;
                   3418:              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]);
                   3419:              j=1; /* Temporary Dangerous patch */
                   3420:              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);
                   3421:              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]);
                   3422:              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);
                   3423:            }
                   3424:            k=k+1;
                   3425:            if (j >= jmax){
                   3426:              jmax=j;
                   3427:              ijmax=i;
                   3428:            }
                   3429:            if (j <= jmin){
                   3430:              jmin=j;
                   3431:              ijmin=i;
                   3432:            }
                   3433:            sum=sum+j;
                   3434:            /*if (j<0) printf("j=%d num=%d \n",j,i);*/
                   3435:            /*    printf("%d %d %d %d\n", s[mw[mi][i]][i] ,s[mw[mi+1][i]][i],j,i);*/
                   3436:          }
                   3437:        }
                   3438:        else{
                   3439:          j= rint( (agev[mw[mi+1][i]][i]*12 - agev[mw[mi][i]][i]*12));
                   3440: /*       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]); */
                   3441: 
                   3442:          k=k+1;
                   3443:          if (j >= jmax) {
                   3444:            jmax=j;
                   3445:            ijmax=i;
                   3446:          }
                   3447:          else if (j <= jmin){
                   3448:            jmin=j;
                   3449:            ijmin=i;
                   3450:          }
                   3451:          /*        if (j<10) printf("j=%d jmin=%d num=%d ",j,jmin,i); */
                   3452:          /*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]);*/
                   3453:          if(j<0){
                   3454:            nberr++;
                   3455:            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]);
                   3456:            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]);
                   3457:          }
                   3458:          sum=sum+j;
                   3459:        }
                   3460:        jk= j/stepm;
                   3461:        jl= j -jk*stepm;
                   3462:        ju= j -(jk+1)*stepm;
                   3463:        if(mle <=1){ /* only if we use a the linear-interpoloation pseudo-likelihood */
                   3464:          if(jl==0){
                   3465:            dh[mi][i]=jk;
                   3466:            bh[mi][i]=0;
                   3467:          }else{ /* We want a negative bias in order to only have interpolation ie
1.136     brouard  3468:                  * to avoid the price of an extra matrix product in likelihood */
1.126     brouard  3469:            dh[mi][i]=jk+1;
                   3470:            bh[mi][i]=ju;
                   3471:          }
                   3472:        }else{
                   3473:          if(jl <= -ju){
                   3474:            dh[mi][i]=jk;
                   3475:            bh[mi][i]=jl;       /* bias is positive if real duration
                   3476:                                 * is higher than the multiple of stepm and negative otherwise.
                   3477:                                 */
                   3478:          }
                   3479:          else{
                   3480:            dh[mi][i]=jk+1;
                   3481:            bh[mi][i]=ju;
                   3482:          }
                   3483:          if(dh[mi][i]==0){
                   3484:            dh[mi][i]=1; /* At least one step */
                   3485:            bh[mi][i]=ju; /* At least one step */
                   3486:            /*  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);*/
                   3487:          }
                   3488:        } /* end if mle */
                   3489:       }
                   3490:     } /* end wave */
                   3491:   }
                   3492:   jmean=sum/k;
                   3493:   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  3494:   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  3495:  }
                   3496: 
                   3497: /*********** Tricode ****************************/
1.145     brouard  3498: void tricode(int *Tvar, int **nbcode, int imx, int *Ndum)
1.126     brouard  3499: {
1.144     brouard  3500:   /**< Uses cptcovn+2*cptcovprod as the number of covariates */
                   3501:   /*     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  3502:    * Boring subroutine which should only output nbcode[Tvar[j]][k]
1.145     brouard  3503:    * Tvar[5] in V2+V1+V3*age+V2*V4 is 2 (V2)
1.169     brouard  3504:    * nbcode[Tvar[j]][1]= 
1.144     brouard  3505:   */
1.130     brouard  3506: 
1.145     brouard  3507:   int ij=1, k=0, j=0, i=0, maxncov=NCOVMAX;
1.136     brouard  3508:   int modmaxcovj=0; /* Modality max of covariates j */
1.145     brouard  3509:   int cptcode=0; /* Modality max of covariates j */
                   3510:   int modmincovj=0; /* Modality min of covariates j */
                   3511: 
                   3512: 
1.126     brouard  3513:   cptcoveff=0; 
                   3514:  
1.144     brouard  3515:   for (k=1; k <= maxncov; k++) ncodemax[k]=0; /* Horrible constant again replaced by NCOVMAX */
1.126     brouard  3516: 
1.145     brouard  3517:   /* Loop on covariates without age and products */
1.186     brouard  3518:   for (j=1; j<=(cptcovs); j++) { /* From model V1 + V2*age+ V3 + V3*V4 keeps V1 + V3 = 2 only */
1.192     brouard  3519:     for (k=-1; k < maxncov; k++) Ndum[k]=0;
1.186     brouard  3520:     for (i=1; i<=imx; i++) { /* Loop on individuals: reads the data file to get the maximum value of the 
1.136     brouard  3521:                               modality of this covariate Vj*/ 
1.145     brouard  3522:       ij=(int)(covar[Tvar[j]][i]); /* ij=0 or 1 or -1. Value of the covariate Tvar[j] for individual i
                   3523:                                    * If product of Vn*Vm, still boolean *:
                   3524:                                    * If it was coded 1, 2, 3, 4 should be splitted into 3 boolean variables
                   3525:                                    * 1 => 0 0 0, 2 => 0 0 1, 3 => 0 1 1, 4=1 0 0   */
                   3526:       /* Finds for covariate j, n=Tvar[j] of Vn . ij is the
1.136     brouard  3527:                                      modality of the nth covariate of individual i. */
1.145     brouard  3528:       if (ij > modmaxcovj)
                   3529:         modmaxcovj=ij; 
                   3530:       else if (ij < modmincovj) 
                   3531:        modmincovj=ij; 
                   3532:       if ((ij < -1) && (ij > NCOVMAX)){
                   3533:        printf( "Error: minimal is less than -1 or maximal is bigger than %d. Exiting. \n", NCOVMAX );
                   3534:        exit(1);
                   3535:       }else
1.136     brouard  3536:       Ndum[ij]++; /*counts and stores the occurence of this modality 0, 1, -1*/
1.145     brouard  3537:       /*  If coded 1, 2, 3 , counts the number of 1 Ndum[1], number of 2, Ndum[2], etc */
1.126     brouard  3538:       /*printf("i=%d ij=%d Ndum[ij]=%d imx=%d",i,ij,Ndum[ij],imx);*/
1.136     brouard  3539:       /* getting the maximum value of the modality of the covariate
                   3540:         (should be 0 or 1 now) Tvar[j]. If V=sex and male is coded 0 and
                   3541:         female is 1, then modmaxcovj=1.*/
1.192     brouard  3542:     } /* end for loop on individuals i */
1.145     brouard  3543:     printf(" Minimal and maximal values of %d th covariate V%d: min=%d max=%d \n", j, Tvar[j], modmincovj, modmaxcovj);
1.192     brouard  3544:     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  3545:     cptcode=modmaxcovj;
1.137     brouard  3546:     /* Ndum[0] = frequency of 0 for model-covariate j, Ndum[1] frequency of 1 etc. */
1.145     brouard  3547:    /*for (i=0; i<=cptcode; i++) {*/
1.192     brouard  3548:     for (k=modmincovj;  k<=modmaxcovj; k++) { /* k=-1 ? 0 and 1*//* For each value k of the modality of model-cov j */
                   3549:       printf("Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3550:       fprintf(ficlog, "Frequencies of covariates %d ie V%d with value %d: %d\n", j, Tvar[j], k, Ndum[k]);
                   3551:       if( Ndum[k] != 0 ){ /* Counts if nobody answered modality k ie empty modality, we skip it and reorder */
                   3552:        if( k != -1){
                   3553:          ncodemax[j]++;  /* ncodemax[j]= Number of modalities of the j th
                   3554:                             covariate for which somebody answered excluding 
                   3555:                             undefined. Usually 2: 0 and 1. */
                   3556:        }
                   3557:        ncodemaxwundef[j]++; /* ncodemax[j]= Number of modalities of the j th
                   3558:                             covariate for which somebody answered including 
                   3559:                             undefined. Usually 3: -1, 0 and 1. */
1.145     brouard  3560:       }
                   3561:       /* In fact  ncodemax[j]=2 (dichotom. variables only) but it could be more for
                   3562:         historical reasons: 3 if coded 1, 2, 3 and 4 and Ndum[2]=0 */
1.131     brouard  3563:     } /* Ndum[-1] number of undefined modalities */
1.126     brouard  3564: 
1.136     brouard  3565:     /* j is a covariate, n=Tvar[j] of Vn; Fills nbcode */
1.186     brouard  3566:     /* For covariate j, modalities could be 1, 2, 3, 4, 5, 6, 7. 
                   3567:        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  3568:        modmincovj=3; modmaxcovj = 7;
1.186     brouard  3569:        There are only 3 modalities non empty 3, 6, 7 (or 2 if 27 is too few) : ncodemax[j]=3;
                   3570:        which will be coded 0, 1, 2 which in binary on 2=3-1 digits are 0=00 1=01, 2=10;
                   3571:        defining two dummy variables: variables V1_1 and V1_2.
1.145     brouard  3572:        nbcode[Tvar[j]][ij]=k;
                   3573:        nbcode[Tvar[j]][1]=0;
                   3574:        nbcode[Tvar[j]][2]=1;
                   3575:        nbcode[Tvar[j]][3]=2;
1.197     brouard  3576:        To be continued (not working yet).
1.145     brouard  3577:     */
1.197     brouard  3578:     ij=0; /* ij is similar to i but can jump over null modalities */
                   3579:     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*/
                   3580:        if (Ndum[i] == 0) { /* If nobody responded to this modality k */
1.192     brouard  3581:          break;
                   3582:        }
                   3583:        ij++;
1.197     brouard  3584:        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  3585:        cptcode = ij; /* New max modality for covar j */
                   3586:     } /* end of loop on modality i=-1 to 1 or more */
                   3587:       
                   3588:     /*   for (k=0; k<= cptcode; k++) { /\* k=-1 ? k=0 to 1 *\//\* Could be 1 to 4 *\//\* cptcode=modmaxcovj *\/ */
                   3589:     /*         /\*recode from 0 *\/ */
                   3590:     /*                                      k is a modality. If we have model=V1+V1*sex  */
                   3591:     /*                                      then: nbcode[1][1]=0 ; nbcode[1][2]=1; nbcode[2][1]=0 ; nbcode[2][2]=1; */
                   3592:     /*                                   But if some modality were not used, it is recoded from 0 to a newer modmaxcovj=cptcode *\/ */
                   3593:     /*         } */
                   3594:     /*         /\* cptcode = ij; *\/ /\* New max modality for covar j *\/ */
                   3595:     /*         if (ij > ncodemax[j]) { */
                   3596:     /*           printf( " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]);  */
                   3597:     /*           fprintf(ficlog, " Error ij=%d > ncodemax[%d]=%d\n", ij, j, ncodemax[j]); */
                   3598:     /*           break; */
                   3599:     /*         } */
                   3600:     /*   }  /\* end of loop on modality k *\/ */
1.137     brouard  3601:   } /* end of loop on model-covariate j. nbcode[Tvarj][1]=0 and nbcode[Tvarj][2]=1 sets the value of covariate j*/  
                   3602:   
1.145     brouard  3603:  for (k=-1; k< maxncov; k++) Ndum[k]=0; 
1.137     brouard  3604:   
1.187     brouard  3605:   for (i=1; i<=ncovmodel-2-nagesqr; i++) { /* -2, cste and age and eventually age*age */ 
1.145     brouard  3606:    /* Listing of all covariables in statement model to see if some covariates appear twice. For example, V1 appears twice in V1+V1*V2.*/ 
                   3607:    ij=Tvar[i]; /* Tvar might be -1 if status was unknown */ 
1.187     brouard  3608:    Ndum[ij]++; /* Might be supersed V1 + V1*age */
1.145     brouard  3609:  } 
1.126     brouard  3610: 
1.192     brouard  3611:  ij=0;
1.145     brouard  3612:  for (i=0; i<=  maxncov-1; i++) { /* modmaxcovj is unknown here. Only Ndum[2(V2),3(age*V3), 5(V3*V2) 6(V1*V4) */
                   3613:    /*printf("Ndum[%d]=%d\n",i, Ndum[i]);*/
1.126     brouard  3614:    if((Ndum[i]!=0) && (i<=ncovcol)){
1.192     brouard  3615:      ij++;
1.145     brouard  3616:      /*printf("diff Ndum[%d]=%d\n",i, Ndum[i]);*/
                   3617:      Tvaraff[ij]=i; /*For printing (unclear) */
1.192     brouard  3618:    }else{
                   3619:        /* Tvaraff[ij]=0; */
                   3620:    }
1.126     brouard  3621:  }
1.192     brouard  3622:  /* ij--; */
1.144     brouard  3623:  cptcoveff=ij; /*Number of total covariates*/
1.145     brouard  3624: 
1.126     brouard  3625: }
                   3626: 
1.145     brouard  3627: 
1.126     brouard  3628: /*********** Health Expectancies ****************/
                   3629: 
1.127     brouard  3630: 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  3631: 
                   3632: {
                   3633:   /* Health expectancies, no variances */
1.164     brouard  3634:   int i, j, nhstepm, hstepm, h, nstepm;
1.126     brouard  3635:   int nhstepma, nstepma; /* Decreasing with age */
                   3636:   double age, agelim, hf;
                   3637:   double ***p3mat;
                   3638:   double eip;
                   3639: 
                   3640:   pstamp(ficreseij);
                   3641:   fprintf(ficreseij,"# (a) Life expectancies by health status at initial age and (b) health expectancies by health status at initial age\n");
                   3642:   fprintf(ficreseij,"# Age");
                   3643:   for(i=1; i<=nlstate;i++){
                   3644:     for(j=1; j<=nlstate;j++){
                   3645:       fprintf(ficreseij," e%1d%1d ",i,j);
                   3646:     }
                   3647:     fprintf(ficreseij," e%1d. ",i);
                   3648:   }
                   3649:   fprintf(ficreseij,"\n");
                   3650: 
                   3651:   
                   3652:   if(estepm < stepm){
                   3653:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3654:   }
                   3655:   else  hstepm=estepm;   
                   3656:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3657:    * This is mainly to measure the difference between two models: for example
                   3658:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3659:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3660:    * progression in between and thus overestimating or underestimating according
                   3661:    * to the curvature of the survival function. If, for the same date, we 
                   3662:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3663:    * to compare the new estimate of Life expectancy with the same linear 
                   3664:    * hypothesis. A more precise result, taking into account a more precise
                   3665:    * curvature will be obtained if estepm is as small as stepm. */
                   3666: 
                   3667:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3668:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3669:      nhstepm is the number of hstepm from age to agelim 
                   3670:      nstepm is the number of stepm from age to agelin. 
                   3671:      Look at hpijx to understand the reason of that which relies in memory size
                   3672:      and note for a fixed period like estepm months */
                   3673:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3674:      survival function given by stepm (the optimization length). Unfortunately it
                   3675:      means that if the survival funtion is printed only each two years of age and if
                   3676:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3677:      results. So we changed our mind and took the option of the best precision.
                   3678:   */
                   3679:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3680: 
                   3681:   agelim=AGESUP;
                   3682:   /* If stepm=6 months */
                   3683:     /* Computed by stepm unit matrices, product of hstepm matrices, stored
                   3684:        in an array of nhstepm length: nhstepm=10, hstepm=4, stepm=6 months */
                   3685:     
                   3686: /* nhstepm age range expressed in number of stepm */
                   3687:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3688:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3689:   /* if (stepm >= YEARM) hstepm=1;*/
                   3690:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3691:   p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3692: 
                   3693:   for (age=bage; age<=fage; age ++){ 
                   3694:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3695:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3696:     /* if (stepm >= YEARM) hstepm=1;*/
                   3697:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3698: 
                   3699:     /* If stepm=6 months */
                   3700:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3701:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3702:     
                   3703:     hpxij(p3mat,nhstepma,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3704:     
                   3705:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3706:     
                   3707:     printf("%d|",(int)age);fflush(stdout);
                   3708:     fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3709:     
                   3710:     /* Computing expectancies */
                   3711:     for(i=1; i<=nlstate;i++)
                   3712:       for(j=1; j<=nlstate;j++)
                   3713:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3714:          eij[i][j][(int)age] += (p3mat[i][j][h]+p3mat[i][j][h+1])/2.0*hf;
                   3715:          
                   3716:          /* 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]);*/
                   3717: 
                   3718:        }
                   3719: 
                   3720:     fprintf(ficreseij,"%3.0f",age );
                   3721:     for(i=1; i<=nlstate;i++){
                   3722:       eip=0;
                   3723:       for(j=1; j<=nlstate;j++){
                   3724:        eip +=eij[i][j][(int)age];
                   3725:        fprintf(ficreseij,"%9.4f", eij[i][j][(int)age] );
                   3726:       }
                   3727:       fprintf(ficreseij,"%9.4f", eip );
                   3728:     }
                   3729:     fprintf(ficreseij,"\n");
                   3730:     
                   3731:   }
                   3732:   free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3733:   printf("\n");
                   3734:   fprintf(ficlog,"\n");
                   3735:   
                   3736: }
                   3737: 
1.127     brouard  3738: 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  3739: 
                   3740: {
                   3741:   /* Covariances of health expectancies eij and of total life expectancies according
                   3742:    to initial status i, ei. .
                   3743:   */
                   3744:   int i, j, nhstepm, hstepm, h, nstepm, k, cptj, cptj2, i2, j2, ij, ji;
                   3745:   int nhstepma, nstepma; /* Decreasing with age */
                   3746:   double age, agelim, hf;
                   3747:   double ***p3matp, ***p3matm, ***varhe;
                   3748:   double **dnewm,**doldm;
                   3749:   double *xp, *xm;
                   3750:   double **gp, **gm;
                   3751:   double ***gradg, ***trgradg;
                   3752:   int theta;
                   3753: 
                   3754:   double eip, vip;
                   3755: 
                   3756:   varhe=ma3x(1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int) fage);
                   3757:   xp=vector(1,npar);
                   3758:   xm=vector(1,npar);
                   3759:   dnewm=matrix(1,nlstate*nlstate,1,npar);
                   3760:   doldm=matrix(1,nlstate*nlstate,1,nlstate*nlstate);
                   3761:   
                   3762:   pstamp(ficresstdeij);
                   3763:   fprintf(ficresstdeij,"# Health expectancies with standard errors\n");
                   3764:   fprintf(ficresstdeij,"# Age");
                   3765:   for(i=1; i<=nlstate;i++){
                   3766:     for(j=1; j<=nlstate;j++)
                   3767:       fprintf(ficresstdeij," e%1d%1d (SE)",i,j);
                   3768:     fprintf(ficresstdeij," e%1d. ",i);
                   3769:   }
                   3770:   fprintf(ficresstdeij,"\n");
                   3771: 
                   3772:   pstamp(ficrescveij);
                   3773:   fprintf(ficrescveij,"# Subdiagonal matrix of covariances of health expectancies by age: cov(eij,ekl)\n");
                   3774:   fprintf(ficrescveij,"# Age");
                   3775:   for(i=1; i<=nlstate;i++)
                   3776:     for(j=1; j<=nlstate;j++){
                   3777:       cptj= (j-1)*nlstate+i;
                   3778:       for(i2=1; i2<=nlstate;i2++)
                   3779:        for(j2=1; j2<=nlstate;j2++){
                   3780:          cptj2= (j2-1)*nlstate+i2;
                   3781:          if(cptj2 <= cptj)
                   3782:            fprintf(ficrescveij,"  %1d%1d,%1d%1d",i,j,i2,j2);
                   3783:        }
                   3784:     }
                   3785:   fprintf(ficrescveij,"\n");
                   3786:   
                   3787:   if(estepm < stepm){
                   3788:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   3789:   }
                   3790:   else  hstepm=estepm;   
                   3791:   /* We compute the life expectancy from trapezoids spaced every estepm months
                   3792:    * This is mainly to measure the difference between two models: for example
                   3793:    * if stepm=24 months pijx are given only every 2 years and by summing them
                   3794:    * we are calculating an estimate of the Life Expectancy assuming a linear 
                   3795:    * progression in between and thus overestimating or underestimating according
                   3796:    * to the curvature of the survival function. If, for the same date, we 
                   3797:    * estimate the model with stepm=1 month, we can keep estepm to 24 months
                   3798:    * to compare the new estimate of Life expectancy with the same linear 
                   3799:    * hypothesis. A more precise result, taking into account a more precise
                   3800:    * curvature will be obtained if estepm is as small as stepm. */
                   3801: 
                   3802:   /* For example we decided to compute the life expectancy with the smallest unit */
                   3803:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   3804:      nhstepm is the number of hstepm from age to agelim 
                   3805:      nstepm is the number of stepm from age to agelin. 
                   3806:      Look at hpijx to understand the reason of that which relies in memory size
                   3807:      and note for a fixed period like estepm months */
                   3808:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   3809:      survival function given by stepm (the optimization length). Unfortunately it
                   3810:      means that if the survival funtion is printed only each two years of age and if
                   3811:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   3812:      results. So we changed our mind and took the option of the best precision.
                   3813:   */
                   3814:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   3815: 
                   3816:   /* If stepm=6 months */
                   3817:   /* nhstepm age range expressed in number of stepm */
                   3818:   agelim=AGESUP;
                   3819:   nstepm=(int) rint((agelim-bage)*YEARM/stepm); 
                   3820:   /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3821:   /* if (stepm >= YEARM) hstepm=1;*/
                   3822:   nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   3823:   
                   3824:   p3matp=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3825:   p3matm=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3826:   gradg=ma3x(0,nhstepm,1,npar,1,nlstate*nlstate);
                   3827:   trgradg =ma3x(0,nhstepm,1,nlstate*nlstate,1,npar);
                   3828:   gp=matrix(0,nhstepm,1,nlstate*nlstate);
                   3829:   gm=matrix(0,nhstepm,1,nlstate*nlstate);
                   3830: 
                   3831:   for (age=bage; age<=fage; age ++){ 
                   3832:     nstepma=(int) rint((agelim-bage)*YEARM/stepm); /* Biggest nstepm */
                   3833:     /* Typically if 20 years nstepm = 20*12/6=40 stepm */ 
                   3834:     /* if (stepm >= YEARM) hstepm=1;*/
                   3835:     nhstepma = nstepma/hstepm;/* Expressed in hstepm, typically nhstepma=40/4=10 */
                   3836: 
                   3837:     /* If stepm=6 months */
                   3838:     /* Computed by stepm unit matrices, product of hstepma matrices, stored
                   3839:        in an array of nhstepma length: nhstepma=10, hstepm=4, stepm=6 months */
                   3840:     
                   3841:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   3842: 
                   3843:     /* Computing  Variances of health expectancies */
                   3844:     /* Gradient is computed with plus gp and minus gm. Code is duplicated in order to
                   3845:        decrease memory allocation */
                   3846:     for(theta=1; theta <=npar; theta++){
                   3847:       for(i=1; i<=npar; i++){ 
                   3848:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   3849:        xm[i] = x[i] - (i==theta ?delti[theta]:0);
                   3850:       }
                   3851:       hpxij(p3matp,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, cij);  
                   3852:       hpxij(p3matm,nhstepm,age,hstepm,xm,nlstate,stepm,oldm,savm, cij);  
                   3853:   
                   3854:       for(j=1; j<= nlstate; j++){
                   3855:        for(i=1; i<=nlstate; i++){
                   3856:          for(h=0; h<=nhstepm-1; h++){
                   3857:            gp[h][(j-1)*nlstate + i] = (p3matp[i][j][h]+p3matp[i][j][h+1])/2.;
                   3858:            gm[h][(j-1)*nlstate + i] = (p3matm[i][j][h]+p3matm[i][j][h+1])/2.;
                   3859:          }
                   3860:        }
                   3861:       }
                   3862:      
                   3863:       for(ij=1; ij<= nlstate*nlstate; ij++)
                   3864:        for(h=0; h<=nhstepm-1; h++){
                   3865:          gradg[h][theta][ij]= (gp[h][ij]-gm[h][ij])/2./delti[theta];
                   3866:        }
                   3867:     }/* End theta */
                   3868:     
                   3869:     
                   3870:     for(h=0; h<=nhstepm-1; h++)
                   3871:       for(j=1; j<=nlstate*nlstate;j++)
                   3872:        for(theta=1; theta <=npar; theta++)
                   3873:          trgradg[h][j][theta]=gradg[h][theta][j];
                   3874:     
                   3875: 
                   3876:      for(ij=1;ij<=nlstate*nlstate;ij++)
                   3877:       for(ji=1;ji<=nlstate*nlstate;ji++)
                   3878:        varhe[ij][ji][(int)age] =0.;
                   3879: 
                   3880:      printf("%d|",(int)age);fflush(stdout);
                   3881:      fprintf(ficlog,"%d|",(int)age);fflush(ficlog);
                   3882:      for(h=0;h<=nhstepm-1;h++){
                   3883:       for(k=0;k<=nhstepm-1;k++){
                   3884:        matprod2(dnewm,trgradg[h],1,nlstate*nlstate,1,npar,1,npar,matcov);
                   3885:        matprod2(doldm,dnewm,1,nlstate*nlstate,1,npar,1,nlstate*nlstate,gradg[k]);
                   3886:        for(ij=1;ij<=nlstate*nlstate;ij++)
                   3887:          for(ji=1;ji<=nlstate*nlstate;ji++)
                   3888:            varhe[ij][ji][(int)age] += doldm[ij][ji]*hf*hf;
                   3889:       }
                   3890:     }
                   3891: 
                   3892:     /* Computing expectancies */
                   3893:     hpxij(p3matm,nhstepm,age,hstepm,x,nlstate,stepm,oldm, savm, cij);  
                   3894:     for(i=1; i<=nlstate;i++)
                   3895:       for(j=1; j<=nlstate;j++)
                   3896:        for (h=0, eij[i][j][(int)age]=0; h<=nhstepm-1; h++){
                   3897:          eij[i][j][(int)age] += (p3matm[i][j][h]+p3matm[i][j][h+1])/2.0*hf;
                   3898:          
                   3899:          /* 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]);*/
                   3900: 
                   3901:        }
                   3902: 
                   3903:     fprintf(ficresstdeij,"%3.0f",age );
                   3904:     for(i=1; i<=nlstate;i++){
                   3905:       eip=0.;
                   3906:       vip=0.;
                   3907:       for(j=1; j<=nlstate;j++){
                   3908:        eip += eij[i][j][(int)age];
                   3909:        for(k=1; k<=nlstate;k++) /* Sum on j and k of cov(eij,eik) */
                   3910:          vip += varhe[(j-1)*nlstate+i][(k-1)*nlstate+i][(int)age];
                   3911:        fprintf(ficresstdeij," %9.4f (%.4f)", eij[i][j][(int)age], sqrt(varhe[(j-1)*nlstate+i][(j-1)*nlstate+i][(int)age]) );
                   3912:       }
                   3913:       fprintf(ficresstdeij," %9.4f (%.4f)", eip, sqrt(vip));
                   3914:     }
                   3915:     fprintf(ficresstdeij,"\n");
                   3916: 
                   3917:     fprintf(ficrescveij,"%3.0f",age );
                   3918:     for(i=1; i<=nlstate;i++)
                   3919:       for(j=1; j<=nlstate;j++){
                   3920:        cptj= (j-1)*nlstate+i;
                   3921:        for(i2=1; i2<=nlstate;i2++)
                   3922:          for(j2=1; j2<=nlstate;j2++){
                   3923:            cptj2= (j2-1)*nlstate+i2;
                   3924:            if(cptj2 <= cptj)
                   3925:              fprintf(ficrescveij," %.4f", varhe[cptj][cptj2][(int)age]);
                   3926:          }
                   3927:       }
                   3928:     fprintf(ficrescveij,"\n");
                   3929:    
                   3930:   }
                   3931:   free_matrix(gm,0,nhstepm,1,nlstate*nlstate);
                   3932:   free_matrix(gp,0,nhstepm,1,nlstate*nlstate);
                   3933:   free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate*nlstate);
                   3934:   free_ma3x(trgradg,0,nhstepm,1,nlstate*nlstate,1,npar);
                   3935:   free_ma3x(p3matm,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3936:   free_ma3x(p3matp,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   3937:   printf("\n");
                   3938:   fprintf(ficlog,"\n");
                   3939: 
                   3940:   free_vector(xm,1,npar);
                   3941:   free_vector(xp,1,npar);
                   3942:   free_matrix(dnewm,1,nlstate*nlstate,1,npar);
                   3943:   free_matrix(doldm,1,nlstate*nlstate,1,nlstate*nlstate);
                   3944:   free_ma3x(varhe,1,nlstate*nlstate,1,nlstate*nlstate,(int) bage, (int)fage);
                   3945: }
                   3946: 
                   3947: /************ Variance ******************/
1.203   ! brouard  3948:  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 *ncvyear, int ij, int estepm, int cptcov, int cptcod, int popbased, int mobilav, char strstart[])
1.126     brouard  3949: {
                   3950:   /* Variance of health expectancies */
                   3951:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double ** savm,double ftolpl);*/
                   3952:   /* double **newm;*/
1.169     brouard  3953:   /* int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav)*/
                   3954:   
                   3955:   int movingaverage();
1.126     brouard  3956:   double **dnewm,**doldm;
                   3957:   double **dnewmp,**doldmp;
                   3958:   int i, j, nhstepm, hstepm, h, nstepm ;
1.164     brouard  3959:   int k;
1.126     brouard  3960:   double *xp;
                   3961:   double **gp, **gm;  /* for var eij */
                   3962:   double ***gradg, ***trgradg; /*for var eij */
                   3963:   double **gradgp, **trgradgp; /* for var p point j */
                   3964:   double *gpp, *gmp; /* for var p point j */
                   3965:   double **varppt; /* for var p point j nlstate to nlstate+ndeath */
                   3966:   double ***p3mat;
                   3967:   double age,agelim, hf;
                   3968:   double ***mobaverage;
                   3969:   int theta;
                   3970:   char digit[4];
                   3971:   char digitp[25];
                   3972: 
                   3973:   char fileresprobmorprev[FILENAMELENGTH];
                   3974: 
                   3975:   if(popbased==1){
                   3976:     if(mobilav!=0)
1.201     brouard  3977:       strcpy(digitp,"-POPULBASED-MOBILAV_");
                   3978:     else strcpy(digitp,"-POPULBASED-NOMOBIL_");
1.126     brouard  3979:   }
                   3980:   else 
1.201     brouard  3981:     strcpy(digitp,"-STABLBASED_");
1.126     brouard  3982: 
                   3983:   if (mobilav!=0) {
                   3984:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   3985:     if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   3986:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   3987:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   3988:     }
                   3989:   }
                   3990: 
1.201     brouard  3991:   strcpy(fileresprobmorprev,"PRMORPREV-"); 
1.126     brouard  3992:   sprintf(digit,"%-d",ij);
                   3993:   /*printf("DIGIT=%s, ij=%d ijr=%-d|\n",digit, ij,ij);*/
                   3994:   strcat(fileresprobmorprev,digit); /* Tvar to be done */
                   3995:   strcat(fileresprobmorprev,digitp); /* Popbased or not, mobilav or not */
1.202     brouard  3996:   strcat(fileresprobmorprev,fileresu);
1.126     brouard  3997:   if((ficresprobmorprev=fopen(fileresprobmorprev,"w"))==NULL) {
                   3998:     printf("Problem with resultfile: %s\n", fileresprobmorprev);
                   3999:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobmorprev);
                   4000:   }
                   4001:   printf("Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4002:  
                   4003:   fprintf(ficlog,"Computing total mortality p.j=w1*p1j+w2*p2j+..: result on file '%s' \n",fileresprobmorprev);
                   4004:   pstamp(ficresprobmorprev);
                   4005:   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);
                   4006:   fprintf(ficresprobmorprev,"# Age cov=%-d",ij);
                   4007:   for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4008:     fprintf(ficresprobmorprev," p.%-d SE",j);
                   4009:     for(i=1; i<=nlstate;i++)
                   4010:       fprintf(ficresprobmorprev," w%1d p%-d%-d",i,i,j);
                   4011:   }  
                   4012:   fprintf(ficresprobmorprev,"\n");
                   4013:   fprintf(ficgp,"\n# Routine varevsij");
1.200     brouard  4014:   fprintf(ficgp,"\nunset title \n");
                   4015: /* fprintf(fichtm, "#Local time at start: %s", strstart);*/
1.126     brouard  4016:   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");
                   4017:   fprintf(fichtm,"\n<br>%s  <br>\n",digitp);
                   4018: /*   } */
                   4019:   varppt = matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4020:   pstamp(ficresvij);
                   4021:   fprintf(ficresvij,"# Variance and covariance of health expectancies e.j \n#  (weighted average of eij where weights are ");
                   4022:   if(popbased==1)
1.128     brouard  4023:     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  4024:   else
                   4025:     fprintf(ficresvij,"the age specific period (stable) prevalences in each health state \n");
                   4026:   fprintf(ficresvij,"# Age");
                   4027:   for(i=1; i<=nlstate;i++)
                   4028:     for(j=1; j<=nlstate;j++)
                   4029:       fprintf(ficresvij," Cov(e.%1d, e.%1d)",i,j);
                   4030:   fprintf(ficresvij,"\n");
                   4031: 
                   4032:   xp=vector(1,npar);
                   4033:   dnewm=matrix(1,nlstate,1,npar);
                   4034:   doldm=matrix(1,nlstate,1,nlstate);
                   4035:   dnewmp= matrix(nlstate+1,nlstate+ndeath,1,npar);
                   4036:   doldmp= matrix(nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4037: 
                   4038:   gradgp=matrix(1,npar,nlstate+1,nlstate+ndeath);
                   4039:   gpp=vector(nlstate+1,nlstate+ndeath);
                   4040:   gmp=vector(nlstate+1,nlstate+ndeath);
                   4041:   trgradgp =matrix(nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
                   4042:   
                   4043:   if(estepm < stepm){
                   4044:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   4045:   }
                   4046:   else  hstepm=estepm;   
                   4047:   /* For example we decided to compute the life expectancy with the smallest unit */
                   4048:   /* hstepm beeing the number of stepms, if hstepm=1 the length of hstepm is stepm. 
                   4049:      nhstepm is the number of hstepm from age to agelim 
                   4050:      nstepm is the number of stepm from age to agelin. 
1.128     brouard  4051:      Look at function hpijx to understand why (it is linked to memory size questions) */
1.126     brouard  4052:   /* We decided (b) to get a life expectancy respecting the most precise curvature of the
                   4053:      survival function given by stepm (the optimization length). Unfortunately it
                   4054:      means that if the survival funtion is printed every two years of age and if
                   4055:      you sum them up and add 1 year (area under the trapezoids) you won't get the same 
                   4056:      results. So we changed our mind and took the option of the best precision.
                   4057:   */
                   4058:   hstepm=hstepm/stepm; /* Typically in stepm units, if stepm=6 & estepm=24 , = 24/6 months = 4 */ 
                   4059:   agelim = AGESUP;
                   4060:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4061:     nstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4062:     nhstepm = nstepm/hstepm;/* Expressed in hstepm, typically nhstepm=40/4=10 */
                   4063:     p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4064:     gradg=ma3x(0,nhstepm,1,npar,1,nlstate);
                   4065:     gp=matrix(0,nhstepm,1,nlstate);
                   4066:     gm=matrix(0,nhstepm,1,nlstate);
                   4067: 
                   4068: 
                   4069:     for(theta=1; theta <=npar; theta++){
                   4070:       for(i=1; i<=npar; i++){ /* Computes gradient x + delta*/
                   4071:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4072:       }
                   4073:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
1.203   ! brouard  4074:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4075: 
                   4076:       if (popbased==1) {
                   4077:        if(mobilav ==0){
                   4078:          for(i=1; i<=nlstate;i++)
                   4079:            prlim[i][i]=probs[(int)age][i][ij];
                   4080:        }else{ /* mobilav */ 
                   4081:          for(i=1; i<=nlstate;i++)
                   4082:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4083:        }
                   4084:       }
                   4085:   
                   4086:       for(j=1; j<= nlstate; j++){
                   4087:        for(h=0; h<=nhstepm; h++){
                   4088:          for(i=1, gp[h][j]=0.;i<=nlstate;i++)
                   4089:            gp[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4090:        }
                   4091:       }
                   4092:       /* This for computing probability of death (h=1 means
                   4093:          computed over hstepm matrices product = hstepm*stepm months) 
                   4094:          as a weighted average of prlim.
                   4095:       */
                   4096:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4097:        for(i=1,gpp[j]=0.; i<= nlstate; i++)
                   4098:          gpp[j] += prlim[i][i]*p3mat[i][j][1];
                   4099:       }    
                   4100:       /* end probability of death */
                   4101: 
                   4102:       for(i=1; i<=npar; i++) /* Computes gradient x - delta */
                   4103:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
                   4104:       hpxij(p3mat,nhstepm,age,hstepm,xp,nlstate,stepm,oldm,savm, ij);  
1.203   ! brouard  4105:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear, ij);
1.126     brouard  4106:  
                   4107:       if (popbased==1) {
                   4108:        if(mobilav ==0){
                   4109:          for(i=1; i<=nlstate;i++)
                   4110:            prlim[i][i]=probs[(int)age][i][ij];
                   4111:        }else{ /* mobilav */ 
                   4112:          for(i=1; i<=nlstate;i++)
                   4113:            prlim[i][i]=mobaverage[(int)age][i][ij];
                   4114:        }
                   4115:       }
                   4116: 
1.128     brouard  4117:       for(j=1; j<= nlstate; j++){  /* Sum of wi * eij = e.j */
1.126     brouard  4118:        for(h=0; h<=nhstepm; h++){
                   4119:          for(i=1, gm[h][j]=0.;i<=nlstate;i++)
                   4120:            gm[h][j] += prlim[i][i]*p3mat[i][j][h];
                   4121:        }
                   4122:       }
                   4123:       /* This for computing probability of death (h=1 means
                   4124:          computed over hstepm matrices product = hstepm*stepm months) 
                   4125:          as a weighted average of prlim.
                   4126:       */
                   4127:       for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4128:        for(i=1,gmp[j]=0.; i<= nlstate; i++)
                   4129:          gmp[j] += prlim[i][i]*p3mat[i][j][1];
                   4130:       }    
                   4131:       /* end probability of death */
                   4132: 
                   4133:       for(j=1; j<= nlstate; j++) /* vareij */
                   4134:        for(h=0; h<=nhstepm; h++){
                   4135:          gradg[h][theta][j]= (gp[h][j]-gm[h][j])/2./delti[theta];
                   4136:        }
                   4137: 
                   4138:       for(j=nlstate+1; j<= nlstate+ndeath; j++){ /* var mu */
                   4139:        gradgp[theta][j]= (gpp[j]-gmp[j])/2./delti[theta];
                   4140:       }
                   4141: 
                   4142:     } /* End theta */
                   4143: 
                   4144:     trgradg =ma3x(0,nhstepm,1,nlstate,1,npar); /* veij */
                   4145: 
                   4146:     for(h=0; h<=nhstepm; h++) /* veij */
                   4147:       for(j=1; j<=nlstate;j++)
                   4148:        for(theta=1; theta <=npar; theta++)
                   4149:          trgradg[h][j][theta]=gradg[h][theta][j];
                   4150: 
                   4151:     for(j=nlstate+1; j<=nlstate+ndeath;j++) /* mu */
                   4152:       for(theta=1; theta <=npar; theta++)
                   4153:        trgradgp[j][theta]=gradgp[theta][j];
                   4154:   
                   4155: 
                   4156:     hf=hstepm*stepm/YEARM;  /* Duration of hstepm expressed in year unit. */
                   4157:     for(i=1;i<=nlstate;i++)
                   4158:       for(j=1;j<=nlstate;j++)
                   4159:        vareij[i][j][(int)age] =0.;
                   4160: 
                   4161:     for(h=0;h<=nhstepm;h++){
                   4162:       for(k=0;k<=nhstepm;k++){
                   4163:        matprod2(dnewm,trgradg[h],1,nlstate,1,npar,1,npar,matcov);
                   4164:        matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg[k]);
                   4165:        for(i=1;i<=nlstate;i++)
                   4166:          for(j=1;j<=nlstate;j++)
                   4167:            vareij[i][j][(int)age] += doldm[i][j]*hf*hf;
                   4168:       }
                   4169:     }
                   4170:   
                   4171:     /* pptj */
                   4172:     matprod2(dnewmp,trgradgp,nlstate+1,nlstate+ndeath,1,npar,1,npar,matcov);
                   4173:     matprod2(doldmp,dnewmp,nlstate+1,nlstate+ndeath,1,npar,nlstate+1,nlstate+ndeath,gradgp);
                   4174:     for(j=nlstate+1;j<=nlstate+ndeath;j++)
                   4175:       for(i=nlstate+1;i<=nlstate+ndeath;i++)
                   4176:        varppt[j][i]=doldmp[j][i];
                   4177:     /* end ppptj */
                   4178:     /*  x centered again */
                   4179:     hpxij(p3mat,nhstepm,age,hstepm,x,nlstate,stepm,oldm,savm, ij);  
1.203   ! brouard  4180:     prevalim(prlim,nlstate,x,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4181:  
                   4182:     if (popbased==1) {
                   4183:       if(mobilav ==0){
                   4184:        for(i=1; i<=nlstate;i++)
                   4185:          prlim[i][i]=probs[(int)age][i][ij];
                   4186:       }else{ /* mobilav */ 
                   4187:        for(i=1; i<=nlstate;i++)
                   4188:          prlim[i][i]=mobaverage[(int)age][i][ij];
                   4189:       }
                   4190:     }
                   4191:              
                   4192:     /* This for computing probability of death (h=1 means
                   4193:        computed over hstepm (estepm) matrices product = hstepm*stepm months) 
                   4194:        as a weighted average of prlim.
                   4195:     */
                   4196:     for(j=nlstate+1;j<=nlstate+ndeath;j++){
                   4197:       for(i=1,gmp[j]=0.;i<= nlstate; i++) 
                   4198:        gmp[j] += prlim[i][i]*p3mat[i][j][1]; 
                   4199:     }    
                   4200:     /* end probability of death */
                   4201: 
                   4202:     fprintf(ficresprobmorprev,"%3d %d ",(int) age, ij);
                   4203:     for(j=nlstate+1; j<=(nlstate+ndeath);j++){
                   4204:       fprintf(ficresprobmorprev," %11.3e %11.3e",gmp[j], sqrt(varppt[j][j]));
                   4205:       for(i=1; i<=nlstate;i++){
                   4206:        fprintf(ficresprobmorprev," %11.3e %11.3e ",prlim[i][i],p3mat[i][j][1]);
                   4207:       }
                   4208:     } 
                   4209:     fprintf(ficresprobmorprev,"\n");
                   4210: 
                   4211:     fprintf(ficresvij,"%.0f ",age );
                   4212:     for(i=1; i<=nlstate;i++)
                   4213:       for(j=1; j<=nlstate;j++){
                   4214:        fprintf(ficresvij," %.4f", vareij[i][j][(int)age]);
                   4215:       }
                   4216:     fprintf(ficresvij,"\n");
                   4217:     free_matrix(gp,0,nhstepm,1,nlstate);
                   4218:     free_matrix(gm,0,nhstepm,1,nlstate);
                   4219:     free_ma3x(gradg,0,nhstepm,1,npar,1,nlstate);
                   4220:     free_ma3x(trgradg,0,nhstepm,1,nlstate,1,npar);
                   4221:     free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   4222:   } /* End age */
                   4223:   free_vector(gpp,nlstate+1,nlstate+ndeath);
                   4224:   free_vector(gmp,nlstate+1,nlstate+ndeath);
                   4225:   free_matrix(gradgp,1,npar,nlstate+1,nlstate+ndeath);
                   4226:   free_matrix(trgradgp,nlstate+1,nlstate+ndeath,1,npar); /* mu or p point j*/
1.199     brouard  4227:   /* fprintf(ficgp,"\nunset parametric;unset label; set ter png small size 320, 240"); */
                   4228:   fprintf(ficgp,"\nunset parametric;unset label; set ter svg size 640, 480");
1.126     brouard  4229:   /* for(j=nlstate+1; j<= nlstate+ndeath; j++){ *//* Only the first actually */
1.131     brouard  4230:   fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Force of mortality (year-1)\";");
1.201     brouard  4231:   fprintf(ficgp,"\nset out \"%s%s.svg\";",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4232: /*   fprintf(ficgp,"\n plot \"%s\"  u 1:($3*%6.3f) not w l 1 ",fileresprobmorprev,YEARM/estepm); */
                   4233: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)*%6.3f) t \"95\%% interval\" w l 2 ",fileresprobmorprev,YEARM/estepm); */
                   4234: /*   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)*%6.3f) not w l 2 ",fileresprobmorprev,YEARM/estepm); */
1.145     brouard  4235:   fprintf(ficgp,"\n plot \"%s\"  u 1:($3) not w l lt 1 ",subdirf(fileresprobmorprev));
1.170     brouard  4236:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3+1.96*$4)) t \"95%% interval\" w l lt 2 ",subdirf(fileresprobmorprev));
1.145     brouard  4237:   fprintf(ficgp,"\n replot \"%s\"  u 1:(($3-1.96*$4)) not w l lt 2 ",subdirf(fileresprobmorprev));
1.126     brouard  4238:   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  4239:   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  4240:   /*  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  4241: */
1.199     brouard  4242: /*   fprintf(ficgp,"\nset out \"varmuptjgr%s%s%s.svg\";replot;",digitp,optionfilefiname,digit); */
1.201     brouard  4243:   fprintf(ficgp,"\nset out;\nset out \"%s%s.svg\";replot;set out;\n",subdirf3(optionfilefiname,"VARMUPTJGR-",digitp),digit);
1.126     brouard  4244: 
                   4245:   free_vector(xp,1,npar);
                   4246:   free_matrix(doldm,1,nlstate,1,nlstate);
                   4247:   free_matrix(dnewm,1,nlstate,1,npar);
                   4248:   free_matrix(doldmp,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4249:   free_matrix(dnewmp,nlstate+1,nlstate+ndeath,1,npar);
                   4250:   free_matrix(varppt,nlstate+1,nlstate+ndeath,nlstate+1,nlstate+ndeath);
                   4251:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   4252:   fclose(ficresprobmorprev);
                   4253:   fflush(ficgp);
                   4254:   fflush(fichtm); 
                   4255: }  /* end varevsij */
                   4256: 
                   4257: /************ Variance of prevlim ******************/
1.203   ! brouard  4258:  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 *ncvyear, int ij, char strstart[])
1.126     brouard  4259: {
                   4260:   /* Variance of prevalence limit */
                   4261:   /*  double **prevalim(double **prlim, int nlstate, double *xp, double age, double **oldm, double **savm,double ftolpl);*/
1.164     brouard  4262: 
1.126     brouard  4263:   double **dnewm,**doldm;
                   4264:   int i, j, nhstepm, hstepm;
                   4265:   double *xp;
                   4266:   double *gp, *gm;
                   4267:   double **gradg, **trgradg;
                   4268:   double age,agelim;
                   4269:   int theta;
                   4270:   
                   4271:   pstamp(ficresvpl);
                   4272:   fprintf(ficresvpl,"# Standard deviation of period (stable) prevalences \n");
                   4273:   fprintf(ficresvpl,"# Age");
                   4274:   for(i=1; i<=nlstate;i++)
                   4275:       fprintf(ficresvpl," %1d-%1d",i,i);
                   4276:   fprintf(ficresvpl,"\n");
                   4277: 
                   4278:   xp=vector(1,npar);
                   4279:   dnewm=matrix(1,nlstate,1,npar);
                   4280:   doldm=matrix(1,nlstate,1,nlstate);
                   4281:   
                   4282:   hstepm=1*YEARM; /* Every year of age */
                   4283:   hstepm=hstepm/stepm; /* Typically in stepm units, if j= 2 years, = 2/6 months = 4 */ 
                   4284:   agelim = AGESUP;
                   4285:   for (age=bage; age<=fage; age ++){ /* If stepm=6 months */
                   4286:     nhstepm=(int) rint((agelim-age)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   4287:     if (stepm >= YEARM) hstepm=1;
                   4288:     nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   4289:     gradg=matrix(1,npar,1,nlstate);
                   4290:     gp=vector(1,nlstate);
                   4291:     gm=vector(1,nlstate);
                   4292: 
                   4293:     for(theta=1; theta <=npar; theta++){
                   4294:       for(i=1; i<=npar; i++){ /* Computes gradient */
                   4295:        xp[i] = x[i] + (i==theta ?delti[theta]:0);
                   4296:       }
1.203   ! brouard  4297:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4298:       for(i=1;i<=nlstate;i++)
                   4299:        gp[i] = prlim[i][i];
                   4300:     
                   4301:       for(i=1; i<=npar; i++) /* Computes gradient */
                   4302:        xp[i] = x[i] - (i==theta ?delti[theta]:0);
1.203   ! brouard  4303:       prevalim(prlim,nlstate,xp,age,oldm,savm,ftolpl,ncvyear,ij);
1.126     brouard  4304:       for(i=1;i<=nlstate;i++)
                   4305:        gm[i] = prlim[i][i];
                   4306: 
                   4307:       for(i=1;i<=nlstate;i++)
                   4308:        gradg[theta][i]= (gp[i]-gm[i])/2./delti[theta];
                   4309:     } /* End theta */
                   4310: 
                   4311:     trgradg =matrix(1,nlstate,1,npar);
                   4312: 
                   4313:     for(j=1; j<=nlstate;j++)
                   4314:       for(theta=1; theta <=npar; theta++)
                   4315:        trgradg[j][theta]=gradg[theta][j];
                   4316: 
                   4317:     for(i=1;i<=nlstate;i++)
                   4318:       varpl[i][(int)age] =0.;
                   4319:     matprod2(dnewm,trgradg,1,nlstate,1,npar,1,npar,matcov);
                   4320:     matprod2(doldm,dnewm,1,nlstate,1,npar,1,nlstate,gradg);
                   4321:     for(i=1;i<=nlstate;i++)
                   4322:       varpl[i][(int)age] = doldm[i][i]; /* Covariances are useless */
                   4323: 
                   4324:     fprintf(ficresvpl,"%.0f ",age );
                   4325:     for(i=1; i<=nlstate;i++)
                   4326:       fprintf(ficresvpl," %.5f (%.5f)",prlim[i][i],sqrt(varpl[i][(int)age]));
                   4327:     fprintf(ficresvpl,"\n");
                   4328:     free_vector(gp,1,nlstate);
                   4329:     free_vector(gm,1,nlstate);
                   4330:     free_matrix(gradg,1,npar,1,nlstate);
                   4331:     free_matrix(trgradg,1,nlstate,1,npar);
                   4332:   } /* End age */
                   4333: 
                   4334:   free_vector(xp,1,npar);
                   4335:   free_matrix(doldm,1,nlstate,1,npar);
                   4336:   free_matrix(dnewm,1,nlstate,1,nlstate);
                   4337: 
                   4338: }
                   4339: 
                   4340: /************ Variance of one-step probabilities  ******************/
                   4341: 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[])
                   4342: {
1.164     brouard  4343:   int i, j=0,  k1, l1, tj;
1.126     brouard  4344:   int k2, l2, j1,  z1;
1.164     brouard  4345:   int k=0, l;
1.145     brouard  4346:   int first=1, first1, first2;
1.126     brouard  4347:   double cv12, mu1, mu2, lc1, lc2, v12, v21, v11, v22,v1,v2, c12, tnalp;
                   4348:   double **dnewm,**doldm;
                   4349:   double *xp;
                   4350:   double *gp, *gm;
                   4351:   double **gradg, **trgradg;
                   4352:   double **mu;
1.164     brouard  4353:   double age, cov[NCOVMAX+1];
1.126     brouard  4354:   double std=2.0; /* Number of standard deviation wide of confidence ellipsoids */
                   4355:   int theta;
                   4356:   char fileresprob[FILENAMELENGTH];
                   4357:   char fileresprobcov[FILENAMELENGTH];
                   4358:   char fileresprobcor[FILENAMELENGTH];
                   4359:   double ***varpij;
                   4360: 
1.201     brouard  4361:   strcpy(fileresprob,"PROB_"); 
1.126     brouard  4362:   strcat(fileresprob,fileres);
                   4363:   if((ficresprob=fopen(fileresprob,"w"))==NULL) {
                   4364:     printf("Problem with resultfile: %s\n", fileresprob);
                   4365:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprob);
                   4366:   }
1.201     brouard  4367:   strcpy(fileresprobcov,"PROBCOV_"); 
1.202     brouard  4368:   strcat(fileresprobcov,fileresu);
1.126     brouard  4369:   if((ficresprobcov=fopen(fileresprobcov,"w"))==NULL) {
                   4370:     printf("Problem with resultfile: %s\n", fileresprobcov);
                   4371:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcov);
                   4372:   }
1.201     brouard  4373:   strcpy(fileresprobcor,"PROBCOR_"); 
1.202     brouard  4374:   strcat(fileresprobcor,fileresu);
1.126     brouard  4375:   if((ficresprobcor=fopen(fileresprobcor,"w"))==NULL) {
                   4376:     printf("Problem with resultfile: %s\n", fileresprobcor);
                   4377:     fprintf(ficlog,"Problem with resultfile: %s\n", fileresprobcor);
                   4378:   }
                   4379:   printf("Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4380:   fprintf(ficlog,"Computing standard deviation of one-step probabilities: result on file '%s' \n",fileresprob);
                   4381:   printf("Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4382:   fprintf(ficlog,"Computing matrix of variance covariance of one-step probabilities: result on file '%s' \n",fileresprobcov);
                   4383:   printf("and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4384:   fprintf(ficlog,"and correlation matrix of one-step probabilities: result on file '%s' \n",fileresprobcor);
                   4385:   pstamp(ficresprob);
                   4386:   fprintf(ficresprob,"#One-step probabilities and stand. devi in ()\n");
                   4387:   fprintf(ficresprob,"# Age");
                   4388:   pstamp(ficresprobcov);
                   4389:   fprintf(ficresprobcov,"#One-step probabilities and covariance matrix\n");
                   4390:   fprintf(ficresprobcov,"# Age");
                   4391:   pstamp(ficresprobcor);
                   4392:   fprintf(ficresprobcor,"#One-step probabilities and correlation matrix\n");
                   4393:   fprintf(ficresprobcor,"# Age");
                   4394: 
                   4395: 
                   4396:   for(i=1; i<=nlstate;i++)
                   4397:     for(j=1; j<=(nlstate+ndeath);j++){
                   4398:       fprintf(ficresprob," p%1d-%1d (SE)",i,j);
                   4399:       fprintf(ficresprobcov," p%1d-%1d ",i,j);
                   4400:       fprintf(ficresprobcor," p%1d-%1d ",i,j);
                   4401:     }  
                   4402:  /* fprintf(ficresprob,"\n");
                   4403:   fprintf(ficresprobcov,"\n");
                   4404:   fprintf(ficresprobcor,"\n");
                   4405:  */
1.131     brouard  4406:   xp=vector(1,npar);
1.126     brouard  4407:   dnewm=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4408:   doldm=matrix(1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4409:   mu=matrix(1,(nlstate)*(nlstate+ndeath), (int) bage, (int)fage);
                   4410:   varpij=ma3x(1,nlstate*(nlstate+ndeath),1,nlstate*(nlstate+ndeath),(int) bage, (int) fage);
                   4411:   first=1;
                   4412:   fprintf(ficgp,"\n# Routine varprob");
                   4413:   fprintf(fichtm,"\n<li><h4> Computing and drawing one step probabilities with their confidence intervals</h4></li>\n");
                   4414:   fprintf(fichtm,"\n");
                   4415: 
1.200     brouard  4416:   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  4417:   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);
                   4418:   fprintf(fichtmcov,"\nEllipsoids of confidence centered on point (p<inf>ij</inf>, p<inf>kl</inf>) are estimated \
1.126     brouard  4419: and drawn. It helps understanding how is the covariance between two incidences.\
                   4420:  They are expressed in year<sup>-1</sup> in order to be less dependent of stepm.<br>\n");
                   4421:   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. \
                   4422: It can be understood this way: if pij and pkl where uncorrelated the (2x2) matrix of covariance \
                   4423: would have been (1/(var pij), 0 , 0, 1/(var pkl)), and the confidence interval would be 2 \
                   4424: standard deviations wide on each axis. <br>\
                   4425:  Now, if both incidences are correlated (usual case) we diagonalised the inverse of the covariance matrix\
                   4426:  and made the appropriate rotation to look at the uncorrelated principal directions.<br>\
                   4427: To be simple, these graphs help to understand the significativity of each parameter in relation to a second other one.<br> \n");
                   4428: 
                   4429:   cov[1]=1;
1.145     brouard  4430:   /* tj=cptcoveff; */
                   4431:   tj = (int) pow(2,cptcoveff);
1.126     brouard  4432:   if (cptcovn<1) {tj=1;ncodemax[1]=1;}
                   4433:   j1=0;
1.145     brouard  4434:   for(j1=1; j1<=tj;j1++){
                   4435:     /*for(i1=1; i1<=ncodemax[t];i1++){ */
                   4436:     /*j1++;*/
1.126     brouard  4437:       if  (cptcovn>0) {
                   4438:        fprintf(ficresprob, "\n#********** Variable "); 
1.198     brouard  4439:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprob, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4440:        fprintf(ficresprob, "**********\n#\n");
                   4441:        fprintf(ficresprobcov, "\n#********** Variable "); 
1.198     brouard  4442:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcov, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4443:        fprintf(ficresprobcov, "**********\n#\n");
                   4444:        
                   4445:        fprintf(ficgp, "\n#********** Variable "); 
1.198     brouard  4446:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficgp, " V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4447:        fprintf(ficgp, "**********\n#\n");
                   4448:        
                   4449:        
                   4450:        fprintf(fichtmcov, "\n<hr  size=\"2\" color=\"#EC5E5E\">********** Variable "); 
1.198     brouard  4451:        for (z1=1; z1<=cptcoveff; z1++) fprintf(fichtm, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4452:        fprintf(fichtmcov, "**********\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4453:        
                   4454:        fprintf(ficresprobcor, "\n#********** Variable ");    
1.198     brouard  4455:        for (z1=1; z1<=cptcoveff; z1++) fprintf(ficresprobcor, "V%d=%d ",Tvaraff[z1],nbcode[Tvaraff[z1]][codtabm(j1,z1)]);
1.126     brouard  4456:        fprintf(ficresprobcor, "**********\n#");    
                   4457:       }
                   4458:       
1.145     brouard  4459:       gradg=matrix(1,npar,1,(nlstate)*(nlstate+ndeath));
                   4460:       trgradg=matrix(1,(nlstate)*(nlstate+ndeath),1,npar);
                   4461:       gp=vector(1,(nlstate)*(nlstate+ndeath));
                   4462:       gm=vector(1,(nlstate)*(nlstate+ndeath));
1.126     brouard  4463:       for (age=bage; age<=fage; age ++){ 
                   4464:        cov[2]=age;
1.187     brouard  4465:        if(nagesqr==1)
                   4466:          cov[3]= age*age;
1.126     brouard  4467:        for (k=1; k<=cptcovn;k++) {
1.200     brouard  4468:          cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,k)];
                   4469:          /*cov[2+nagesqr+k]=nbcode[Tvar[k]][codtabm(j1,Tvar[k])];*//* j1 1 2 3 4
1.145     brouard  4470:                                                         * 1  1 1 1 1
                   4471:                                                         * 2  2 1 1 1
                   4472:                                                         * 3  1 2 1 1
                   4473:                                                         */
                   4474:          /* nbcode[1][1]=0 nbcode[1][2]=1;*/
1.126     brouard  4475:        }
1.186     brouard  4476:        /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=cov[2+Tage[k]]*cov[2]; */
1.200     brouard  4477:        for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,k)]*cov[2];
1.126     brouard  4478:        for (k=1; k<=cptcovprod;k++)
1.200     brouard  4479:          cov[2+nagesqr+Tprod[k]]=nbcode[Tvard[k][1]][codtabm(ij,k)]*nbcode[Tvard[k][2]][codtabm(ij,k)];
1.126     brouard  4480:        
                   4481:     
                   4482:        for(theta=1; theta <=npar; theta++){
                   4483:          for(i=1; i<=npar; i++)
                   4484:            xp[i] = x[i] + (i==theta ?delti[theta]:(double)0);
                   4485:          
                   4486:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4487:          
                   4488:          k=0;
                   4489:          for(i=1; i<= (nlstate); i++){
                   4490:            for(j=1; j<=(nlstate+ndeath);j++){
                   4491:              k=k+1;
                   4492:              gp[k]=pmmij[i][j];
                   4493:            }
                   4494:          }
                   4495:          
                   4496:          for(i=1; i<=npar; i++)
                   4497:            xp[i] = x[i] - (i==theta ?delti[theta]:(double)0);
                   4498:     
                   4499:          pmij(pmmij,cov,ncovmodel,xp,nlstate);
                   4500:          k=0;
                   4501:          for(i=1; i<=(nlstate); i++){
                   4502:            for(j=1; j<=(nlstate+ndeath);j++){
                   4503:              k=k+1;
                   4504:              gm[k]=pmmij[i][j];
                   4505:            }
                   4506:          }
                   4507:      
                   4508:          for(i=1; i<= (nlstate)*(nlstate+ndeath); i++) 
                   4509:            gradg[theta][i]=(gp[i]-gm[i])/(double)2./delti[theta];  
                   4510:        }
                   4511: 
                   4512:        for(j=1; j<=(nlstate)*(nlstate+ndeath);j++)
                   4513:          for(theta=1; theta <=npar; theta++)
                   4514:            trgradg[j][theta]=gradg[theta][j];
                   4515:        
                   4516:        matprod2(dnewm,trgradg,1,(nlstate)*(nlstate+ndeath),1,npar,1,npar,matcov); 
                   4517:        matprod2(doldm,dnewm,1,(nlstate)*(nlstate+ndeath),1,npar,1,(nlstate)*(nlstate+ndeath),gradg);
                   4518: 
                   4519:        pmij(pmmij,cov,ncovmodel,x,nlstate);
                   4520:        
                   4521:        k=0;
                   4522:        for(i=1; i<=(nlstate); i++){
                   4523:          for(j=1; j<=(nlstate+ndeath);j++){
                   4524:            k=k+1;
                   4525:            mu[k][(int) age]=pmmij[i][j];
                   4526:          }
                   4527:        }
                   4528:        for(i=1;i<=(nlstate)*(nlstate+ndeath);i++)
                   4529:          for(j=1;j<=(nlstate)*(nlstate+ndeath);j++)
                   4530:            varpij[i][j][(int)age] = doldm[i][j];
                   4531: 
                   4532:        /*printf("\n%d ",(int)age);
                   4533:          for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4534:          printf("%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4535:          fprintf(ficlog,"%e [%e ;%e] ",gm[i],gm[i]-2*sqrt(doldm[i][i]),gm[i]+2*sqrt(doldm[i][i]));
                   4536:          }*/
                   4537: 
                   4538:        fprintf(ficresprob,"\n%d ",(int)age);
                   4539:        fprintf(ficresprobcov,"\n%d ",(int)age);
                   4540:        fprintf(ficresprobcor,"\n%d ",(int)age);
                   4541: 
                   4542:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++)
                   4543:          fprintf(ficresprob,"%11.3e (%11.3e) ",mu[i][(int) age],sqrt(varpij[i][i][(int)age]));
                   4544:        for (i=1; i<=(nlstate)*(nlstate+ndeath);i++){
                   4545:          fprintf(ficresprobcov,"%11.3e ",mu[i][(int) age]);
                   4546:          fprintf(ficresprobcor,"%11.3e ",mu[i][(int) age]);
                   4547:        }
                   4548:        i=0;
                   4549:        for (k=1; k<=(nlstate);k++){
                   4550:          for (l=1; l<=(nlstate+ndeath);l++){ 
1.145     brouard  4551:            i++;
1.126     brouard  4552:            fprintf(ficresprobcov,"\n%d %d-%d",(int)age,k,l);
                   4553:            fprintf(ficresprobcor,"\n%d %d-%d",(int)age,k,l);
                   4554:            for (j=1; j<=i;j++){
1.145     brouard  4555:              /* printf(" k=%d l=%d i=%d j=%d\n",k,l,i,j);fflush(stdout); */
1.126     brouard  4556:              fprintf(ficresprobcov," %11.3e",varpij[i][j][(int)age]);
                   4557:              fprintf(ficresprobcor," %11.3e",varpij[i][j][(int) age]/sqrt(varpij[i][i][(int) age])/sqrt(varpij[j][j][(int)age]));
                   4558:            }
                   4559:          }
                   4560:        }/* end of loop for state */
                   4561:       } /* end of loop for age */
1.145     brouard  4562:       free_vector(gp,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4563:       free_vector(gm,1,(nlstate+ndeath)*(nlstate+ndeath));
                   4564:       free_matrix(trgradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4565:       free_matrix(gradg,1,(nlstate+ndeath)*(nlstate+ndeath),1,npar);
                   4566:       
1.126     brouard  4567:       /* Confidence intervalle of pij  */
                   4568:       /*
1.131     brouard  4569:        fprintf(ficgp,"\nunset parametric;unset label");
1.126     brouard  4570:        fprintf(ficgp,"\nset log y;unset log x; set xlabel \"Age\";set ylabel \"probability (year-1)\"");
                   4571:        fprintf(ficgp,"\nset ter png small\nset size 0.65,0.65");
                   4572:        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);
                   4573:        fprintf(fichtm,"\n<br><img src=\"pijgr%s.png\"> ",optionfilefiname);
                   4574:        fprintf(ficgp,"\nset out \"pijgr%s.png\"",optionfilefiname);
                   4575:        fprintf(ficgp,"\nplot \"%s\" every :::%d::%d u 1:2 \"\%%lf",k1,k2,xfilevarprob);
                   4576:       */
                   4577: 
                   4578:       /* Drawing ellipsoids of confidence of two variables p(k1-l1,k2-l2)*/
1.145     brouard  4579:       first1=1;first2=2;
1.126     brouard  4580:       for (k2=1; k2<=(nlstate);k2++){
                   4581:        for (l2=1; l2<=(nlstate+ndeath);l2++){ 
                   4582:          if(l2==k2) continue;
                   4583:          j=(k2-1)*(nlstate+ndeath)+l2;
                   4584:          for (k1=1; k1<=(nlstate);k1++){
                   4585:            for (l1=1; l1<=(nlstate+ndeath);l1++){ 
                   4586:              if(l1==k1) continue;
                   4587:              i=(k1-1)*(nlstate+ndeath)+l1;
                   4588:              if(i<=j) continue;
                   4589:              for (age=bage; age<=fage; age ++){ 
                   4590:                if ((int)age %5==0){
                   4591:                  v1=varpij[i][i][(int)age]/stepm*YEARM/stepm*YEARM;
                   4592:                  v2=varpij[j][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4593:                  cv12=varpij[i][j][(int)age]/stepm*YEARM/stepm*YEARM;
                   4594:                  mu1=mu[i][(int) age]/stepm*YEARM ;
                   4595:                  mu2=mu[j][(int) age]/stepm*YEARM;
                   4596:                  c12=cv12/sqrt(v1*v2);
                   4597:                  /* Computing eigen value of matrix of covariance */
                   4598:                  lc1=((v1+v2)+sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
                   4599:                  lc2=((v1+v2)-sqrt((v1+v2)*(v1+v2) - 4*(v1*v2-cv12*cv12)))/2.;
1.135     brouard  4600:                  if ((lc2 <0) || (lc1 <0) ){
1.145     brouard  4601:                    if(first2==1){
                   4602:                      first1=0;
                   4603:                    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);
                   4604:                    }
                   4605:                    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);
                   4606:                    /* lc1=fabs(lc1); */ /* If we want to have them positive */
                   4607:                    /* lc2=fabs(lc2); */
1.135     brouard  4608:                  }
                   4609: 
1.126     brouard  4610:                  /* Eigen vectors */
                   4611:                  v11=(1./sqrt(1+(v1-lc1)*(v1-lc1)/cv12/cv12));
                   4612:                  /*v21=sqrt(1.-v11*v11); *//* error */
                   4613:                  v21=(lc1-v1)/cv12*v11;
                   4614:                  v12=-v21;
                   4615:                  v22=v11;
                   4616:                  tnalp=v21/v11;
                   4617:                  if(first1==1){
                   4618:                    first1=0;
                   4619:                    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);
                   4620:                  }
                   4621:                  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);
                   4622:                  /*printf(fignu*/
                   4623:                  /* mu1+ v11*lc1*cost + v12*lc2*sin(t) */
                   4624:                  /* mu2+ v21*lc1*cost + v22*lc2*sin(t) */
                   4625:                  if(first==1){
                   4626:                    first=0;
1.200     brouard  4627:                    fprintf(ficgp,"\n# Ellipsoids of confidence\n#\n");
1.126     brouard  4628:                    fprintf(ficgp,"\nset parametric;unset label");
                   4629:                    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  4630:                    fprintf(ficgp,"\nset ter svg size 640, 480");
1.126     brouard  4631:                    fprintf(fichtmcov,"\n<br>Ellipsoids of confidence cov(p%1d%1d,p%1d%1d) expressed in year<sup>-1</sup>\
1.201     brouard  4632:  :<a href=\"%s_%d%1d%1d-%1d%1d.svg\">\
                   4633: %s_%d%1d%1d-%1d%1d.svg</A>, ",k1,l1,k2,l2,\
                   4634:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2,\
                   4635:                            subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
                   4636:                    fprintf(fichtmcov,"\n<br><img src=\"%s_%d%1d%1d-%1d%1d.svg\"> ",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4637:                    fprintf(fichtmcov,"\n<br> Correlation at age %d (%.3f),",(int) age, c12);
1.201     brouard  4638:                    fprintf(ficgp,"\nset out \"%s_%d%1d%1d-%1d%1d.svg\"",subdirf2(optionfilefiname,"VARPIJGR_"), j1,k1,l1,k2,l2);
1.126     brouard  4639:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4640:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4641:                    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",\
                   4642:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4643:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4644:                  }else{
                   4645:                    first=0;
                   4646:                    fprintf(fichtmcov," %d (%.3f),",(int) age, c12);
                   4647:                    fprintf(ficgp,"\n# Age %d, p%1d%1d - p%1d%1d",(int) age, k1,l1,k2,l2);
                   4648:                    fprintf(ficgp,"\nset label \"%d\" at %11.3e,%11.3e center",(int) age, mu1,mu2);
                   4649:                    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",\
                   4650:                            mu1,std,v11,sqrt(lc1),v12,sqrt(lc2),\
                   4651:                            mu2,std,v21,sqrt(lc1),v22,sqrt(lc2));
                   4652:                  }/* if first */
                   4653:                } /* age mod 5 */
                   4654:              } /* end loop age */
1.201     brouard  4655:              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  4656:              first=1;
                   4657:            } /*l12 */
                   4658:          } /* k12 */
                   4659:        } /*l1 */
                   4660:       }/* k1 */
1.169     brouard  4661:       /* } */ /* loop covariates */
1.126     brouard  4662:   }
                   4663:   free_ma3x(varpij,1,nlstate,1,nlstate+ndeath,(int) bage, (int)fage);
                   4664:   free_matrix(mu,1,(nlstate+ndeath)*(nlstate+ndeath),(int) bage, (int)fage);
                   4665:   free_matrix(doldm,1,(nlstate)*(nlstate+ndeath),1,(nlstate)*(nlstate+ndeath));
                   4666:   free_matrix(dnewm,1,(nlstate)*(nlstate+ndeath),1,npar);
                   4667:   free_vector(xp,1,npar);
                   4668:   fclose(ficresprob);
                   4669:   fclose(ficresprobcov);
                   4670:   fclose(ficresprobcor);
                   4671:   fflush(ficgp);
                   4672:   fflush(fichtmcov);
                   4673: }
                   4674: 
                   4675: 
                   4676: /******************* Printing html file ***********/
1.201     brouard  4677: void printinghtml(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  4678:                  int lastpass, int stepm, int weightopt, char model[],\
                   4679:                  int imx,int jmin, int jmax, double jmeanint,char rfileres[],\
                   4680:                  int popforecast, int estepm ,\
                   4681:                  double jprev1, double mprev1,double anprev1, \
                   4682:                  double jprev2, double mprev2,double anprev2){
                   4683:   int jj1, k1, i1, cpt;
                   4684: 
                   4685:    fprintf(fichtm,"<ul><li><a href='#firstorder'>Result files (first order: no variance)</a>\n \
                   4686:    <li><a href='#secondorder'>Result files (second order (variance)</a>\n \
                   4687: </ul>");
                   4688:    fprintf(fichtm,"<ul><li><h4><a name='firstorder'>Result files (first order: no variance)</a></h4>\n \
                   4689:  - 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  4690:           jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,subdirf2(fileresu,"P_"),subdirf2(fileresu,"P_"));
1.126     brouard  4691:    fprintf(fichtm,"\
                   4692:  - Estimated transition probabilities over %d (stepm) months: <a href=\"%s\">%s</a><br>\n ",
1.201     brouard  4693:           stepm,subdirf2(fileresu,"PIJ_"),subdirf2(fileresu,"PIJ_"));
1.126     brouard  4694:    fprintf(fichtm,"\
                   4695:  - Period (stable) prevalence in each health state: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4696:           subdirf2(fileresu,"PL_"),subdirf2(fileresu,"PL_"));
1.126     brouard  4697:    fprintf(fichtm,"\
1.128     brouard  4698:  - (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  4699:    <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4700:           estepm,subdirf2(fileresu,"E_"),subdirf2(fileresu,"E_"));
1.126     brouard  4701:    fprintf(fichtm,"\
                   4702:  - Population projections by age and states: \
1.201     brouard  4703:    <a href=\"%s\">%s</a> <br>\n</li>", subdirf2(fileresu,"F_"),subdirf2(fileresu,"F_"));
1.126     brouard  4704: 
                   4705: fprintf(fichtm," \n<ul><li><b>Graphs</b></li><p>");
                   4706: 
1.145     brouard  4707:  m=pow(2,cptcoveff);
1.126     brouard  4708:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4709: 
                   4710:  jj1=0;
                   4711:  for(k1=1; k1<=m;k1++){
1.192     brouard  4712:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4713:      jj1++;
                   4714:      if (cptcovn > 0) {
                   4715:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
1.192     brouard  4716:        for (cpt=1; cpt<=cptcoveff;cpt++){ 
1.198     brouard  4717:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
                   4718:         printf(" V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);fflush(stdout);
1.192     brouard  4719:        }
1.126     brouard  4720:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4721:      }
1.201     brouard  4722:      /* aij, bij */
                   4723:      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> \
                   4724: <img src=\"%s_%d-1.svg\">",subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);
1.126     brouard  4725:      /* Pij */
1.202     brouard  4726:      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  4727: <img src=\"%s_%d-2.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1);     
1.126     brouard  4728:      /* Quasi-incidences */
1.201     brouard  4729:      fprintf(fichtm,"<br>\n- Iij or Conditional probabilities to be observed in state j being in state i %d (stepm) months\
                   4730:  before but expressed in per year i.e. quasi incidences if stepm is small and probabilities too,\
                   4731:  incidence (rates) are the limit when h tends to zero of the ratio of the probability hPij \
                   4732: divided by h: hPij/h : <a href=\"%s_%d-3.svg\">%s_%d-3.svg</a><br> \
                   4733: <img src=\"%s_%d-3.svg\">",stepm,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1,subdirf2(optionfilefiname,"PE_"),jj1); 
                   4734:      /* Survival functions (period) in state j */
                   4735:      for(cpt=1; cpt<=nlstate;cpt++){
                   4736:        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> \
                   4737: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1,subdirf2(optionfilefiname,"LIJ_"),cpt,jj1);
                   4738:      }
                   4739:      /* State specific survival functions (period) */
                   4740:      for(cpt=1; cpt<=nlstate;cpt++){
                   4741:        fprintf(fichtm,"<br>\n- Survival functions from state %d in any different live states and total.\
                   4742:  Or probability to survive in various states (1 to %d) being in state %d at different ages.\
                   4743:  <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);
                   4744:      }
                   4745:      /* Period (stable) prevalence in each health state */
                   4746:      for(cpt=1; cpt<=nlstate;cpt++){
                   4747:        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> \
                   4748: <img src=\"%s_%d-%d.svg\">", cpt, cpt, nlstate, subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1,subdirf2(optionfilefiname,"P_"),cpt,jj1);
                   4749:      }
1.126     brouard  4750:      for(cpt=1; cpt<=nlstate;cpt++) {
1.201     brouard  4751:        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> \
                   4752: <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  4753:      }
1.192     brouard  4754:    /* } /\* end i1 *\/ */
1.126     brouard  4755:  }/* End k1 */
                   4756:  fprintf(fichtm,"</ul>");
                   4757: 
                   4758:  fprintf(fichtm,"\
                   4759: \n<br><li><h4> <a name='secondorder'>Result files (second order: variances)</a></h4>\n\
1.193     brouard  4760:  - Parameter file with estimated parameters and covariance matrix: <a href=\"%s\">%s</a> <br> \
1.203   ! brouard  4761:  - 95%% confidence intervals and Wald tests of the estimated parameters are in the log file if optimization has been done (mle != 0).<br> \
1.197     brouard  4762: But because parameters are usually highly correlated (a higher incidence of disability \
                   4763: and a higher incidence of recovery can give very close observed transition) it might \
                   4764: be very useful to look not only at linear confidence intervals estimated from the \
                   4765: variances but at the covariance matrix. And instead of looking at the estimated coefficients \
                   4766: (parameters) of the logistic regression, it might be more meaningful to visualize the \
                   4767: covariance matrix of the one-step probabilities. \
                   4768: See page 'Matrix of variance-covariance of one-step probabilities' below. \n", rfileres,rfileres);
1.126     brouard  4769: 
1.193     brouard  4770:  fprintf(fichtm," - Standard deviation of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4771:         subdirf2(fileresu,"PROB_"),subdirf2(fileresu,"PROB_"));
1.126     brouard  4772:  fprintf(fichtm,"\
                   4773:  - Variance-covariance of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4774:         subdirf2(fileresu,"PROBCOV_"),subdirf2(fileresu,"PROBCOV_"));
1.126     brouard  4775: 
                   4776:  fprintf(fichtm,"\
                   4777:  - Correlation matrix of one-step probabilities: <a href=\"%s\">%s</a> <br>\n",
1.201     brouard  4778:         subdirf2(fileresu,"PROBCOR_"),subdirf2(fileresu,"PROBCOR_"));
1.126     brouard  4779:  fprintf(fichtm,"\
                   4780:  - 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): \
                   4781:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4782:           estepm,subdirf2(fileresu,"CVE_"),subdirf2(fileresu,"CVE_"));
1.126     brouard  4783:  fprintf(fichtm,"\
                   4784:  - (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): \
                   4785:    <a href=\"%s\">%s</a> <br>\n</li>",
1.201     brouard  4786:           estepm,subdirf2(fileresu,"STDE_"),subdirf2(fileresu,"STDE_"));
1.126     brouard  4787:  fprintf(fichtm,"\
1.128     brouard  4788:  - 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  4789:         estepm, subdirf2(fileresu,"V_"),subdirf2(fileresu,"V_"));
1.126     brouard  4790:  fprintf(fichtm,"\
1.128     brouard  4791:  - 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  4792:         estepm, subdirf2(fileresu,"T_"),subdirf2(fileresu,"T_"));
1.126     brouard  4793:  fprintf(fichtm,"\
                   4794:  - Standard deviation of period (stable) prevalences: <a href=\"%s\">%s</a> <br>\n",\
1.201     brouard  4795:         subdirf2(fileresu,"VPL_"),subdirf2(fileresu,"VPL_"));
1.126     brouard  4796: 
                   4797: /*  if(popforecast==1) fprintf(fichtm,"\n */
                   4798: /*  - Prevalences forecasting: <a href=\"f%s\">f%s</a> <br>\n */
                   4799: /*  - Population forecasting (if popforecast=1): <a href=\"pop%s\">pop%s</a> <br>\n */
                   4800: /*     <br>",fileres,fileres,fileres,fileres); */
                   4801: /*  else  */
                   4802: /*    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); */
                   4803:  fflush(fichtm);
                   4804:  fprintf(fichtm," <ul><li><b>Graphs</b></li><p>");
                   4805: 
1.145     brouard  4806:  m=pow(2,cptcoveff);
1.126     brouard  4807:  if (cptcovn < 1) {m=1;ncodemax[1]=1;}
                   4808: 
                   4809:  jj1=0;
                   4810:  for(k1=1; k1<=m;k1++){
1.192     brouard  4811:    /* for(i1=1; i1<=ncodemax[k1];i1++){ */
1.126     brouard  4812:      jj1++;
                   4813:      if (cptcovn > 0) {
                   4814:        fprintf(fichtm,"<hr  size=\"2\" color=\"#EC5E5E\">************ Results for covariates");
                   4815:        for (cpt=1; cpt<=cptcoveff;cpt++) 
1.198     brouard  4816:         fprintf(fichtm," V%d=%d ",Tvaraff[cpt],nbcode[Tvaraff[cpt]][codtabm(jj1,cpt)]);
1.126     brouard  4817:        fprintf(fichtm," ************\n<hr size=\"2\" color=\"#EC5E5E\">");
                   4818:      }
                   4819:      for(cpt=1; cpt<=nlstate;cpt++) {
                   4820:        fprintf(fichtm,"<br>- Observed (cross-sectional) and period (incidence based) \
1.199     brouard  4821: prevalence (with 95%% confidence interval) in state (%d): %s%d_%d.svg <br>\
1.201     brouard  4822: <img src=\"%s_%d-%d.svg\">",cpt,subdirf2(optionfilefiname,"V_"),cpt,jj1,subdirf2(optionfilefiname,"V_"),cpt,jj1);  
1.126     brouard  4823:      }
                   4824:      fprintf(fichtm,"\n<br>- Total life expectancy by age and \
1.128     brouard  4825: health expectancies in states (1) and (2). If popbased=1 the smooth (due to the model) \
                   4826: true period expectancies (those weighted with period prevalences are also\
                   4827:  drawn in addition to the population based expectancies computed using\
1.201     brouard  4828:  observed and cahotic prevalences: %s_%d.svg<br>\
                   4829: <img src=\"%s_%d.svg\">",subdirf2(optionfilefiname,"E_"),jj1,subdirf2(optionfilefiname,"E_"),jj1);
1.192     brouard  4830:    /* } /\* end i1 *\/ */
1.126     brouard  4831:  }/* End k1 */
                   4832:  fprintf(fichtm,"</ul>");
                   4833:  fflush(fichtm);
                   4834: }
                   4835: 
                   4836: /******************* Gnuplot file **************/
1.201     brouard  4837: void printinggnuplot(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  4838: 
                   4839:   char dirfileres[132],optfileres[132];
1.164     brouard  4840:   int cpt=0,k1=0,i=0,k=0,j=0,jk=0,k2=0,k3=0,ij=0,l=0;
1.130     brouard  4841:   int ng=0;
1.201     brouard  4842:   int vpopbased;
1.126     brouard  4843: /*   if((ficgp=fopen(optionfilegnuplot,"a"))==NULL) { */
                   4844: /*     printf("Problem with file %s",optionfilegnuplot); */
                   4845: /*     fprintf(ficlog,"Problem with file %s",optionfilegnuplot); */
                   4846: /*   } */
                   4847: 
                   4848:   /*#ifdef windows */
                   4849:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   4850:     /*#endif */
                   4851:   m=pow(2,cptcoveff);
                   4852: 
1.202     brouard  4853:   /* Contribution to likelihood */
                   4854:   /* Plot the probability implied in the likelihood */
                   4855:     fprintf(ficgp,"\n# Contributions to the Likelihood, mle >=1. For mle=4 no interpolation, pure matrix products.\n#\n");
                   4856:     fprintf(ficgp,"\n set log y; unset log x;set xlabel \"Age\"; set ylabel \"Likelihood (-2Log(L))\";");
                   4857:     /* fprintf(ficgp,"\nset ter svg size 640, 480"); */ /* Too big for svg */
                   4858:     fprintf(ficgp,"\nset ter png size 640, 480");
                   4859: /* good for mle=4 plot by number of matrix products.
                   4860:    replot  "rrtest1/toto.txt" u 2:($4 == 1 && $5==2 ? $9 : 1/0):5 t "p12" with point lc 1 */
                   4861: /* replot exp(p1+p2*x)/(1+exp(p1+p2*x)+exp(p3+p4*x)+exp(p5+p6*x)) t "p12(x)"  */
                   4862:     /* fprintf(ficgp,"\nset out \"%s.svg\";",subdirf2(optionfilefiname,"ILK_")); */
                   4863:     fprintf(ficgp,"\nset out \"%s.png\";",subdirf2(optionfilefiname,"ILK_"));
                   4864:     fprintf(ficgp,"\nplot  \"%s\" u 2:(-$11):3 t \"All sample, all transitions\" with dots lc variable",subdirf(fileresilk));
                   4865:     fprintf(ficgp,"\nreplot  \"%s\" u 2:($3 <= 3 ? -$11 : 1/0):3 t \"First 3 individuals\" with line lc variable", subdirf(fileresilk));
1.203   ! brouard  4866:     fprintf(ficgp,"\nset out;unset log\n");
1.202     brouard  4867:     /* fprintf(ficgp,"\nset out \"%s.svg\"; replot; set out; # bug gnuplot",subdirf2(optionfilefiname,"ILK_")); */
                   4868: 
1.126     brouard  4869:   strcpy(dirfileres,optionfilefiname);
                   4870:   strcpy(optfileres,"vpl");
                   4871:  /* 1eme*/
1.201     brouard  4872:   fprintf(ficgp,"\n# 1st: Period (stable) prevalence with CI: 'VPL_' files\n");
1.126     brouard  4873:   for (cpt=1; cpt<= nlstate ; cpt ++) {
1.145     brouard  4874:     for (k1=1; k1<= m ; k1 ++) { /* plot [100000000000000000000:-100000000000000000000] "mysbiaspar/vplrmysbiaspar.txt to check */
1.201     brouard  4875:      fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"V_"),cpt,k1);
                   4876:      fprintf(ficgp,"\n#set out \"V_%s_%d-%d.svg\" \n",optionfilefiname,cpt,k1);
1.126     brouard  4877:      fprintf(ficgp,"set xlabel \"Age\" \n\
                   4878: set ylabel \"Probability\" \n\
1.199     brouard  4879: set ter svg size 640, 480\n\
1.201     brouard  4880: plot [%.f:%.f] \"%s\" every :::%d::%d u 1:2 \"%%lf",ageminpar,fage,subdirf2(fileresu,"VPL_"),k1-1,k1-1);
1.126     brouard  4881: 
                   4882:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4883:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4884:        else        fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4885:      }
1.201     brouard  4886:      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  4887:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4888:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4889:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4890:      } 
1.201     brouard  4891:      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  4892:      for (i=1; i<= nlstate ; i ++) {
1.170     brouard  4893:        if (i==cpt) fprintf(ficgp," %%lf (%%lf)");
                   4894:        else fprintf(ficgp," %%*lf (%%*lf)");
1.126     brouard  4895:      }  
1.201     brouard  4896:      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));
                   4897:      fprintf(ficgp,"\nset out \n");
                   4898:     } /* k1 */
                   4899:   } /* cpt */
1.126     brouard  4900:   /*2 eme*/
1.153     brouard  4901:   fprintf(ficgp,"\n# 2nd: Total life expectancy with CI: 't' files\n");
1.126     brouard  4902:   for (k1=1; k1<= m ; k1 ++) { 
1.201     brouard  4903:     fprintf(ficgp,"\nset out \"%s_%d.svg\" \n",subdirf2(optionfilefiname,"E_"),k1);
                   4904:     for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
                   4905:       if(vpopbased==0)
                   4906:        fprintf(ficgp,"set ylabel \"Years\" \nset ter svg size 640, 480\nplot [%.f:%.f] ",ageminpar,fage);
                   4907:       else
                   4908:        fprintf(ficgp,"\nreplot ");
                   4909:       for (i=1; i<= nlstate+1 ; i ++) {
                   4910:        k=2*i;
                   4911:        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);
                   4912:        for (j=1; j<= nlstate+1 ; j ++) {
                   4913:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4914:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4915:        }   
                   4916:        if (i== 1) fprintf(ficgp,"\" t\"TLE\" w l lt %d, \\\n",i);
                   4917:        else fprintf(ficgp,"\" t\"LE in state (%d)\" w l lt %d, \\\n",i-1,i+1);
                   4918:        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);
                   4919:        for (j=1; j<= nlstate+1 ; j ++) {
                   4920:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4921:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4922:        }   
                   4923:        fprintf(ficgp,"\" t\"\" w l lt 0,");
                   4924:        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);
                   4925:        for (j=1; j<= nlstate+1 ; j ++) {
                   4926:          if (j==i) fprintf(ficgp," %%lf (%%lf)");
                   4927:          else fprintf(ficgp," %%*lf (%%*lf)");
                   4928:        }   
                   4929:        if (i== (nlstate+1)) fprintf(ficgp,"\" t\"\" w l lt 0");
                   4930:        else fprintf(ficgp,"\" t\"\" w l lt 0,\\\n");
                   4931:       } /* state */
                   4932:     } /* vpopbased */
                   4933:     fprintf(ficgp,"\nset out;set out \"%s_%d.svg\"; replot; set out; \n",subdirf2(optionfilefiname,"E_"),k1); /* Buggy gnuplot */
                   4934:   } /* k1 */
1.126     brouard  4935:   /*3eme*/
                   4936:   
                   4937:   for (k1=1; k1<= m ; k1 ++) { 
                   4938:     for (cpt=1; cpt<= nlstate ; cpt ++) {
                   4939:       /*       k=2+nlstate*(2*cpt-2); */
                   4940:       k=2+(nlstate+1)*(cpt-1);
1.201     brouard  4941:       fprintf(ficgp,"\nset out \"%s_%d%d.svg\" \n",subdirf2(optionfilefiname,"EXP_"),cpt,k1);
1.199     brouard  4942:       fprintf(ficgp,"set ter svg size 640, 480\n\
1.201     brouard  4943: 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  4944:       /*fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d-2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4945:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4946:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4947:        fprintf(ficgp,",\"e%s\" every :::%d::%d u 1:($%d+2*$%d) \"\%%lf ",fileres,k1-1,k1-1,k,k+1);
                   4948:        for (i=1; i<= nlstate*2 ; i ++) fprintf(ficgp,"\%%lf (\%%lf) ");
                   4949:        fprintf(ficgp,"\" t \"e%d1\" w l",cpt);
                   4950:        
                   4951:       */
                   4952:       for (i=1; i< nlstate ; i ++) {
1.201     brouard  4953:        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  4954:        /*      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);*/
                   4955:        
                   4956:       } 
1.201     brouard  4957:       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  4958:     }
                   4959:   }
                   4960:   
1.201     brouard  4961:   /* Survival functions (period) from state i in state j by initial state i */
                   4962:   for (k1=1; k1<= m ; k1 ++) { /* For each multivariate if any */
                   4963:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
                   4964:       k=3;
                   4965:       fprintf(ficgp,"\n#\n#\n# Survival functions in state j : 'lij' files, cov=%d state=%d",k1, cpt);
                   4966:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJ_"),cpt,k1);
                   4967:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   4968: set ter svg size 640, 480\n\
                   4969: unset log y\n\
                   4970: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4971:       for (i=1; i<= nlstate ; i ++){
                   4972:        if(i==1)
                   4973:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   4974:        else
                   4975:          fprintf(ficgp,", '' ");
                   4976:        l=(nlstate+ndeath)*(i-1)+1;
                   4977:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
                   4978:        for (j=2; j<= nlstate+ndeath ; j ++)
                   4979:          fprintf(ficgp,"+$%d",k+l+j-1);
                   4980:        fprintf(ficgp,")) t \"l(%d,%d)\" w l",i,cpt);
                   4981:       } /* nlstate */
                   4982:       fprintf(ficgp,"\nset out\n");
                   4983:     } /* end cpt state*/ 
                   4984:   } /* end covariate */  
                   4985: 
                   4986:   /* Survival functions (period) from state i in state j by final state j */
1.202     brouard  4987:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.201     brouard  4988:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each inital state  */
                   4989:       k=3;
                   4990:       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);
                   4991:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"LIJT_"),cpt,k1);
                   4992:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability to be alive\" \n\
                   4993: set ter svg size 640, 480\n\
                   4994: unset log y\n\
                   4995: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   4996:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   4997:        if(j==1)
                   4998:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
                   4999:        else
                   5000:          fprintf(ficgp,", '' ");
                   5001:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5002:        fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):($%d",k1,k+l);
                   5003:        /* for (i=2; i<= nlstate+ndeath ; i ++) */
                   5004:        /*   fprintf(ficgp,"+$%d",k+l+i-1); */
                   5005:        fprintf(ficgp,") t \"l(%d,%d)\" w l",cpt,j);
                   5006:       } /* nlstate */
                   5007:       fprintf(ficgp,", '' ");
                   5008:       fprintf(ficgp," u (($1==%d && (floor($2)%%5 == 0)) ? ($3):1/0):(",k1);
                   5009:       for (j=1; j<= nlstate ; j ++){ /* Lived in state j */
                   5010:        l=(nlstate+ndeath)*(cpt-1) +j;
                   5011:        if(j < nlstate)
                   5012:          fprintf(ficgp,"$%d +",k+l);
                   5013:        else
                   5014:          fprintf(ficgp,"$%d) t\"l(%d,.)\" w l",k+l,cpt);
                   5015:       }
                   5016:       fprintf(ficgp,"\nset out\n");
                   5017:     } /* end cpt state*/ 
                   5018:   } /* end covariate */  
                   5019: 
1.202     brouard  5020:   /* CV preval stable (period) for each covariate */
                   5021:   for (k1=1; k1<= m ; k1 ++) { /* For each covariate if any */
1.153     brouard  5022:     for (cpt=1; cpt<=nlstate ; cpt ++) { /* For each life state */
1.126     brouard  5023:       k=3;
1.153     brouard  5024:       fprintf(ficgp,"\n#\n#\n#CV preval stable (period): 'pij' files, cov=%d state=%d",k1, cpt);
1.201     brouard  5025:       fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" \n",subdirf2(optionfilefiname,"P_"),cpt,k1);
1.126     brouard  5026:       fprintf(ficgp,"set xlabel \"Age\" \nset ylabel \"Probability\" \n\
1.199     brouard  5027: set ter svg size 640, 480\n\
1.126     brouard  5028: unset log y\n\
1.153     brouard  5029: plot [%.f:%.f]  ", ageminpar, agemaxpar);
                   5030:       for (i=1; i<= nlstate ; i ++){
                   5031:        if(i==1)
1.201     brouard  5032:          fprintf(ficgp,"\"%s\"",subdirf2(fileresu,"PIJ_"));
1.153     brouard  5033:        else
                   5034:          fprintf(ficgp,", '' ");
1.154     brouard  5035:        l=(nlstate+ndeath)*(i-1)+1;
                   5036:        fprintf(ficgp," u ($1==%d ? ($3):1/0):($%d/($%d",k1,k+l+(cpt-1),k+l);
1.201     brouard  5037:        for (j=2; j<= nlstate ; j ++)
                   5038:          fprintf(ficgp,"+$%d",k+l+j-1);
1.153     brouard  5039:        fprintf(ficgp,")) t \"prev(%d,%d)\" w l",i,cpt);
                   5040:       } /* nlstate */
1.201     brouard  5041:       fprintf(ficgp,"\nset out\n");
1.153     brouard  5042:     } /* end cpt state*/ 
                   5043:   } /* end covariate */  
1.201     brouard  5044: 
1.126     brouard  5045:   /* proba elementaires */
1.187     brouard  5046:   fprintf(ficgp,"\n##############\n#MLE estimated parameters\n#############\n");
1.126     brouard  5047:   for(i=1,jk=1; i <=nlstate; i++){
1.187     brouard  5048:     fprintf(ficgp,"# initial state %d\n",i);
1.126     brouard  5049:     for(k=1; k <=(nlstate+ndeath); k++){
                   5050:       if (k != i) {
1.187     brouard  5051:        fprintf(ficgp,"#   current state %d\n",k);
1.126     brouard  5052:        for(j=1; j <=ncovmodel; j++){
1.187     brouard  5053:          fprintf(ficgp,"p%d=%f; ",jk,p[jk]);
1.126     brouard  5054:          jk++; 
                   5055:        }
1.187     brouard  5056:        fprintf(ficgp,"\n");
1.126     brouard  5057:       }
                   5058:     }
                   5059:    }
1.187     brouard  5060:   fprintf(ficgp,"##############\n#\n");
                   5061: 
1.145     brouard  5062:   /*goto avoid;*/
1.200     brouard  5063:   fprintf(ficgp,"\n##############\n#Graphics of probabilities or incidences\n#############\n");
1.187     brouard  5064:   fprintf(ficgp,"# logi(p12/p11)=a12+b12*age+c12age*age+d12*V1+e12*V1*age\n");
                   5065:   fprintf(ficgp,"# logi(p12/p11)=p1 +p2*age +p3*age*age+ p4*V1+ p5*V1*age\n");
                   5066:   fprintf(ficgp,"# logi(p13/p11)=a13+b13*age+c13age*age+d13*V1+e13*V1*age\n");
                   5067:   fprintf(ficgp,"# logi(p13/p11)=p6 +p7*age +p8*age*age+ p9*V1+ p10*V1*age\n");
                   5068:   fprintf(ficgp,"# p12+p13+p14+p11=1=p11(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5069:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5070:   fprintf(ficgp,"# p11=1/(1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5071:   fprintf(ficgp,"#                      +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age)+...)\n");
                   5072:   fprintf(ficgp,"# p12=exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)/\n");
                   5073:   fprintf(ficgp,"#     (1+exp(a12+b12*age+c12age*age+d12*V1+e12*V1*age)\n");
                   5074:   fprintf(ficgp,"#       +exp(a13+b13*age+c13age*age+d13*V1+e13*V1*age))\n");
                   5075:   fprintf(ficgp,"#       +exp(a14+b14*age+c14age*age+d14*V1+e14*V1*age)+...)\n");
                   5076:   fprintf(ficgp,"#\n");
1.201     brouard  5077:    for(ng=1; ng<=3;ng++){ /* Number of graphics: first is logit, 2nd is probabilities, third is incidences per year*/
1.187     brouard  5078:      fprintf(ficgp,"# ng=%d\n",ng);
                   5079:      fprintf(ficgp,"#   jk=1 to 2^%d=%d\n",cptcoveff,m);
1.126     brouard  5080:      for(jk=1; jk <=m; jk++) {
1.187     brouard  5081:        fprintf(ficgp,"#    jk=%d\n",jk);
1.201     brouard  5082:        fprintf(ficgp,"\nset out \"%s_%d-%d.svg\" ",subdirf2(optionfilefiname,"PE_"),jk,ng);
                   5083:        fprintf(ficgp,"\nset ter svg size 640, 480 ");
                   5084:        if (ng==1){
                   5085:         fprintf(ficgp,"\nset ylabel \"Value of the logit of the model\"\n"); /* exp(a12+b12*x) could be nice */
                   5086:         fprintf(ficgp,"\nunset log y");
                   5087:        }else if (ng==2){
                   5088:         fprintf(ficgp,"\nset ylabel \"Probability\"\n");
                   5089:         fprintf(ficgp,"\nset log y");
                   5090:        }else if (ng==3){
1.126     brouard  5091:         fprintf(ficgp,"\nset ylabel \"Quasi-incidence per year\"\n");
1.201     brouard  5092:         fprintf(ficgp,"\nset log y");
                   5093:        }else
                   5094:         fprintf(ficgp,"\nunset title ");
                   5095:        fprintf(ficgp,"\nplot  [%.f:%.f] ",ageminpar,agemaxpar);
1.126     brouard  5096:        i=1;
                   5097:        for(k2=1; k2<=nlstate; k2++) {
                   5098:         k3=i;
                   5099:         for(k=1; k<=(nlstate+ndeath); k++) {
                   5100:           if (k != k2){
1.201     brouard  5101:             switch( ng) {
                   5102:             case 1:
1.187     brouard  5103:               if(nagesqr==0)
1.201     brouard  5104:                 fprintf(ficgp," p%d+p%d*x",i,i+1);
1.187     brouard  5105:               else /* nagesqr =1 */
1.201     brouard  5106:                 fprintf(ficgp," p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5107:               break;
                   5108:             case 2: /* ng=2 */
1.187     brouard  5109:               if(nagesqr==0)
                   5110:                 fprintf(ficgp," exp(p%d+p%d*x",i,i+1);
                   5111:               else /* nagesqr =1 */
1.201     brouard  5112:                   fprintf(ficgp," exp(p%d+p%d*x+p%d*x*x",i,i+1,i+1+nagesqr);
                   5113:               break;
                   5114:             case 3:
                   5115:               if(nagesqr==0)
                   5116:                 fprintf(ficgp," %f*exp(p%d+p%d*x",YEARM/stepm,i,i+1);
                   5117:               else /* nagesqr =1 */
                   5118:                 fprintf(ficgp," %f*exp(p%d+p%d*x+p%d*x*x",YEARM/stepm,i,i+1,i+1+nagesqr);
                   5119:               break;
                   5120:             }
1.141     brouard  5121:             ij=1;/* To be checked else nbcode[0][0] wrong */
1.187     brouard  5122:             for(j=3; j <=ncovmodel-nagesqr; j++) {
1.197     brouard  5123:               /* printf("Tage[%d]=%d, j=%d\n", ij, Tage[ij], j); */
                   5124:               if(ij <=cptcovage) { /* Bug valgrind */
                   5125:                 if((j-2)==Tage[ij]) { /* Bug valgrind */
1.200     brouard  5126:                   fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5127:                   /* fprintf(ficgp,"+p%d*%d*x",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
1.197     brouard  5128:                   ij++;
                   5129:                 }
1.186     brouard  5130:               }
                   5131:               else
1.198     brouard  5132:                 fprintf(ficgp,"+p%d*%d",i+j+nagesqr-1,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.126     brouard  5133:             }
1.201     brouard  5134:             if(ng != 1){
                   5135:               fprintf(ficgp,")/(1");
1.126     brouard  5136:             
1.201     brouard  5137:               for(k1=1; k1 <=nlstate; k1++){ 
                   5138:                 if(nagesqr==0)
                   5139:                   fprintf(ficgp,"+exp(p%d+p%d*x",k3+(k1-1)*ncovmodel,k3+(k1-1)*ncovmodel+1);
                   5140:                 else /* nagesqr =1 */
                   5141:                   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);
                   5142:                 
                   5143:                 ij=1;
                   5144:                 for(j=3; j <=ncovmodel-nagesqr; j++){
                   5145:                   if(ij <=cptcovage) { /* Bug valgrind */
                   5146:                     if((j-2)==Tage[ij]) { /* Bug valgrind */
                   5147:                       fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
                   5148:                       /* fprintf(ficgp,"+p%d*%d*x",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,Tvar[j-2])]); */
                   5149:                       ij++;
                   5150:                     }
1.197     brouard  5151:                   }
1.201     brouard  5152:                   else
                   5153:                     fprintf(ficgp,"+p%d*%d",k3+(k1-1)*ncovmodel+1+j-2+nagesqr,nbcode[Tvar[j-2]][codtabm(jk,j-2)]);
1.186     brouard  5154:                 }
1.201     brouard  5155:                 fprintf(ficgp,")");
1.126     brouard  5156:               }
                   5157:               fprintf(ficgp,")");
1.201     brouard  5158:               if(ng ==2)
                   5159:                 fprintf(ficgp," t \"p%d%d\" ", k2,k);
                   5160:               else /* ng= 3 */
                   5161:                 fprintf(ficgp," t \"i%d%d\" ", k2,k);
                   5162:             }else{ /* end ng <> 1 */
                   5163:               fprintf(ficgp," t \"logit(p%d%d)\" ", k2,k);
1.126     brouard  5164:             }
                   5165:             if ((k+k2)!= (nlstate*2+ndeath)) fprintf(ficgp,",");
                   5166:             i=i+ncovmodel;
                   5167:           }
                   5168:         } /* end k */
                   5169:        } /* end k2 */
1.201     brouard  5170:        fprintf(ficgp,"\n set out\n");
1.126     brouard  5171:      } /* end jk */
                   5172:    } /* end ng */
1.164     brouard  5173:  /* avoid: */
1.126     brouard  5174:    fflush(ficgp); 
                   5175: }  /* end gnuplot */
                   5176: 
                   5177: 
                   5178: /*************** Moving average **************/
                   5179: int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav){
                   5180: 
                   5181:   int i, cpt, cptcod;
                   5182:   int modcovmax =1;
                   5183:   int mobilavrange, mob;
                   5184:   double age;
                   5185: 
                   5186:   modcovmax=2*cptcoveff;/* Max number of modalities. We suppose 
                   5187:                           a covariate has 2 modalities */
                   5188:   if (cptcovn<1) modcovmax=1; /* At least 1 pass */
                   5189: 
                   5190:   if(mobilav==1||mobilav ==3 ||mobilav==5 ||mobilav== 7){
                   5191:     if(mobilav==1) mobilavrange=5; /* default */
                   5192:     else mobilavrange=mobilav;
                   5193:     for (age=bage; age<=fage; age++)
                   5194:       for (i=1; i<=nlstate;i++)
                   5195:        for (cptcod=1;cptcod<=modcovmax;cptcod++)
                   5196:          mobaverage[(int)age][i][cptcod]=probs[(int)age][i][cptcod];
                   5197:     /* We keep the original values on the extreme ages bage, fage and for 
                   5198:        fage+1 and bage-1 we use a 3 terms moving average; for fage+2 bage+2
                   5199:        we use a 5 terms etc. until the borders are no more concerned. 
                   5200:     */ 
                   5201:     for (mob=3;mob <=mobilavrange;mob=mob+2){
                   5202:       for (age=bage+(mob-1)/2; age<=fage-(mob-1)/2; age++){
                   5203:        for (i=1; i<=nlstate;i++){
                   5204:          for (cptcod=1;cptcod<=modcovmax;cptcod++){
                   5205:            mobaverage[(int)age][i][cptcod] =probs[(int)age][i][cptcod];
                   5206:              for (cpt=1;cpt<=(mob-1)/2;cpt++){
                   5207:                mobaverage[(int)age][i][cptcod] +=probs[(int)age-cpt][i][cptcod];
                   5208:                mobaverage[(int)age][i][cptcod] +=probs[(int)age+cpt][i][cptcod];
                   5209:              }
                   5210:            mobaverage[(int)age][i][cptcod]=mobaverage[(int)age][i][cptcod]/mob;
                   5211:          }
                   5212:        }
                   5213:       }/* end age */
                   5214:     }/* end mob */
                   5215:   }else return -1;
                   5216:   return 0;
                   5217: }/* End movingaverage */
                   5218: 
                   5219: 
                   5220: /************** Forecasting ******************/
1.169     brouard  5221: 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  5222:   /* proj1, year, month, day of starting projection 
                   5223:      agemin, agemax range of age
                   5224:      dateprev1 dateprev2 range of dates during which prevalence is computed
                   5225:      anproj2 year of en of projection (same day and month as proj1).
                   5226:   */
1.164     brouard  5227:   int yearp, stepsize, hstepm, nhstepm, j, k, cptcod, i, h, i1;
1.126     brouard  5228:   double agec; /* generic age */
                   5229:   double agelim, ppij, yp,yp1,yp2,jprojmean,mprojmean,anprojmean;
                   5230:   double *popeffectif,*popcount;
                   5231:   double ***p3mat;
                   5232:   double ***mobaverage;
                   5233:   char fileresf[FILENAMELENGTH];
                   5234: 
                   5235:   agelim=AGESUP;
                   5236:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5237:  
1.201     brouard  5238:   strcpy(fileresf,"F_"); 
                   5239:   strcat(fileresf,fileresu);
1.126     brouard  5240:   if((ficresf=fopen(fileresf,"w"))==NULL) {
                   5241:     printf("Problem with forecast resultfile: %s\n", fileresf);
                   5242:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", fileresf);
                   5243:   }
                   5244:   printf("Computing forecasting: result on file '%s' \n", fileresf);
                   5245:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", fileresf);
                   5246: 
                   5247:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5248: 
                   5249:   if (mobilav!=0) {
                   5250:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5251:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5252:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5253:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5254:     }
                   5255:   }
                   5256: 
                   5257:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5258:   if (stepm<=12) stepsize=1;
                   5259:   if(estepm < stepm){
                   5260:     printf ("Problem %d lower than %d\n",estepm, stepm);
                   5261:   }
                   5262:   else  hstepm=estepm;   
                   5263: 
                   5264:   hstepm=hstepm/stepm; 
                   5265:   yp1=modf(dateintmean,&yp);/* extracts integral of datemean in yp  and
                   5266:                                fractional in yp1 */
                   5267:   anprojmean=yp;
                   5268:   yp2=modf((yp1*12),&yp);
                   5269:   mprojmean=yp;
                   5270:   yp1=modf((yp2*30.5),&yp);
                   5271:   jprojmean=yp;
                   5272:   if(jprojmean==0) jprojmean=1;
                   5273:   if(mprojmean==0) jprojmean=1;
                   5274: 
                   5275:   i1=cptcoveff;
                   5276:   if (cptcovn < 1){i1=1;}
                   5277:   
                   5278:   fprintf(ficresf,"# Mean day of interviews %.lf/%.lf/%.lf (%.2f) between %.2f and %.2f \n",jprojmean,mprojmean,anprojmean,dateintmean,dateprev1,dateprev2); 
                   5279:   
                   5280:   fprintf(ficresf,"#****** Routine prevforecast **\n");
                   5281: 
                   5282: /*           if (h==(int)(YEARM*yearp)){ */
                   5283:   for(cptcov=1, k=0;cptcov<=i1;cptcov++){
                   5284:     for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5285:       k=k+1;
                   5286:       fprintf(ficresf,"\n#******");
                   5287:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5288:        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  5289:       }
                   5290:       fprintf(ficresf,"******\n");
                   5291:       fprintf(ficresf,"# Covariate valuofcovar yearproj age");
                   5292:       for(j=1; j<=nlstate+ndeath;j++){ 
                   5293:        for(i=1; i<=nlstate;i++)              
                   5294:           fprintf(ficresf," p%d%d",i,j);
                   5295:        fprintf(ficresf," p.%d",j);
                   5296:       }
                   5297:       for (yearp=0; yearp<=(anproj2-anproj1);yearp +=stepsize) { 
                   5298:        fprintf(ficresf,"\n");
                   5299:        fprintf(ficresf,"\n# Forecasting at date %.lf/%.lf/%.lf ",jproj1,mproj1,anproj1+yearp);   
                   5300: 
                   5301:        for (agec=fage; agec>=(ageminpar-1); agec--){ 
                   5302:          nhstepm=(int) rint((agelim-agec)*YEARM/stepm); 
                   5303:          nhstepm = nhstepm/hstepm; 
                   5304:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5305:          oldm=oldms;savm=savms;
                   5306:          hpxij(p3mat,nhstepm,agec,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5307:        
                   5308:          for (h=0; h<=nhstepm; h++){
                   5309:            if (h*hstepm/YEARM*stepm ==yearp) {
                   5310:               fprintf(ficresf,"\n");
                   5311:               for(j=1;j<=cptcoveff;j++) 
1.198     brouard  5312:                 fprintf(ficresf,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5313:              fprintf(ficresf,"%.f %.f ",anproj1+yearp,agec+h*hstepm/YEARM*stepm);
                   5314:            } 
                   5315:            for(j=1; j<=nlstate+ndeath;j++) {
                   5316:              ppij=0.;
                   5317:              for(i=1; i<=nlstate;i++) {
                   5318:                if (mobilav==1) 
                   5319:                  ppij=ppij+p3mat[i][j][h]*mobaverage[(int)agec][i][cptcod];
                   5320:                else {
                   5321:                  ppij=ppij+p3mat[i][j][h]*probs[(int)(agec)][i][cptcod];
                   5322:                }
                   5323:                if (h*hstepm/YEARM*stepm== yearp) {
                   5324:                  fprintf(ficresf," %.3f", p3mat[i][j][h]);
                   5325:                }
                   5326:              } /* end i */
                   5327:              if (h*hstepm/YEARM*stepm==yearp) {
                   5328:                fprintf(ficresf," %.3f", ppij);
                   5329:              }
                   5330:            }/* end j */
                   5331:          } /* end h */
                   5332:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5333:        } /* end agec */
                   5334:       } /* end yearp */
                   5335:     } /* end cptcod */
                   5336:   } /* end  cptcov */
                   5337:        
                   5338:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5339: 
                   5340:   fclose(ficresf);
                   5341: }
                   5342: 
                   5343: /************** Forecasting *****not tested NB*************/
1.169     brouard  5344: 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  5345:   
                   5346:   int cpt, stepsize, hstepm, nhstepm, j,k,c, cptcod, i,h;
                   5347:   int *popage;
                   5348:   double calagedatem, agelim, kk1, kk2;
                   5349:   double *popeffectif,*popcount;
                   5350:   double ***p3mat,***tabpop,***tabpopprev;
                   5351:   double ***mobaverage;
                   5352:   char filerespop[FILENAMELENGTH];
                   5353: 
                   5354:   tabpop= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5355:   tabpopprev= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5356:   agelim=AGESUP;
                   5357:   calagedatem=(anpyram+mpyram/12.+jpyram/365.-dateintmean)*YEARM;
                   5358:   
                   5359:   prevalence(probs, ageminpar, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   5360:   
                   5361:   
1.201     brouard  5362:   strcpy(filerespop,"POP_"); 
                   5363:   strcat(filerespop,fileresu);
1.126     brouard  5364:   if((ficrespop=fopen(filerespop,"w"))==NULL) {
                   5365:     printf("Problem with forecast resultfile: %s\n", filerespop);
                   5366:     fprintf(ficlog,"Problem with forecast resultfile: %s\n", filerespop);
                   5367:   }
                   5368:   printf("Computing forecasting: result on file '%s' \n", filerespop);
                   5369:   fprintf(ficlog,"Computing forecasting: result on file '%s' \n", filerespop);
                   5370: 
                   5371:   if (cptcoveff==0) ncodemax[cptcoveff]=1;
                   5372: 
                   5373:   if (mobilav!=0) {
                   5374:     mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5375:     if (movingaverage(probs, ageminpar, fage, mobaverage,mobilav)!=0){
                   5376:       fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   5377:       printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   5378:     }
                   5379:   }
                   5380: 
                   5381:   stepsize=(int) (stepm+YEARM-1)/YEARM;
                   5382:   if (stepm<=12) stepsize=1;
                   5383:   
                   5384:   agelim=AGESUP;
                   5385:   
                   5386:   hstepm=1;
                   5387:   hstepm=hstepm/stepm; 
                   5388:   
                   5389:   if (popforecast==1) {
                   5390:     if((ficpop=fopen(popfile,"r"))==NULL) {
                   5391:       printf("Problem with population file : %s\n",popfile);exit(0);
                   5392:       fprintf(ficlog,"Problem with population file : %s\n",popfile);exit(0);
                   5393:     } 
                   5394:     popage=ivector(0,AGESUP);
                   5395:     popeffectif=vector(0,AGESUP);
                   5396:     popcount=vector(0,AGESUP);
                   5397:     
                   5398:     i=1;   
                   5399:     while ((c=fscanf(ficpop,"%d %lf\n",&popage[i],&popcount[i])) != EOF) i=i+1;
                   5400:    
                   5401:     imx=i;
                   5402:     for (i=1; i<imx;i++) popeffectif[popage[i]]=popcount[i];
                   5403:   }
                   5404: 
                   5405:   for(cptcov=1,k=0;cptcov<=i2;cptcov++){
                   5406:    for(cptcod=1;cptcod<=ncodemax[cptcoveff];cptcod++){
                   5407:       k=k+1;
                   5408:       fprintf(ficrespop,"\n#******");
                   5409:       for(j=1;j<=cptcoveff;j++) {
1.198     brouard  5410:        fprintf(ficrespop," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  5411:       }
                   5412:       fprintf(ficrespop,"******\n");
                   5413:       fprintf(ficrespop,"# Age");
                   5414:       for(j=1; j<=nlstate+ndeath;j++) fprintf(ficrespop," P.%d",j);
                   5415:       if (popforecast==1)  fprintf(ficrespop," [Population]");
                   5416:       
                   5417:       for (cpt=0; cpt<=0;cpt++) { 
                   5418:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5419:        
                   5420:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5421:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5422:          nhstepm = nhstepm/hstepm; 
                   5423:          
                   5424:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5425:          oldm=oldms;savm=savms;
                   5426:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5427:        
                   5428:          for (h=0; h<=nhstepm; h++){
                   5429:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5430:              fprintf(ficrespop,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5431:            } 
                   5432:            for(j=1; j<=nlstate+ndeath;j++) {
                   5433:              kk1=0.;kk2=0;
                   5434:              for(i=1; i<=nlstate;i++) {              
                   5435:                if (mobilav==1) 
                   5436:                  kk1=kk1+p3mat[i][j][h]*mobaverage[(int)agedeb+1][i][cptcod];
                   5437:                else {
                   5438:                  kk1=kk1+p3mat[i][j][h]*probs[(int)(agedeb+1)][i][cptcod];
                   5439:                }
                   5440:              }
                   5441:              if (h==(int)(calagedatem+12*cpt)){
                   5442:                tabpop[(int)(agedeb)][j][cptcod]=kk1;
                   5443:                  /*fprintf(ficrespop," %.3f", kk1);
                   5444:                    if (popforecast==1) fprintf(ficrespop," [%.f]", kk1*popeffectif[(int)agedeb+1]);*/
                   5445:              }
                   5446:            }
                   5447:            for(i=1; i<=nlstate;i++){
                   5448:              kk1=0.;
                   5449:                for(j=1; j<=nlstate;j++){
                   5450:                  kk1= kk1+tabpop[(int)(agedeb)][j][cptcod]; 
                   5451:                }
                   5452:                  tabpopprev[(int)(agedeb)][i][cptcod]=tabpop[(int)(agedeb)][i][cptcod]/kk1*popeffectif[(int)(agedeb+(calagedatem+12*cpt)*hstepm/YEARM*stepm-1)];
                   5453:            }
                   5454: 
                   5455:            if (h==(int)(calagedatem+12*cpt)) for(j=1; j<=nlstate;j++) 
                   5456:              fprintf(ficrespop," %15.2f",tabpopprev[(int)(agedeb+1)][j][cptcod]);
                   5457:          }
                   5458:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5459:        }
                   5460:       }
                   5461:  
                   5462:   /******/
                   5463: 
                   5464:       for (cpt=1; cpt<=(anpyram1-anpyram);cpt++) { 
                   5465:        fprintf(ficrespop,"\n\n# Forecasting at date %.lf/%.lf/%.lf ",jpyram,mpyram,anpyram+cpt);   
                   5466:        for (agedeb=(fage-((int)calagedatem %12/12.)); agedeb>=(ageminpar-((int)calagedatem %12)/12.); agedeb--){ 
                   5467:          nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); 
                   5468:          nhstepm = nhstepm/hstepm; 
                   5469:          
                   5470:          p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5471:          oldm=oldms;savm=savms;
                   5472:          hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   5473:          for (h=0; h<=nhstepm; h++){
                   5474:            if (h==(int) (calagedatem+YEARM*cpt)) {
                   5475:              fprintf(ficresf,"\n %3.f ",agedeb+h*hstepm/YEARM*stepm);
                   5476:            } 
                   5477:            for(j=1; j<=nlstate+ndeath;j++) {
                   5478:              kk1=0.;kk2=0;
                   5479:              for(i=1; i<=nlstate;i++) {              
                   5480:                kk1=kk1+p3mat[i][j][h]*tabpopprev[(int)agedeb+1][i][cptcod];    
                   5481:              }
                   5482:              if (h==(int)(calagedatem+12*cpt)) fprintf(ficresf," %15.2f", kk1);        
                   5483:            }
                   5484:          }
                   5485:          free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   5486:        }
                   5487:       }
                   5488:    } 
                   5489:   }
                   5490:  
                   5491:   if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5492: 
                   5493:   if (popforecast==1) {
                   5494:     free_ivector(popage,0,AGESUP);
                   5495:     free_vector(popeffectif,0,AGESUP);
                   5496:     free_vector(popcount,0,AGESUP);
                   5497:   }
                   5498:   free_ma3x(tabpop,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5499:   free_ma3x(tabpopprev,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   5500:   fclose(ficrespop);
                   5501: } /* End of popforecast */
                   5502: 
                   5503: int fileappend(FILE *fichier, char *optionfich)
                   5504: {
                   5505:   if((fichier=fopen(optionfich,"a"))==NULL) {
                   5506:     printf("Problem with file: %s\n", optionfich);
                   5507:     fprintf(ficlog,"Problem with file: %s\n", optionfich);
                   5508:     return (0);
                   5509:   }
                   5510:   fflush(fichier);
                   5511:   return (1);
                   5512: }
                   5513: 
                   5514: 
                   5515: /**************** function prwizard **********************/
                   5516: void prwizard(int ncovmodel, int nlstate, int ndeath,  char model[], FILE *ficparo)
                   5517: {
                   5518: 
                   5519:   /* Wizard to print covariance matrix template */
                   5520: 
1.164     brouard  5521:   char ca[32], cb[32];
                   5522:   int i,j, k, li, lj, lk, ll, jj, npar, itimes;
1.126     brouard  5523:   int numlinepar;
                   5524: 
                   5525:   printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5526:   fprintf(ficparo,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   5527:   for(i=1; i <=nlstate; i++){
                   5528:     jj=0;
                   5529:     for(j=1; j <=nlstate+ndeath; j++){
                   5530:       if(j==i) continue;
                   5531:       jj++;
                   5532:       /*ca[0]= k+'a'-1;ca[1]='\0';*/
                   5533:       printf("%1d%1d",i,j);
                   5534:       fprintf(ficparo,"%1d%1d",i,j);
                   5535:       for(k=1; k<=ncovmodel;k++){
                   5536:        /*        printf(" %lf",param[i][j][k]); */
                   5537:        /*        fprintf(ficparo," %lf",param[i][j][k]); */
                   5538:        printf(" 0.");
                   5539:        fprintf(ficparo," 0.");
                   5540:       }
                   5541:       printf("\n");
                   5542:       fprintf(ficparo,"\n");
                   5543:     }
                   5544:   }
                   5545:   printf("# Scales (for hessian or gradient estimation)\n");
                   5546:   fprintf(ficparo,"# Scales (for hessian or gradient estimation)\n");
                   5547:   npar= (nlstate+ndeath-1)*nlstate*ncovmodel; /* Number of parameters*/ 
                   5548:   for(i=1; i <=nlstate; i++){
                   5549:     jj=0;
                   5550:     for(j=1; j <=nlstate+ndeath; j++){
                   5551:       if(j==i) continue;
                   5552:       jj++;
                   5553:       fprintf(ficparo,"%1d%1d",i,j);
                   5554:       printf("%1d%1d",i,j);
                   5555:       fflush(stdout);
                   5556:       for(k=1; k<=ncovmodel;k++){
                   5557:        /*      printf(" %le",delti3[i][j][k]); */
                   5558:        /*      fprintf(ficparo," %le",delti3[i][j][k]); */
                   5559:        printf(" 0.");
                   5560:        fprintf(ficparo," 0.");
                   5561:       }
                   5562:       numlinepar++;
                   5563:       printf("\n");
                   5564:       fprintf(ficparo,"\n");
                   5565:     }
                   5566:   }
                   5567:   printf("# Covariance matrix\n");
                   5568: /* # 121 Var(a12)\n\ */
                   5569: /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5570: /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   5571: /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   5572: /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   5573: /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   5574: /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   5575: /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   5576:   fflush(stdout);
                   5577:   fprintf(ficparo,"# Covariance matrix\n");
                   5578:   /* # 121 Var(a12)\n\ */
                   5579:   /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   5580:   /* #   ...\n\ */
                   5581:   /* # 232 Cov(b23,a12)  Cov(b23,b12) ... Var (b23)\n" */
                   5582:   
                   5583:   for(itimes=1;itimes<=2;itimes++){
                   5584:     jj=0;
                   5585:     for(i=1; i <=nlstate; i++){
                   5586:       for(j=1; j <=nlstate+ndeath; j++){
                   5587:        if(j==i) continue;
                   5588:        for(k=1; k<=ncovmodel;k++){
                   5589:          jj++;
                   5590:          ca[0]= k+'a'-1;ca[1]='\0';
                   5591:          if(itimes==1){
                   5592:            printf("#%1d%1d%d",i,j,k);
                   5593:            fprintf(ficparo,"#%1d%1d%d",i,j,k);
                   5594:          }else{
                   5595:            printf("%1d%1d%d",i,j,k);
                   5596:            fprintf(ficparo,"%1d%1d%d",i,j,k);
                   5597:            /*  printf(" %.5le",matcov[i][j]); */
                   5598:          }
                   5599:          ll=0;
                   5600:          for(li=1;li <=nlstate; li++){
                   5601:            for(lj=1;lj <=nlstate+ndeath; lj++){
                   5602:              if(lj==li) continue;
                   5603:              for(lk=1;lk<=ncovmodel;lk++){
                   5604:                ll++;
                   5605:                if(ll<=jj){
                   5606:                  cb[0]= lk +'a'-1;cb[1]='\0';
                   5607:                  if(ll<jj){
                   5608:                    if(itimes==1){
                   5609:                      printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5610:                      fprintf(ficparo," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   5611:                    }else{
                   5612:                      printf(" 0.");
                   5613:                      fprintf(ficparo," 0.");
                   5614:                    }
                   5615:                  }else{
                   5616:                    if(itimes==1){
                   5617:                      printf(" Var(%s%1d%1d)",ca,i,j);
                   5618:                      fprintf(ficparo," Var(%s%1d%1d)",ca,i,j);
                   5619:                    }else{
                   5620:                      printf(" 0.");
                   5621:                      fprintf(ficparo," 0.");
                   5622:                    }
                   5623:                  }
                   5624:                }
                   5625:              } /* end lk */
                   5626:            } /* end lj */
                   5627:          } /* end li */
                   5628:          printf("\n");
                   5629:          fprintf(ficparo,"\n");
                   5630:          numlinepar++;
                   5631:        } /* end k*/
                   5632:       } /*end j */
                   5633:     } /* end i */
                   5634:   } /* end itimes */
                   5635: 
                   5636: } /* end of prwizard */
                   5637: /******************* Gompertz Likelihood ******************************/
                   5638: double gompertz(double x[])
                   5639: { 
                   5640:   double A,B,L=0.0,sump=0.,num=0.;
                   5641:   int i,n=0; /* n is the size of the sample */
                   5642: 
                   5643:   for (i=0;i<=imx-1 ; i++) {
                   5644:     sump=sump+weight[i];
                   5645:     /*    sump=sump+1;*/
                   5646:     num=num+1;
                   5647:   }
                   5648:  
                   5649:  
                   5650:   /* for (i=0; i<=imx; i++) 
                   5651:      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]);*/
                   5652: 
                   5653:   for (i=1;i<=imx ; i++)
                   5654:     {
                   5655:       if (cens[i] == 1 && wav[i]>1)
                   5656:        A=-x[1]/(x[2])*(exp(x[2]*(agecens[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)));
                   5657:       
                   5658:       if (cens[i] == 0 && wav[i]>1)
                   5659:        A=-x[1]/(x[2])*(exp(x[2]*(agedc[i]-agegomp))-exp(x[2]*(ageexmed[i]-agegomp)))
                   5660:             +log(x[1]/YEARM)+x[2]*(agedc[i]-agegomp)+log(YEARM);  
                   5661:       
                   5662:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5663:       if (wav[i] > 1 ) { /* ??? */
                   5664:        L=L+A*weight[i];
                   5665:        /*      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]);*/
                   5666:       }
                   5667:     }
                   5668: 
                   5669:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5670:  
                   5671:   return -2*L*num/sump;
                   5672: }
                   5673: 
1.136     brouard  5674: #ifdef GSL
                   5675: /******************* Gompertz_f Likelihood ******************************/
                   5676: double gompertz_f(const gsl_vector *v, void *params)
                   5677: { 
                   5678:   double A,B,LL=0.0,sump=0.,num=0.;
                   5679:   double *x= (double *) v->data;
                   5680:   int i,n=0; /* n is the size of the sample */
                   5681: 
                   5682:   for (i=0;i<=imx-1 ; i++) {
                   5683:     sump=sump+weight[i];
                   5684:     /*    sump=sump+1;*/
                   5685:     num=num+1;
                   5686:   }
                   5687:  
                   5688:  
                   5689:   /* for (i=0; i<=imx; i++) 
                   5690:      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]);*/
                   5691:   printf("x[0]=%lf x[1]=%lf\n",x[0],x[1]);
                   5692:   for (i=1;i<=imx ; i++)
                   5693:     {
                   5694:       if (cens[i] == 1 && wav[i]>1)
                   5695:        A=-x[0]/(x[1])*(exp(x[1]*(agecens[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)));
                   5696:       
                   5697:       if (cens[i] == 0 && wav[i]>1)
                   5698:        A=-x[0]/(x[1])*(exp(x[1]*(agedc[i]-agegomp))-exp(x[1]*(ageexmed[i]-agegomp)))
                   5699:             +log(x[0]/YEARM)+x[1]*(agedc[i]-agegomp)+log(YEARM);  
                   5700:       
                   5701:       /*if (wav[i] > 1 && agecens[i] > 15) {*/ /* ??? */
                   5702:       if (wav[i] > 1 ) { /* ??? */
                   5703:        LL=LL+A*weight[i];
                   5704:        /*      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]);*/
                   5705:       }
                   5706:     }
                   5707: 
                   5708:  /*printf("x1=%2.9f x2=%2.9f x3=%2.9f L=%f\n",x[1],x[2],x[3],L);*/
                   5709:   printf("x[0]=%lf x[1]=%lf -2*LL*num/sump=%lf\n",x[0],x[1],-2*LL*num/sump);
                   5710:  
                   5711:   return -2*LL*num/sump;
                   5712: }
                   5713: #endif
                   5714: 
1.126     brouard  5715: /******************* Printing html file ***********/
1.201     brouard  5716: void printinghtmlmort(char fileresu[], char title[], char datafile[], int firstpass, \
1.126     brouard  5717:                  int lastpass, int stepm, int weightopt, char model[],\
                   5718:                  int imx,  double p[],double **matcov,double agemortsup){
                   5719:   int i,k;
                   5720: 
                   5721:   fprintf(fichtm,"<ul><li><h4>Result files </h4>\n Force of mortality. Parameters of the Gompertz fit (with confidence interval in brackets):<br>");
                   5722:   fprintf(fichtm,"  mu(age) =%lf*exp(%lf*(age-%d)) per year<br><br>",p[1],p[2],agegomp);
                   5723:   for (i=1;i<=2;i++) 
                   5724:     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  5725:   fprintf(fichtm,"<br><br><img src=\"graphmort.svg\">");
1.126     brouard  5726:   fprintf(fichtm,"</ul>");
                   5727: 
                   5728: fprintf(fichtm,"<ul><li><h4>Life table</h4>\n <br>");
                   5729: 
                   5730:  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>");
                   5731: 
                   5732:  for (k=agegomp;k<(agemortsup-2);k++) 
                   5733:    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]);
                   5734: 
                   5735:  
                   5736:   fflush(fichtm);
                   5737: }
                   5738: 
                   5739: /******************* Gnuplot file **************/
1.201     brouard  5740: void printinggnuplotmort(char fileresu[], char optionfilefiname[], double ageminpar, double agemaxpar, double fage , char pathc[], double p[]){
1.126     brouard  5741: 
                   5742:   char dirfileres[132],optfileres[132];
1.164     brouard  5743: 
1.126     brouard  5744:   int ng;
                   5745: 
                   5746: 
                   5747:   /*#ifdef windows */
                   5748:   fprintf(ficgp,"cd \"%s\" \n",pathc);
                   5749:     /*#endif */
                   5750: 
                   5751: 
                   5752:   strcpy(dirfileres,optionfilefiname);
                   5753:   strcpy(optfileres,"vpl");
1.199     brouard  5754:   fprintf(ficgp,"set out \"graphmort.svg\"\n "); 
1.126     brouard  5755:   fprintf(ficgp,"set xlabel \"Age\"\n set ylabel \"Force of mortality (per year)\" \n "); 
1.199     brouard  5756:   fprintf(ficgp, "set ter svg size 640, 480\n set log y\n"); 
1.145     brouard  5757:   /* fprintf(ficgp, "set size 0.65,0.65\n"); */
1.126     brouard  5758:   fprintf(ficgp,"plot [%d:100] %lf*exp(%lf*(x-%d))",agegomp,p[1],p[2],agegomp);
                   5759: 
                   5760: } 
                   5761: 
1.136     brouard  5762: int readdata(char datafile[], int firstobs, int lastobs, int *imax)
                   5763: {
1.126     brouard  5764: 
1.136     brouard  5765:   /*-------- data file ----------*/
                   5766:   FILE *fic;
                   5767:   char dummy[]="                         ";
1.164     brouard  5768:   int i=0, j=0, n=0;
1.136     brouard  5769:   int linei, month, year,iout;
                   5770:   char line[MAXLINE], linetmp[MAXLINE];
1.164     brouard  5771:   char stra[MAXLINE], strb[MAXLINE];
1.136     brouard  5772:   char *stratrunc;
                   5773:   int lstra;
1.126     brouard  5774: 
                   5775: 
1.136     brouard  5776:   if((fic=fopen(datafile,"r"))==NULL)    {
1.195     brouard  5777:     printf("Problem while opening datafile: %s\n", datafile);fflush(stdout);
                   5778:     fprintf(ficlog,"Problem while opening datafile: %s\n", datafile);fflush(ficlog);return 1;
1.136     brouard  5779:   }
1.126     brouard  5780: 
1.136     brouard  5781:   i=1;
                   5782:   linei=0;
                   5783:   while ((fgets(line, MAXLINE, fic) != NULL) &&((i >= firstobs) && (i <=lastobs))) {
                   5784:     linei=linei+1;
                   5785:     for(j=strlen(line); j>=0;j--){  /* Untabifies line */
                   5786:       if(line[j] == '\t')
                   5787:        line[j] = ' ';
                   5788:     }
                   5789:     for(j=strlen(line)-1; (line[j]==' ')||(line[j]==10)||(line[j]==13);j--){
                   5790:       ;
                   5791:     };
                   5792:     line[j+1]=0;  /* Trims blanks at end of line */
                   5793:     if(line[0]=='#'){
                   5794:       fprintf(ficlog,"Comment line\n%s\n",line);
                   5795:       printf("Comment line\n%s\n",line);
                   5796:       continue;
                   5797:     }
                   5798:     trimbb(linetmp,line); /* Trims multiple blanks in line */
1.164     brouard  5799:     strcpy(line, linetmp);
1.136     brouard  5800:   
1.126     brouard  5801: 
1.136     brouard  5802:     for (j=maxwav;j>=1;j--){
1.137     brouard  5803:       cutv(stra, strb, line, ' '); 
1.136     brouard  5804:       if(strb[0]=='.') { /* Missing status */
                   5805:        lval=-1;
                   5806:       }else{
                   5807:        errno=0;
                   5808:        lval=strtol(strb,&endptr,10); 
                   5809:       /*       if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))*/
                   5810:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5811:          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);
                   5812:          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  5813:          return 1;
                   5814:        }
                   5815:       }
                   5816:       s[j][i]=lval;
                   5817:       
                   5818:       strcpy(line,stra);
                   5819:       cutv(stra, strb,line,' ');
1.169     brouard  5820:       if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5821:       }
1.169     brouard  5822:       else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5823:        month=99;
                   5824:        year=9999;
                   5825:       }else{
1.141     brouard  5826:        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);
                   5827:        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  5828:        return 1;
                   5829:       }
                   5830:       anint[j][i]= (double) year; 
                   5831:       mint[j][i]= (double)month; 
                   5832:       strcpy(line,stra);
                   5833:     } /* ENd Waves */
                   5834:     
                   5835:     cutv(stra, strb,line,' '); 
1.169     brouard  5836:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5837:     }
1.169     brouard  5838:     else  if( (iout=sscanf(strb,"%s.",dummy)) != 0){
1.136     brouard  5839:       month=99;
                   5840:       year=9999;
                   5841:     }else{
1.141     brouard  5842:       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);
                   5843:        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  5844:        return 1;
                   5845:     }
                   5846:     andc[i]=(double) year; 
                   5847:     moisdc[i]=(double) month; 
                   5848:     strcpy(line,stra);
                   5849:     
                   5850:     cutv(stra, strb,line,' '); 
1.169     brouard  5851:     if( (iout=sscanf(strb,"%d/%d",&month, &year)) != 0){
1.136     brouard  5852:     }
1.169     brouard  5853:     else  if( (iout=sscanf(strb,"%s.", dummy)) != 0){
1.136     brouard  5854:       month=99;
                   5855:       year=9999;
                   5856:     }else{
1.141     brouard  5857:       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);
                   5858:       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  5859:        return 1;
                   5860:     }
                   5861:     if (year==9999) {
1.141     brouard  5862:       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);
                   5863:       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  5864:        return 1;
1.126     brouard  5865: 
1.136     brouard  5866:     }
                   5867:     annais[i]=(double)(year);
                   5868:     moisnais[i]=(double)(month); 
                   5869:     strcpy(line,stra);
                   5870:     
                   5871:     cutv(stra, strb,line,' '); 
                   5872:     errno=0;
                   5873:     dval=strtod(strb,&endptr); 
                   5874:     if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5875:       printf("Error reading data around '%f' at line number %d, \"%s\" for individual %d\nShould be a weight.  Exiting.\n",dval, i,line,linei);
                   5876:       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  5877:       fflush(ficlog);
                   5878:       return 1;
                   5879:     }
                   5880:     weight[i]=dval; 
                   5881:     strcpy(line,stra);
                   5882:     
                   5883:     for (j=ncovcol;j>=1;j--){
                   5884:       cutv(stra, strb,line,' '); 
                   5885:       if(strb[0]=='.') { /* Missing status */
                   5886:        lval=-1;
                   5887:       }else{
                   5888:        errno=0;
                   5889:        lval=strtol(strb,&endptr,10); 
                   5890:        if( strb[0]=='\0' || (*endptr != '\0')){
1.141     brouard  5891:          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);
                   5892:          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  5893:          return 1;
                   5894:        }
                   5895:       }
                   5896:       if(lval <-1 || lval >1){
1.141     brouard  5897:        printf("Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5898:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5899:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5900:  For example, for multinomial values like 1, 2 and 3,\n \
                   5901:  build V1=0 V2=0 for the reference value (1),\n \
                   5902:         V1=1 V2=0 for (2) \n \
                   5903:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5904:  output of IMaCh is often meaningless.\n \
                   5905:  Exiting.\n",lval,linei, i,line,j);
1.141     brouard  5906:        fprintf(ficlog,"Error reading data around '%ld' at line number %d for individual %d, '%s'\n \
1.136     brouard  5907:  Should be a value of %d(nth) covariate (0 should be the value for the reference and 1\n \
                   5908:  for the alternative. IMaCh does not build design variables automatically, do it yourself.\n \
                   5909:  For example, for multinomial values like 1, 2 and 3,\n \
                   5910:  build V1=0 V2=0 for the reference value (1),\n \
                   5911:         V1=1 V2=0 for (2) \n \
                   5912:  and V1=0 V2=1 for (3). V1=1 V2=1 should not exist and the corresponding\n \
                   5913:  output of IMaCh is often meaningless.\n \
                   5914:  Exiting.\n",lval,linei, i,line,j);fflush(ficlog);
                   5915:        return 1;
                   5916:       }
                   5917:       covar[j][i]=(double)(lval);
                   5918:       strcpy(line,stra);
                   5919:     }  
                   5920:     lstra=strlen(stra);
                   5921:      
                   5922:     if(lstra > 9){ /* More than 2**32 or max of what printf can write with %ld */
                   5923:       stratrunc = &(stra[lstra-9]);
                   5924:       num[i]=atol(stratrunc);
                   5925:     }
                   5926:     else
                   5927:       num[i]=atol(stra);
                   5928:     /*if((s[2][i]==2) && (s[3][i]==-1)&&(s[4][i]==9)){
                   5929:       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;}*/
                   5930:     
                   5931:     i=i+1;
                   5932:   } /* End loop reading  data */
1.126     brouard  5933: 
1.136     brouard  5934:   *imax=i-1; /* Number of individuals */
                   5935:   fclose(fic);
                   5936:  
                   5937:   return (0);
1.164     brouard  5938:   /* endread: */
1.136     brouard  5939:     printf("Exiting readdata: ");
                   5940:     fclose(fic);
                   5941:     return (1);
1.126     brouard  5942: 
                   5943: 
                   5944: 
1.136     brouard  5945: }
1.145     brouard  5946: void removespace(char *str) {
                   5947:   char *p1 = str, *p2 = str;
                   5948:   do
                   5949:     while (*p2 == ' ')
                   5950:       p2++;
1.169     brouard  5951:   while (*p1++ == *p2++);
1.145     brouard  5952: }
                   5953: 
                   5954: int decodemodel ( char model[], int lastobs) /**< This routine decode the model and returns:
1.187     brouard  5955:    * Model  V1+V2+V3+V8+V7*V8+V5*V6+V8*age+V3*age+age*age
                   5956:    * - nagesqr = 1 if age*age in the model, otherwise 0.
                   5957:    * - cptcovt total number of covariates of the model nbocc(+)+1 = 8 excepting constant and age and age*age
                   5958:    * - cptcovn or number of covariates k of the models excluding age*products =6 and age*age
1.145     brouard  5959:    * - cptcovage number of covariates with age*products =2
                   5960:    * - cptcovs number of simple covariates
                   5961:    * - 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
                   5962:    *     which is a new column after the 9 (ncovcol) variables. 
                   5963:    * - if k is a product Vn*Vm covar[k][i] is filled with correct values for each individual
                   5964:    * - Tprod[l] gives the kth covariates of the product Vn*Vm l=1 to cptcovprod-cptcovage
                   5965:    *    Tprod[1]@2 {5, 6}: position of first product V7*V8 is 5, and second V5*V6 is 6.
                   5966:    * - Tvard[k]  p Tvard[1][1]@4 {7, 8, 5, 6} for V7*V8 and V5*V6 .
                   5967:  */
1.136     brouard  5968: {
1.145     brouard  5969:   int i, j, k, ks;
1.164     brouard  5970:   int  j1, k1, k2;
1.136     brouard  5971:   char modelsav[80];
1.145     brouard  5972:   char stra[80], strb[80], strc[80], strd[80],stre[80];
1.187     brouard  5973:   char *strpt;
1.136     brouard  5974: 
1.145     brouard  5975:   /*removespace(model);*/
1.136     brouard  5976:   if (strlen(model) >1){ /* If there is at least 1 covariate */
1.145     brouard  5977:     j=0, j1=0, k1=0, k2=-1, ks=0, cptcovn=0;
1.137     brouard  5978:     if (strstr(model,"AGE") !=0){
1.192     brouard  5979:       printf("Error. AGE must be in lower case 'age' model=1+age+%s. ",model);
                   5980:       fprintf(ficlog,"Error. AGE must be in lower case model=1+age+%s. ",model);fflush(ficlog);
1.136     brouard  5981:       return 1;
                   5982:     }
1.141     brouard  5983:     if (strstr(model,"v") !=0){
                   5984:       printf("Error. 'v' must be in upper case 'V' model=%s ",model);
                   5985:       fprintf(ficlog,"Error. 'v' must be in upper case model=%s ",model);fflush(ficlog);
                   5986:       return 1;
                   5987:     }
1.187     brouard  5988:     strcpy(modelsav,model); 
                   5989:     if ((strpt=strstr(model,"age*age")) !=0){
                   5990:       printf(" strpt=%s, model=%s\n",strpt, model);
                   5991:       if(strpt != model){
                   5992:       printf("Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5993:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5994:  corresponding column of parameters.\n",model);
                   5995:       fprintf(ficlog,"Error in model: 'model=%s'; 'age*age' should in first place before other covariates\n \
1.192     brouard  5996:  'model=1+age+age*age+V1.' or 'model=1+age+age*age+V1+V1*age.', please swap as well as \n \
1.187     brouard  5997:  corresponding column of parameters.\n",model); fflush(ficlog);
                   5998:       return 1;
                   5999:     }
                   6000: 
                   6001:       nagesqr=1;
                   6002:       if (strstr(model,"+age*age") !=0)
                   6003:        substrchaine(modelsav, model, "+age*age");
                   6004:       else if (strstr(model,"age*age+") !=0)
                   6005:        substrchaine(modelsav, model, "age*age+");
                   6006:       else 
                   6007:        substrchaine(modelsav, model, "age*age");
                   6008:     }else
                   6009:       nagesqr=0;
                   6010:     if (strlen(modelsav) >1){
                   6011:       j=nbocc(modelsav,'+'); /**< j=Number of '+' */
                   6012:       j1=nbocc(modelsav,'*'); /**< j1=Number of '*' */
                   6013:       cptcovs=j+1-j1; /**<  Number of simple covariates V1+V1*age+V3 +V3*V4+age*age=> V1 + V3 =2  */
                   6014:       cptcovt= j+1; /* Number of total covariates in the model, not including
                   6015:                   * cst, age and age*age 
                   6016:                   * V1+V1*age+ V3 + V3*V4+age*age=> 4*/
                   6017:                   /* including age products which are counted in cptcovage.
                   6018:                  * but the covariates which are products must be treated 
                   6019:                  * separately: ncovn=4- 2=2 (V1+V3). */
                   6020:       cptcovprod=j1; /**< Number of products  V1*V2 +v3*age = 2 */
                   6021:       cptcovprodnoage=0; /**< Number of covariate products without age: V3*V4 =1  */
                   6022: 
                   6023:     
                   6024:       /*   Design
                   6025:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9 Weight
                   6026:        *  <          ncovcol=8                >
                   6027:        * Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8
                   6028:        *   k=  1    2      3       4     5       6      7        8
                   6029:        *  cptcovn number of covariates (not including constant and age ) = # of + plus 1 = 7+1=8
                   6030:        *  covar[k,i], value of kth covariate if not including age for individual i:
                   6031:        *       covar[1][i]= (V2), covar[4][i]=(V3), covar[8][i]=(V8)
                   6032:        *  Tvar[k] # of the kth covariate:  Tvar[1]=2  Tvar[4]=3 Tvar[8]=8
                   6033:        *       if multiplied by age: V3*age Tvar[3=V3*age]=3 (V3) Tvar[7]=8 and 
                   6034:        *  Tage[++cptcovage]=k
                   6035:        *       if products, new covar are created after ncovcol with k1
                   6036:        *  Tvar[k]=ncovcol+k1; # of the kth covariate product:  Tvar[5]=ncovcol+1=10  Tvar[6]=ncovcol+1=11
                   6037:        *  Tprod[k1]=k; Tprod[1]=5 Tprod[2]= 6; gives the position of the k1th product
                   6038:        *  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
                   6039:        *  Tvar[cptcovn+k2]=Tvard[k1][1];Tvar[cptcovn+k2+1]=Tvard[k1][2];
                   6040:        *  Tvar[8+1]=5;Tvar[8+2]=6;Tvar[8+3]=7;Tvar[8+4]=8 inverted
                   6041:        *  V1   V2   V3   V4  V5  V6  V7  V8  V9  V10  V11
                   6042:        *  <          ncovcol=8                >
                   6043:        *       Model V2 + V1 + V3*age + V3 + V5*V6 + V7*V8 + V8*age + V8    d1   d1   d2  d2
                   6044:        *          k=  1    2      3       4     5       6      7        8    9   10   11  12
                   6045:        *     Tvar[k]= 2    1      3       3    10      11      8        8    5    6    7   8
                   6046:        * p Tvar[1]@12={2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6047:        * p Tprod[1]@2={                         6, 5}
                   6048:        *p Tvard[1][1]@4= {7, 8, 5, 6}
                   6049:        * covar[k][i]= V2   V1      ?      V3    V5*V6?   V7*V8?  ?       V8   
                   6050:        *  cov[Tage[kk]+2]=covar[Tvar[Tage[kk]]][i]*cov[2];
                   6051:        *How to reorganize?
                   6052:        * Model V1 + V2 + V3 + V8 + V5*V6 + V7*V8 + V3*age + V8*age
                   6053:        * Tvars {2,   1,     3,      3,   11,     10,     8,       8,   7,   8,   5,  6}
                   6054:        *       {2,   1,     4,      8,    5,      6,     3,       7}
                   6055:        * Struct []
                   6056:        */
1.145     brouard  6057: 
1.187     brouard  6058:       /* This loop fills the array Tvar from the string 'model'.*/
                   6059:       /* j is the number of + signs in the model V1+V2+V3 j=2 i=3 to 1 */
                   6060:       /*   modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4  */
                   6061:       /*       k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tage[cptcovage=1]=4 */
                   6062:       /*       k=3 V4 Tvar[k=3]= 4 (from V4) */
                   6063:       /*       k=2 V1 Tvar[k=2]= 1 (from V1) */
                   6064:       /*       k=1 Tvar[1]=2 (from V2) */
                   6065:       /*       k=5 Tvar[5] */
                   6066:       /* for (k=1; k<=cptcovn;k++) { */
1.198     brouard  6067:       /*       cov[2+k]=nbcode[Tvar[k]][codtabm(ij,Tvar[k])]; */
1.187     brouard  6068:       /*       } */
1.198     brouard  6069:       /* for (k=1; k<=cptcovage;k++) cov[2+Tage[k]]=nbcode[Tvar[Tage[k]]][codtabm(ij,Tvar[Tage[k])]]*cov[2]; */
1.187     brouard  6070:       /*
                   6071:        * Treating invertedly V2+V1+V3*age+V2*V4 is as if written V2*V4 +V3*age + V1 + V2 */
                   6072:       for(k=cptcovt; k>=1;k--) /**< Number of covariates */
1.145     brouard  6073:         Tvar[k]=0;
1.187     brouard  6074:       cptcovage=0;
                   6075:       for(k=1; k<=cptcovt;k++){ /* Loop on total covariates of the model */
                   6076:        cutl(stra,strb,modelsav,'+'); /* keeps in strb after the first '+' 
                   6077:                                         modelsav==V2+V1+V4+V3*age strb=V3*age stra=V2+V1+V4 */ 
                   6078:        if (nbocc(modelsav,'+')==0) strcpy(strb,modelsav); /* and analyzes it */
                   6079:        /*      printf("i=%d a=%s b=%s sav=%s\n",i, stra,strb,modelsav);*/
                   6080:        /*scanf("%d",i);*/
                   6081:        if (strchr(strb,'*')) {  /**< Model includes a product V2+V1+V4+V3*age strb=V3*age */
                   6082:          cutl(strc,strd,strb,'*'); /**< strd*strc  Vm*Vn: strb=V3*age(input) strc=age strd=V3 ; V3*V2 strc=V2, strd=V3 */
                   6083:          if (strcmp(strc,"age")==0) { /**< Model includes age: Vn*age */
                   6084:            /* covar is not filled and then is empty */
                   6085:            cptcovprod--;
                   6086:            cutl(stre,strb,strd,'V'); /* strd=V3(input): stre="3" */
                   6087:            Tvar[k]=atoi(stre);  /* V2+V1+V4+V3*age Tvar[4]=3 ; V1+V2*age Tvar[2]=2; V1+V1*age Tvar[2]=1 */
                   6088:            cptcovage++; /* Sums the number of covariates which include age as a product */
                   6089:            Tage[cptcovage]=k;  /* Tvar[4]=3, Tage[1] = 4 or V1+V1*age Tvar[2]=1, Tage[1]=2 */
                   6090:            /*printf("stre=%s ", stre);*/
                   6091:          } else if (strcmp(strd,"age")==0) { /* or age*Vn */
                   6092:            cptcovprod--;
                   6093:            cutl(stre,strb,strc,'V');
                   6094:            Tvar[k]=atoi(stre);
                   6095:            cptcovage++;
                   6096:            Tage[cptcovage]=k;
                   6097:          } else {  /* Age is not in the model product V2+V1+V1*V4+V3*age+V3*V2  strb=V3*V2*/
                   6098:            /* loops on k1=1 (V3*V2) and k1=2 V4*V3 */
                   6099:            cptcovn++;
                   6100:            cptcovprodnoage++;k1++;
                   6101:            cutl(stre,strb,strc,'V'); /* strc= Vn, stre is n; strb=V3*V2 stre=3 strc=*/
                   6102:            Tvar[k]=ncovcol+k1; /* For model-covariate k tells which data-covariate to use but
                   6103:                                   because this model-covariate is a construction we invent a new column
                   6104:                                   ncovcol + k1
                   6105:                                   If already ncovcol=4 and model=V2+V1+V1*V4+age*V3+V3*V2
                   6106:                                   Tvar[3=V1*V4]=4+1 Tvar[5=V3*V2]=4 + 2= 6, etc */
                   6107:            cutl(strc,strb,strd,'V'); /* strd was Vm, strc is m */
                   6108:            Tprod[k1]=k;  /* Tprod[1]=3(=V1*V4) for V2+V1+V1*V4+age*V3+V3*V2  */
                   6109:            Tvard[k1][1] =atoi(strc); /* m 1 for V1*/
                   6110:            Tvard[k1][2] =atoi(stre); /* n 4 for V4*/
                   6111:            k2=k2+2;
                   6112:            Tvar[cptcovt+k2]=Tvard[k1][1]; /* Tvar[(cptcovt=4+k2=1)=5]= 1 (V1) */
                   6113:            Tvar[cptcovt+k2+1]=Tvard[k1][2];  /* Tvar[(cptcovt=4+(k2=1)+1)=6]= 4 (V4) */
                   6114:            for (i=1; i<=lastobs;i++){
                   6115:              /* Computes the new covariate which is a product of
                   6116:                 covar[n][i]* covar[m][i] and stores it at ncovol+k1 May not be defined */
                   6117:              covar[ncovcol+k1][i]=covar[atoi(stre)][i]*covar[atoi(strc)][i];
                   6118:            }
                   6119:          } /* End age is not in the model */
                   6120:        } /* End if model includes a product */
                   6121:        else { /* no more sum */
                   6122:          /*printf("d=%s c=%s b=%s\n", strd,strc,strb);*/
                   6123:          /*  scanf("%d",i);*/
                   6124:          cutl(strd,strc,strb,'V');
                   6125:          ks++; /**< Number of simple covariates */
1.145     brouard  6126:          cptcovn++;
1.187     brouard  6127:          Tvar[k]=atoi(strd);
                   6128:        }
                   6129:        strcpy(modelsav,stra);  /* modelsav=V2+V1+V4 stra=V2+V1+V4 */ 
                   6130:        /*printf("a=%s b=%s sav=%s\n", stra,strb,modelsav);
                   6131:          scanf("%d",i);*/
                   6132:       } /* end of loop + on total covariates */
                   6133:     } /* end if strlen(modelsave == 0) age*age might exist */
                   6134:   } /* end if strlen(model == 0) */
1.136     brouard  6135:   
                   6136:   /*The number n of Vn is stored in Tvar. cptcovage =number of age covariate. Tage gives the position of age. cptcovprod= number of products.
                   6137:     If model=V1+V1*age then Tvar[1]=1 Tvar[2]=1 cptcovage=1 Tage[1]=2 cptcovprod=0*/
                   6138: 
                   6139:   /* printf("tvar1=%d tvar2=%d tvar3=%d cptcovage=%d Tage=%d",Tvar[1],Tvar[2],Tvar[3],cptcovage,Tage[1]);
                   6140:   printf("cptcovprod=%d ", cptcovprod);
                   6141:   fprintf(ficlog,"cptcovprod=%d ", cptcovprod);
                   6142: 
                   6143:   scanf("%d ",i);*/
                   6144: 
                   6145: 
1.137     brouard  6146:   return (0); /* with covar[new additional covariate if product] and Tage if age */ 
1.164     brouard  6147:   /*endread:*/
1.136     brouard  6148:     printf("Exiting decodemodel: ");
                   6149:     return (1);
                   6150: }
                   6151: 
1.169     brouard  6152: int calandcheckages(int imx, int maxwav, double *agemin, double *agemax, int *nberr, int *nbwarn )
1.136     brouard  6153: {
                   6154:   int i, m;
                   6155: 
                   6156:   for (i=1; i<=imx; i++) {
                   6157:     for(m=2; (m<= maxwav); m++) {
                   6158:       if (((int)mint[m][i]== 99) && (s[m][i] <= nlstate)){
                   6159:        anint[m][i]=9999;
                   6160:        s[m][i]=-1;
                   6161:       }
                   6162:       if((int)moisdc[i]==99 && (int)andc[i]==9999 && s[m][i]>nlstate){
1.169     brouard  6163:        *nberr = *nberr + 1;
                   6164:        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);
                   6165:        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  6166:        s[m][i]=-1;
                   6167:       }
                   6168:       if((int)moisdc[i]==99 && (int)andc[i]!=9999 && s[m][i]>nlstate){
1.169     brouard  6169:        (*nberr)++;
1.136     brouard  6170:        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]); 
                   6171:        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]); 
                   6172:        s[m][i]=-1; /* We prefer to skip it (and to skip it in version 0.8a1 too */
                   6173:       }
                   6174:     }
                   6175:   }
                   6176: 
                   6177:   for (i=1; i<=imx; i++)  {
                   6178:     agedc[i]=(moisdc[i]/12.+andc[i])-(moisnais[i]/12.+annais[i]);
                   6179:     for(m=firstpass; (m<= lastpass); m++){
                   6180:       if(s[m][i] >0 || s[m][i]==-2 || s[m][i]==-4 || s[m][i]==-5){
                   6181:        if (s[m][i] >= nlstate+1) {
1.169     brouard  6182:          if(agedc[i]>0){
                   6183:            if((int)moisdc[i]!=99 && (int)andc[i]!=9999){
1.136     brouard  6184:              agev[m][i]=agedc[i];
                   6185:          /*if(moisdc[i]==99 && andc[i]==9999) s[m][i]=-1;*/
1.169     brouard  6186:            }else {
1.136     brouard  6187:              if ((int)andc[i]!=9999){
                   6188:                nbwarn++;
                   6189:                printf("Warning negative age at death: %ld line:%d\n",num[i],i);
                   6190:                fprintf(ficlog,"Warning negative age at death: %ld line:%d\n",num[i],i);
                   6191:                agev[m][i]=-1;
                   6192:              }
                   6193:            }
1.169     brouard  6194:          } /* agedc > 0 */
1.136     brouard  6195:        }
                   6196:        else if(s[m][i] !=9){ /* Standard case, age in fractional
                   6197:                                 years but with the precision of a month */
                   6198:          agev[m][i]=(mint[m][i]/12.+1./24.+anint[m][i])-(moisnais[i]/12.+1./24.+annais[i]);
                   6199:          if((int)mint[m][i]==99 || (int)anint[m][i]==9999)
                   6200:            agev[m][i]=1;
                   6201:          else if(agev[m][i] < *agemin){ 
                   6202:            *agemin=agev[m][i];
                   6203:            printf(" Min anint[%d][%d]=%.2f annais[%d]=%.2f, agemin=%.2f\n",m,i,anint[m][i], i,annais[i], *agemin);
                   6204:          }
                   6205:          else if(agev[m][i] >*agemax){
                   6206:            *agemax=agev[m][i];
1.156     brouard  6207:            /* printf(" Max anint[%d][%d]=%.0f annais[%d]=%.0f, agemax=%.2f\n",m,i,anint[m][i], i,annais[i], *agemax);*/
1.136     brouard  6208:          }
                   6209:          /*agev[m][i]=anint[m][i]-annais[i];*/
                   6210:          /*     agev[m][i] = age[i]+2*m;*/
                   6211:        }
                   6212:        else { /* =9 */
                   6213:          agev[m][i]=1;
                   6214:          s[m][i]=-1;
                   6215:        }
                   6216:       }
                   6217:       else /*= 0 Unknown */
                   6218:        agev[m][i]=1;
                   6219:     }
                   6220:     
                   6221:   }
                   6222:   for (i=1; i<=imx; i++)  {
                   6223:     for(m=firstpass; (m<=lastpass); m++){
                   6224:       if (s[m][i] > (nlstate+ndeath)) {
1.169     brouard  6225:        (*nberr)++;
1.136     brouard  6226:        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);     
                   6227:        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);     
                   6228:        return 1;
                   6229:       }
                   6230:     }
                   6231:   }
                   6232: 
                   6233:   /*for (i=1; i<=imx; i++){
                   6234:   for (m=firstpass; (m<lastpass); m++){
                   6235:      printf("%ld %d %.lf %d %d\n", num[i],(covar[1][i]),agev[m][i],s[m][i],s[m+1][i]);
                   6236: }
                   6237: 
                   6238: }*/
                   6239: 
                   6240: 
1.139     brouard  6241:   printf("Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax);
                   6242:   fprintf(ficlog,"Total number of individuals= %d, Agemin = %.2f, Agemax= %.2f\n\n", imx, *agemin, *agemax); 
1.136     brouard  6243: 
                   6244:   return (0);
1.164     brouard  6245:  /* endread:*/
1.136     brouard  6246:     printf("Exiting calandcheckages: ");
                   6247:     return (1);
                   6248: }
                   6249: 
1.172     brouard  6250: #if defined(_MSC_VER)
                   6251: /*printf("Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6252: /*fprintf(ficlog, "Visual C++ compiler: %s \n;", _MSC_FULL_VER);*/
                   6253: //#include "stdafx.h"
                   6254: //#include <stdio.h>
                   6255: //#include <tchar.h>
                   6256: //#include <windows.h>
                   6257: //#include <iostream>
                   6258: typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
                   6259: 
                   6260: LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6261: 
                   6262: BOOL IsWow64()
                   6263: {
                   6264:        BOOL bIsWow64 = FALSE;
                   6265: 
                   6266:        //typedef BOOL (APIENTRY *LPFN_ISWOW64PROCESS)
                   6267:        //  (HANDLE, PBOOL);
                   6268: 
                   6269:        //LPFN_ISWOW64PROCESS fnIsWow64Process;
                   6270: 
                   6271:        HMODULE module = GetModuleHandle(_T("kernel32"));
                   6272:        const char funcName[] = "IsWow64Process";
                   6273:        fnIsWow64Process = (LPFN_ISWOW64PROCESS)
                   6274:                GetProcAddress(module, funcName);
                   6275: 
                   6276:        if (NULL != fnIsWow64Process)
                   6277:        {
                   6278:                if (!fnIsWow64Process(GetCurrentProcess(),
                   6279:                        &bIsWow64))
                   6280:                        //throw std::exception("Unknown error");
                   6281:                        printf("Unknown error\n");
                   6282:        }
                   6283:        return bIsWow64 != FALSE;
                   6284: }
                   6285: #endif
1.177     brouard  6286: 
1.191     brouard  6287: void syscompilerinfo(int logged)
1.167     brouard  6288:  {
                   6289:    /* #include "syscompilerinfo.h"*/
1.185     brouard  6290:    /* command line Intel compiler 32bit windows, XP compatible:*/
                   6291:    /* /GS /W3 /Gy
                   6292:       /Zc:wchar_t /Zi /O2 /Fd"Release\vc120.pdb" /D "WIN32" /D "NDEBUG" /D
                   6293:       "_CONSOLE" /D "_LIB" /D "_USING_V110_SDK71_" /D "_UNICODE" /D
                   6294:       "UNICODE" /Qipo /Zc:forScope /Gd /Oi /MT /Fa"Release\" /EHsc /nologo
1.186     brouard  6295:       /Fo"Release\" /Qprof-dir "Release\" /Fp"Release\IMaCh.pch"
                   6296:    */ 
                   6297:    /* 64 bits */
1.185     brouard  6298:    /*
                   6299:      /GS /W3 /Gy
                   6300:      /Zc:wchar_t /Zi /O2 /Fd"x64\Release\vc120.pdb" /D "WIN32" /D "NDEBUG"
                   6301:      /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope
                   6302:      /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" /Qprof-dir
                   6303:      "x64\Release\" /Fp"x64\Release\IMaCh.pch" */
                   6304:    /* Optimization are useless and O3 is slower than O2 */
                   6305:    /*
                   6306:      /GS /W3 /Gy /Zc:wchar_t /Zi /O3 /Fd"x64\Release\vc120.pdb" /D "WIN32" 
                   6307:      /D "NDEBUG" /D "_CONSOLE" /D "_LIB" /D "_UNICODE" /D "UNICODE" /Qipo 
                   6308:      /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Qparallel 
                   6309:      /Fo"x64\Release\" /Qprof-dir "x64\Release\" /Fp"x64\Release\IMaCh.pch" 
                   6310:    */
1.186     brouard  6311:    /* Link is */ /* /OUT:"visual studio
1.185     brouard  6312:       2013\Projects\IMaCh\Release\IMaCh.exe" /MANIFEST /NXCOMPAT
                   6313:       /PDB:"visual studio
                   6314:       2013\Projects\IMaCh\Release\IMaCh.pdb" /DYNAMICBASE
                   6315:       "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib"
                   6316:       "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib"
                   6317:       "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib"
                   6318:       /MACHINE:X86 /OPT:REF /SAFESEH /INCREMENTAL:NO
                   6319:       /SUBSYSTEM:CONSOLE",5.01" /MANIFESTUAC:"level='asInvoker'
                   6320:       uiAccess='false'"
                   6321:       /ManifestFile:"Release\IMaCh.exe.intermediate.manifest" /OPT:ICF
                   6322:       /NOLOGO /TLBID:1
                   6323:    */
1.177     brouard  6324: #if defined __INTEL_COMPILER
1.178     brouard  6325: #if defined(__GNUC__)
                   6326:        struct utsname sysInfo;  /* For Intel on Linux and OS/X */
                   6327: #endif
1.177     brouard  6328: #elif defined(__GNUC__) 
1.179     brouard  6329: #ifndef  __APPLE__
1.174     brouard  6330: #include <gnu/libc-version.h>  /* Only on gnu */
1.179     brouard  6331: #endif
1.177     brouard  6332:    struct utsname sysInfo;
1.178     brouard  6333:    int cross = CROSS;
                   6334:    if (cross){
                   6335:           printf("Cross-");
1.191     brouard  6336:           if(logged) fprintf(ficlog, "Cross-");
1.178     brouard  6337:    }
1.174     brouard  6338: #endif
                   6339: 
1.171     brouard  6340: #include <stdint.h>
1.178     brouard  6341: 
1.191     brouard  6342:    printf("Compiled with:");if(logged)fprintf(ficlog,"Compiled with:");
1.169     brouard  6343: #if defined(__clang__)
1.191     brouard  6344:    printf(" Clang/LLVM");if(logged)fprintf(ficlog," Clang/LLVM");      /* Clang/LLVM. ---------------------------------------------- */
1.169     brouard  6345: #endif
                   6346: #if defined(__ICC) || defined(__INTEL_COMPILER)
1.191     brouard  6347:    printf(" Intel ICC/ICPC");if(logged)fprintf(ficlog," Intel ICC/ICPC");/* Intel ICC/ICPC. ------------------------------------------ */
1.169     brouard  6348: #endif
                   6349: #if defined(__GNUC__) || defined(__GNUG__)
1.191     brouard  6350:    printf(" GNU GCC/G++");if(logged)fprintf(ficlog," GNU GCC/G++");/* GNU GCC/G++. --------------------------------------------- */
1.169     brouard  6351: #endif
                   6352: #if defined(__HP_cc) || defined(__HP_aCC)
1.191     brouard  6353:    printf(" Hewlett-Packard C/aC++");if(logged)fprintf(fcilog," Hewlett-Packard C/aC++"); /* Hewlett-Packard C/aC++. ---------------------------------- */
1.169     brouard  6354: #endif
                   6355: #if defined(__IBMC__) || defined(__IBMCPP__)
1.191     brouard  6356:    printf(" IBM XL C/C++"); if(logged) fprintf(ficlog," IBM XL C/C++");/* IBM XL C/C++. -------------------------------------------- */
1.169     brouard  6357: #endif
                   6358: #if defined(_MSC_VER)
1.191     brouard  6359:    printf(" Microsoft Visual Studio");if(logged)fprintf(ficlog," Microsoft Visual Studio");/* Microsoft Visual Studio. --------------------------------- */
1.169     brouard  6360: #endif
                   6361: #if defined(__PGI)
1.191     brouard  6362:    printf(" Portland Group PGCC/PGCPP");if(logged) fprintf(ficlog," Portland Group PGCC/PGCPP");/* Portland Group PGCC/PGCPP. ------------------------------- */
1.169     brouard  6363: #endif
                   6364: #if defined(__SUNPRO_C) || defined(__SUNPRO_CC)
1.191     brouard  6365:    printf(" Oracle Solaris Studio");if(logged)fprintf(ficlog," Oracle Solaris Studio\n");/* Oracle Solaris Studio. ----------------------------------- */
1.167     brouard  6366: #endif
1.191     brouard  6367:    printf(" for "); if (logged) fprintf(ficlog, " for ");
1.169     brouard  6368:    
1.167     brouard  6369: // http://stackoverflow.com/questions/4605842/how-to-identify-platform-compiler-from-preprocessor-macros
                   6370: #ifdef _WIN32 // note the underscore: without it, it's not msdn official!
                   6371:     // Windows (x64 and x86)
1.191     brouard  6372:    printf("Windows (x64 and x86) ");if(logged) fprintf(ficlog,"Windows (x64 and x86) ");
1.167     brouard  6373: #elif __unix__ // all unices, not all compilers
                   6374:     // Unix
1.191     brouard  6375:    printf("Unix ");if(logged) fprintf(ficlog,"Unix ");
1.167     brouard  6376: #elif __linux__
                   6377:     // linux
1.191     brouard  6378:    printf("linux ");if(logged) fprintf(ficlog,"linux ");
1.167     brouard  6379: #elif __APPLE__
1.174     brouard  6380:     // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though..
1.191     brouard  6381:    printf("Mac OS ");if(logged) fprintf(ficlog,"Mac OS ");
1.167     brouard  6382: #endif
                   6383: 
                   6384: /*  __MINGW32__          */
                   6385: /*  __CYGWIN__  */
                   6386: /* __MINGW64__  */
                   6387: // http://msdn.microsoft.com/en-us/library/b0084kay.aspx
                   6388: /* _MSC_VER  //the Visual C++ compiler is 17.00.51106.1, the _MSC_VER macro evaluates to 1700. Type cl /?  */
                   6389: /* _MSC_FULL_VER //the Visual C++ compiler is 15.00.20706.01, the _MSC_FULL_VER macro evaluates to 150020706 */
                   6390: /* _WIN64  // Defined for applications for Win64. */
                   6391: /* _M_X64 // Defined for compilations that target x64 processors. */
                   6392: /* _DEBUG // Defined when you compile with /LDd, /MDd, and /MTd. */
1.171     brouard  6393: 
1.167     brouard  6394: #if UINTPTR_MAX == 0xffffffff
1.191     brouard  6395:    printf(" 32-bit"); if(logged) fprintf(ficlog," 32-bit");/* 32-bit */
1.167     brouard  6396: #elif UINTPTR_MAX == 0xffffffffffffffff
1.191     brouard  6397:    printf(" 64-bit"); if(logged) fprintf(ficlog," 64-bit");/* 64-bit */
1.167     brouard  6398: #else
1.191     brouard  6399:    printf(" wtf-bit"); if(logged) fprintf(ficlog," wtf-bit");/* wtf */
1.167     brouard  6400: #endif
                   6401: 
1.169     brouard  6402: #if defined(__GNUC__)
                   6403: # if defined(__GNUC_PATCHLEVEL__)
                   6404: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6405:                             + __GNUC_MINOR__ * 100 \
                   6406:                             + __GNUC_PATCHLEVEL__)
                   6407: # else
                   6408: #  define __GNUC_VERSION__ (__GNUC__ * 10000 \
                   6409:                             + __GNUC_MINOR__ * 100)
                   6410: # endif
1.174     brouard  6411:    printf(" using GNU C version %d.\n", __GNUC_VERSION__);
1.191     brouard  6412:    if(logged) fprintf(ficlog, " using GNU C version %d.\n", __GNUC_VERSION__);
1.176     brouard  6413: 
                   6414:    if (uname(&sysInfo) != -1) {
                   6415:      printf("Running on: %s %s %s %s %s\n",sysInfo.sysname, sysInfo.nodename, sysInfo.release, sysInfo.version, sysInfo.machine);
1.191     brouard  6416:         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  6417:    }
                   6418:    else
                   6419:       perror("uname() error");
1.179     brouard  6420:    //#ifndef __INTEL_COMPILER 
                   6421: #if !defined (__INTEL_COMPILER) && !defined(__APPLE__)
1.174     brouard  6422:    printf("GNU libc version: %s\n", gnu_get_libc_version()); 
1.191     brouard  6423:    if(logged) fprintf(ficlog,"GNU libc version: %s\n", gnu_get_libc_version());
1.177     brouard  6424: #endif
1.169     brouard  6425: #endif
1.172     brouard  6426: 
                   6427:    //   void main()
                   6428:    //   {
1.169     brouard  6429: #if defined(_MSC_VER)
1.174     brouard  6430:    if (IsWow64()){
1.191     brouard  6431:           printf("\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
                   6432:           if (logged) fprintf(ficlog, "\nThe program (probably compiled for 32bit) is running under WOW64 (64bit) emulation.\n");
1.174     brouard  6433:    }
                   6434:    else{
1.191     brouard  6435:           printf("\nThe program is not running under WOW64 (i.e probably on a 64bit Windows).\n");
                   6436:           if (logged) fprintf(ficlog, "\nThe programm is not running under WOW64 (i.e probably on a 64bit Windows).\n");
1.174     brouard  6437:    }
1.172     brouard  6438:    //     printf("\nPress Enter to continue...");
                   6439:    //     getchar();
                   6440:    //   }
                   6441: 
1.169     brouard  6442: #endif
                   6443:    
1.167     brouard  6444: 
                   6445:  }
1.136     brouard  6446: 
1.203   ! brouard  6447:  int prevalence_limit(double *p, double **prlim, double ageminpar, double agemaxpar, double ftolpl, int *ncvyear){
1.180     brouard  6448:   /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
                   6449:   int i, j, k, i1 ;
1.202     brouard  6450:   /* double ftolpl = 1.e-10; */
1.180     brouard  6451:   double age, agebase, agelim;
1.203   ! brouard  6452:   double tot;
1.180     brouard  6453: 
1.202     brouard  6454:   strcpy(filerespl,"PL_");
                   6455:   strcat(filerespl,fileresu);
                   6456:   if((ficrespl=fopen(filerespl,"w"))==NULL) {
                   6457:     printf("Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6458:     fprintf(ficlog,"Problem with period (stable) prevalence resultfile: %s\n", filerespl);return 1;
                   6459:   }
                   6460:   printf("Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6461:   fprintf(ficlog,"Computing period (stable) prevalence: result on file '%s' \n", filerespl);
                   6462:   pstamp(ficrespl);
1.203   ! brouard  6463:   fprintf(ficrespl,"# Period (stable) prevalence. Precision given by ftolpl=%g \n", ftolpl);
1.202     brouard  6464:   fprintf(ficrespl,"#Age ");
                   6465:   for(i=1; i<=nlstate;i++) fprintf(ficrespl,"%d-%d ",i,i);
                   6466:   fprintf(ficrespl,"\n");
1.180     brouard  6467:   
                   6468:     /* prlim=matrix(1,nlstate,1,nlstate);*/ /* back in main */
                   6469: 
                   6470:     agebase=ageminpar;
                   6471:     agelim=agemaxpar;
                   6472: 
                   6473:     i1=pow(2,cptcoveff);
                   6474:     if (cptcovn < 1){i1=1;}
                   6475: 
                   6476:     for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   6477:     /* for(cptcov=1,k=0;cptcov<=1;cptcov++){ */
                   6478:       //for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){
                   6479:        k=k+1;
                   6480:        /* to clean */
1.198     brouard  6481:        //printf("cptcov=%d cptcod=%d codtab=%d\n",cptcov, cptcod,codtabm(cptcod,cptcov));
1.200     brouard  6482:        fprintf(ficrespl,"#******");
                   6483:        printf("#******");
                   6484:        fprintf(ficlog,"#******");
1.180     brouard  6485:        for(j=1;j<=cptcoveff;j++) {
1.198     brouard  6486:          fprintf(ficrespl," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6487:          printf(" V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   6488:          fprintf(ficlog," V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6489:        }
                   6490:        fprintf(ficrespl,"******\n");
                   6491:        printf("******\n");
                   6492:        fprintf(ficlog,"******\n");
                   6493: 
                   6494:        fprintf(ficrespl,"#Age ");
                   6495:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  6496:          fprintf(ficrespl,"V%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.180     brouard  6497:        }
1.203   ! brouard  6498:        for(i=1; i<=nlstate;i++) fprintf(ficrespl,"  %d-%d   ",i,i);
        !          6499:        fprintf(ficrespl,"Total Years_to_converge\n");
1.180     brouard  6500:        
                   6501:        for (age=agebase; age<=agelim; age++){
                   6502:        /* for (age=agebase; age<=agebase; age++){ */
1.203   ! brouard  6503:          prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k);
1.180     brouard  6504:          fprintf(ficrespl,"%.0f ",age );
                   6505:          for(j=1;j<=cptcoveff;j++)
1.198     brouard  6506:            fprintf(ficrespl,"%d %d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.203   ! brouard  6507:          tot=0.;
        !          6508:          for(i=1; i<=nlstate;i++){
        !          6509:            tot +=  prlim[i][i];
1.180     brouard  6510:            fprintf(ficrespl," %.5f", prlim[i][i]);
1.203   ! brouard  6511:          }
        !          6512:          fprintf(ficrespl," %.3f %d\n", tot, *ncvyear);
1.180     brouard  6513:        } /* Age */
                   6514:        /* was end of cptcod */
                   6515:     } /* cptcov */
1.184     brouard  6516:        return 0;
1.180     brouard  6517: }
                   6518: 
                   6519: int hPijx(double *p, int bage, int fage){
                   6520:     /*------------- h Pij x at various ages ------------*/
                   6521: 
                   6522:   int stepsize;
                   6523:   int agelim;
                   6524:   int hstepm;
                   6525:   int nhstepm;
                   6526:   int h, i, i1, j, k;
                   6527: 
                   6528:   double agedeb;
                   6529:   double ***p3mat;
                   6530: 
1.201     brouard  6531:     strcpy(filerespij,"PIJ_");  strcat(filerespij,fileresu);
1.180     brouard  6532:     if((ficrespij=fopen(filerespij,"w"))==NULL) {
                   6533:       printf("Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6534:       fprintf(ficlog,"Problem with Pij resultfile: %s\n", filerespij); return 1;
                   6535:     }
                   6536:     printf("Computing pij: result on file '%s' \n", filerespij);
                   6537:     fprintf(ficlog,"Computing pij: result on file '%s' \n", filerespij);
                   6538:   
                   6539:     stepsize=(int) (stepm+YEARM-1)/YEARM;
                   6540:     /*if (stepm<=24) stepsize=2;*/
                   6541: 
                   6542:     agelim=AGESUP;
                   6543:     hstepm=stepsize*YEARM; /* Every year of age */
                   6544:     hstepm=hstepm/stepm; /* Typically 2 years, = 2/6 months = 4 */ 
                   6545: 
                   6546:     /* hstepm=1;   aff par mois*/
                   6547:     pstamp(ficrespij);
                   6548:     fprintf(ficrespij,"#****** h Pij x Probability to be in state j at age x+h being in i at x ");
                   6549:     i1= pow(2,cptcoveff);
1.183     brouard  6550:    /* for(cptcov=1,k=0;cptcov<=i1;cptcov++){ */
                   6551:    /*    /\*for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*\/ */
                   6552:    /*          k=k+1;  */
                   6553:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   6554:       fprintf(ficrespij,"\n#****** ");
                   6555:       for(j=1;j<=cptcoveff;j++) 
1.198     brouard  6556:        fprintf(ficrespij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.183     brouard  6557:       fprintf(ficrespij,"******\n");
                   6558:       
                   6559:       for (agedeb=fage; agedeb>=bage; agedeb--){ /* If stepm=6 months */
                   6560:        nhstepm=(int) rint((agelim-agedeb)*YEARM/stepm); /* Typically 20 years = 20*12/6=40 */ 
                   6561:        nhstepm = nhstepm/hstepm; /* Typically 40/4=10 */
                   6562:        
                   6563:        /*        nhstepm=nhstepm*YEARM; aff par mois*/
1.180     brouard  6564:        
1.183     brouard  6565:        p3mat=ma3x(1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6566:        oldm=oldms;savm=savms;
                   6567:        hpxij(p3mat,nhstepm,agedeb,hstepm,p,nlstate,stepm,oldm,savm, k);  
                   6568:        fprintf(ficrespij,"# Cov Agex agex+h hpijx with i,j=");
                   6569:        for(i=1; i<=nlstate;i++)
                   6570:          for(j=1; j<=nlstate+ndeath;j++)
                   6571:            fprintf(ficrespij," %1d-%1d",i,j);
                   6572:        fprintf(ficrespij,"\n");
                   6573:        for (h=0; h<=nhstepm; h++){
                   6574:          /*agedebphstep = agedeb + h*hstepm/YEARM*stepm;*/
                   6575:          fprintf(ficrespij,"%d %3.f %3.f",k, agedeb, agedeb + h*hstepm/YEARM*stepm );
1.180     brouard  6576:          for(i=1; i<=nlstate;i++)
                   6577:            for(j=1; j<=nlstate+ndeath;j++)
1.183     brouard  6578:              fprintf(ficrespij," %.5f", p3mat[i][j][h]);
1.180     brouard  6579:          fprintf(ficrespij,"\n");
                   6580:        }
1.183     brouard  6581:        free_ma3x(p3mat,1,nlstate+ndeath,1, nlstate+ndeath, 0,nhstepm);
                   6582:        fprintf(ficrespij,"\n");
                   6583:       }
1.180     brouard  6584:       /*}*/
                   6585:     }
1.184     brouard  6586:        return 0;
1.180     brouard  6587: }
                   6588: 
                   6589: 
1.136     brouard  6590: /***********************************************/
                   6591: /**************** Main Program *****************/
                   6592: /***********************************************/
                   6593: 
                   6594: int main(int argc, char *argv[])
                   6595: {
                   6596: #ifdef GSL
                   6597:   const gsl_multimin_fminimizer_type *T;
                   6598:   size_t iteri = 0, it;
                   6599:   int rval = GSL_CONTINUE;
                   6600:   int status = GSL_SUCCESS;
                   6601:   double ssval;
                   6602: #endif
                   6603:   int movingaverage(double ***probs, double bage,double fage, double ***mobaverage, int mobilav);
1.164     brouard  6604:   int i,j, k, n=MAXN,iter=0,m,size=100, cptcod;
1.203   ! brouard  6605:   int ncvyearnp=0;
        !          6606:   int *ncvyear=&ncvyearnp; /* Number of years needed for the period prevalence to converge */
1.164     brouard  6607:   int jj, ll, li, lj, lk;
1.136     brouard  6608:   int numlinepar=0; /* Current linenumber of parameter file */
1.197     brouard  6609:   int num_filled;
1.136     brouard  6610:   int itimes;
                   6611:   int NDIM=2;
                   6612:   int vpopbased=0;
                   6613: 
1.164     brouard  6614:   char ca[32], cb[32];
1.136     brouard  6615:   /*  FILE *fichtm; *//* Html File */
                   6616:   /* FILE *ficgp;*/ /*Gnuplot File */
                   6617:   struct stat info;
1.191     brouard  6618:   double agedeb=0.;
1.194     brouard  6619: 
                   6620:   double ageminpar=AGEOVERFLOW,agemin=AGEOVERFLOW, agemaxpar=-AGEOVERFLOW, agemax=-AGEOVERFLOW;
1.136     brouard  6621: 
1.165     brouard  6622:   double fret;
1.191     brouard  6623:   double dum=0.; /* Dummy variable */
1.136     brouard  6624:   double ***p3mat;
                   6625:   double ***mobaverage;
1.164     brouard  6626: 
                   6627:   char line[MAXLINE];
1.197     brouard  6628:   char path[MAXLINE],pathc[MAXLINE],pathcd[MAXLINE],pathtot[MAXLINE];
                   6629: 
                   6630:   char model[MAXLINE], modeltemp[MAXLINE];
1.136     brouard  6631:   char pathr[MAXLINE], pathimach[MAXLINE]; 
1.164     brouard  6632:   char *tok, *val; /* pathtot */
1.136     brouard  6633:   int firstobs=1, lastobs=10;
1.195     brouard  6634:   int c,  h , cpt, c2;
1.191     brouard  6635:   int jl=0;
                   6636:   int i1, j1, jk, stepsize=0;
1.194     brouard  6637:   int count=0;
                   6638: 
1.164     brouard  6639:   int *tab; 
1.136     brouard  6640:   int mobilavproj=0 , prevfcast=0 ; /* moving average of prev, If prevfcast=1 prevalence projection */
                   6641:   int mobilav=0,popforecast=0;
1.191     brouard  6642:   int hstepm=0, nhstepm=0;
1.136     brouard  6643:   int agemortsup;
                   6644:   float  sumlpop=0.;
                   6645:   double jprev1=1, mprev1=1,anprev1=2000,jprev2=1, mprev2=1,anprev2=2000;
                   6646:   double jpyram=1, mpyram=1,anpyram=2000,jpyram1=1, mpyram1=1,anpyram1=2000;
                   6647: 
1.191     brouard  6648:   double bage=0, fage=110., age, agelim=0., agebase=0.;
1.136     brouard  6649:   double ftolpl=FTOL;
                   6650:   double **prlim;
                   6651:   double ***param; /* Matrix of parameters */
                   6652:   double  *p;
                   6653:   double **matcov; /* Matrix of covariance */
1.203   ! brouard  6654:   double **hess; /* Hessian matrix */
1.136     brouard  6655:   double ***delti3; /* Scale */
                   6656:   double *delti; /* Scale */
                   6657:   double ***eij, ***vareij;
                   6658:   double **varpl; /* Variances of prevalence limits by age */
                   6659:   double *epj, vepp;
1.164     brouard  6660: 
1.136     brouard  6661:   double dateprev1, dateprev2,jproj1=1,mproj1=1,anproj1=2000,jproj2=1,mproj2=1,anproj2=2000;
                   6662:   double **ximort;
1.145     brouard  6663:   char *alph[]={"a","a","b","c","d","e"}, str[4]="1234";
1.136     brouard  6664:   int *dcwave;
                   6665: 
1.164     brouard  6666:   char z[1]="c";
1.136     brouard  6667: 
                   6668:   /*char  *strt;*/
                   6669:   char strtend[80];
1.126     brouard  6670: 
1.164     brouard  6671: 
1.126     brouard  6672: /*   setlocale (LC_ALL, ""); */
                   6673: /*   bindtextdomain (PACKAGE, LOCALEDIR); */
                   6674: /*   textdomain (PACKAGE); */
                   6675: /*   setlocale (LC_CTYPE, ""); */
                   6676: /*   setlocale (LC_MESSAGES, ""); */
                   6677: 
                   6678:   /*   gettimeofday(&start_time, (struct timezone*)0); */ /* at first time */
1.157     brouard  6679:   rstart_time = time(NULL);  
                   6680:   /*  (void) gettimeofday(&start_time,&tzp);*/
                   6681:   start_time = *localtime(&rstart_time);
1.126     brouard  6682:   curr_time=start_time;
1.157     brouard  6683:   /*tml = *localtime(&start_time.tm_sec);*/
                   6684:   /* strcpy(strstart,asctime(&tml)); */
                   6685:   strcpy(strstart,asctime(&start_time));
1.126     brouard  6686: 
                   6687: /*  printf("Localtime (at start)=%s",strstart); */
1.157     brouard  6688: /*  tp.tm_sec = tp.tm_sec +86400; */
                   6689: /*  tm = *localtime(&start_time.tm_sec); */
1.126     brouard  6690: /*   tmg.tm_year=tmg.tm_year +dsign*dyear; */
                   6691: /*   tmg.tm_mon=tmg.tm_mon +dsign*dmonth; */
                   6692: /*   tmg.tm_hour=tmg.tm_hour + 1; */
1.157     brouard  6693: /*   tp.tm_sec = mktime(&tmg); */
1.126     brouard  6694: /*   strt=asctime(&tmg); */
                   6695: /*   printf("Time(after) =%s",strstart);  */
                   6696: /*  (void) time (&time_value);
                   6697: *  printf("time=%d,t-=%d\n",time_value,time_value-86400);
                   6698: *  tm = *localtime(&time_value);
                   6699: *  strstart=asctime(&tm);
                   6700: *  printf("tim_value=%d,asctime=%s\n",time_value,strstart); 
                   6701: */
                   6702: 
                   6703:   nberr=0; /* Number of errors and warnings */
                   6704:   nbwarn=0;
1.184     brouard  6705: #ifdef WIN32
                   6706:   _getcwd(pathcd, size);
                   6707: #else
1.126     brouard  6708:   getcwd(pathcd, size);
1.184     brouard  6709: #endif
1.191     brouard  6710:   syscompilerinfo(0);
1.196     brouard  6711:   printf("\nIMaCh version %s, %s\n%s",version, copyright, fullversion);
1.126     brouard  6712:   if(argc <=1){
                   6713:     printf("\nEnter the parameter file name: ");
                   6714:     fgets(pathr,FILENAMELENGTH,stdin);
                   6715:     i=strlen(pathr);
                   6716:     if(pathr[i-1]=='\n')
                   6717:       pathr[i-1]='\0';
1.156     brouard  6718:     i=strlen(pathr);
                   6719:     if(pathr[i-1]==' ') /* This may happen when dragging on oS/X! */
                   6720:       pathr[i-1]='\0';
1.126     brouard  6721:    for (tok = pathr; tok != NULL; ){
                   6722:       printf("Pathr |%s|\n",pathr);
                   6723:       while ((val = strsep(&tok, "\"" )) != NULL && *val == '\0');
                   6724:       printf("val= |%s| pathr=%s\n",val,pathr);
                   6725:       strcpy (pathtot, val);
                   6726:       if(pathr[0] == '\0') break; /* Dirty */
                   6727:     }
                   6728:   }
                   6729:   else{
                   6730:     strcpy(pathtot,argv[1]);
                   6731:   }
                   6732:   /*if(getcwd(pathcd, MAXLINE)!= NULL)printf ("Error pathcd\n");*/
                   6733:   /*cygwin_split_path(pathtot,path,optionfile);
                   6734:     printf("pathtot=%s, path=%s, optionfile=%s\n",pathtot,path,optionfile);*/
                   6735:   /* cutv(path,optionfile,pathtot,'\\');*/
                   6736: 
                   6737:   /* Split argv[0], imach program to get pathimach */
                   6738:   printf("\nargv[0]=%s argv[1]=%s, \n",argv[0],argv[1]);
                   6739:   split(argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6740:   printf("\nargv[0]=%s pathimach=%s, \noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",argv[0],pathimach,optionfile,optionfilext,optionfilefiname);
                   6741:  /*   strcpy(pathimach,argv[0]); */
                   6742:   /* Split argv[1]=pathtot, parameter file name to get path, optionfile, extension and name */
                   6743:   split(pathtot,path,optionfile,optionfilext,optionfilefiname);
                   6744:   printf("\npathtot=%s,\npath=%s,\noptionfile=%s \noptionfilext=%s \noptionfilefiname=%s\n",pathtot,path,optionfile,optionfilext,optionfilefiname);
1.184     brouard  6745: #ifdef WIN32
                   6746:   _chdir(path); /* Can be a relative path */
                   6747:   if(_getcwd(pathcd,MAXLINE) > 0) /* So pathcd is the full path */
                   6748: #else
1.126     brouard  6749:   chdir(path); /* Can be a relative path */
1.184     brouard  6750:   if (getcwd(pathcd, MAXLINE) > 0) /* So pathcd is the full path */
                   6751: #endif
                   6752:   printf("Current directory %s!\n",pathcd);
1.126     brouard  6753:   strcpy(command,"mkdir ");
                   6754:   strcat(command,optionfilefiname);
                   6755:   if((outcmd=system(command)) != 0){
1.169     brouard  6756:     printf("Directory already exists (or can't create it) %s%s, err=%d\n",path,optionfilefiname,outcmd);
1.126     brouard  6757:     /* fprintf(ficlog,"Problem creating directory %s%s\n",path,optionfilefiname); */
                   6758:     /* fclose(ficlog); */
                   6759: /*     exit(1); */
                   6760:   }
                   6761: /*   if((imk=mkdir(optionfilefiname))<0){ */
                   6762: /*     perror("mkdir"); */
                   6763: /*   } */
                   6764: 
                   6765:   /*-------- arguments in the command line --------*/
                   6766: 
1.186     brouard  6767:   /* Main Log file */
1.126     brouard  6768:   strcat(filelog, optionfilefiname);
                   6769:   strcat(filelog,".log");    /* */
                   6770:   if((ficlog=fopen(filelog,"w"))==NULL)    {
                   6771:     printf("Problem with logfile %s\n",filelog);
                   6772:     goto end;
                   6773:   }
                   6774:   fprintf(ficlog,"Log filename:%s\n",filelog);
1.197     brouard  6775:   fprintf(ficlog,"Version %s %s",version,fullversion);
1.126     brouard  6776:   fprintf(ficlog,"\nEnter the parameter file name: \n");
                   6777:   fprintf(ficlog,"pathimach=%s\npathtot=%s\n\
                   6778:  path=%s \n\
                   6779:  optionfile=%s\n\
                   6780:  optionfilext=%s\n\
1.156     brouard  6781:  optionfilefiname='%s'\n",pathimach,pathtot,path,optionfile,optionfilext,optionfilefiname);
1.126     brouard  6782: 
1.197     brouard  6783:   syscompilerinfo(1);
1.167     brouard  6784: 
1.126     brouard  6785:   printf("Local time (at start):%s",strstart);
                   6786:   fprintf(ficlog,"Local time (at start): %s",strstart);
                   6787:   fflush(ficlog);
                   6788: /*   (void) gettimeofday(&curr_time,&tzp); */
1.157     brouard  6789: /*   printf("Elapsed time %d\n", asc_diff_time(curr_time.tm_sec-start_time.tm_sec,tmpout)); */
1.126     brouard  6790: 
                   6791:   /* */
                   6792:   strcpy(fileres,"r");
                   6793:   strcat(fileres, optionfilefiname);
1.201     brouard  6794:   strcat(fileresu, optionfilefiname); /* Without r in front */
1.126     brouard  6795:   strcat(fileres,".txt");    /* Other files have txt extension */
1.201     brouard  6796:   strcat(fileresu,".txt");    /* Other files have txt extension */
1.126     brouard  6797: 
1.186     brouard  6798:   /* Main ---------arguments file --------*/
1.126     brouard  6799: 
                   6800:   if((ficpar=fopen(optionfile,"r"))==NULL)    {
1.155     brouard  6801:     printf("Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
                   6802:     fprintf(ficlog,"Problem with optionfile '%s' with errno='%s'\n",optionfile,strerror(errno));
1.126     brouard  6803:     fflush(ficlog);
1.149     brouard  6804:     /* goto end; */
                   6805:     exit(70); 
1.126     brouard  6806:   }
                   6807: 
                   6808: 
                   6809: 
                   6810:   strcpy(filereso,"o");
1.201     brouard  6811:   strcat(filereso,fileresu);
1.126     brouard  6812:   if((ficparo=fopen(filereso,"w"))==NULL) { /* opened on subdirectory */
                   6813:     printf("Problem with Output resultfile: %s\n", filereso);
                   6814:     fprintf(ficlog,"Problem with Output resultfile: %s\n", filereso);
                   6815:     fflush(ficlog);
                   6816:     goto end;
                   6817:   }
                   6818: 
                   6819:   /* Reads comments: lines beginning with '#' */
                   6820:   numlinepar=0;
1.197     brouard  6821: 
                   6822:     /* First parameter line */
                   6823:   while(fgets(line, MAXLINE, ficpar)) {
                   6824:     /* If line starts with a # it is a comment */
                   6825:     if (line[0] == '#') {
                   6826:       numlinepar++;
                   6827:       fputs(line,stdout);
                   6828:       fputs(line,ficparo);
                   6829:       fputs(line,ficlog);
                   6830:       continue;
                   6831:     }else
                   6832:       break;
                   6833:   }
                   6834:   if((num_filled=sscanf(line,"title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", \
                   6835:                        title, datafile, &lastobs, &firstpass,&lastpass)) !=EOF){
                   6836:     if (num_filled != 5) {
                   6837:       printf("Should be 5 parameters\n");
                   6838:     }
1.126     brouard  6839:     numlinepar++;
1.197     brouard  6840:     printf("title=%s datafile=%s lastobs=%d firstpass=%d lastpass=%d\n", title, datafile, lastobs, firstpass,lastpass);
                   6841:   }
                   6842:   /* Second parameter line */
                   6843:   while(fgets(line, MAXLINE, ficpar)) {
                   6844:     /* If line starts with a # it is a comment */
                   6845:     if (line[0] == '#') {
                   6846:       numlinepar++;
                   6847:       fputs(line,stdout);
                   6848:       fputs(line,ficparo);
                   6849:       fputs(line,ficlog);
                   6850:       continue;
                   6851:     }else
                   6852:       break;
                   6853:   }
                   6854:   if((num_filled=sscanf(line,"ftol=%lf stepm=%d ncovcol=%d nlstate=%d ndeath=%d maxwav=%d mle=%d weight=%d\n", \
                   6855:                        &ftol, &stepm, &ncovcol, &nlstate, &ndeath, &maxwav, &mle, &weightopt)) !=EOF){
                   6856:     if (num_filled != 8) {
                   6857:       printf("Not 8\n");
                   6858:     }
                   6859:     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  6860:   }
1.203   ! brouard  6861:   /* ftolpl=6*ftol*1.e5; /\* 6.e-3 make convergences in less than 80 loops for the prevalence limit *\/ */
        !          6862:   ftolpl=6.e-3; /* 6.e-3 make convergences in less than 80 loops for the prevalence limit */
1.197     brouard  6863:   /* Third parameter line */
                   6864:   while(fgets(line, MAXLINE, ficpar)) {
                   6865:     /* If line starts with a # it is a comment */
                   6866:     if (line[0] == '#') {
                   6867:       numlinepar++;
                   6868:       fputs(line,stdout);
                   6869:       fputs(line,ficparo);
                   6870:       fputs(line,ficlog);
                   6871:       continue;
                   6872:     }else
                   6873:       break;
                   6874:   }
1.201     brouard  6875:   if((num_filled=sscanf(line,"model=1+age%[^.\n]", model)) !=EOF){
                   6876:     if (num_filled == 0)
                   6877:             model[0]='\0';
                   6878:     else if (num_filled != 1){
1.197     brouard  6879:       printf("ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6880:       fprintf(ficlog,"ERROR %d: Model should be at minimum 'model=1+age.' %s\n",num_filled, line);
                   6881:       model[0]='\0';
                   6882:       goto end;
                   6883:     }
                   6884:     else{
                   6885:       if (model[0]=='+'){
                   6886:        for(i=1; i<=strlen(model);i++)
                   6887:          modeltemp[i-1]=model[i];
1.201     brouard  6888:        strcpy(model,modeltemp); 
1.197     brouard  6889:       }
                   6890:     }
1.199     brouard  6891:     /* printf(" model=1+age%s modeltemp= %s, model=%s\n",model, modeltemp, model);fflush(stdout); */
1.203   ! brouard  6892:     printf("model=1+age+%s\n",model);fflush(stdout);
1.197     brouard  6893:   }
                   6894:   /* 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); */
                   6895:   /* numlinepar=numlinepar+3; /\* In general *\/ */
                   6896:   /* 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.203   ! brouard  6897:   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);
        !          6898:   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  6899:   fflush(ficlog);
1.190     brouard  6900:   /* if(model[0]=='#'|| model[0]== '\0'){ */
                   6901:   if(model[0]=='#'){
1.187     brouard  6902:     printf("Error in 'model' line: model should start with 'model=1+age+' and end with '.' \n \
                   6903:  'model=1+age+.' or 'model=1+age+V1.' or 'model=1+age+age*age+V1+V1*age.' or \n \
                   6904:  'model=1+age+V1+V2.' or 'model=1+age+V1+V2+V1*V2.' etc. \n");         \
                   6905:     if(mle != -1){
                   6906:       printf("Fix the model line and run imach with mle=-1 to get a correct template of the parameter file.\n");
                   6907:       exit(1);
                   6908:     }
                   6909:   }
1.126     brouard  6910:   while((c=getc(ficpar))=='#' && c!= EOF){
                   6911:     ungetc(c,ficpar);
                   6912:     fgets(line, MAXLINE, ficpar);
                   6913:     numlinepar++;
1.195     brouard  6914:     if(line[1]=='q'){ /* This #q will quit imach (the answer is q) */
                   6915:       z[0]=line[1];
                   6916:     }
                   6917:     /* printf("****line [1] = %c \n",line[1]); */
1.141     brouard  6918:     fputs(line, stdout);
                   6919:     //puts(line);
1.126     brouard  6920:     fputs(line,ficparo);
                   6921:     fputs(line,ficlog);
                   6922:   }
                   6923:   ungetc(c,ficpar);
                   6924: 
                   6925:    
1.145     brouard  6926:   covar=matrix(0,NCOVMAX,1,n);  /**< used in readdata */
1.136     brouard  6927:   cptcovn=0; /*Number of covariates, i.e. number of '+' in model statement plus one, indepently of n in Vn*/
                   6928:   /* v1+v2+v3+v2*v4+v5*age makes cptcovn = 5
                   6929:      v1+v2*age+v2*v3 makes cptcovn = 3
                   6930:   */
                   6931:   if (strlen(model)>1) 
1.187     brouard  6932:     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  6933:   else
1.187     brouard  6934:     ncovmodel=2; /* Constant and age */
1.133     brouard  6935:   nforce= (nlstate+ndeath-1)*nlstate; /* Number of forces ij from state i to j */
                   6936:   npar= nforce*ncovmodel; /* Number of parameters like aij*/
1.131     brouard  6937:   if(npar >MAXPARM || nlstate >NLSTATEMAX || ndeath >NDEATHMAX || ncovmodel>NCOVMAX){
                   6938:     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);
                   6939:     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);
                   6940:     fflush(stdout);
                   6941:     fclose (ficlog);
                   6942:     goto end;
                   6943:   }
1.126     brouard  6944:   delti3= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6945:   delti=delti3[1][1];
                   6946:   /*delti=vector(1,npar); *//* Scale of each paramater (output from hesscov)*/
                   6947:   if(mle==-1){ /* Print a wizard for help writing covariance matrix */
                   6948:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.191     brouard  6949:     printf(" You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
                   6950:     fprintf(ficlog," You chose mle=-1, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6951:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   6952:     fclose (ficparo);
                   6953:     fclose (ficlog);
                   6954:     goto end;
                   6955:     exit(0);
                   6956:   }
1.186     brouard  6957:   else if(mle==-3) { /* Main Wizard */
1.126     brouard  6958:     prwizard(ncovmodel, nlstate, ndeath, model, ficparo);
1.192     brouard  6959:     printf(" You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
                   6960:     fprintf(ficlog," You chose mle=-3, look at file %s for a template of covariance matrix \n",filereso);
1.126     brouard  6961:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6962:     matcov=matrix(1,npar,1,npar);
1.203   ! brouard  6963:     hess=matrix(1,npar,1,npar);
1.126     brouard  6964:   }
                   6965:   else{
1.145     brouard  6966:     /* Read guessed parameters */
1.126     brouard  6967:     /* Reads comments: lines beginning with '#' */
                   6968:     while((c=getc(ficpar))=='#' && c!= EOF){
                   6969:       ungetc(c,ficpar);
                   6970:       fgets(line, MAXLINE, ficpar);
                   6971:       numlinepar++;
1.141     brouard  6972:       fputs(line,stdout);
1.126     brouard  6973:       fputs(line,ficparo);
                   6974:       fputs(line,ficlog);
                   6975:     }
                   6976:     ungetc(c,ficpar);
                   6977:     
                   6978:     param= ma3x(1,nlstate,1,nlstate+ndeath-1,1,ncovmodel);
                   6979:     for(i=1; i <=nlstate; i++){
                   6980:       j=0;
                   6981:       for(jj=1; jj <=nlstate+ndeath; jj++){
                   6982:        if(jj==i) continue;
                   6983:        j++;
                   6984:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.193     brouard  6985:        if ((i1 != i) || (j1 != jj)){
1.126     brouard  6986:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n \
                   6987: It might be a problem of design; if ncovcol and the model are correct\n \
                   6988: run imach with mle=-1 to get a correct template of the parameter file.\n",numlinepar, i,j, i1, j1);
                   6989:          exit(1);
                   6990:        }
                   6991:        fprintf(ficparo,"%1d%1d",i1,j1);
                   6992:        if(mle==1)
1.193     brouard  6993:          printf("%1d%1d",i,jj);
                   6994:        fprintf(ficlog,"%1d%1d",i,jj);
1.126     brouard  6995:        for(k=1; k<=ncovmodel;k++){
                   6996:          fscanf(ficpar," %lf",&param[i][j][k]);
                   6997:          if(mle==1){
                   6998:            printf(" %lf",param[i][j][k]);
                   6999:            fprintf(ficlog," %lf",param[i][j][k]);
                   7000:          }
                   7001:          else
                   7002:            fprintf(ficlog," %lf",param[i][j][k]);
                   7003:          fprintf(ficparo," %lf",param[i][j][k]);
                   7004:        }
                   7005:        fscanf(ficpar,"\n");
                   7006:        numlinepar++;
                   7007:        if(mle==1)
                   7008:          printf("\n");
                   7009:        fprintf(ficlog,"\n");
                   7010:        fprintf(ficparo,"\n");
                   7011:       }
                   7012:     }  
                   7013:     fflush(ficlog);
                   7014: 
1.145     brouard  7015:     /* Reads scales values */
1.126     brouard  7016:     p=param[1][1];
                   7017:     
                   7018:     /* Reads comments: lines beginning with '#' */
                   7019:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7020:       ungetc(c,ficpar);
                   7021:       fgets(line, MAXLINE, ficpar);
                   7022:       numlinepar++;
1.141     brouard  7023:       fputs(line,stdout);
1.126     brouard  7024:       fputs(line,ficparo);
                   7025:       fputs(line,ficlog);
                   7026:     }
                   7027:     ungetc(c,ficpar);
                   7028: 
                   7029:     for(i=1; i <=nlstate; i++){
                   7030:       for(j=1; j <=nlstate+ndeath-1; j++){
                   7031:        fscanf(ficpar,"%1d%1d",&i1,&j1);
1.164     brouard  7032:        if ( (i1-i) * (j1-j) != 0){
1.126     brouard  7033:          printf("Error in line parameters number %d, %1d%1d instead of %1d%1d \n",numlinepar, i,j, i1, j1);
                   7034:          exit(1);
                   7035:        }
                   7036:        printf("%1d%1d",i,j);
                   7037:        fprintf(ficparo,"%1d%1d",i1,j1);
                   7038:        fprintf(ficlog,"%1d%1d",i1,j1);
                   7039:        for(k=1; k<=ncovmodel;k++){
                   7040:          fscanf(ficpar,"%le",&delti3[i][j][k]);
                   7041:          printf(" %le",delti3[i][j][k]);
                   7042:          fprintf(ficparo," %le",delti3[i][j][k]);
                   7043:          fprintf(ficlog," %le",delti3[i][j][k]);
                   7044:        }
                   7045:        fscanf(ficpar,"\n");
                   7046:        numlinepar++;
                   7047:        printf("\n");
                   7048:        fprintf(ficparo,"\n");
                   7049:        fprintf(ficlog,"\n");
                   7050:       }
                   7051:     }
                   7052:     fflush(ficlog);
                   7053: 
1.145     brouard  7054:     /* Reads covariance matrix */
1.126     brouard  7055:     delti=delti3[1][1];
                   7056: 
                   7057: 
                   7058:     /* free_ma3x(delti3,1,nlstate,1,nlstate+ndeath-1,1,ncovmodel); */ /* Hasn't to to freed here otherwise delti is no more allocated */
                   7059:   
                   7060:     /* Reads comments: lines beginning with '#' */
                   7061:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7062:       ungetc(c,ficpar);
                   7063:       fgets(line, MAXLINE, ficpar);
                   7064:       numlinepar++;
1.141     brouard  7065:       fputs(line,stdout);
1.126     brouard  7066:       fputs(line,ficparo);
                   7067:       fputs(line,ficlog);
                   7068:     }
                   7069:     ungetc(c,ficpar);
                   7070:   
                   7071:     matcov=matrix(1,npar,1,npar);
1.203   ! brouard  7072:     hess=matrix(1,npar,1,npar);
1.131     brouard  7073:     for(i=1; i <=npar; i++)
                   7074:       for(j=1; j <=npar; j++) matcov[i][j]=0.;
                   7075:       
1.194     brouard  7076:     /* Scans npar lines */
1.126     brouard  7077:     for(i=1; i <=npar; i++){
1.194     brouard  7078:       count=fscanf(ficpar,"%1d%1d%1d",&i1,&j1,&jk);
                   7079:       if(count != 3){
                   7080:        printf("Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7081: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7082: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7083:        fprintf(ficlog,"Error! Error in parameter file %s at line %d after line starting with %1d%1d%1d\n\
                   7084: This is probably because your covariance matrix doesn't \n  contain exactly %d lines corresponding to your model line '1+age+%s'.\n\
                   7085: Please run with mle=-1 to get a correct covariance matrix.\n",optionfile,numlinepar, i1,j1,jk, npar, model);
                   7086:        exit(1);
                   7087:       }else
1.126     brouard  7088:       if(mle==1)
1.194     brouard  7089:        printf("%1d%1d%1d",i1,j1,jk);
                   7090:       fprintf(ficlog,"%1d%1d%1d",i1,j1,jk);
                   7091:       fprintf(ficparo,"%1d%1d%1d",i1,j1,jk);
1.126     brouard  7092:       for(j=1; j <=i; j++){
                   7093:        fscanf(ficpar," %le",&matcov[i][j]);
                   7094:        if(mle==1){
                   7095:          printf(" %.5le",matcov[i][j]);
                   7096:        }
                   7097:        fprintf(ficlog," %.5le",matcov[i][j]);
                   7098:        fprintf(ficparo," %.5le",matcov[i][j]);
                   7099:       }
                   7100:       fscanf(ficpar,"\n");
                   7101:       numlinepar++;
                   7102:       if(mle==1)
                   7103:        printf("\n");
                   7104:       fprintf(ficlog,"\n");
                   7105:       fprintf(ficparo,"\n");
                   7106:     }
1.194     brouard  7107:     /* End of read covariance matrix npar lines */
1.126     brouard  7108:     for(i=1; i <=npar; i++)
                   7109:       for(j=i+1;j<=npar;j++)
                   7110:        matcov[i][j]=matcov[j][i];
                   7111:     
                   7112:     if(mle==1)
                   7113:       printf("\n");
                   7114:     fprintf(ficlog,"\n");
                   7115:     
                   7116:     fflush(ficlog);
                   7117:     
                   7118:     /*-------- Rewriting parameter file ----------*/
                   7119:     strcpy(rfileres,"r");    /* "Rparameterfile */
                   7120:     strcat(rfileres,optionfilefiname);    /* Parameter file first name*/
                   7121:     strcat(rfileres,".");    /* */
                   7122:     strcat(rfileres,optionfilext);    /* Other files have txt extension */
                   7123:     if((ficres =fopen(rfileres,"w"))==NULL) {
1.201     brouard  7124:       printf("Problem writing new parameter file: %s\n", rfileres);goto end;
                   7125:       fprintf(ficlog,"Problem writing new parameter file: %s\n", rfileres);goto end;
1.126     brouard  7126:     }
                   7127:     fprintf(ficres,"#%s\n",version);
                   7128:   }    /* End of mle != -3 */
                   7129: 
1.186     brouard  7130:   /*  Main data
                   7131:    */
1.126     brouard  7132:   n= lastobs;
                   7133:   num=lvector(1,n);
                   7134:   moisnais=vector(1,n);
                   7135:   annais=vector(1,n);
                   7136:   moisdc=vector(1,n);
                   7137:   andc=vector(1,n);
                   7138:   agedc=vector(1,n);
                   7139:   cod=ivector(1,n);
                   7140:   weight=vector(1,n);
                   7141:   for(i=1;i<=n;i++) weight[i]=1.0; /* Equal weights, 1 by default */
                   7142:   mint=matrix(1,maxwav,1,n);
                   7143:   anint=matrix(1,maxwav,1,n);
1.131     brouard  7144:   s=imatrix(1,maxwav+1,1,n); /* s[i][j] health state for wave i and individual j */ 
1.126     brouard  7145:   tab=ivector(1,NCOVMAX);
1.144     brouard  7146:   ncodemax=ivector(1,NCOVMAX); /* Number of code per covariate; if O and 1 only, 2**ncov; V1+V2+V3+V4=>16 */
1.192     brouard  7147:   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  7148: 
1.136     brouard  7149:   /* Reads data from file datafile */
                   7150:   if (readdata(datafile, firstobs, lastobs, &imx)==1)
                   7151:     goto end;
                   7152: 
                   7153:   /* Calculation of the number of parameters from char model */
1.137     brouard  7154:     /*    modelsav=V2+V1+V4+age*V3 strb=age*V3 stra=V2+V1+V4 
                   7155:        k=4 (age*V3) Tvar[k=4]= 3 (from V3) Tag[cptcovage=1]=4
                   7156:        k=3 V4 Tvar[k=3]= 4 (from V4)
                   7157:        k=2 V1 Tvar[k=2]= 1 (from V1)
                   7158:        k=1 Tvar[1]=2 (from V2)
                   7159:     */
                   7160:   Tvar=ivector(1,NCOVMAX); /* Was 15 changed to NCOVMAX. */
                   7161:   /*  V2+V1+V4+age*V3 is a model with 4 covariates (3 plus signs). 
                   7162:       For each model-covariate stores the data-covariate id. Tvar[1]=2, Tvar[2]=1, Tvar[3]=4, 
                   7163:       Tvar[4=age*V3] is 3 and 'age' is recorded in Tage.
                   7164:   */
                   7165:   /* For model-covariate k tells which data-covariate to use but
                   7166:     because this model-covariate is a construction we invent a new column
                   7167:     ncovcol + k1
                   7168:     If already ncovcol=4 and model=V2+V1+V1*V4+age*V3
                   7169:     Tvar[3=V1*V4]=4+1 etc */
1.145     brouard  7170:   Tprod=ivector(1,NCOVMAX); /* Gives the position of a product */
1.137     brouard  7171:   /* Tprod[k1=1]=3(=V1*V4) for V2+V1+V1*V4+age*V3
                   7172:      if  V2+V1+V1*V4+age*V3+V3*V2   TProd[k1=2]=5 (V3*V2)
                   7173:   */
1.145     brouard  7174:   Tvaraff=ivector(1,NCOVMAX); /* Unclear */
                   7175:   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  7176:                            * For V3*V2 (in V2+V1+V1*V4+age*V3+V3*V2), V3*V2 position is 2nd. 
                   7177:                            * Tvard[k1=2][1]=3 (V3) Tvard[k1=2][2]=2(V2) */
1.145     brouard  7178:   Tage=ivector(1,NCOVMAX); /* Gives the covariate id of covariates associated with age: V2 + V1 + age*V4 + V3*age
1.137     brouard  7179:                         4 covariates (3 plus signs)
                   7180:                         Tage[1=V3*age]= 4; Tage[2=age*V4] = 3
                   7181:                      */  
1.136     brouard  7182: 
1.186     brouard  7183: /* Main decodemodel */
                   7184: 
1.187     brouard  7185: 
1.136     brouard  7186:   if(decodemodel(model, lastobs) == 1)
                   7187:     goto end;
                   7188: 
1.137     brouard  7189:   if((double)(lastobs-imx)/(double)imx > 1.10){
                   7190:     nbwarn++;
                   7191:     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); 
                   7192:     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); 
                   7193:   }
1.136     brouard  7194:     /*  if(mle==1){*/
1.137     brouard  7195:   if (weightopt != 1) { /* Maximisation without weights. We can have weights different from 1 but want no weight*/
                   7196:     for(i=1;i<=imx;i++) weight[i]=1.0; /* changed to imx */
1.136     brouard  7197:   }
                   7198: 
                   7199:     /*-calculation of age at interview from date of interview and age at death -*/
                   7200:   agev=matrix(1,maxwav,1,imx);
                   7201: 
                   7202:   if(calandcheckages(imx, maxwav, &agemin, &agemax, &nberr, &nbwarn) == 1)
                   7203:     goto end;
                   7204: 
1.126     brouard  7205: 
1.136     brouard  7206:   agegomp=(int)agemin;
                   7207:   free_vector(moisnais,1,n);
                   7208:   free_vector(annais,1,n);
1.126     brouard  7209:   /* free_matrix(mint,1,maxwav,1,n);
                   7210:      free_matrix(anint,1,maxwav,1,n);*/
                   7211:   free_vector(moisdc,1,n);
                   7212:   free_vector(andc,1,n);
1.145     brouard  7213:   /* */
                   7214:   
1.126     brouard  7215:   wav=ivector(1,imx);
                   7216:   dh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7217:   bh=imatrix(1,lastpass-firstpass+1,1,imx);
                   7218:   mw=imatrix(1,lastpass-firstpass+1,1,imx);
                   7219:    
                   7220:   /* Concatenates waves */
                   7221:   concatwav(wav, dh, bh, mw, s, agedc, agev,  firstpass, lastpass, imx, nlstate, stepm);
1.145     brouard  7222:   /* */
                   7223:  
1.126     brouard  7224:   /* Routine tricode is to calculate cptcoveff (real number of unique covariates) and to associate covariable number and modality */
                   7225: 
                   7226:   nbcode=imatrix(0,NCOVMAX,0,NCOVMAX); 
                   7227:   ncodemax[1]=1;
1.145     brouard  7228:   Ndum =ivector(-1,NCOVMAX);  
1.187     brouard  7229:   if (ncovmodel-nagesqr > 2 ) /* That is if covariate other than cst, age and age*age */
1.145     brouard  7230:     tricode(Tvar,nbcode,imx, Ndum); /**< Fills nbcode[Tvar[j]][l]; */
1.186     brouard  7231:   /* Nbcode gives the value of the lth modality of jth covariate, in
                   7232:      V2+V1*age, there are 3 covariates Tvar[2]=1 (V1).*/
                   7233:   /* 1 to ncodemax[j] is the maximum value of this jth covariate */
1.145     brouard  7234: 
1.200     brouard  7235:   /*  codtab=imatrix(1,100,1,10);*/ /* codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) */
1.198     brouard  7236:   /*printf(" codtab[1,1],codtab[100,10]=%d,%d\n", codtab[1][1],codtabm(100,10));*/
1.186     brouard  7237:   /* codtab gives the value 1 or 2 of the hth combination of k covariates (1 or 2).*/
1.145     brouard  7238:   h=0;
                   7239: 
                   7240: 
                   7241:   /*if (cptcovn > 0) */
1.126     brouard  7242:       
1.145     brouard  7243:  
1.126     brouard  7244:   m=pow(2,cptcoveff);
                   7245:  
1.144     brouard  7246:          /**< codtab(h,k)  k   = codtab[h,k]=( (h-1) - mod(k-1,2**(k-1) )/2**(k-1) + 1
1.186     brouard  7247:           * For k=4 covariates, h goes from 1 to 2**k
                   7248:           * codtabm(h,k)=  1 & (h-1) >> (k-1) ;
                   7249:           *     h\k   1     2     3     4
1.143     brouard  7250:           *______________________________  
                   7251:           *     1 i=1 1 i=1 1 i=1 1 i=1 1
                   7252:           *     2     2     1     1     1
                   7253:           *     3 i=2 1     2     1     1
                   7254:           *     4     2     2     1     1
                   7255:           *     5 i=3 1 i=2 1     2     1
                   7256:           *     6     2     1     2     1
                   7257:           *     7 i=4 1     2     2     1
                   7258:           *     8     2     2     2     1
1.197     brouard  7259:           *     9 i=5 1 i=3 1 i=2 1     2
                   7260:           *    10     2     1     1     2
                   7261:           *    11 i=6 1     2     1     2
                   7262:           *    12     2     2     1     2
                   7263:           *    13 i=7 1 i=4 1     2     2    
                   7264:           *    14     2     1     2     2
                   7265:           *    15 i=8 1     2     2     2
                   7266:           *    16     2     2     2     2
1.143     brouard  7267:           */
1.202     brouard  7268:   /* /\* for(h=1; h <=100 ;h++){  *\/ */
                   7269:   /*   /\* printf("h=%2d ", h); *\/ */
                   7270:   /*    /\* for(k=1; k <=10; k++){ *\/ */
                   7271:   /*      /\* printf("k=%d %d ",k,codtabm(h,k)); *\/ */
                   7272:   /*    /\*   codtab[h][k]=codtabm(h,k); *\/ */
                   7273:   /*    /\* } *\/ */
                   7274:   /*    /\* printf("\n"); *\/ */
                   7275:   /* } */
1.197     brouard  7276:   /* for(k=1;k<=cptcoveff; k++){ /\* scans any effective covariate *\/ */
                   7277:   /*   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 *\/  */
                   7278:   /*     for(j=1; j <= ncodemax[k]; j++){ /\* For each modality of this covariate ncodemax=2*\/ */
                   7279:   /*   for(cpt=1; cpt <=pow(2,k-1); cpt++){  /\* cpt=1 to 8/2**(3+1-1 or 3+1-3) =1 or 4 *\/  */
                   7280:   /*     h++; */
                   7281:   /*     if (h>m)  */
                   7282:   /*       h=1; */
                   7283:   /*     codtab[h][k]=j; */
                   7284:   /*     /\* codtab[12][3]=1; *\/ */
                   7285:   /*     /\*codtab[h][Tvar[k]]=j;*\/ */
                   7286:   /*     /\* 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]]); *\/ */
                   7287:   /*   }  */
                   7288:   /*     } */
                   7289:   /*   } */
                   7290:   /* }  */
1.126     brouard  7291:   /* printf("codtab[1][2]=%d codtab[2][2]=%d",codtab[1][2],codtab[2][2]); 
                   7292:      codtab[1][2]=1;codtab[2][2]=2; */
1.197     brouard  7293:   /* for(i=1; i <=m ;i++){  */
                   7294:   /*    for(k=1; k <=cptcovn; k++){ */
                   7295:   /*      printf("i=%d k=%d %d %d ",i,k,codtab[i][k], cptcoveff); */
                   7296:   /*    } */
                   7297:   /*    printf("\n"); */
                   7298:   /* } */
                   7299:   /*   scanf("%d",i);*/
1.145     brouard  7300: 
                   7301:  free_ivector(Ndum,-1,NCOVMAX);
                   7302: 
                   7303: 
1.126     brouard  7304:     
1.186     brouard  7305:   /* Initialisation of ----------- gnuplot -------------*/
1.126     brouard  7306:   strcpy(optionfilegnuplot,optionfilefiname);
                   7307:   if(mle==-3)
1.201     brouard  7308:     strcat(optionfilegnuplot,"-MORT_");
1.126     brouard  7309:   strcat(optionfilegnuplot,".gp");
                   7310: 
                   7311:   if((ficgp=fopen(optionfilegnuplot,"w"))==NULL) {
                   7312:     printf("Problem with file %s",optionfilegnuplot);
                   7313:   }
                   7314:   else{
                   7315:     fprintf(ficgp,"\n# %s\n", version); 
                   7316:     fprintf(ficgp,"# %s\n", optionfilegnuplot); 
1.141     brouard  7317:     //fprintf(ficgp,"set missing 'NaNq'\n");
                   7318:     fprintf(ficgp,"set datafile missing 'NaNq'\n");
1.126     brouard  7319:   }
                   7320:   /*  fclose(ficgp);*/
1.186     brouard  7321: 
                   7322: 
                   7323:   /* Initialisation of --------- index.htm --------*/
1.126     brouard  7324: 
                   7325:   strcpy(optionfilehtm,optionfilefiname); /* Main html file */
                   7326:   if(mle==-3)
1.201     brouard  7327:     strcat(optionfilehtm,"-MORT_");
1.126     brouard  7328:   strcat(optionfilehtm,".htm");
                   7329:   if((fichtm=fopen(optionfilehtm,"w"))==NULL)    {
1.131     brouard  7330:     printf("Problem with %s \n",optionfilehtm);
                   7331:     exit(0);
1.126     brouard  7332:   }
                   7333: 
                   7334:   strcpy(optionfilehtmcov,optionfilefiname); /* Only for matrix of covariance */
                   7335:   strcat(optionfilehtmcov,"-cov.htm");
                   7336:   if((fichtmcov=fopen(optionfilehtmcov,"w"))==NULL)    {
                   7337:     printf("Problem with %s \n",optionfilehtmcov), exit(0);
                   7338:   }
                   7339:   else{
                   7340:   fprintf(fichtmcov,"<html><head>\n<title>IMaCh Cov %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7341: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7342: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n",\
                   7343:          optionfilehtmcov,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model);
                   7344:   }
                   7345: 
                   7346:   fprintf(fichtm,"<html><head>\n<title>IMaCh %s</title></head>\n <body><font size=\"2\">%s <br> %s</font> \
                   7347: <hr size=\"2\" color=\"#EC5E5E\"> \n\
                   7348: Title=%s <br>Datafile=%s Firstpass=%d Lastpass=%d Stepm=%d Weight=%d Model=%s<br>\n\
                   7349: \n\
                   7350: <hr  size=\"2\" color=\"#EC5E5E\">\
                   7351:  <ul><li><h4>Parameter files</h4>\n\
                   7352:  - Parameter file: <a href=\"%s.%s\">%s.%s</a><br>\n\
                   7353:  - Copy of the parameter file: <a href=\"o%s\">o%s</a><br>\n\
                   7354:  - Log file of the run: <a href=\"%s\">%s</a><br>\n\
                   7355:  - Gnuplot file name: <a href=\"%s\">%s</a><br>\n\
                   7356:  - Date and time at start: %s</ul>\n",\
                   7357:          optionfilehtm,version,fullversion,title,datafile,firstpass,lastpass,stepm, weightopt, model,\
                   7358:          optionfilefiname,optionfilext,optionfilefiname,optionfilext,\
                   7359:          fileres,fileres,\
                   7360:          filelog,filelog,optionfilegnuplot,optionfilegnuplot,strstart);
                   7361:   fflush(fichtm);
                   7362: 
                   7363:   strcpy(pathr,path);
                   7364:   strcat(pathr,optionfilefiname);
1.184     brouard  7365: #ifdef WIN32
                   7366:   _chdir(optionfilefiname); /* Move to directory named optionfile */
                   7367: #else
1.126     brouard  7368:   chdir(optionfilefiname); /* Move to directory named optionfile */
1.184     brouard  7369: #endif
                   7370:          
1.126     brouard  7371:   
                   7372:   /* Calculates basic frequencies. Computes observed prevalence at single age
                   7373:      and prints on file fileres'p'. */
                   7374:   freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint,strstart);
                   7375: 
                   7376:   fprintf(fichtm,"\n");
                   7377:   fprintf(fichtm,"<br>Total number of observations=%d <br>\n\
                   7378: Youngest age at first (selected) pass %.2f, oldest age %.2f<br>\n\
                   7379: Interval (in months) between two waves: Min=%d Max=%d Mean=%.2lf<br>\n",\
                   7380:          imx,agemin,agemax,jmin,jmax,jmean);
                   7381:   pmmij= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7382:     oldms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7383:     newms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7384:     savms= matrix(1,nlstate+ndeath,1,nlstate+ndeath); /* creation */
                   7385:     oldm=oldms; newm=newms; savm=savms; /* Keeps fixed addresses to free */
                   7386:     
                   7387:    
                   7388:   /* For Powell, parameters are in a vector p[] starting at p[1]
                   7389:      so we point p on param[1][1] so that p[1] maps on param[1][1][1] */
                   7390:   p=param[1][1]; /* *(*(*(param +1)+1)+0) */
                   7391: 
                   7392:   globpr=0; /* To get the number ipmx of contributions and the sum of weights*/
1.186     brouard  7393:   /* For mortality only */
1.126     brouard  7394:   if (mle==-3){
1.136     brouard  7395:     ximort=matrix(1,NDIM,1,NDIM); 
1.186     brouard  7396:     /*     ximort=gsl_matrix_alloc(1,NDIM,1,NDIM); */
1.126     brouard  7397:     cens=ivector(1,n);
                   7398:     ageexmed=vector(1,n);
                   7399:     agecens=vector(1,n);
                   7400:     dcwave=ivector(1,n);
                   7401:  
                   7402:     for (i=1; i<=imx; i++){
                   7403:       dcwave[i]=-1;
                   7404:       for (m=firstpass; m<=lastpass; m++)
                   7405:        if (s[m][i]>nlstate) {
                   7406:          dcwave[i]=m;
                   7407:          /*    printf("i=%d j=%d s=%d dcwave=%d\n",i,j, s[j][i],dcwave[i]);*/
                   7408:          break;
                   7409:        }
                   7410:     }
                   7411: 
                   7412:     for (i=1; i<=imx; i++) {
                   7413:       if (wav[i]>0){
                   7414:        ageexmed[i]=agev[mw[1][i]][i];
                   7415:        j=wav[i];
                   7416:        agecens[i]=1.; 
                   7417: 
                   7418:        if (ageexmed[i]> 1 && wav[i] > 0){
                   7419:          agecens[i]=agev[mw[j][i]][i];
                   7420:          cens[i]= 1;
                   7421:        }else if (ageexmed[i]< 1) 
                   7422:          cens[i]= -1;
                   7423:        if (agedc[i]< AGESUP && agedc[i]>1 && dcwave[i]>firstpass && dcwave[i]<=lastpass)
                   7424:          cens[i]=0 ;
                   7425:       }
                   7426:       else cens[i]=-1;
                   7427:     }
                   7428:     
                   7429:     for (i=1;i<=NDIM;i++) {
                   7430:       for (j=1;j<=NDIM;j++)
                   7431:        ximort[i][j]=(i == j ? 1.0 : 0.0);
                   7432:     }
                   7433:     
1.145     brouard  7434:     /*p[1]=0.0268; p[NDIM]=0.083;*/
1.126     brouard  7435:     /*printf("%lf %lf", p[1], p[2]);*/
                   7436:     
                   7437:     
1.136     brouard  7438: #ifdef GSL
                   7439:     printf("GSL optimization\n");  fprintf(ficlog,"Powell\n");
1.162     brouard  7440: #else
1.126     brouard  7441:     printf("Powell\n");  fprintf(ficlog,"Powell\n");
1.136     brouard  7442: #endif
1.201     brouard  7443:     strcpy(filerespow,"POW-MORT_"); 
                   7444:     strcat(filerespow,fileresu);
1.126     brouard  7445:     if((ficrespow=fopen(filerespow,"w"))==NULL) {
                   7446:       printf("Problem with resultfile: %s\n", filerespow);
                   7447:       fprintf(ficlog,"Problem with resultfile: %s\n", filerespow);
                   7448:     }
1.136     brouard  7449: #ifdef GSL
                   7450:     fprintf(ficrespow,"# GSL optimization\n# iter -2*LL");
1.162     brouard  7451: #else
1.126     brouard  7452:     fprintf(ficrespow,"# Powell\n# iter -2*LL");
1.136     brouard  7453: #endif
1.126     brouard  7454:     /*  for (i=1;i<=nlstate;i++)
                   7455:        for(j=1;j<=nlstate+ndeath;j++)
                   7456:        if(j!=i)fprintf(ficrespow," p%1d%1d",i,j);
                   7457:     */
                   7458:     fprintf(ficrespow,"\n");
1.136     brouard  7459: #ifdef GSL
                   7460:     /* gsl starts here */ 
                   7461:     T = gsl_multimin_fminimizer_nmsimplex;
                   7462:     gsl_multimin_fminimizer *sfm = NULL;
                   7463:     gsl_vector *ss, *x;
                   7464:     gsl_multimin_function minex_func;
                   7465: 
                   7466:     /* Initial vertex size vector */
                   7467:     ss = gsl_vector_alloc (NDIM);
                   7468:     
                   7469:     if (ss == NULL){
                   7470:       GSL_ERROR_VAL ("failed to allocate space for ss", GSL_ENOMEM, 0);
                   7471:     }
                   7472:     /* Set all step sizes to 1 */
                   7473:     gsl_vector_set_all (ss, 0.001);
                   7474: 
                   7475:     /* Starting point */
1.126     brouard  7476:     
1.136     brouard  7477:     x = gsl_vector_alloc (NDIM);
                   7478:     
                   7479:     if (x == NULL){
                   7480:       gsl_vector_free(ss);
                   7481:       GSL_ERROR_VAL ("failed to allocate space for x", GSL_ENOMEM, 0);
                   7482:     }
                   7483:   
                   7484:     /* Initialize method and iterate */
                   7485:     /*     p[1]=0.0268; p[NDIM]=0.083; */
1.186     brouard  7486:     /*     gsl_vector_set(x, 0, 0.0268); */
                   7487:     /*     gsl_vector_set(x, 1, 0.083); */
1.136     brouard  7488:     gsl_vector_set(x, 0, p[1]);
                   7489:     gsl_vector_set(x, 1, p[2]);
                   7490: 
                   7491:     minex_func.f = &gompertz_f;
                   7492:     minex_func.n = NDIM;
                   7493:     minex_func.params = (void *)&p; /* ??? */
                   7494:     
                   7495:     sfm = gsl_multimin_fminimizer_alloc (T, NDIM);
                   7496:     gsl_multimin_fminimizer_set (sfm, &minex_func, x, ss);
                   7497:     
                   7498:     printf("Iterations beginning .....\n\n");
                   7499:     printf("Iter. #    Intercept       Slope     -Log Likelihood     Simplex size\n");
                   7500: 
                   7501:     iteri=0;
                   7502:     while (rval == GSL_CONTINUE){
                   7503:       iteri++;
                   7504:       status = gsl_multimin_fminimizer_iterate(sfm);
                   7505:       
                   7506:       if (status) printf("error: %s\n", gsl_strerror (status));
                   7507:       fflush(0);
                   7508:       
                   7509:       if (status) 
                   7510:         break;
                   7511:       
                   7512:       rval = gsl_multimin_test_size (gsl_multimin_fminimizer_size (sfm), 1e-6);
                   7513:       ssval = gsl_multimin_fminimizer_size (sfm);
                   7514:       
                   7515:       if (rval == GSL_SUCCESS)
                   7516:         printf ("converged to a local maximum at\n");
                   7517:       
                   7518:       printf("%5d ", iteri);
                   7519:       for (it = 0; it < NDIM; it++){
                   7520:        printf ("%10.5f ", gsl_vector_get (sfm->x, it));
                   7521:       }
                   7522:       printf("f() = %-10.5f ssize = %.7f\n", sfm->fval, ssval);
                   7523:     }
                   7524:     
                   7525:     printf("\n\n Please note: Program should be run many times with varying starting points to detemine global maximum\n\n");
                   7526:     
                   7527:     gsl_vector_free(x); /* initial values */
                   7528:     gsl_vector_free(ss); /* inital step size */
                   7529:     for (it=0; it<NDIM; it++){
                   7530:       p[it+1]=gsl_vector_get(sfm->x,it);
                   7531:       fprintf(ficrespow," %.12lf", p[it]);
                   7532:     }
                   7533:     gsl_multimin_fminimizer_free (sfm); /* p *(sfm.x.data) et p *(sfm.x.data+1)  */
                   7534: #endif
                   7535: #ifdef POWELL
                   7536:      powell(p,ximort,NDIM,ftol,&iter,&fret,gompertz);
                   7537: #endif  
1.126     brouard  7538:     fclose(ficrespow);
                   7539:     
1.203   ! brouard  7540:     hesscov(matcov, hess, p, NDIM, delti, 1e-4, gompertz); 
1.126     brouard  7541: 
                   7542:     for(i=1; i <=NDIM; i++)
                   7543:       for(j=i+1;j<=NDIM;j++)
                   7544:        matcov[i][j]=matcov[j][i];
                   7545:     
                   7546:     printf("\nCovariance matrix\n ");
1.203   ! brouard  7547:     fprintf(ficlog,"\nCovariance matrix\n ");
1.126     brouard  7548:     for(i=1; i <=NDIM; i++) {
                   7549:       for(j=1;j<=NDIM;j++){ 
                   7550:        printf("%f ",matcov[i][j]);
1.203   ! brouard  7551:        fprintf(ficlog,"%f ",matcov[i][j]);
1.126     brouard  7552:       }
1.203   ! brouard  7553:       printf("\n ");  fprintf(ficlog,"\n ");
1.126     brouard  7554:     }
                   7555:     
                   7556:     printf("iter=%d MLE=%f Eq=%lf*exp(%lf*(age-%d))\n",iter,-gompertz(p),p[1],p[2],agegomp);
1.193     brouard  7557:     for (i=1;i<=NDIM;i++) {
1.126     brouard  7558:       printf("%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
1.193     brouard  7559:       fprintf(ficlog,"%f [%f ; %f]\n",p[i],p[i]-2*sqrt(matcov[i][i]),p[i]+2*sqrt(matcov[i][i]));
                   7560:     }
1.126     brouard  7561:     lsurv=vector(1,AGESUP);
                   7562:     lpop=vector(1,AGESUP);
                   7563:     tpop=vector(1,AGESUP);
                   7564:     lsurv[agegomp]=100000;
                   7565:     
                   7566:     for (k=agegomp;k<=AGESUP;k++) {
                   7567:       agemortsup=k;
                   7568:       if (p[1]*exp(p[2]*(k-agegomp))>1) break;
                   7569:     }
                   7570:     
                   7571:     for (k=agegomp;k<agemortsup;k++)
                   7572:       lsurv[k+1]=lsurv[k]-lsurv[k]*(p[1]*exp(p[2]*(k-agegomp)));
                   7573:     
                   7574:     for (k=agegomp;k<agemortsup;k++){
                   7575:       lpop[k]=(lsurv[k]+lsurv[k+1])/2.;
                   7576:       sumlpop=sumlpop+lpop[k];
                   7577:     }
                   7578:     
                   7579:     tpop[agegomp]=sumlpop;
                   7580:     for (k=agegomp;k<(agemortsup-3);k++){
                   7581:       /*  tpop[k+1]=2;*/
                   7582:       tpop[k+1]=tpop[k]-lpop[k];
                   7583:     }
                   7584:     
                   7585:     
                   7586:     printf("\nAge   lx     qx    dx    Lx     Tx     e(x)\n");
                   7587:     for (k=agegomp;k<(agemortsup-2);k++) 
                   7588:       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]);
                   7589:     
                   7590:     
                   7591:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7592:     if(ageminpar == AGEOVERFLOW ||agemaxpar == AGEOVERFLOW){
                   7593:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7594: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7595: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7596:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7597: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7598: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7599:     }else
1.201     brouard  7600:       printinggnuplotmort(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
                   7601:     printinghtmlmort(fileresu,title,datafile, firstpass, lastpass, \
1.126     brouard  7602:                     stepm, weightopt,\
                   7603:                     model,imx,p,matcov,agemortsup);
                   7604:     
                   7605:     free_vector(lsurv,1,AGESUP);
                   7606:     free_vector(lpop,1,AGESUP);
                   7607:     free_vector(tpop,1,AGESUP);
1.136     brouard  7608: #ifdef GSL
                   7609:     free_ivector(cens,1,n);
                   7610:     free_vector(agecens,1,n);
                   7611:     free_ivector(dcwave,1,n);
                   7612:     free_matrix(ximort,1,NDIM,1,NDIM);
                   7613: #endif
1.186     brouard  7614:   } /* Endof if mle==-3 mortality only */
                   7615:   /* Standard maximisation */
1.203   ! brouard  7616:   else{ /* For mle !=- 3 */
1.132     brouard  7617:     globpr=0;/* debug */
1.186     brouard  7618:     /* Computes likelihood for initial parameters */
1.132     brouard  7619:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
1.126     brouard  7620:     printf("First Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7621:     for (k=1; k<=npar;k++)
                   7622:       printf(" %d %8.5f",k,p[k]);
                   7623:     printf("\n");
1.186     brouard  7624:     globpr=1; /* again, to print the contributions */
1.126     brouard  7625:     likelione(ficres, p, npar, nlstate, &globpr, &ipmx, &sw, &fretone, funcone); /* Prints the contributions to the likelihood */
                   7626:     printf("Second Likeli=%12.6f ipmx=%ld sw=%12.6f",fretone,ipmx,sw);
                   7627:     for (k=1; k<=npar;k++)
                   7628:       printf(" %d %8.5f",k,p[k]);
                   7629:     printf("\n");
1.186     brouard  7630:     if(mle>=1){ /* Could be 1 or 2, Real Maximisation */
1.126     brouard  7631:       mlikeli(ficres,p, npar, ncovmodel, nlstate, ftol, func);
                   7632:     }
                   7633:     
                   7634:     /*--------- results files --------------*/
1.192     brouard  7635:     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  7636:     
                   7637:     
                   7638:     fprintf(ficres,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7639:     printf("# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7640:     fprintf(ficlog,"# Parameters nlstate*nlstate*ncov a12*1 + b12 * age + ...\n");
                   7641:     for(i=1,jk=1; i <=nlstate; i++){
                   7642:       for(k=1; k <=(nlstate+ndeath); k++){
                   7643:        if (k != i) {
                   7644:          printf("%d%d ",i,k);
                   7645:          fprintf(ficlog,"%d%d ",i,k);
                   7646:          fprintf(ficres,"%1d%1d ",i,k);
                   7647:          for(j=1; j <=ncovmodel; j++){
1.190     brouard  7648:            printf("%12.7f ",p[jk]);
                   7649:            fprintf(ficlog,"%12.7f ",p[jk]);
                   7650:            fprintf(ficres,"%12.7f ",p[jk]);
1.126     brouard  7651:            jk++; 
                   7652:          }
                   7653:          printf("\n");
                   7654:          fprintf(ficlog,"\n");
                   7655:          fprintf(ficres,"\n");
                   7656:        }
                   7657:       }
                   7658:     }
1.203   ! brouard  7659:     if(mle != 0){
        !          7660:       /* Computing hessian and covariance matrix only at a peak of the Likelihood, that is after optimization */
1.126     brouard  7661:       ftolhess=ftol; /* Usually correct */
1.203   ! brouard  7662:       hesscov(matcov, hess, p, npar, delti, ftolhess, func);
        !          7663:       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");
        !          7664:       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");
        !          7665:       for(i=1,jk=1; i <=nlstate; i++){
        !          7666:        for(k=1; k <=(nlstate+ndeath); k++){
        !          7667:          if (k != i) {
        !          7668:            printf("%d%d ",i,k);
        !          7669:            fprintf(ficlog,"%d%d ",i,k);
        !          7670:            for(j=1; j <=ncovmodel; j++){
        !          7671:              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]));
        !          7672:              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]));
        !          7673:              jk++; 
        !          7674:            }
        !          7675:            printf("\n");
        !          7676:            fprintf(ficlog,"\n");
1.193     brouard  7677:          }
                   7678:        }
                   7679:       }
1.203   ! brouard  7680:     } /* end of hesscov and Wald tests */
1.193     brouard  7681: 
1.203   ! brouard  7682:     /*  */
1.126     brouard  7683:     fprintf(ficres,"# Scales (for hessian or gradient estimation)\n");
                   7684:     printf("# Scales (for hessian or gradient estimation)\n");
                   7685:     fprintf(ficlog,"# Scales (for hessian or gradient estimation)\n");
                   7686:     for(i=1,jk=1; i <=nlstate; i++){
                   7687:       for(j=1; j <=nlstate+ndeath; j++){
                   7688:        if (j!=i) {
                   7689:          fprintf(ficres,"%1d%1d",i,j);
                   7690:          printf("%1d%1d",i,j);
                   7691:          fprintf(ficlog,"%1d%1d",i,j);
                   7692:          for(k=1; k<=ncovmodel;k++){
                   7693:            printf(" %.5e",delti[jk]);
                   7694:            fprintf(ficlog," %.5e",delti[jk]);
                   7695:            fprintf(ficres," %.5e",delti[jk]);
                   7696:            jk++;
                   7697:          }
                   7698:          printf("\n");
                   7699:          fprintf(ficlog,"\n");
                   7700:          fprintf(ficres,"\n");
                   7701:        }
                   7702:       }
                   7703:     }
                   7704:     
                   7705:     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");
1.203   ! brouard  7706:     if(mle >= 1) /* To big for the screen */
1.126     brouard  7707:       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");
                   7708:     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");
                   7709:     /* # 121 Var(a12)\n\ */
                   7710:     /* # 122 Cov(b12,a12) Var(b12)\n\ */
                   7711:     /* # 131 Cov(a13,a12) Cov(a13,b12, Var(a13)\n\ */
                   7712:     /* # 132 Cov(b13,a12) Cov(b13,b12, Cov(b13,a13) Var(b13)\n\ */
                   7713:     /* # 212 Cov(a21,a12) Cov(a21,b12, Cov(a21,a13) Cov(a21,b13) Var(a21)\n\ */
                   7714:     /* # 212 Cov(b21,a12) Cov(b21,b12, Cov(b21,a13) Cov(b21,b13) Cov(b21,a21) Var(b21)\n\ */
                   7715:     /* # 232 Cov(a23,a12) Cov(a23,b12, Cov(a23,a13) Cov(a23,b13) Cov(a23,a21) Cov(a23,b21) Var(a23)\n\ */
                   7716:     /* # 232 Cov(b23,a12) Cov(b23,b12) ... Var (b23)\n" */
                   7717:     
                   7718:     
                   7719:     /* Just to have a covariance matrix which will be more understandable
                   7720:        even is we still don't want to manage dictionary of variables
                   7721:     */
                   7722:     for(itimes=1;itimes<=2;itimes++){
                   7723:       jj=0;
                   7724:       for(i=1; i <=nlstate; i++){
                   7725:        for(j=1; j <=nlstate+ndeath; j++){
                   7726:          if(j==i) continue;
                   7727:          for(k=1; k<=ncovmodel;k++){
                   7728:            jj++;
                   7729:            ca[0]= k+'a'-1;ca[1]='\0';
                   7730:            if(itimes==1){
                   7731:              if(mle>=1)
                   7732:                printf("#%1d%1d%d",i,j,k);
                   7733:              fprintf(ficlog,"#%1d%1d%d",i,j,k);
                   7734:              fprintf(ficres,"#%1d%1d%d",i,j,k);
                   7735:            }else{
                   7736:              if(mle>=1)
                   7737:                printf("%1d%1d%d",i,j,k);
                   7738:              fprintf(ficlog,"%1d%1d%d",i,j,k);
                   7739:              fprintf(ficres,"%1d%1d%d",i,j,k);
                   7740:            }
                   7741:            ll=0;
                   7742:            for(li=1;li <=nlstate; li++){
                   7743:              for(lj=1;lj <=nlstate+ndeath; lj++){
                   7744:                if(lj==li) continue;
                   7745:                for(lk=1;lk<=ncovmodel;lk++){
                   7746:                  ll++;
                   7747:                  if(ll<=jj){
                   7748:                    cb[0]= lk +'a'-1;cb[1]='\0';
                   7749:                    if(ll<jj){
                   7750:                      if(itimes==1){
                   7751:                        if(mle>=1)
                   7752:                          printf(" Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7753:                        fprintf(ficlog," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7754:                        fprintf(ficres," Cov(%s%1d%1d,%s%1d%1d)",ca,i,j,cb, li,lj);
                   7755:                      }else{
                   7756:                        if(mle>=1)
                   7757:                          printf(" %.5e",matcov[jj][ll]); 
                   7758:                        fprintf(ficlog," %.5e",matcov[jj][ll]); 
                   7759:                        fprintf(ficres," %.5e",matcov[jj][ll]); 
                   7760:                      }
                   7761:                    }else{
                   7762:                      if(itimes==1){
                   7763:                        if(mle>=1)
                   7764:                          printf(" Var(%s%1d%1d)",ca,i,j);
                   7765:                        fprintf(ficlog," Var(%s%1d%1d)",ca,i,j);
                   7766:                        fprintf(ficres," Var(%s%1d%1d)",ca,i,j);
                   7767:                      }else{
                   7768:                        if(mle>=1)
1.203   ! brouard  7769:                          printf(" %.7e",matcov[jj][ll]); 
        !          7770:                        fprintf(ficlog," %.7e",matcov[jj][ll]); 
        !          7771:                        fprintf(ficres," %.7e",matcov[jj][ll]); 
1.126     brouard  7772:                      }
                   7773:                    }
                   7774:                  }
                   7775:                } /* end lk */
                   7776:              } /* end lj */
                   7777:            } /* end li */
                   7778:            if(mle>=1)
                   7779:              printf("\n");
                   7780:            fprintf(ficlog,"\n");
                   7781:            fprintf(ficres,"\n");
                   7782:            numlinepar++;
                   7783:          } /* end k*/
                   7784:        } /*end j */
                   7785:       } /* end i */
                   7786:     } /* end itimes */
                   7787:     
                   7788:     fflush(ficlog);
                   7789:     fflush(ficres);
                   7790:     
                   7791:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7792:       ungetc(c,ficpar);
                   7793:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7794:       fputs(line,stdout);
1.126     brouard  7795:       fputs(line,ficparo);
                   7796:     }
                   7797:     ungetc(c,ficpar);
                   7798:     
                   7799:     estepm=0;
                   7800:     fscanf(ficpar,"agemin=%lf agemax=%lf bage=%lf fage=%lf estepm=%d\n",&ageminpar,&agemaxpar, &bage, &fage, &estepm);
                   7801:     if (estepm==0 || estepm < stepm) estepm=stepm;
                   7802:     if (fage <= 2) {
                   7803:       bage = ageminpar;
                   7804:       fage = agemaxpar;
                   7805:     }
                   7806:     
                   7807:     fprintf(ficres,"# agemin agemax for life expectancy, bage fage (if mle==0 ie no data nor Max likelihood).\n");
                   7808:     fprintf(ficres,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
                   7809:     fprintf(ficparo,"agemin=%.0f agemax=%.0f bage=%.0f fage=%.0f estepm=%d\n",ageminpar,agemaxpar,bage,fage, estepm);
1.186     brouard  7810: 
                   7811:     /* Other stuffs, more or less useful */    
1.126     brouard  7812:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7813:       ungetc(c,ficpar);
                   7814:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7815:       fputs(line,stdout);
1.126     brouard  7816:       fputs(line,ficparo);
                   7817:     }
                   7818:     ungetc(c,ficpar);
                   7819:     
                   7820:     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);
                   7821:     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);
                   7822:     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);
                   7823:     printf("begin-prev-date=%.lf/%.lf/%.lf end-prev-date=%.lf/%.lf/%.lf mov_average=%d\n",jprev1, mprev1,anprev1,jprev2, mprev2,anprev2,mobilav);
                   7824:     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);
                   7825:     
                   7826:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7827:       ungetc(c,ficpar);
                   7828:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7829:       fputs(line,stdout);
1.126     brouard  7830:       fputs(line,ficparo);
                   7831:     }
                   7832:     ungetc(c,ficpar);
                   7833:     
                   7834:     
                   7835:     dateprev1=anprev1+(mprev1-1)/12.+(jprev1-1)/365.;
                   7836:     dateprev2=anprev2+(mprev2-1)/12.+(jprev2-1)/365.;
                   7837:     
                   7838:     fscanf(ficpar,"pop_based=%d\n",&popbased);
1.193     brouard  7839:     fprintf(ficlog,"pop_based=%d\n",popbased);
1.126     brouard  7840:     fprintf(ficparo,"pop_based=%d\n",popbased);   
                   7841:     fprintf(ficres,"pop_based=%d\n",popbased);   
                   7842:     
                   7843:     while((c=getc(ficpar))=='#' && c!= EOF){
                   7844:       ungetc(c,ficpar);
                   7845:       fgets(line, MAXLINE, ficpar);
1.141     brouard  7846:       fputs(line,stdout);
1.126     brouard  7847:       fputs(line,ficparo);
                   7848:     }
                   7849:     ungetc(c,ficpar);
                   7850:     
                   7851:     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);
                   7852:     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);
                   7853:     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);
                   7854:     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);
                   7855:     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);
                   7856:     /* day and month of proj2 are not used but only year anproj2.*/
                   7857:     
                   7858:     
                   7859:     
1.145     brouard  7860:      /* freqsummary(fileres, agemin, agemax, s, agev, nlstate, imx,Tvaraff,nbcode, ncodemax,mint,anint); */
                   7861:     /* ,dateprev1,dateprev2,jprev1, mprev1,anprev1,jprev2, mprev2,anprev2); */
1.126     brouard  7862:     
                   7863:     replace_back_to_slash(pathc,pathcd); /* Even gnuplot wants a / */
1.194     brouard  7864:     if(ageminpar == AGEOVERFLOW ||agemaxpar == -AGEOVERFLOW){
                   7865:        printf("Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7866: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7867: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7868:        fprintf(ficlog,"Warning! Error in gnuplot file with ageminpar %f or agemaxpar %f overflow\n\
                   7869: This is probably because your parameter file doesn't \n  contain the exact number of lines (or columns) corresponding to your model line.\n\
                   7870: Please run with mle=-1 to get a correct covariance matrix.\n",ageminpar,agemaxpar);
                   7871:     }else
1.201     brouard  7872:       printinggnuplot(fileresu, optionfilefiname,ageminpar,agemaxpar,fage, pathc,p);
1.126     brouard  7873:     
1.201     brouard  7874:     printinghtml(fileresu,title,datafile, firstpass, lastpass, stepm, weightopt,\
1.126     brouard  7875:                 model,imx,jmin,jmax,jmean,rfileres,popforecast,estepm,\
                   7876:                 jprev1,mprev1,anprev1,jprev2,mprev2,anprev2);
                   7877:       
                   7878:    /*------------ free_vector  -------------*/
                   7879:    /*  chdir(path); */
                   7880:  
                   7881:     free_ivector(wav,1,imx);
                   7882:     free_imatrix(dh,1,lastpass-firstpass+1,1,imx);
                   7883:     free_imatrix(bh,1,lastpass-firstpass+1,1,imx);
                   7884:     free_imatrix(mw,1,lastpass-firstpass+1,1,imx);   
                   7885:     free_lvector(num,1,n);
                   7886:     free_vector(agedc,1,n);
                   7887:     /*free_matrix(covar,0,NCOVMAX,1,n);*/
                   7888:     /*free_matrix(covar,1,NCOVMAX,1,n);*/
                   7889:     fclose(ficparo);
                   7890:     fclose(ficres);
                   7891: 
                   7892: 
1.186     brouard  7893:     /* Other results (useful)*/
                   7894: 
                   7895: 
1.126     brouard  7896:     /*--------------- Prevalence limit  (period or stable prevalence) --------------*/
1.180     brouard  7897:     /*#include "prevlim.h"*/  /* Use ficrespl, ficlog */
                   7898:     prlim=matrix(1,nlstate,1,nlstate);
1.203   ! brouard  7899:     prevalence_limit(p, prlim,  ageminpar, agemaxpar, ftolpl, ncvyear);
1.126     brouard  7900:     fclose(ficrespl);
                   7901: 
1.145     brouard  7902: #ifdef FREEEXIT2
                   7903: #include "freeexit2.h"
                   7904: #endif
                   7905: 
1.126     brouard  7906:     /*------------- h Pij x at various ages ------------*/
1.180     brouard  7907:     /*#include "hpijx.h"*/
                   7908:     hPijx(p, bage, fage);
1.145     brouard  7909:     fclose(ficrespij);
1.126     brouard  7910: 
1.145     brouard  7911:   /*-------------- Variance of one-step probabilities---*/
                   7912:     k=1;
1.126     brouard  7913:     varprob(optionfilefiname, matcov, p, delti, nlstate, bage, fage,k,Tvar,nbcode, ncodemax,strstart);
                   7914: 
                   7915: 
                   7916:     probs= ma3x(1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7917:     for(i=1;i<=AGESUP;i++)
                   7918:       for(j=1;j<=NCOVMAX;j++)
                   7919:        for(k=1;k<=NCOVMAX;k++)
                   7920:          probs[i][j][k]=0.;
                   7921: 
                   7922:     /*---------- Forecasting ------------------*/
                   7923:     /*if((stepm == 1) && (strcmp(model,".")==0)){*/
                   7924:     if(prevfcast==1){
                   7925:       /*    if(stepm ==1){*/
1.201     brouard  7926:       prevforecast(fileresu, anproj1, mproj1, jproj1, agemin, agemax, dateprev1, dateprev2, mobilavproj, bage, fage, firstpass, lastpass, anproj2, p, cptcoveff);
1.126     brouard  7927:       /* (popforecast==1) populforecast(fileres, anpyram,mpyram,jpyram, agemin,agemax, dateprev1, dateprev2,mobilav, agedeb, fage, popforecast, popfile, anpyram1,p, i1);*/
                   7928:       /*      }  */
                   7929:       /*      else{ */
                   7930:       /*        erreur=108; */
                   7931:       /*        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); */
                   7932:       /*        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); */
                   7933:       /*      } */
                   7934:     }
1.186     brouard  7935:  
                   7936:     /* ------ Other prevalence ratios------------ */
1.126     brouard  7937: 
1.127     brouard  7938:     /* Computes prevalence between agemin (i.e minimal age computed) and no more ageminpar */
                   7939: 
                   7940:     prevalence(probs, agemin, agemax, s, agev, nlstate, imx, Tvar, nbcode, ncodemax, mint, anint, dateprev1, dateprev2, firstpass, lastpass);
                   7941:     /*  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",\
                   7942:        ageminpar, agemax, s[lastpass][imx], agev[lastpass][imx], nlstate, imx, mint[lastpass][imx],anint[lastpass][imx], dateprev1, dateprev2, firstpass, lastpass);
                   7943:     */
1.126     brouard  7944: 
1.127     brouard  7945:     if (mobilav!=0) {
                   7946:       mobaverage= ma3x(1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   7947:       if (movingaverage(probs, bage, fage, mobaverage,mobilav)!=0){
                   7948:        fprintf(ficlog," Error in movingaverage mobilav=%d\n",mobilav);
                   7949:        printf(" Error in movingaverage mobilav=%d\n",mobilav);
                   7950:       }
1.126     brouard  7951:     }
                   7952: 
                   7953: 
1.127     brouard  7954:     /*---------- Health expectancies, no variances ------------*/
                   7955: 
1.201     brouard  7956:     strcpy(filerese,"E_");
                   7957:     strcat(filerese,fileresu);
1.126     brouard  7958:     if((ficreseij=fopen(filerese,"w"))==NULL) {
                   7959:       printf("Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7960:       fprintf(ficlog,"Problem with Health Exp. resultfile: %s\n", filerese); exit(0);
                   7961:     }
                   7962:     printf("Computing Health Expectancies: result on file '%s' \n", filerese);
                   7963:     fprintf(ficlog,"Computing Health Expectancies: result on file '%s' \n", filerese);
1.145     brouard  7964:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   7965:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   7966:           
                   7967:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
1.127     brouard  7968:        fprintf(ficreseij,"\n#****** ");
                   7969:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  7970:          fprintf(ficreseij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.127     brouard  7971:        }
                   7972:        fprintf(ficreseij,"******\n");
                   7973: 
                   7974:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   7975:        oldm=oldms;savm=savms;
                   7976:        evsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, strstart);  
                   7977:       
                   7978:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
1.145     brouard  7979:       /*}*/
1.127     brouard  7980:     }
                   7981:     fclose(ficreseij);
                   7982: 
                   7983: 
                   7984:     /*---------- Health expectancies and variances ------------*/
                   7985: 
                   7986: 
1.201     brouard  7987:     strcpy(filerest,"T_");
                   7988:     strcat(filerest,fileresu);
1.127     brouard  7989:     if((ficrest=fopen(filerest,"w"))==NULL) {
                   7990:       printf("Problem with total LE resultfile: %s\n", filerest);goto end;
                   7991:       fprintf(ficlog,"Problem with total LE resultfile: %s\n", filerest);goto end;
                   7992:     }
                   7993:     printf("Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7994:     fprintf(ficlog,"Computing Total Life expectancies with their standard errors: file '%s' \n", filerest); 
                   7995: 
1.126     brouard  7996: 
1.201     brouard  7997:     strcpy(fileresstde,"STDE_");
                   7998:     strcat(fileresstde,fileresu);
1.126     brouard  7999:     if((ficresstdeij=fopen(fileresstde,"w"))==NULL) {
                   8000:       printf("Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8001:       fprintf(ficlog,"Problem with Health Exp. and std errors resultfile: %s\n", fileresstde); exit(0);
                   8002:     }
                   8003:     printf("Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8004:     fprintf(ficlog,"Computing Health Expectancies and standard errors: result on file '%s' \n", fileresstde);
                   8005: 
1.201     brouard  8006:     strcpy(filerescve,"CVE_");
                   8007:     strcat(filerescve,fileresu);
1.126     brouard  8008:     if((ficrescveij=fopen(filerescve,"w"))==NULL) {
                   8009:       printf("Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8010:       fprintf(ficlog,"Problem with Covar. Health Exp. resultfile: %s\n", filerescve); exit(0);
                   8011:     }
                   8012:     printf("Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8013:     fprintf(ficlog,"Computing Covar. of Health Expectancies: result on file '%s' \n", filerescve);
                   8014: 
1.201     brouard  8015:     strcpy(fileresv,"V_");
                   8016:     strcat(fileresv,fileresu);
1.126     brouard  8017:     if((ficresvij=fopen(fileresv,"w"))==NULL) {
                   8018:       printf("Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8019:       fprintf(ficlog,"Problem with variance resultfile: %s\n", fileresv);exit(0);
                   8020:     }
                   8021:     printf("Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   8022:     fprintf(ficlog,"Computing Variance-covariance of DFLEs: file '%s' \n", fileresv);
                   8023: 
1.145     brouard  8024:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8025:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8026:           
                   8027:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8028:        fprintf(ficrest,"\n#****** ");
1.126     brouard  8029:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8030:          fprintf(ficrest,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8031:        fprintf(ficrest,"******\n");
                   8032: 
                   8033:        fprintf(ficresstdeij,"\n#****** ");
                   8034:        fprintf(ficrescveij,"\n#****** ");
                   8035:        for(j=1;j<=cptcoveff;j++) {
1.200     brouard  8036:          fprintf(ficresstdeij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
                   8037:          fprintf(ficrescveij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8038:        }
                   8039:        fprintf(ficresstdeij,"******\n");
                   8040:        fprintf(ficrescveij,"******\n");
                   8041: 
                   8042:        fprintf(ficresvij,"\n#****** ");
                   8043:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8044:          fprintf(ficresvij,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8045:        fprintf(ficresvij,"******\n");
                   8046: 
                   8047:        eij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8048:        oldm=oldms;savm=savms;
1.127     brouard  8049:        cvevsij(eij, p, nlstate, stepm, (int) bage, (int)fage, oldm, savm, k, estepm, delti, matcov, strstart);  
1.145     brouard  8050:        /*
                   8051:         */
                   8052:        /* goto endfree; */
1.126     brouard  8053:  
                   8054:        vareij=ma3x(1,nlstate,1,nlstate,(int) bage, (int) fage);
                   8055:        pstamp(ficrest);
1.145     brouard  8056: 
                   8057: 
1.128     brouard  8058:        for(vpopbased=0; vpopbased <= popbased; vpopbased++){ /* Done for vpopbased=0 and vpopbased=1 if popbased==1*/
1.199     brouard  8059:          oldm=oldms;savm=savms; /* ZZ Segmentation fault */
1.161     brouard  8060:          cptcod= 0; /* To be deleted */
1.203   ! brouard  8061:          varevsij(optionfilefiname, vareij, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyear, k, estepm, cptcov,cptcod,vpopbased,mobilav, strstart); /* cptcod not initialized Intel */
1.145     brouard  8062:          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  8063:          if(vpopbased==1)
                   8064:            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);
                   8065:          else
                   8066:            fprintf(ficrest,"the age specific period (stable) prevalences in each health state \n");
1.201     brouard  8067:          fprintf(ficrest,"# Age popbased mobilav e.. (std) ");
1.128     brouard  8068:          for (i=1;i<=nlstate;i++) fprintf(ficrest,"e.%d (std) ",i);
                   8069:          fprintf(ficrest,"\n");
1.199     brouard  8070:          /* printf("Which p?\n"); for(i=1;i<=npar;i++)printf("p[i=%d]=%lf,",i,p[i]);printf("\n"); */
1.128     brouard  8071:          epj=vector(1,nlstate+1);
                   8072:          for(age=bage; age <=fage ;age++){
1.203   ! brouard  8073:            prevalim(prlim, nlstate, p, age, oldm, savm, ftolpl, ncvyear, k); /*ZZ Is it the correct prevalim */
1.128     brouard  8074:            if (vpopbased==1) {
                   8075:              if(mobilav ==0){
                   8076:                for(i=1; i<=nlstate;i++)
                   8077:                  prlim[i][i]=probs[(int)age][i][k];
                   8078:              }else{ /* mobilav */ 
                   8079:                for(i=1; i<=nlstate;i++)
                   8080:                  prlim[i][i]=mobaverage[(int)age][i][k];
                   8081:              }
1.126     brouard  8082:            }
                   8083:        
1.201     brouard  8084:            fprintf(ficrest," %4.0f %d %d",age, vpopbased, mobilav);
1.199     brouard  8085:            /* printf(" age %4.0f ",age); */
1.128     brouard  8086:            for(j=1, epj[nlstate+1]=0.;j <=nlstate;j++){
                   8087:              for(i=1, epj[j]=0.;i <=nlstate;i++) {
                   8088:                epj[j] += prlim[i][i]*eij[i][j][(int)age];
1.199     brouard  8089:                /*ZZZ  printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]);*/
                   8090:                /* printf("%lf %lf ", prlim[i][i] ,eij[i][j][(int)age]); */
1.128     brouard  8091:              }
                   8092:              epj[nlstate+1] +=epj[j];
1.126     brouard  8093:            }
1.199     brouard  8094:            /* printf(" age %4.0f \n",age); */
1.126     brouard  8095: 
1.128     brouard  8096:            for(i=1, vepp=0.;i <=nlstate;i++)
                   8097:              for(j=1;j <=nlstate;j++)
                   8098:                vepp += vareij[i][j][(int)age];
                   8099:            fprintf(ficrest," %7.3f (%7.3f)", epj[nlstate+1],sqrt(vepp));
                   8100:            for(j=1;j <=nlstate;j++){
                   8101:              fprintf(ficrest," %7.3f (%7.3f)", epj[j],sqrt(vareij[j][j][(int)age]));
                   8102:            }
                   8103:            fprintf(ficrest,"\n");
1.126     brouard  8104:          }
                   8105:        }
                   8106:        free_ma3x(eij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8107:        free_ma3x(vareij,1,nlstate,1,nlstate,(int) bage, (int)fage);
                   8108:        free_vector(epj,1,nlstate+1);
1.145     brouard  8109:       /*}*/
1.126     brouard  8110:     }
                   8111:     free_vector(weight,1,n);
1.145     brouard  8112:     free_imatrix(Tvard,1,NCOVMAX,1,2);
1.126     brouard  8113:     free_imatrix(s,1,maxwav+1,1,n);
                   8114:     free_matrix(anint,1,maxwav,1,n); 
                   8115:     free_matrix(mint,1,maxwav,1,n);
                   8116:     free_ivector(cod,1,n);
                   8117:     free_ivector(tab,1,NCOVMAX);
                   8118:     fclose(ficresstdeij);
                   8119:     fclose(ficrescveij);
                   8120:     fclose(ficresvij);
                   8121:     fclose(ficrest);
                   8122:     fclose(ficpar);
                   8123:   
                   8124:     /*------- Variance of period (stable) prevalence------*/   
                   8125: 
1.201     brouard  8126:     strcpy(fileresvpl,"VPL_");
                   8127:     strcat(fileresvpl,fileresu);
1.126     brouard  8128:     if((ficresvpl=fopen(fileresvpl,"w"))==NULL) {
                   8129:       printf("Problem with variance of period (stable) prevalence  resultfile: %s\n", fileresvpl);
                   8130:       exit(0);
                   8131:     }
                   8132:     printf("Computing Variance-covariance of period (stable) prevalence: file '%s' \n", fileresvpl);
                   8133: 
1.145     brouard  8134:     /*for(cptcov=1,k=0;cptcov<=i1;cptcov++){
                   8135:       for(cptcod=1;cptcod<=ncodemax[cptcov];cptcod++){*/
                   8136:           
                   8137:     for (k=1; k <= (int) pow(2,cptcoveff); k++){
                   8138:        fprintf(ficresvpl,"\n#****** ");
1.126     brouard  8139:        for(j=1;j<=cptcoveff;j++) 
1.200     brouard  8140:          fprintf(ficresvpl,"V%d=%d ",Tvaraff[j],nbcode[Tvaraff[j]][codtabm(k,j)]);
1.126     brouard  8141:        fprintf(ficresvpl,"******\n");
                   8142:       
                   8143:        varpl=matrix(1,nlstate,(int) bage, (int) fage);
                   8144:        oldm=oldms;savm=savms;
1.203   ! brouard  8145:        varprevlim(fileres, varpl, matcov, p, delti, nlstate, stepm, (int) bage, (int) fage, oldm, savm, prlim, ftolpl, ncvyear, k, strstart);
1.126     brouard  8146:        free_matrix(varpl,1,nlstate,(int) bage, (int)fage);
1.145     brouard  8147:       /*}*/
1.126     brouard  8148:     }
                   8149: 
                   8150:     fclose(ficresvpl);
                   8151: 
                   8152:     /*---------- End : free ----------------*/
                   8153:     if (mobilav!=0) free_ma3x(mobaverage,1, AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8154:     free_ma3x(probs,1,AGESUP,1,NCOVMAX, 1,NCOVMAX);
                   8155:   }  /* mle==-3 arrives here for freeing */
1.164     brouard  8156:  /* endfree:*/
1.141     brouard  8157:     free_matrix(prlim,1,nlstate,1,nlstate); /*here or after loop ? */
1.126     brouard  8158:     free_matrix(pmmij,1,nlstate+ndeath,1,nlstate+ndeath);
                   8159:     free_matrix(oldms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8160:     free_matrix(newms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8161:     free_matrix(savms, 1,nlstate+ndeath,1,nlstate+ndeath);
                   8162:     free_matrix(covar,0,NCOVMAX,1,n);
                   8163:     free_matrix(matcov,1,npar,1,npar);
1.203   ! brouard  8164:     free_matrix(hess,1,npar,1,npar);
1.126     brouard  8165:     /*free_vector(delti,1,npar);*/
                   8166:     free_ma3x(delti3,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel); 
                   8167:     free_matrix(agev,1,maxwav,1,imx);
                   8168:     free_ma3x(param,1,nlstate,1, nlstate+ndeath-1,1,ncovmodel);
                   8169: 
1.145     brouard  8170:     free_ivector(ncodemax,1,NCOVMAX);
1.192     brouard  8171:     free_ivector(ncodemaxwundef,1,NCOVMAX);
1.145     brouard  8172:     free_ivector(Tvar,1,NCOVMAX);
                   8173:     free_ivector(Tprod,1,NCOVMAX);
                   8174:     free_ivector(Tvaraff,1,NCOVMAX);
                   8175:     free_ivector(Tage,1,NCOVMAX);
1.126     brouard  8176: 
                   8177:     free_imatrix(nbcode,0,NCOVMAX,0,NCOVMAX);
1.200     brouard  8178:     /* free_imatrix(codtab,1,100,1,10); */
1.126     brouard  8179:   fflush(fichtm);
                   8180:   fflush(ficgp);
                   8181:   
                   8182: 
                   8183:   if((nberr >0) || (nbwarn>0)){
                   8184:     printf("End of Imach with %d errors and/or %d warnings\n",nberr,nbwarn);
                   8185:     fprintf(ficlog,"End of Imach with %d errors and/or warnings %d\n",nberr,nbwarn);
                   8186:   }else{
                   8187:     printf("End of Imach\n");
                   8188:     fprintf(ficlog,"End of Imach\n");
                   8189:   }
                   8190:   printf("See log file on %s\n",filelog);
                   8191:   /*  gettimeofday(&end_time, (struct timezone*)0);*/  /* after time */
1.157     brouard  8192:   /*(void) gettimeofday(&end_time,&tzp);*/
                   8193:   rend_time = time(NULL);  
                   8194:   end_time = *localtime(&rend_time);
                   8195:   /* tml = *localtime(&end_time.tm_sec); */
                   8196:   strcpy(strtend,asctime(&end_time));
1.126     brouard  8197:   printf("Local time at start %s\nLocal time at end   %s",strstart, strtend); 
                   8198:   fprintf(ficlog,"Local time at start %s\nLocal time at end   %s\n",strstart, strtend); 
1.157     brouard  8199:   printf("Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
1.126     brouard  8200: 
1.157     brouard  8201:   printf("Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
                   8202:   fprintf(ficlog,"Total time used %s\n", asc_diff_time(rend_time -rstart_time,tmpout));
                   8203:   fprintf(ficlog,"Total time was %.0lf Sec.\n", difftime(rend_time,rstart_time));
1.126     brouard  8204:   /*  printf("Total time was %d uSec.\n", total_usecs);*/
                   8205: /*   if(fileappend(fichtm,optionfilehtm)){ */
                   8206:   fprintf(fichtm,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8207:   fclose(fichtm);
                   8208:   fprintf(fichtmcov,"<br>Local time at start %s<br>Local time at end   %s<br>\n</body></html>",strstart, strtend);
                   8209:   fclose(fichtmcov);
                   8210:   fclose(ficgp);
                   8211:   fclose(ficlog);
                   8212:   /*------ End -----------*/
                   8213: 
                   8214: 
                   8215:    printf("Before Current directory %s!\n",pathcd);
1.184     brouard  8216: #ifdef WIN32
                   8217:    if (_chdir(pathcd) != 0)
                   8218:           printf("Can't move to directory %s!\n",path);
                   8219:    if(_getcwd(pathcd,MAXLINE) > 0)
                   8220: #else
1.126     brouard  8221:    if(chdir(pathcd) != 0)
1.184     brouard  8222:           printf("Can't move to directory %s!\n", path);
                   8223:    if (getcwd(pathcd, MAXLINE) > 0)
                   8224: #endif 
1.126     brouard  8225:     printf("Current directory %s!\n",pathcd);
                   8226:   /*strcat(plotcmd,CHARSEPARATOR);*/
                   8227:   sprintf(plotcmd,"gnuplot");
1.157     brouard  8228: #ifdef _WIN32
1.126     brouard  8229:   sprintf(plotcmd,"\"%sgnuplot.exe\"",pathimach);
                   8230: #endif
                   8231:   if(!stat(plotcmd,&info)){
1.158     brouard  8232:     printf("Error or gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8233:     if(!stat(getenv("GNUPLOTBIN"),&info)){
1.158     brouard  8234:       printf("Error or gnuplot program not found: '%s' Environment GNUPLOTBIN not set.\n",plotcmd);fflush(stdout);
1.126     brouard  8235:     }else
                   8236:       strcpy(pplotcmd,plotcmd);
1.157     brouard  8237: #ifdef __unix
1.126     brouard  8238:     strcpy(plotcmd,GNUPLOTPROGRAM);
                   8239:     if(!stat(plotcmd,&info)){
1.158     brouard  8240:       printf("Error gnuplot program not found: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8241:     }else
                   8242:       strcpy(pplotcmd,plotcmd);
                   8243: #endif
                   8244:   }else
                   8245:     strcpy(pplotcmd,plotcmd);
                   8246:   
                   8247:   sprintf(plotcmd,"%s %s",pplotcmd, optionfilegnuplot);
1.158     brouard  8248:   printf("Starting graphs with: '%s'\n",plotcmd);fflush(stdout);
1.126     brouard  8249: 
                   8250:   if((outcmd=system(plotcmd)) != 0){
1.158     brouard  8251:     printf("gnuplot command might not be in your path: '%s', err=%d\n", plotcmd, outcmd);
1.154     brouard  8252:     printf("\n Trying if gnuplot resides on the same directory that IMaCh\n");
1.152     brouard  8253:     sprintf(plotcmd,"%sgnuplot %s", pathimach, optionfilegnuplot);
1.150     brouard  8254:     if((outcmd=system(plotcmd)) != 0)
1.153     brouard  8255:       printf("\n Still a problem with gnuplot command %s, err=%d\n", plotcmd, outcmd);
1.126     brouard  8256:   }
1.158     brouard  8257:   printf(" Successful, please wait...");
1.126     brouard  8258:   while (z[0] != 'q') {
                   8259:     /* chdir(path); */
1.154     brouard  8260:     printf("\nType e to edit results with your browser, g to graph again and q for exit: ");
1.126     brouard  8261:     scanf("%s",z);
                   8262: /*     if (z[0] == 'c') system("./imach"); */
                   8263:     if (z[0] == 'e') {
1.158     brouard  8264: #ifdef __APPLE__
1.152     brouard  8265:       sprintf(pplotcmd, "open %s", optionfilehtm);
1.157     brouard  8266: #elif __linux
                   8267:       sprintf(pplotcmd, "xdg-open %s", optionfilehtm);
1.153     brouard  8268: #else
1.152     brouard  8269:       sprintf(pplotcmd, "%s", optionfilehtm);
1.153     brouard  8270: #endif
                   8271:       printf("Starting browser with: %s",pplotcmd);fflush(stdout);
                   8272:       system(pplotcmd);
1.126     brouard  8273:     }
                   8274:     else if (z[0] == 'g') system(plotcmd);
                   8275:     else if (z[0] == 'q') exit(0);
                   8276:   }
                   8277:   end:
                   8278:   while (z[0] != 'q') {
1.195     brouard  8279:     printf("\nType  q for exiting: "); fflush(stdout);
1.126     brouard  8280:     scanf("%s",z);
                   8281:   }
                   8282: }

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