Compute condition number of information matrix
[openmx:openmx.git] / src / Compute.cpp
1 /*
2  *  Copyright 2013 The OpenMx Project
3  *
4  *  Licensed under the Apache License, Version 2.0 (the "License");
5  *  you may not use this file except in compliance with the License.
6  *  You may obtain a copy of the License at
7  *
8  *       http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *   Unless required by applicable law or agreed to in writing, software
11  *   distributed under the License is distributed on an "AS IS" BASIS,
12  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  */
16
17 #include <algorithm>
18
19 #include "omxDefines.h"
20 #include "Compute.h"
21 #include "omxState.h"
22 #include "omxExportBackendState.h"
23 #include "omxRFitFunction.h"
24 #include "matrix.h"
25 #include "omxBuffer.h"
26
27 void pda(const double *ar, int rows, int cols);
28
29 void FitContext::init()
30 {
31         size_t numParam = varGroup->vars.size();
32         wanted = 0;
33         sampleSize = 0;  // remove? TODO
34         mac = parent? parent->mac : 0;
35         fit = parent? parent->fit : 0;
36         caution = parent? parent->caution : 0;
37         est = new double[numParam];
38         flavor = new int[numParam];
39         grad = new double[numParam];
40         hess = new double[numParam * numParam];
41         hessCondNum = NA_REAL;
42         infoA = NULL;
43         infoB = NULL;
44         ihess = new double[numParam * numParam];
45         stderrs = NULL;
46         changedEstimates = false;
47         inform = INFORM_UNINITIALIZED;
48         iterations = 0;
49 }
50
51 void FitContext::allocStderrs()
52 {
53         if (stderrs) return;
54
55         size_t numParam = varGroup->vars.size();
56         stderrs = new double[numParam];
57
58         for (size_t px=0; px < numParam; ++px) {
59                 stderrs[px] = NA_REAL;
60         }
61 }
62
63 FitContext::FitContext(std::vector<double> &startingValues)
64 {
65         parent = NULL;
66         varGroup = Global->freeGroup[0];
67         init();
68
69         size_t numParam = varGroup->vars.size();
70         if (startingValues.size() != numParam) {
71                 error("Got %d starting values for %d parameters",
72                       startingValues.size(), numParam);
73         }
74         memcpy(est, startingValues.data(), sizeof(double) * numParam);
75
76         for (size_t v1=0; v1 < numParam; v1++) {
77                 grad[v1] = nan("unset");
78                 for (size_t v2=0; v2 < numParam; v2++) {
79                         hess[v1 * numParam + v2] = nan("unset");
80                 }
81         }
82 }
83
84 FitContext::FitContext(FitContext *parent, FreeVarGroup *varGroup)
85 {
86         this->parent = parent;
87         this->varGroup = varGroup;
88         init();
89
90         FreeVarGroup *src = parent->varGroup;
91         FreeVarGroup *dest = varGroup;
92         size_t svars = parent->varGroup->vars.size();
93         size_t dvars = varGroup->vars.size();
94         if (dvars == 0) return;
95         mapToParent.resize(dvars);
96
97         size_t d1 = 0;
98         for (size_t s1=0; s1 < src->vars.size(); ++s1) {
99                 if (src->vars[s1] != dest->vars[d1]) continue;
100                 mapToParent[d1] = s1;
101                 est[d1] = parent->est[s1];
102
103                 if (parent->wanted & (FF_COMPUTE_GRADIENT | FF_COMPUTE_HESSIAN)) {
104                         grad[d1] = parent->grad[s1];
105
106                         size_t d2 = 0;
107                         for (size_t s2=0; s2 < src->vars.size(); ++s2) {
108                                 if (src->vars[s2] != dest->vars[d2]) continue;
109                                 hess[d1 * dvars + d2] = parent->hess[s1 * svars + s2];
110                                 if (++d2 == dvars) break;
111                         }
112                 }
113
114                 // ihess TODO?
115
116                 if (++d1 == dvars) break;
117         }
118         if (d1 != dvars) error("Parent free parameter group is not a superset");
119
120         wanted = parent->wanted;
121         hessCondNum = parent->hessCondNum;
122
123         // pda(parent->est, 1, svars);
124         // pda(est, 1, dvars);
125         // pda(parent->grad, 1, svars);
126         // pda(grad, 1, dvars);
127         // pda(parent->hess, svars, svars);
128         // pda(hess, dvars, dvars);
129 }
130
131 void FitContext::copyParamToModel(omxMatrix *mat)
132 { copyParamToModel(mat->currentState); }
133
134 void FitContext::copyParamToModel(omxMatrix *mat, double *at)
135 { copyParamToModel(mat->currentState, at); }
136
137 void FitContext::updateParent()
138 {
139         FreeVarGroup *src = varGroup;
140         FreeVarGroup *dest = parent->varGroup;
141         size_t svars = varGroup->vars.size();
142         size_t dvars = parent->varGroup->vars.size();
143
144         parent->wanted |= wanted;
145         parent->fit = fit;
146         parent->mac = mac;
147         parent->caution = caution;
148         parent->hessCondNum = hessCondNum;
149
150         // rewrite using mapToParent TODO
151
152         if (svars > 0) {
153                 size_t s1 = 0;
154                 for (size_t d1=0; d1 < dest->vars.size(); ++d1) {
155                         if (dest->vars[d1] != src->vars[s1]) continue;
156                         parent->est[d1] = est[s1];
157
158                         if (wanted & (FF_COMPUTE_GRADIENT | FF_COMPUTE_HESSIAN)) {
159                                 parent->grad[d1] = grad[s1];
160
161                                 size_t s2 = 0;
162                                 for (size_t d2=0; d2 < dest->vars.size(); ++d2) {
163                                         if (dest->vars[d2] != src->vars[s2]) continue;
164                                         parent->hess[d1 * dvars + d2] = hess[s1 * svars + s2];
165                                         if (++s2 == svars) break;
166                                 }
167                         }
168
169                         // ihess TODO?
170
171                         if (++s1 == svars) break;
172                 }
173                 if (wanted & FF_COMPUTE_PARAMFLAVOR) {
174                         for (size_t s1=0; s1 < src->vars.size(); ++s1) {
175                                 parent->flavor[mapToParent[s1]] = flavor[s1];
176                         }
177                 }
178                 if (stderrs) {
179                         parent->allocStderrs();
180                         for (size_t s1=0; s1 < src->vars.size(); ++s1) {
181                                 parent->stderrs[mapToParent[s1]] = stderrs[s1];
182                         }
183                 }
184         }
185         
186         // pda(est, 1, svars);
187         // pda(parent->est, 1, dvars);
188         // pda(grad, 1, svars);
189         // pda(parent->grad, 1, dvars);
190         // pda(hess, svars, svars);
191         // pda(parent->hess, dvars, dvars);
192 }
193
194 void FitContext::updateParentAndFree()
195 {
196         updateParent();
197         delete this;
198 }
199
200 void FitContext::log(const char *where)
201 {
202         log(where, wanted);
203 }
204
205 void FitContext::log(const char *where, int what)
206 {
207         size_t count = varGroup->vars.size();
208         std::string buf(where);
209         buf += " ---\n";
210         if (what & FF_COMPUTE_MAXABSCHANGE) buf += string_snprintf("MAC: %.5f\n", mac);
211         if (what & FF_COMPUTE_FIT) buf += string_snprintf("fit: %.5f\n", fit);
212         if (what & FF_COMPUTE_ESTIMATE) {
213                 buf += string_snprintf("est %lu: c(", count);
214                 for (size_t vx=0; vx < count; ++vx) {
215                         buf += string_snprintf("%.5f", est[vx]);
216                         if (vx < count - 1) buf += ", ";
217                 }
218                 buf += ")\n";
219         }
220         if (what & FF_COMPUTE_GRADIENT) {
221                 buf += string_snprintf("grad %lu: c(", count);
222                 for (size_t vx=0; vx < count; ++vx) {
223                         buf += string_snprintf("%.5f", grad[vx]);
224                         if (vx < count - 1) buf += ", ";
225                 }
226                 buf += ")\n";
227         }
228         if (what & (FF_COMPUTE_HESSIAN)) {
229                 buf += string_snprintf("hess %lux%lu: c(", count, count);
230                 for (size_t v1=0; v1 < count; ++v1) {
231                         for (size_t v2=0; v2 < count; ++v2) {
232                                 buf += string_snprintf("%.5f", hess[v1 * count + v2]);
233                                 if (v1 < count-1 || v2 < count-1) buf += ", ";
234                         }
235                         buf += "\n";
236                 }
237                 buf += ")\n";
238         }
239         if (what & FF_COMPUTE_IHESSIAN) {
240                 buf += string_snprintf("ihess %lux%lu: c(", count, count);
241                 for (size_t v1=0; v1 < count; ++v1) {
242                         for (size_t v2=0; v2 < count; ++v2) {
243                                 buf += string_snprintf("%.5f", ihess[v1 * count + v2]);
244                                 if (v1 < count-1 || v2 < count-1) buf += ", ";
245                         }
246                         buf += "\n";
247                 }
248                 buf += ")\n";
249         }
250         if (what & FF_COMPUTE_HGPROD) {
251                 buf += string_snprintf("ihess %%*%% grad %lu: list(", hgProd.size());
252                 for (size_t px=0; px < hgProd.size(); ++px) {
253                         buf += string_snprintf("c(%d, %d, %d)", hgProd[px].hentry,
254                                                hgProd[px].gentry, hgProd[px].dest);
255                         if (px < hgProd.size() - 1) buf += ", ";
256                 }
257                 buf += ")\n";
258         }
259         mxLogBig(buf);
260 }
261
262 static void _fixSymmetry(const char *name, double *mat, size_t numParam, bool force)
263 {
264         for (size_t h1=1; h1 < numParam; h1++) {
265                 for (size_t h2=0; h2 < h1; h2++) {
266                         if (!force && mat[h2 * numParam + h1] != 0) {
267                                 omxRaiseErrorf(globalState, "%s is not upper triangular", name);
268                                 break;
269                         }
270                         mat[h2 * numParam + h1] = mat[h1 * numParam + h2];
271                 }
272         }
273 }
274
275 void FitContext::fixHessianSymmetry(int want, bool force)
276 {
277         size_t numParam = varGroup->vars.size();
278
279         if (want & (FF_COMPUTE_HESSIAN)) {
280                 _fixSymmetry("Hessian/information", hess, numParam, force);
281         }
282
283         if (want & FF_COMPUTE_IHESSIAN) {
284                 _fixSymmetry("Inverse Hessian", ihess, numParam, force);
285         }
286 }
287
288 static void omxRepopulateRFitFunction(omxFitFunction* oo, double* x, int n)
289 {
290         omxRFitFunction* rFitFunction = (omxRFitFunction*)oo->argStruct;
291
292         SEXP theCall, estimate;
293
294         PROTECT(estimate = allocVector(REALSXP, n));
295         double *est = REAL(estimate);
296         for(int i = 0; i < n ; i++) {
297                 est[i] = x[i];
298         }
299
300         PROTECT(theCall = allocVector(LANGSXP, 4));
301
302         SETCAR(theCall, install("imxUpdateModelValues"));
303         SETCADR(theCall, rFitFunction->model);
304         SETCADDR(theCall, rFitFunction->flatModel);
305         SETCADDDR(theCall, estimate);
306
307         REPROTECT(rFitFunction->model = eval(theCall, R_GlobalEnv), rFitFunction->modelIndex);
308
309         UNPROTECT(2); // theCall, estimate
310 }
311
312 void FitContext::copyParamToModel(omxState* os)
313 {
314         copyParamToModel(os, est);
315 }
316
317 void FitContext::maybeCopyParamToModel(omxState* os)
318 {
319         if (changedEstimates) {
320                 copyParamToModel(os, est);
321                 changedEstimates = false;
322         }
323 }
324
325 void FitContext::copyParamToModel(omxState* os, double *at)
326 {
327         size_t numParam = varGroup->vars.size();
328         if(OMX_DEBUG) {
329                 mxLog("Copying %lu free parameter estimates to model %p", numParam, os);
330         }
331
332         if(numParam == 0) return;
333
334         // Confidence Intervals & Hessian Calculation probe the parameter space
335         // near the best estimate. If stale, we need to restore the best estimate
336         // before returning results to the user.
337         os->stale = at != est;
338
339         os->computeCount++;
340
341         if(OMX_VERBOSE) {
342                 std::string buf;
343                 buf += string_snprintf("Call: %d.%d (%ld) ", os->majorIteration, os->minorIteration, os->computeCount);
344                 buf += ("Estimates: [");
345                 for(size_t k = 0; k < numParam; k++) {
346                         buf += string_snprintf(" %f", at[k]);
347                 }
348                 buf += ("]\n");
349                 mxLogBig(buf);
350         }
351
352         for(size_t k = 0; k < numParam; k++) {
353                 omxFreeVar* freeVar = varGroup->vars[k];
354                 for(size_t l = 0; l < freeVar->locations.size(); l++) {
355                         omxFreeVarLocation *loc = &freeVar->locations[l];
356                         omxMatrix *matrix = os->matrixList[loc->matrix];
357                         int row = loc->row;
358                         int col = loc->col;
359                         omxSetMatrixElement(matrix, row, col, at[k]);
360                         if(OMX_DEBUG) {
361                                 mxLog("Setting location (%d, %d) of matrix %d to value %f for var %lu",
362                                         row, col, loc->matrix, at[k], k);
363                         }
364                 }
365         }
366
367         if (RFitFunction) omxRepopulateRFitFunction(RFitFunction, at, numParam);
368
369         varGroup->markDirty(os);
370
371         if (!os->childList) return;
372
373         for(int i = 0; i < Global->numChildren; i++) {
374                 copyParamToModel(os->childList[i], at);
375         }
376 }
377
378 double *FitContext::take(int want)
379 {
380         if (!(want & (wanted | FF_COMPUTE_ESTIMATE))) {
381                 error("Attempt to take %d but not available", want);
382         }
383
384         double *ret = NULL;
385         switch(want) {
386         case FF_COMPUTE_ESTIMATE:
387                 ret = est;
388                 est = NULL;
389                 break;
390         case FF_COMPUTE_HESSIAN:
391                 ret = hess;
392                 hess = NULL;
393                 break;
394         case FF_COMPUTE_IHESSIAN:
395                 ret = ihess;
396                 ihess = NULL;
397                 break;
398         default:
399                 error("Taking of %d is not implemented", want);
400         }
401         if (!ret) error("Attempt to take %d, already taken", want);
402         return ret;
403 }
404
405 void FitContext::preInfo()
406 {
407         size_t numParam = varGroup->vars.size();
408         size_t npsq = numParam * numParam;
409         if (!infoA) infoA = new double[npsq];
410         if (!infoB) infoB = new double[npsq];
411         OMXZERO(infoA, npsq);
412         OMXZERO(infoB, npsq);
413 }
414
415 void FitContext::postInfo()
416 {
417         size_t numParam = varGroup->vars.size();
418         switch (infoMethod) {
419         case INFO_METHOD_SANDWICH:{
420                 omxBuffer<double> work(numParam * numParam);
421                 Matrix amat(infoA, numParam, numParam);
422                 InvertSymmetricIndef(amat, 'U');
423                 _fixSymmetry("InfoB", infoB, numParam, false);
424                 Matrix bmat(infoB, numParam, numParam);
425                 Matrix wmat(work.data(), numParam, numParam);
426                 Matrix hmat(ihess, numParam, numParam);
427                 // DTRMM can do it without extra workspace TODO
428                 SymMatrixMultiply('L', 'U', 1, 0, amat, bmat, wmat);
429                 SymMatrixMultiply('R', 'U', 1, 0, amat, wmat, hmat);
430                 wanted |= FF_COMPUTE_IHESSIAN;
431                 break;}
432         case INFO_METHOD_MEAT:
433                 // copy upper triangle only TODO
434                 for (size_t d1=0; d1 < numParam; ++d1) {
435                         for (size_t d2=0; d2 < numParam; ++d2) {
436                                 int cell = d1 * numParam + d2;
437                                 hess[cell] = infoB[cell];
438                         }
439                 }
440                 fixHessianSymmetry(FF_COMPUTE_HESSIAN);
441                 wanted |= FF_COMPUTE_HESSIAN;
442                 break;
443         case INFO_METHOD_BREAD:
444                 // copy upper triangle only TODO
445                 for (size_t d1=0; d1 < numParam; ++d1) {
446                         for (size_t d2=0; d2 < numParam; ++d2) {
447                                 int cell = d1 * numParam + d2;
448                                 hess[cell] = infoA[cell];
449                         }
450                 }
451                 fixHessianSymmetry(FF_COMPUTE_HESSIAN);
452                 wanted |= FF_COMPUTE_HESSIAN;
453                 break;
454         default:
455                 error("Unknown information matrix estimation method %d", infoMethod);
456         }
457 }
458
459 FitContext::~FitContext()
460 {
461         if (est) delete [] est;
462         if (flavor) delete [] flavor;
463         if (grad) delete [] grad;
464         if (hess) delete [] hess;
465         if (ihess) delete [] ihess;
466         if (stderrs) delete [] stderrs;
467         if (infoA) delete [] infoA;
468         if (infoB) delete [] infoB;
469 }
470
471 omxFitFunction *FitContext::RFitFunction = NULL;
472
473 void FitContext::setRFitFunction(omxFitFunction *rff)
474 {
475         if (rff) {
476                 Global->numThreads = 1;
477                 if (RFitFunction) {
478                         error("You can only create 1 MxRFitFunction per independent model");
479                 }
480         }
481         RFitFunction = rff;
482 }
483
484 Ramsay1975::Ramsay1975(FitContext *fc, int flavor, double caution, int verbose,
485                        double minCaution)
486 {
487         this->fc = fc;
488         this->flavor = flavor;
489         this->verbose = verbose;
490         this->caution = caution;
491         this->minCaution = minCaution;
492         maxCaution = 0.0;
493         highWatermark = std::max(0.5, caution);  // arbitrary guess
494
495         numParam = fc->varGroup->vars.size();
496         prevAdj1.assign(numParam, 0);
497         prevAdj2.resize(numParam);
498         prevEst.resize(numParam);
499         memcpy(prevEst.data(), fc->est, sizeof(double) * numParam);
500 }
501
502 void Ramsay1975::recordEstimate(int px, double newEst)
503 {
504         omxFreeVar *fv = fc->varGroup->vars[px];
505         bool hitBound=false;
506         double param = newEst;
507         if (param < fv->lbound) {
508                 hitBound=true;
509                 param = prevEst[px] - (prevEst[px] - fv->lbound) / 2;
510         }
511         if (param > fv->ubound) {
512                 hitBound=true;
513                 param = prevEst[px] + (fv->ubound - prevEst[px]) / 2;
514         }
515         
516         prevAdj2[px] = prevAdj1[px];
517         prevAdj1[px] = param - prevEst[px];
518         
519         if (verbose >= 4) {
520                 std::string buf;
521                 buf += string_snprintf("~%d~%s: %.4f -> %.4f", px, fv->name, prevEst[px], param);
522                 if (hitBound) {
523                         buf += string_snprintf(" wanted %.4f but hit bound", newEst);
524                 }
525                 if (prevAdj1[px] * prevAdj2[px] < 0) {
526                         buf += " *OSC*";
527                 }
528                 buf += "\n";
529                 mxLogBig(buf);
530         }
531
532         fc->est[px] = param;
533         prevEst[px] = param;
534 }
535
536 void Ramsay1975::apply()
537 {
538         for (size_t px=0; px < numParam; ++px) {
539                 recordEstimate(px, (1 - caution) * fc->est[px] + caution * prevEst[px]);
540         }
541 }
542
543 void Ramsay1975::recalibrate(bool *restart)
544 {
545         double normPrevAdj2 = 0;
546         double normAdjDiff = 0;
547         std::vector<double> adjDiff(numParam);
548
549         // The choice of norm is also arbitrary. Other norms might work better.
550         for (size_t px=0; px < numParam; ++px) {
551                 if (fc->flavor[px] != flavor) continue;
552                 adjDiff[px] = prevAdj1[px] - prevAdj2[px];
553                 normPrevAdj2 += prevAdj2[px] * prevAdj2[px];
554         }
555
556         for (size_t px=0; px < numParam; ++px) {
557                 if (fc->flavor[px] != flavor) continue;
558                 normAdjDiff += adjDiff[px] * adjDiff[px];
559         }
560         if (normAdjDiff == 0) {
561                 return;
562                 //error("Ramsay: no free variables of flavor %d", flavor);
563         }
564
565         double ratio = sqrt(normPrevAdj2 / normAdjDiff);
566         //if (verbose >= 3) mxLog("Ramsay[%d]: sqrt(%.5f/%.5f) = %.5f",
567         // flavor, normPrevAdj2, normAdjDiff, ratio);
568
569         double newCaution = 1 - (1-caution) * ratio;
570         if (newCaution > .95) newCaution = .95;  // arbitrary guess
571         if (newCaution < 0) newCaution /= 2;     // don't get overconfident
572         if (newCaution < minCaution) newCaution = minCaution;
573         if (newCaution < caution) {
574                 caution = newCaution/3 + 2*caution/3;  // don't speed up too fast, arbitrary ratio
575         } else {
576                 caution = newCaution;
577         }
578         maxCaution = std::max(maxCaution, caution);
579         if (caution < highWatermark || (normPrevAdj2 < 1e-3 && normAdjDiff < 1e-3)) {
580                 if (verbose >= 3) mxLog("Ramsay[%d]: %.2f caution", flavor, caution);
581         } else {
582                 if (verbose >= 3) mxLog("Ramsay[%d]: caution %.2f > %.2f, extreme oscillation, restart recommended",
583                                         flavor, caution, highWatermark);
584                 *restart = TRUE;
585         }
586         highWatermark += .02; // arbitrary guess
587 }
588
589 void Ramsay1975::restart()
590 {
591         memcpy(prevEst.data(), fc->est, sizeof(double) * numParam);
592         prevAdj1.assign(numParam, 0);
593         prevAdj2.assign(numParam, 0);
594         highWatermark = 1 - (1 - highWatermark) * .5; // arbitrary guess
595         caution = std::max(caution, highWatermark);   // arbitrary guess
596         maxCaution = std::max(maxCaution, caution);
597         highWatermark = caution;
598         if (verbose >= 3) {
599                 mxLog("Ramsay[%d]: restart with %.2f caution %.2f highWatermark",
600                       flavor, caution, highWatermark);
601         }
602 }
603
604 omxCompute::omxCompute()
605 {
606         varGroup = NULL;
607 }
608
609 omxCompute::~omxCompute()
610 {}
611
612 void omxCompute::initFromFrontend(SEXP rObj)
613 {
614         SEXP slotValue;
615         PROTECT(slotValue = GET_SLOT(rObj, install("id")));
616         if (length(slotValue) == 1) {
617                 int id = INTEGER(slotValue)[0];
618                 varGroup = Global->findVarGroup(id);
619         }
620
621         if (!varGroup) {
622                 if (!R_has_slot(rObj, install("free.set"))) {
623                         varGroup = Global->freeGroup[0];
624                 } else {
625                         PROTECT(slotValue = GET_SLOT(rObj, install("free.set")));
626                         if (length(slotValue) != 0) {
627                                 // it's a free.set with no free variables
628                                 varGroup = Global->findVarGroup(-1);
629                         } else {
630                                 varGroup = Global->freeGroup[0];
631                         }
632                 }
633         }
634 }
635
636 class omxComputeSequence : public omxCompute {
637         typedef omxCompute super;
638         std::vector< omxCompute* > clist;
639
640  public:
641         virtual void initFromFrontend(SEXP rObj);
642         virtual void compute(FitContext *fc);
643         virtual void reportResults(FitContext *fc, MxRList *out);
644         virtual double getOptimizerStatus();
645         virtual ~omxComputeSequence();
646 };
647
648 class omxComputeIterate : public omxCompute {
649         typedef omxCompute super;
650         std::vector< omxCompute* > clist;
651         int maxIter;
652         double tolerance;
653         int verbose;
654
655  public:
656         virtual void initFromFrontend(SEXP rObj);
657         virtual void compute(FitContext *fc);
658         virtual void reportResults(FitContext *fc, MxRList *out);
659         virtual double getOptimizerStatus();
660         virtual ~omxComputeIterate();
661 };
662
663 class omxComputeOnce : public omxCompute {
664         typedef omxCompute super;
665         std::vector< omxMatrix* > algebras;
666         std::vector< omxExpectation* > expectations;
667         int verbose;
668         const char *context;
669         bool mac;
670         bool fit;
671         bool gradient;
672         bool hessian;
673         bool ihessian;
674         bool infoMat;
675         enum ComputeInfoMethod infoMethod;
676         bool hgprod;
677
678  public:
679         virtual void initFromFrontend(SEXP rObj);
680         virtual omxFitFunction *getFitFunction();
681         virtual void compute(FitContext *fc);
682         virtual void reportResults(FitContext *fc, MxRList *out);
683 };
684
685 class ComputeEM : public omxCompute {
686         typedef omxCompute super;
687         std::vector< omxExpectation* > expectations;
688         omxCompute *fit1;
689         omxCompute *fit2;
690         int maxIter;
691         int mstepIter;
692         int totalMstepIter;
693         double tolerance;
694         double semTolerance;
695         int verbose;
696         bool useRamsay;
697         bool information;
698         std::vector<Ramsay1975*> ramsay;
699         std::vector<double*> estHistory;
700         std::vector<int> paramHistLen;
701         FitContext *recentFC;  //nice if can use std::unique_ptr
702         std::vector<double> optimum;
703         double bestFit;
704         static const double MIDDLE_START;
705         static const double MIDDLE_END;
706         static const size_t minHistLength;
707         size_t histLen;
708
709         void setExpectationContext(const char *context);
710         void probeEM(FitContext *fc, int vx, size_t cx, double *rij);
711         bool checkConvergence(omxBuffer<double> &rijWork, int h1, int h2,
712                               std::vector<bool> *semConverged, omxBuffer<double> *diffWork,
713                               omxBuffer<double> *rij);
714
715  public:
716         virtual void initFromFrontend(SEXP rObj);
717         virtual void compute(FitContext *fc);
718         virtual void reportResults(FitContext *fc, MxRList *out);
719         virtual double getOptimizerStatus();
720         virtual ~ComputeEM();
721 };
722
723 const double ComputeEM::MIDDLE_START = 0.21072103131565256273; // -log(.9)*2 constexpr
724 const double ComputeEM::MIDDLE_END = 0.0020010006671670687271; // -log(.999)*2
725 const size_t ComputeEM::minHistLength = 40;
726
727 class ComputeStandardError : public omxCompute {
728         typedef omxCompute super;
729  public:
730         virtual void reportResults(FitContext *fc, MxRList *out);
731 };
732
733 class ComputeConditionNumber : public omxCompute {
734         typedef omxCompute super;
735  public:
736         virtual void reportResults(FitContext *fc, MxRList *out);
737 };
738
739 static class omxCompute *newComputeSequence()
740 { return new omxComputeSequence(); }
741
742 static class omxCompute *newComputeIterate()
743 { return new omxComputeIterate(); }
744
745 static class omxCompute *newComputeOnce()
746 { return new omxComputeOnce(); }
747
748 static class omxCompute *newComputeEM()
749 { return new ComputeEM(); }
750
751 static class omxCompute *newComputeStandardError()
752 { return new ComputeStandardError(); }
753
754 static class omxCompute *newComputeConditionNumber()
755 { return new ComputeConditionNumber(); }
756
757 struct omxComputeTableEntry {
758         char name[32];
759         omxCompute *(*ctor)();
760 };
761
762 static const struct omxComputeTableEntry omxComputeTable[] = {
763         {"MxComputeEstimatedHessian", &newComputeEstimatedHessian},
764         {"MxComputeGradientDescent", &newComputeGradientDescent},
765         {"MxComputeSequence", &newComputeSequence },
766         {"MxComputeIterate", &newComputeIterate },
767         {"MxComputeOnce", &newComputeOnce },
768         {"MxComputeNewtonRaphson", &newComputeNewtonRaphson},
769         {"MxComputeEM", &newComputeEM },
770         {"MxComputeStandardError", &newComputeStandardError},
771         {"MxComputeConditionNumber", &newComputeConditionNumber}
772 };
773
774 omxCompute *omxNewCompute(omxState* os, const char *type)
775 {
776         omxCompute *got = NULL;
777
778         for (size_t fx=0; fx < OMX_STATIC_ARRAY_SIZE(omxComputeTable); fx++) {
779                 const struct omxComputeTableEntry *entry = omxComputeTable + fx;
780                 if(strcmp(type, entry->name) == 0) {
781                         got = entry->ctor();
782                         break;
783                 }
784         }
785
786         if (!got) error("Compute %s is not implemented", type);
787
788         return got;
789 }
790
791 void omxComputeSequence::initFromFrontend(SEXP rObj)
792 {
793         super::initFromFrontend(rObj);
794
795         SEXP slotValue;
796         PROTECT(slotValue = GET_SLOT(rObj, install("steps")));
797
798         for (int cx = 0; cx < length(slotValue); cx++) {
799                 SEXP step = VECTOR_ELT(slotValue, cx);
800                 SEXP s4class;
801                 PROTECT(s4class = STRING_ELT(getAttrib(step, install("class")), 0));
802                 omxCompute *compute = omxNewCompute(globalState, CHAR(s4class));
803                 compute->initFromFrontend(step);
804                 if (isErrorRaised(globalState)) break;
805                 clist.push_back(compute);
806         }
807 }
808
809 void omxComputeSequence::compute(FitContext *fc)
810 {
811         for (size_t cx=0; cx < clist.size(); ++cx) {
812                 FitContext *context = fc;
813                 if (fc->varGroup != clist[cx]->varGroup) {
814                         context = new FitContext(fc, clist[cx]->varGroup);
815                 }
816                 clist[cx]->compute(context);
817                 if (context != fc) context->updateParentAndFree();
818                 if (isErrorRaised(globalState)) break;
819         }
820 }
821
822 void omxComputeSequence::reportResults(FitContext *fc, MxRList *out)
823 {
824         // put this stuff in a new list?
825         // merge with Iterate TODO
826         for (size_t cx=0; cx < clist.size(); ++cx) {
827                 FitContext *context = fc;
828                 if (fc->varGroup != clist[cx]->varGroup) {
829                         context = new FitContext(fc, clist[cx]->varGroup);
830                 }
831                 clist[cx]->reportResults(context, out);
832                 if (context != fc) context->updateParentAndFree();
833                 if (isErrorRaised(globalState)) break;
834         }
835 }
836
837 double omxComputeSequence::getOptimizerStatus()
838 {
839         // for backward compatibility, not indended to work generally
840         for (size_t cx=0; cx < clist.size(); ++cx) {
841                 double got = clist[cx]->getOptimizerStatus();
842                 if (got != NA_REAL) return got;
843         }
844         return NA_REAL;
845 }
846
847 omxComputeSequence::~omxComputeSequence()
848 {
849         for (size_t cx=0; cx < clist.size(); ++cx) {
850                 delete clist[cx];
851         }
852 }
853
854 void omxComputeIterate::initFromFrontend(SEXP rObj)
855 {
856         SEXP slotValue;
857
858         super::initFromFrontend(rObj);
859
860         PROTECT(slotValue = GET_SLOT(rObj, install("maxIter")));
861         maxIter = INTEGER(slotValue)[0];
862
863         PROTECT(slotValue = GET_SLOT(rObj, install("tolerance")));
864         tolerance = REAL(slotValue)[0];
865         if (tolerance <= 0) error("tolerance must be positive");
866
867         PROTECT(slotValue = GET_SLOT(rObj, install("steps")));
868
869         for (int cx = 0; cx < length(slotValue); cx++) {
870                 SEXP step = VECTOR_ELT(slotValue, cx);
871                 SEXP s4class;
872                 PROTECT(s4class = STRING_ELT(getAttrib(step, install("class")), 0));
873                 omxCompute *compute = omxNewCompute(globalState, CHAR(s4class));
874                 compute->initFromFrontend(step);
875                 if (isErrorRaised(globalState)) break;
876                 clist.push_back(compute);
877         }
878
879         PROTECT(slotValue = GET_SLOT(rObj, install("verbose")));
880         verbose = asInteger(slotValue);
881 }
882
883 void omxComputeIterate::compute(FitContext *fc)
884 {
885         int iter = 0;
886         double prevFit = 0;
887         double mac = tolerance * 10;
888         while (1) {
889                 for (size_t cx=0; cx < clist.size(); ++cx) {
890                         FitContext *context = fc;
891                         if (fc->varGroup != clist[cx]->varGroup) {
892                                 context = new FitContext(fc, clist[cx]->varGroup);
893                         }
894                         clist[cx]->compute(context);
895                         if (context != fc) context->updateParentAndFree();
896                         if (isErrorRaised(globalState)) break;
897                 }
898                 if (fc->wanted & FF_COMPUTE_MAXABSCHANGE) {
899                         if (fc->mac < 0) {
900                                 warning("MAC estimated at %.4f; something is wrong", fc->mac);
901                                 break;
902                         } else {
903                                 mac = fc->mac;
904                                 if (verbose) mxLog("ComputeIterate: mac %.9g", mac);
905                         }
906                 }
907                 if (fc->wanted & FF_COMPUTE_FIT) {
908                         if (fc->fit == 0) {
909                                 warning("Fit estimated at 0; something is wrong");
910                                 break;
911                         }
912                         if (prevFit != 0) {
913                                 double change = prevFit - fc->fit;
914                                 if (verbose) mxLog("ComputeIterate: fit %.9g change %.9g", fc->fit, change);
915                                 mac = fabs(change);
916                         } else {
917                                 if (verbose) mxLog("ComputeIterate: initial fit %.9g", fc->fit);
918                         }
919                         prevFit = fc->fit;
920                 }
921                 if (!(fc->wanted & (FF_COMPUTE_MAXABSCHANGE | FF_COMPUTE_FIT))) {
922                         omxRaiseErrorf(globalState, "ComputeIterate: neither MAC nor fit available");
923                 }
924                 if (isErrorRaised(globalState) || ++iter > maxIter || mac < tolerance) break;
925         }
926 }
927
928 void omxComputeIterate::reportResults(FitContext *fc, MxRList *out)
929 {
930         for (size_t cx=0; cx < clist.size(); ++cx) {
931                 FitContext *context = fc;
932                 if (fc->varGroup != clist[cx]->varGroup) {
933                         context = new FitContext(fc, clist[cx]->varGroup);
934                 }
935                 clist[cx]->reportResults(context, out);
936                 if (context != fc) context->updateParentAndFree();
937                 if (isErrorRaised(globalState)) break;
938         }
939 }
940
941 double omxComputeIterate::getOptimizerStatus()
942 {
943         // for backward compatibility, not indended to work generally
944         for (size_t cx=0; cx < clist.size(); ++cx) {
945                 double got = clist[cx]->getOptimizerStatus();
946                 if (got != NA_REAL) return got;
947         }
948         return NA_REAL;
949 }
950
951 omxComputeIterate::~omxComputeIterate()
952 {
953         for (size_t cx=0; cx < clist.size(); ++cx) {
954                 delete clist[cx];
955         }
956 }
957
958 void ComputeEM::initFromFrontend(SEXP rObj)
959 {
960         recentFC = NULL;
961
962         SEXP slotValue;
963         SEXP s4class;
964
965         super::initFromFrontend(rObj);
966
967         PROTECT(slotValue = GET_SLOT(rObj, install("maxIter")));
968         maxIter = INTEGER(slotValue)[0];
969
970         PROTECT(slotValue = GET_SLOT(rObj, install("information")));
971         information = asLogical(slotValue);
972
973         PROTECT(slotValue = GET_SLOT(rObj, install("ramsay")));
974         useRamsay = asLogical(slotValue);
975
976         PROTECT(slotValue = GET_SLOT(rObj, install("tolerance")));
977         tolerance = REAL(slotValue)[0];
978         if (tolerance <= 0) error("tolerance must be positive");
979
980         PROTECT(slotValue = GET_SLOT(rObj, install("what")));
981         for (int wx=0; wx < length(slotValue); ++wx) {
982                 int objNum = INTEGER(slotValue)[wx];
983                 omxExpectation *expectation = globalState->expectationList[objNum];
984                 setFreeVarGroup(expectation, varGroup);
985                 omxCompleteExpectation(expectation);
986                 expectations.push_back(expectation);
987         }
988
989         PROTECT(slotValue = GET_SLOT(rObj, install("mstep.fit")));
990         PROTECT(s4class = STRING_ELT(getAttrib(slotValue, install("class")), 0));
991         fit1 = omxNewCompute(globalState, CHAR(s4class));
992         fit1->initFromFrontend(slotValue);
993
994         PROTECT(slotValue = GET_SLOT(rObj, install("fit")));
995         PROTECT(s4class = STRING_ELT(getAttrib(slotValue, install("class")), 0));
996         fit2 = omxNewCompute(globalState, CHAR(s4class));
997         fit2->initFromFrontend(slotValue);
998
999         PROTECT(slotValue = GET_SLOT(rObj, install("verbose")));
1000         verbose = asInteger(slotValue);
1001
1002         semTolerance = sqrt(tolerance);  // override needed?
1003 }
1004
1005 void ComputeEM::setExpectationContext(const char *context)
1006 {
1007         for (size_t wx=0; wx < expectations.size(); ++wx) {
1008                 omxExpectation *expectation = expectations[wx];
1009                 if (verbose >= 4) mxLog("ComputeEM: expectation[%lu] %s context %s", wx, expectation->name, context);
1010                 omxExpectationCompute(expectation, context);
1011         }
1012 }
1013
1014 void ComputeEM::probeEM(FitContext *fc, int vx, size_t hx, double *rij)
1015 {
1016         const int freeVarsEM = (int) fit1->varGroup->vars.size();
1017         const size_t freeVars = fc->varGroup->vars.size();
1018         bool pseudoHist = paramHistLen[vx] <= int(hx);
1019         const int base = vx * freeVarsEM;
1020
1021         memcpy(fc->est, optimum.data(), sizeof(double) * freeVars);
1022         FitContext *emfc = new FitContext(fc, fit1->varGroup);
1023
1024         double popt = optimum[emfc->mapToParent[vx]];
1025         double starting;
1026         if (pseudoHist) {
1027                 size_t phx = hx - paramHistLen[vx];
1028                 double sign = phx%2? -1 : 1;
1029                 double smallest = 0;
1030                 double range = 0;
1031                 if (paramHistLen[vx] >= 2) {
1032                         smallest = fabs(estHistory[paramHistLen[vx]-1][vx] - popt);
1033                         range = 10 * (fabs(estHistory[0][vx] - popt) - smallest);
1034                 }
1035                 if (smallest < tolerance) smallest = tolerance;
1036                 if (range < 5 * semTolerance) range = 5 * semTolerance;
1037                 //mxLog("%d smallest %f range %f", vx, smallest, range);
1038                 starting = popt + sign * ((phx+1) * range / (histLen - paramHistLen[vx] + 1) + smallest);
1039         } else {
1040                 starting = estHistory[hx][vx];
1041         }
1042
1043         double denom = starting - popt;
1044         if (verbose >= 2) mxLog("ComputeEM: probing param %d from %shistory %ld/%ld offset %.6f",
1045                                 vx, pseudoHist? "pseudo-":"", hx, histLen, denom);
1046
1047         emfc->est[vx] = starting;
1048         emfc->copyParamToModel(globalState);
1049         fit1->compute(emfc);
1050
1051         for (int v1=0; v1 < freeVarsEM; ++v1) {
1052                 double got = (emfc->est[v1] - optimum[emfc->mapToParent[v1]]) / denom;
1053                 rij[base + v1] = got;
1054         }
1055         //pda(rij.data() + base, 1, freeVarsEM);
1056         delete emfc;
1057 }
1058
1059 bool ComputeEM::checkConvergence(omxBuffer<double> &rijWork, int h1, int h2,
1060                                  std::vector<bool> *semConverged, omxBuffer<double> *diffWork,
1061                                  omxBuffer<double> *rij)
1062 {
1063         size_t freeVarsEM = semConverged->size();
1064         double *rij1 = rijWork.data() + h1 * freeVarsEM * freeVarsEM;
1065         double *rij2 = rijWork.data() + h2 * freeVarsEM * freeVarsEM;
1066         size_t good = 0;
1067         for (size_t v1=0; v1 < freeVarsEM; ++v1) {
1068                 if ((*semConverged)[v1]) { ++good; continue; }
1069                 const int base = v1 * freeVarsEM;
1070                 bool match = true;
1071                 double diff = 0;
1072                 for (size_t v2=0; v2 < freeVarsEM; ++v2) {
1073                         double diff1 = fabs(rij1[base + v2] - rij2[base + v2]);
1074                         if (diff1 > semTolerance) match = false;
1075                         diff += diff1;
1076                 }
1077                 (*diffWork)[v1 * histLen + h1] = diff / freeVarsEM; // TODO normalization unnecessary
1078                 if (match) {
1079                         if (verbose >= 2) {
1080                                 pda(diffWork->data() + v1 * histLen, 1, h1);
1081                                 mxLog("ComputeEM: param %lu converged", v1);
1082                         }
1083                         (*semConverged)[v1] = true;
1084                         for (size_t v2=0; v2 < freeVarsEM; ++v2) {
1085                                 (*rij)[base + v2] = (rij1[base + v2] + rij2[base + v2]) / 2;
1086                         }
1087                         ++good;
1088                 }
1089         }
1090         return good == freeVarsEM;
1091 }
1092
1093 void ComputeEM::compute(FitContext *fc)
1094 {
1095         int totalMstepIter = 0;
1096         int iter = 0;
1097         double prevFit = 0;
1098         double mac = tolerance * 10;
1099         bool converged = false;
1100         const size_t freeVars = fc->varGroup->vars.size();
1101         const int freeVarsEM = (int) fit1->varGroup->vars.size();
1102         bool in_middle = false;
1103         histLen = 0;
1104
1105         OMXZERO(fc->flavor, freeVars);
1106
1107         FitContext *tmp = new FitContext(fc, fit1->varGroup);
1108         for (int vx=0; vx < freeVarsEM; ++vx) {
1109                 fc->flavor[tmp->mapToParent[vx]] = 1;
1110         }
1111         tmp->updateParentAndFree();
1112
1113         ramsay.push_back(new Ramsay1975(fc, int(ramsay.size()), 0, verbose, -1.25)); // other param
1114         ramsay.push_back(new Ramsay1975(fc, int(ramsay.size()), 0, verbose, -1));    // EM param
1115
1116         if (verbose >= 1) mxLog("ComputeEM: Welcome, tolerance=%g ramsay=%d info=%d flavors=%ld",
1117                                 tolerance, useRamsay, information, ramsay.size());
1118
1119         while (1) {
1120                 setExpectationContext("EM");
1121
1122                 if (recentFC) delete recentFC;
1123                 recentFC = new FitContext(fc, fit1->varGroup);
1124                 fit1->compute(recentFC);
1125                 if (recentFC->inform == INFORM_ITERATION_LIMIT) {
1126                         fc->inform = INFORM_ITERATION_LIMIT;
1127                         omxRaiseErrorf(globalState, "ComputeEM: iteration limited reached");
1128                         break;
1129                 }
1130                 mstepIter = recentFC->iterations;
1131                 recentFC->updateParent();
1132
1133                 setExpectationContext("");
1134
1135                 {
1136                         FitContext *context = fc;
1137                         if (fc->varGroup != fit2->varGroup) {
1138                                 context = new FitContext(fc, fit2->varGroup);
1139                         }
1140
1141                         // For IFA, PREOPTIMIZE updates latent distribution parameters
1142                         omxFitFunction *ff2 = fit2->getFitFunction();
1143                         if (ff2) omxFitFunctionCompute(ff2, FF_COMPUTE_PREOPTIMIZE, context);
1144
1145                         if (!useRamsay) {
1146                                 fc->maybeCopyParamToModel(globalState);
1147                         } else {
1148                                 context->updateParent();
1149
1150                                 bool wantRestart;
1151                                 if (iter > 3 && iter % 3 == 0) {
1152                                         for (size_t rx=0; rx < ramsay.size(); ++rx) {
1153                                                 ramsay[rx]->recalibrate(&wantRestart);
1154                                         }
1155                                 }
1156                                 for (size_t rx=0; rx < ramsay.size(); ++rx) {
1157                                         ramsay[rx]->apply();
1158                                 }
1159                                 fc->copyParamToModel(globalState);
1160                         }
1161
1162                         fit2->compute(context);
1163                         if (context != fc) context->updateParentAndFree();
1164                 }
1165
1166                 totalMstepIter += mstepIter;
1167
1168                 if (!(fc->wanted & FF_COMPUTE_FIT)) {
1169                         omxRaiseErrorf(globalState, "ComputeEM: fit not available");
1170                         break;
1171                 }
1172                 if (fc->fit == 0) {
1173                         omxRaiseErrorf(globalState, "Fit estimated at 0; something is wrong");
1174                         break;
1175                 }
1176                 double change = 0;
1177                 if (prevFit != 0) {
1178                         change = prevFit - fc->fit;
1179                         if (0 < change && change < MIDDLE_START) in_middle = true;
1180                         if (verbose >= 2) mxLog("ComputeEM[%d]: msteps %d fit %.9g change %.9g",
1181                                                 iter, mstepIter, fc->fit, change);
1182                         mac = fabs(change);
1183                 } else {
1184                         if (verbose >= 2) mxLog("ComputeEM: msteps %d initial fit %.9g",
1185                                                 mstepIter, fc->fit);
1186                 }
1187
1188                 if (in_middle && change > MIDDLE_END) estHistory.push_back(recentFC->take(FF_COMPUTE_ESTIMATE));
1189                 prevFit = fc->fit;
1190                 converged = mac < tolerance;
1191                 if (isErrorRaised(globalState) || ++iter > maxIter || converged) break;
1192         }
1193
1194         fc->wanted = FF_COMPUTE_FIT | FF_COMPUTE_ESTIMATE;
1195         bestFit = fc->fit;
1196         if (verbose >= 1) mxLog("ComputeEM: cycles %d/%d total mstep %d fit %f",
1197                                 iter, maxIter,totalMstepIter, bestFit);
1198
1199         if (!converged || !information) return;
1200
1201         if (verbose >= 1) mxLog("ComputeEM: semTolerance=%f", semTolerance);
1202
1203         // what about latent distribution parameters? TODO
1204
1205         recentFC->fixHessianSymmetry(FF_COMPUTE_IHESSIAN);
1206         double *ihess = recentFC->take(FF_COMPUTE_IHESSIAN);
1207
1208         optimum.resize(freeVars);
1209         memcpy(optimum.data(), fc->est, sizeof(double) * freeVars);
1210         paramHistLen.assign(freeVarsEM, 0);
1211
1212         for (int v1=0; v1 < freeVarsEM; ++v1) {
1213                 for (size_t hx = 0; hx < estHistory.size(); ++hx) {
1214                         if (fabs(optimum[v1] - estHistory[hx][v1]) < tolerance) break; // TODO good threshold?
1215                         if (hx > 0 && fabs(estHistory[hx-1][v1] - estHistory[hx][v1]) < tolerance) {
1216                                 // This parameter converged earlier than the others. We will
1217                                 // get a match if we compare the change at 2 offsets that are
1218                                 // too close together, but that doesn't tell us whether the
1219                                 // change estimate is accurate.
1220                                 if (hx == 1) paramHistLen[v1] = 0;
1221                                 break;
1222                         }
1223                         paramHistLen[v1] += 1;
1224                 }
1225         }
1226
1227         histLen = std::max(estHistory.size(), minHistLength);
1228         omxBuffer<double> rij(freeVarsEM * freeVarsEM);
1229         omxBuffer<double> rijWork(freeVarsEM * freeVarsEM * histLen);
1230         omxBuffer<double> diffWork(histLen * freeVarsEM);
1231         OMXZERO(diffWork.data(), histLen * freeVarsEM); // TODO remove
1232         std::vector<bool> semConverged(freeVarsEM);
1233         setExpectationContext("EM");
1234
1235         for (size_t cx = 0; cx < 2; ++cx) {
1236                 double *rij1 = rijWork.data() + cx * freeVarsEM * freeVarsEM;
1237                 for (int vx=0; vx < freeVarsEM && !isErrorRaised(globalState); ++vx) {
1238                         probeEM(fc, vx, cx, rij1);
1239                 }
1240         }
1241         if (!checkConvergence(rijWork, 0, 1, &semConverged, &diffWork, &rij)) {
1242                 for (size_t cx = 2; cx < histLen; ++cx) {
1243                         double *rij1 = rijWork.data() + cx * freeVarsEM * freeVarsEM;
1244                         for (int vx=0; vx < freeVarsEM && !isErrorRaised(globalState); ++vx) {
1245                                 if (semConverged[vx]) continue;
1246                                 probeEM(fc, vx, cx, rij1);
1247                         }
1248                         if (checkConvergence(rijWork, cx-1, cx, &semConverged, &diffWork, &rij)) break;
1249                 }
1250         }
1251         for (int v1=0; v1 < freeVarsEM; ++v1) {
1252                 if (semConverged[v1]) continue;
1253                 const int base = v1 * freeVarsEM;
1254
1255                 double minDiff = 1 * freeVarsEM;
1256                 int bestPair = -1;
1257                 for (size_t hx = 0; hx < histLen-1; ++hx) {
1258                         double trial = diffWork[v1 * histLen + hx];
1259                         if (minDiff > trial) {
1260                                 minDiff = trial;
1261                                 bestPair = hx;
1262                         }
1263                 }
1264                 if (verbose >= 2) {
1265                         pda(diffWork.data() + v1 * histLen, 1, histLen-1);
1266                         mxLog("ComputeEM: param %d failed to converge; min diff %f at %d/%d",
1267                               v1, minDiff, bestPair, bestPair+1);
1268                 }
1269
1270                 for (int v2=0; v2 < freeVarsEM; ++v2) {
1271                         double *rij1 = rijWork.data() + bestPair * freeVarsEM * freeVarsEM;
1272                         double *rij2 = rijWork.data() + (bestPair+1) * freeVarsEM * freeVarsEM;
1273                         rij[base + v2] = (rij1[base + v2] + rij2[base + v2]) / 2;
1274                 }
1275         }
1276
1277         memcpy(fc->est, optimum.data(), sizeof(double) * freeVars);
1278         fc->copyParamToModel(globalState);
1279
1280         //pda(rij.data(), freeVarsEM, freeVarsEM);
1281
1282         // rij = I-rij
1283         for (int v1=0; v1 < freeVarsEM; ++v1) {
1284                 for (int v2=0; v2 < freeVarsEM; ++v2) {
1285                         int cell = v1 * freeVarsEM + v2;
1286                         double entry = rij[cell];
1287                         if (v1 == v2) entry = 1 - entry;
1288                         else entry = -entry;
1289                         rij[cell] = entry;
1290                 }
1291         }
1292         // make symmetric
1293         for (int v1=1; v1 < freeVarsEM; ++v1) {
1294                 for (int v2=0; v2 < v1; ++v2) {
1295                         int c1 = v1 * freeVarsEM + v2;
1296                         int c2 = v2 * freeVarsEM + v1;
1297                         double mean = (rij[c1] + rij[c2])/2;
1298                         rij[c1] = mean;
1299                         rij[c2] = mean;
1300                 }
1301         }
1302
1303         //mxLog("symm");
1304         //pda(rij.data(), freeVarsEM, freeVarsEM);
1305
1306         //pda(ihess, freeVarsEM, freeVarsEM);
1307
1308         // ihess = ihess %*% rij^{-1}
1309         if (0) {
1310                 omxBuffer<int> ipiv(freeVarsEM);
1311                 int info;
1312                 F77_CALL(dgesv)(&freeVarsEM, &freeVarsEM, rij.data(), &freeVarsEM,
1313                                 ipiv.data(), ihess, &freeVarsEM, &info);
1314                 if (info < 0) error("dgesv %d", info);
1315                 if (info > 0) {
1316                         if (verbose >= 1) mxLog("ComputeEM: EM map is not positive definite %d", info);
1317                         return;
1318                 }
1319         } else {
1320                 char uplo = 'U';
1321                 omxBuffer<int> ipiv(freeVarsEM);
1322                 int info;
1323                 double worksize;
1324                 int lwork = -1;
1325                 F77_CALL(dsysv)(&uplo, &freeVarsEM, &freeVarsEM, rij.data(), &freeVarsEM,
1326                                 ipiv.data(), ihess, &freeVarsEM, &worksize, &lwork, &info);
1327                 lwork = worksize;
1328                 omxBuffer<double> work(lwork);
1329                 F77_CALL(dsysv)(&uplo, &freeVarsEM, &freeVarsEM, rij.data(), &freeVarsEM,
1330                                 ipiv.data(), ihess, &freeVarsEM, work.data(), &lwork, &info);
1331                 if (info < 0) error("dsysv %d", info);
1332                 if (info > 0) {
1333                         if (verbose >= 1) mxLog("ComputeEM: EM map is exactly singular %d", info);
1334                         return;
1335                 }
1336         }
1337
1338         for (int v1=0; v1 < freeVarsEM; ++v1) {
1339                 for (int v2=0; v2 <= v1; ++v2) {
1340                         fc->ihess[recentFC->mapToParent[v1] * freeVars + recentFC->mapToParent[v2]] =
1341                                 ihess[v1 * freeVarsEM + v2];
1342                 }
1343         }
1344
1345         fc->wanted |= FF_COMPUTE_IHESSIAN;
1346         //pda(ihess, freeVarsEM, freeVarsEM);
1347
1348         delete [] ihess;
1349 }
1350
1351 void ComputeEM::reportResults(FitContext *fc, MxRList *out)
1352 {
1353         out->push_back(std::make_pair(mkChar("minimum"), ScalarReal(bestFit)));
1354         out->push_back(std::make_pair(mkChar("Minus2LogLikelihood"), ScalarReal(bestFit)));
1355
1356         size_t numFree = fc->varGroup->vars.size();
1357         if (!numFree) return;
1358
1359         if (optimum.size() == numFree) { // move to glue TODO
1360                 SEXP Rvec;
1361                 PROTECT(Rvec = allocVector(REALSXP, numFree));
1362                 memcpy(REAL(Rvec), optimum.data(), sizeof(double)*numFree);
1363                 out->push_back(std::make_pair(mkChar("estimate"), Rvec));
1364         }
1365 }
1366
1367 double ComputeEM::getOptimizerStatus()
1368 {
1369         // for backward compatibility, not indended to work generally
1370         return NA_REAL;
1371 }
1372
1373 ComputeEM::~ComputeEM()
1374 {
1375         for (size_t rx=0; rx < ramsay.size(); ++rx) {
1376                 delete ramsay[rx];
1377         }
1378         ramsay.clear();
1379
1380         delete fit1;
1381         delete fit2;
1382
1383         for (size_t hx=0; hx < estHistory.size(); ++hx) {
1384                 delete [] estHistory[hx];
1385         }
1386         estHistory.clear();
1387         if (recentFC) delete recentFC;
1388 }
1389
1390 void omxComputeOnce::initFromFrontend(SEXP rObj)
1391 {
1392         super::initFromFrontend(rObj);
1393
1394         SEXP slotValue;
1395         PROTECT(slotValue = GET_SLOT(rObj, install("what")));
1396         for (int wx=0; wx < length(slotValue); ++wx) {
1397                 int objNum = INTEGER(slotValue)[wx];
1398                 if (objNum >= 0) {
1399                         omxMatrix *algebra = globalState->algebraList[objNum];
1400                         if (algebra->fitFunction) {
1401                                 setFreeVarGroup(algebra->fitFunction, varGroup);
1402                                 omxCompleteFitFunction(algebra);
1403                         }
1404                         algebras.push_back(algebra);
1405                 } else {
1406                         omxExpectation *expectation = globalState->expectationList[~objNum];
1407                         setFreeVarGroup(expectation, varGroup);
1408                         omxCompleteExpectation(expectation);
1409                         expectations.push_back(expectation);
1410                 }
1411         }
1412
1413         PROTECT(slotValue = GET_SLOT(rObj, install("verbose")));
1414         verbose = asInteger(slotValue);
1415
1416         context = "";
1417
1418         PROTECT(slotValue = GET_SLOT(rObj, install("context")));
1419         if (length(slotValue) == 0) {
1420                 // OK
1421         } else if (length(slotValue) == 1) {
1422                 SEXP elem;
1423                 PROTECT(elem = STRING_ELT(slotValue, 0));
1424                 context = CHAR(elem);
1425         }
1426
1427         PROTECT(slotValue = GET_SLOT(rObj, install("maxAbsChange")));
1428         mac = asLogical(slotValue);
1429
1430         PROTECT(slotValue = GET_SLOT(rObj, install("fit")));
1431         fit = asLogical(slotValue);
1432
1433         PROTECT(slotValue = GET_SLOT(rObj, install("gradient")));
1434         gradient = asLogical(slotValue);
1435
1436         PROTECT(slotValue = GET_SLOT(rObj, install("hessian")));
1437         hessian = asLogical(slotValue);
1438
1439         PROTECT(slotValue = GET_SLOT(rObj, install("information")));
1440         infoMat = asLogical(slotValue);
1441
1442         if (hessian && infoMat) error("Cannot compute the Hessian and Fisher Information matrix simultaneously");
1443
1444         if (infoMat) {
1445                 const char *iMethod = "";
1446                 PROTECT(slotValue = GET_SLOT(rObj, install("info.method")));
1447                 if (length(slotValue) == 0) {
1448                         // OK
1449                 } else if (length(slotValue) == 1) {
1450                         SEXP elem;
1451                         PROTECT(elem = STRING_ELT(slotValue, 0));
1452                         iMethod = CHAR(elem);
1453                 }
1454
1455                 if (strcmp(iMethod, "sandwich")==0) {
1456                         infoMethod = INFO_METHOD_SANDWICH;
1457                 } else if (strcmp(iMethod, "meat")==0) {
1458                         infoMethod = INFO_METHOD_MEAT;
1459                 } else if (strcmp(iMethod, "bread")==0) {
1460                         infoMethod = INFO_METHOD_BREAD;
1461                 } else {
1462                         error("Unknown information matrix estimation method '%s'", iMethod);
1463                 }
1464         }
1465
1466         PROTECT(slotValue = GET_SLOT(rObj, install("ihessian")));
1467         ihessian = asLogical(slotValue);
1468
1469         PROTECT(slotValue = GET_SLOT(rObj, install("hgprod")));
1470         hgprod = asLogical(slotValue);
1471
1472         if (algebras.size() == 1 && algebras[0]->fitFunction) {
1473                 omxFitFunction *ff = algebras[0]->fitFunction;
1474                 if (gradient && !ff->gradientAvailable) {
1475                         error("Gradient requested but not available");
1476                 }
1477                 if ((hessian || ihessian || hgprod) && !ff->hessianAvailable) {
1478                         // add a separate flag for hgprod TODO
1479                         error("Hessian requested but not available");
1480                 }
1481                 // add check for information TODO
1482         }
1483 }
1484
1485 omxFitFunction *omxComputeOnce::getFitFunction()
1486 {
1487         if (algebras.size() == 1 && algebras[0]->fitFunction) {
1488                 return algebras[0]->fitFunction;
1489         } else {
1490                 return NULL;
1491         }
1492 }
1493
1494 void omxComputeOnce::compute(FitContext *fc)
1495 {
1496         if (algebras.size()) {
1497                 int want = 0;
1498                 size_t numParam = fc->varGroup->vars.size();
1499                 if (mac) {
1500                         want |= FF_COMPUTE_MAXABSCHANGE;
1501                         fc->mac = 0;
1502                 }
1503                 if (fit) {
1504                         want |= FF_COMPUTE_FIT;
1505                         fc->fit = 0;
1506                 }
1507                 if (gradient) {
1508                         want |= FF_COMPUTE_GRADIENT;
1509                         OMXZERO(fc->grad, numParam);
1510                 }
1511                 if (hessian) {
1512                         want |= FF_COMPUTE_HESSIAN;
1513                         OMXZERO(fc->hess, numParam * numParam);
1514                 }
1515                 if (infoMat) {
1516                         want |= FF_COMPUTE_INFO;
1517                         fc->infoMethod = infoMethod;
1518                         fc->preInfo();
1519                 }
1520                 if (ihessian) {
1521                         want |= FF_COMPUTE_IHESSIAN;
1522                         OMXZERO(fc->ihess, numParam * numParam);
1523                 }
1524                 if (hgprod) {
1525                         want |= FF_COMPUTE_HGPROD;
1526                         fc->hgProd.resize(0);
1527                 }
1528                 if (!want) return;
1529
1530                 for (size_t wx=0; wx < algebras.size(); ++wx) {
1531                         omxMatrix *algebra = algebras[wx];
1532                         if (algebra->fitFunction) {
1533                                 if (verbose) mxLog("ComputeOnce: fit %p want %d",
1534                                                    algebra->fitFunction, want);
1535
1536                                 omxFitFunctionCompute(algebra->fitFunction, FF_COMPUTE_PREOPTIMIZE, fc);
1537                                 fc->maybeCopyParamToModel(globalState);
1538
1539                                 omxFitFunctionCompute(algebra->fitFunction, want, fc);
1540                                 fc->fit = algebra->data[0];
1541                                 if (infoMat) {
1542                                         fc->postInfo();
1543                                 }
1544                                 fc->fixHessianSymmetry(want);
1545                         } else {
1546                                 if (verbose) mxLog("ComputeOnce: algebra %p", algebra);
1547                                 omxForceCompute(algebra);
1548                         }
1549                 }
1550         } else if (expectations.size()) {
1551                 for (size_t wx=0; wx < expectations.size(); ++wx) {
1552                         omxExpectation *expectation = expectations[wx];
1553                         if (verbose) mxLog("ComputeOnce: expectation[%lu] %p context %s", wx, expectation, context);
1554                         omxExpectationCompute(expectation, context);
1555                 }
1556         }
1557 }
1558
1559 void omxComputeOnce::reportResults(FitContext *fc, MxRList *out)
1560 {
1561         if (algebras.size()==0 || algebras[0]->fitFunction == NULL) return;
1562
1563         omxMatrix *algebra = algebras[0];
1564
1565         omxPopulateFitFunction(algebra, out);
1566
1567         out->push_back(std::make_pair(mkChar("minimum"), ScalarReal(fc->fit)));
1568         out->push_back(std::make_pair(mkChar("Minus2LogLikelihood"), ScalarReal(fc->fit)));
1569
1570         size_t numFree = fc->varGroup->vars.size();
1571         if (numFree) {
1572                 SEXP estimate;
1573                 PROTECT(estimate = allocVector(REALSXP, numFree));
1574                 memcpy(REAL(estimate), fc->est, sizeof(double)*numFree);
1575                 out->push_back(std::make_pair(mkChar("estimate"), estimate));
1576
1577                 if (gradient) {
1578                         SEXP Rgradient;
1579                         PROTECT(Rgradient = allocVector(REALSXP, numFree));
1580                         memcpy(REAL(Rgradient), fc->grad, sizeof(double) * numFree);
1581                         out->push_back(std::make_pair(mkChar("gradient"), Rgradient));
1582                 }
1583
1584                 if (hessian || infoMat) {
1585                         SEXP Rhessian;
1586                         PROTECT(Rhessian = allocMatrix(REALSXP, numFree, numFree));
1587                         memcpy(REAL(Rhessian), fc->hess, sizeof(double) * numFree * numFree);
1588                         out->push_back(std::make_pair(mkChar("hessian"), Rhessian));
1589                 }
1590
1591                 if (ihessian) {
1592                         SEXP Rihessian;
1593                         PROTECT(Rihessian = allocMatrix(REALSXP, numFree, numFree));
1594                         memcpy(REAL(Rihessian), fc->ihess, sizeof(double) * numFree * numFree);
1595                         out->push_back(std::make_pair(mkChar("ihessian"), Rihessian));
1596                 }
1597
1598                 if (hgprod) {
1599                         // TODO
1600                 }
1601         }
1602 }
1603
1604 void ComputeStandardError::reportResults(FitContext *fc, MxRList *out)
1605 {
1606         if (isErrorRaised(globalState)) return;
1607
1608         int numParams = int(fc->varGroup->vars.size());
1609
1610         if (!(fc->wanted & (FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN))) {
1611                 return;
1612         }
1613
1614         if (!(fc->wanted & FF_COMPUTE_IHESSIAN)) {
1615                 // Populate upper triangle
1616                 for(int i = 0; i < numParams; i++) {
1617                         for(int j = 0; j <= i; j++) {
1618                                 fc->ihess[i*numParams+j] = fc->hess[i*numParams+j];
1619                         }
1620                 }
1621
1622                 Matrix wmat(fc->ihess, numParams, numParams);
1623                 InvertSymmetricIndef(wmat, 'U');
1624                 fc->fixHessianSymmetry(FF_COMPUTE_IHESSIAN, true);
1625                 fc->wanted |= FF_COMPUTE_IHESSIAN;
1626         }
1627
1628         // This function calculates the standard errors from the Hessian matrix
1629         // sqrt(diag(solve(hessian)))
1630
1631         // We report the fit in -2LL units instead of -LL so we need to adjust here.
1632         const double scale = sqrt(2); // constexpr
1633
1634         fc->allocStderrs();
1635         for(int i = 0; i < numParams; i++) {
1636                 double got = fc->ihess[i * numParams + i];
1637                 if (got <= 0) continue;
1638                 fc->stderrs[i] = scale * sqrt(got);
1639         }
1640 }
1641
1642 void ComputeConditionNumber::reportResults(FitContext *fc, MxRList *out)
1643 {
1644         if (isErrorRaised(globalState)) return;
1645
1646         int numParams = int(fc->varGroup->vars.size());
1647
1648         if (!(fc->wanted & (FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN))) {
1649                 out->push_back(std::make_pair(mkChar("conditionNumber"), ScalarReal(NA_REAL)));
1650                 return;
1651         }
1652
1653         if (!(fc->wanted & FF_COMPUTE_HESSIAN)) {
1654                 // Populate upper triangle
1655                 for(int i = 0; i < numParams; i++) {
1656                         for(int j = 0; j <= i; j++) {
1657                                 fc->hess[i*numParams+j] = fc->ihess[i*numParams+j];
1658                         }
1659                 }
1660
1661                 Matrix wmat(fc->hess, numParams, numParams);
1662                 InvertSymmetricIndef(wmat, 'U');
1663                 fc->fixHessianSymmetry(FF_COMPUTE_HESSIAN, true);
1664                 fc->wanted |= FF_COMPUTE_HESSIAN;
1665         }
1666
1667         omxBuffer<double> hessWork(numParams * numParams);
1668         memcpy(hessWork.data(), fc->hess, sizeof(double) * numParams * numParams);
1669
1670         char jobz = 'N';
1671         char range = 'A';
1672         char uplo = 'U';
1673         double abstol = 0;
1674         int m;
1675         omxBuffer<double> w(numParams);
1676         double optWork;
1677         int lwork = -1;
1678         omxBuffer<int> iwork(5 * numParams);
1679         int info;
1680         double realIgn = 0;
1681         int intIgn = 0;
1682         F77_CALL(dsyevx)(&jobz, &range, &uplo, &numParams, hessWork.data(),
1683                          &numParams, &realIgn, &realIgn, &intIgn, &intIgn, &abstol, &m, w.data(),
1684                          NULL, &numParams, &optWork, &lwork, iwork.data(), NULL, &info);
1685
1686         lwork = optWork;
1687         omxBuffer<double> work(lwork);
1688         F77_CALL(dsyevx)(&jobz, &range, &uplo, &numParams, hessWork.data(),
1689                          &numParams, &realIgn, &realIgn, &intIgn, &intIgn, &abstol, &m, w.data(),
1690                          NULL, &numParams, work.data(), &lwork, iwork.data(), NULL, &info);
1691         if (info != 0) error("dsyevx %d", info);
1692
1693         double got = w[numParams-1] / w[0];
1694         if (isfinite(got)) fc->hessCondNum = got;
1695 }