Report Hessian consistently
[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[FREEVARGROUP_ALL];
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 void omxCompute::collectResultsHelper(FitContext *fc, std::vector< omxCompute* > &clist,
610                                       LocalComputeResult *lcr, MxRList *out)
611 {
612         for (std::vector< omxCompute* >::iterator it = clist.begin(); it != clist.end(); ++it) {
613                 omxCompute *c1 = *it;
614                 FitContext *context = fc;
615                 if (fc->varGroup != c1->varGroup) {
616                         context = new FitContext(fc, c1->varGroup);
617                 }
618                 c1->collectResults(context, lcr, out);
619                 if (context != fc) context->updateParentAndFree();
620         }
621 }
622
623 void omxCompute::collectResults(FitContext *fc, LocalComputeResult *lcr, MxRList *out)
624 {
625         MxRList *slots = new MxRList();
626         reportResults(fc, slots, out);
627         if (slots->size()) {
628                 lcr->push_back(std::make_pair(computeId, slots));
629         } else {
630                 delete slots;
631         }
632 }
633
634 omxCompute::~omxCompute()
635 {}
636
637 void omxCompute::initFromFrontend(SEXP rObj)
638 {
639         SEXP slotValue;
640         PROTECT(slotValue = GET_SLOT(rObj, install("id")));
641         if (length(slotValue) == 1) {
642                 computeId = INTEGER(slotValue)[0];
643                 varGroup = Global->findVarGroup(computeId);
644         }
645
646         if (!varGroup) {
647                 if (!R_has_slot(rObj, install("free.set"))) {
648                         varGroup = Global->freeGroup[FREEVARGROUP_ALL];
649                 } else {
650                         PROTECT(slotValue = GET_SLOT(rObj, install("free.set")));
651                         if (length(slotValue) != 0) {
652                                 // it's a free.set with no free variables
653                                 varGroup = Global->findVarGroup(FREEVARGROUP_NONE);
654                         } else {
655                                 varGroup = Global->freeGroup[FREEVARGROUP_ALL];
656                         }
657                 }
658         }
659 }
660
661 class ComputeContainer : public omxCompute {
662         typedef omxCompute super;
663 protected:
664         std::vector< omxCompute* > clist;
665 public:
666         virtual void collectResults(FitContext *fc, LocalComputeResult *lcr, MxRList *out);
667         virtual double getOptimizerStatus();
668 };
669
670 void ComputeContainer::collectResults(FitContext *fc, LocalComputeResult *lcr, MxRList *out)
671 {
672         super::collectResults(fc, lcr, out);
673         collectResultsHelper(fc, clist, lcr, out);
674 }
675
676 double ComputeContainer::getOptimizerStatus()
677 {
678         // for backward compatibility, not indended to work generally
679         for (size_t cx=0; cx < clist.size(); ++cx) {
680                 double got = clist[cx]->getOptimizerStatus();
681                 if (got != NA_REAL) return got;
682         }
683         return NA_REAL;
684 }
685
686 class omxComputeSequence : public ComputeContainer {
687         typedef ComputeContainer super;
688
689  public:
690         virtual void initFromFrontend(SEXP rObj);
691         virtual void compute(FitContext *fc);
692         virtual ~omxComputeSequence();
693 };
694
695 class omxComputeIterate : public ComputeContainer {
696         typedef ComputeContainer super;
697         int maxIter;
698         double tolerance;
699         int verbose;
700
701  public:
702         virtual void initFromFrontend(SEXP rObj);
703         virtual void compute(FitContext *fc);
704         virtual ~omxComputeIterate();
705 };
706
707 class omxComputeOnce : public omxCompute {
708         typedef omxCompute super;
709         std::vector< omxMatrix* > algebras;
710         std::vector< omxExpectation* > expectations;
711         int verbose;
712         const char *context;
713         bool mac;
714         bool fit;
715         bool gradient;
716         bool hessian;
717         bool ihessian;
718         bool infoMat;
719         enum ComputeInfoMethod infoMethod;
720         bool hgprod;
721
722  public:
723         virtual void initFromFrontend(SEXP rObj);
724         virtual omxFitFunction *getFitFunction();
725         virtual void compute(FitContext *fc);
726         virtual void reportResults(FitContext *fc, MxRList *slots, MxRList *out);
727 };
728
729 class ComputeEM : public omxCompute {
730         typedef omxCompute super;
731         std::vector< omxExpectation* > expectations;
732         omxCompute *fit1;
733         omxCompute *fit2;
734         int maxIter;
735         int mstepIter;
736         int totalMstepIter;
737         double tolerance;
738         double semTolerance;
739         int verbose;
740         bool useRamsay;
741         bool information;
742         double *semMethod;
743         int semMethodLen;
744         bool semDebug;
745         std::vector<Ramsay1975*> ramsay;
746         double noiseTarget;
747         double noiseTolerance;
748         std::vector<double*> estHistory;
749         std::vector<double> probeOffset;
750         std::vector<double> diffWork;
751         std::vector<int> paramHistLen;
752         FitContext *recentFC;  //nice if can use std::unique_ptr
753         std::vector<double> optimum;
754         double bestFit;
755         static const double MIDDLE_START;
756         static const double MIDDLE_END;
757         size_t maxHistLen;
758         int semProbeCount;
759
760         void setExpectationContext(const char *context);
761         void probeEM(FitContext *fc, int vx, double offset, std::vector<double> *rijWork);
762         void recordDiff(int v1, std::vector<double> &rijWork, double *stdDiff, bool *mengOK);
763
764  public:
765         virtual void initFromFrontend(SEXP rObj);
766         virtual void compute(FitContext *fc);
767         virtual void collectResults(FitContext *fc, LocalComputeResult *lcr, MxRList *out);
768         virtual void reportResults(FitContext *fc, MxRList *slots, MxRList *out);
769         virtual double getOptimizerStatus();
770         virtual ~ComputeEM();
771 };
772
773 const double ComputeEM::MIDDLE_START = 0.21072103131565256273; // -log(.9)*2 constexpr
774 const double ComputeEM::MIDDLE_END = 0.0020010006671670687271; // -log(.999)*2
775
776 class ComputeStandardError : public omxCompute {
777         typedef omxCompute super;
778  public:
779         virtual void reportResults(FitContext *fc, MxRList *slots, MxRList *out);
780 };
781
782 class ComputeConditionNumber : public omxCompute {
783         typedef omxCompute super;
784  public:
785         virtual void reportResults(FitContext *fc, MxRList *slots, MxRList *out);
786 };
787
788 static class omxCompute *newComputeSequence()
789 { return new omxComputeSequence(); }
790
791 static class omxCompute *newComputeIterate()
792 { return new omxComputeIterate(); }
793
794 static class omxCompute *newComputeOnce()
795 { return new omxComputeOnce(); }
796
797 static class omxCompute *newComputeEM()
798 { return new ComputeEM(); }
799
800 static class omxCompute *newComputeStandardError()
801 { return new ComputeStandardError(); }
802
803 static class omxCompute *newComputeConditionNumber()
804 { return new ComputeConditionNumber(); }
805
806 struct omxComputeTableEntry {
807         char name[32];
808         omxCompute *(*ctor)();
809 };
810
811 static const struct omxComputeTableEntry omxComputeTable[] = {
812         {"MxComputeEstimatedHessian", &newComputeEstimatedHessian},
813         {"MxComputeGradientDescent", &newComputeGradientDescent},
814         {"MxComputeSequence", &newComputeSequence },
815         {"MxComputeIterate", &newComputeIterate },
816         {"MxComputeOnce", &newComputeOnce },
817         {"MxComputeNewtonRaphson", &newComputeNewtonRaphson},
818         {"MxComputeEM", &newComputeEM },
819         {"MxComputeStandardError", &newComputeStandardError},
820         {"MxComputeConditionNumber", &newComputeConditionNumber}
821 };
822
823 omxCompute *omxNewCompute(omxState* os, const char *type)
824 {
825         omxCompute *got = NULL;
826
827         for (size_t fx=0; fx < OMX_STATIC_ARRAY_SIZE(omxComputeTable); fx++) {
828                 const struct omxComputeTableEntry *entry = omxComputeTable + fx;
829                 if(strcmp(type, entry->name) == 0) {
830                         got = entry->ctor();
831                         break;
832                 }
833         }
834
835         if (!got) error("Compute %s is not implemented", type);
836
837         return got;
838 }
839
840 void omxComputeSequence::initFromFrontend(SEXP rObj)
841 {
842         super::initFromFrontend(rObj);
843
844         SEXP slotValue;
845         PROTECT(slotValue = GET_SLOT(rObj, install("steps")));
846
847         for (int cx = 0; cx < length(slotValue); cx++) {
848                 SEXP step = VECTOR_ELT(slotValue, cx);
849                 SEXP s4class;
850                 PROTECT(s4class = STRING_ELT(getAttrib(step, install("class")), 0));
851                 omxCompute *compute = omxNewCompute(globalState, CHAR(s4class));
852                 compute->initFromFrontend(step);
853                 if (isErrorRaised(globalState)) break;
854                 clist.push_back(compute);
855         }
856 }
857
858 void omxComputeSequence::compute(FitContext *fc)
859 {
860         for (size_t cx=0; cx < clist.size(); ++cx) {
861                 FitContext *context = fc;
862                 if (fc->varGroup != clist[cx]->varGroup) {
863                         context = new FitContext(fc, clist[cx]->varGroup);
864                 }
865                 clist[cx]->compute(context);
866                 if (context != fc) context->updateParentAndFree();
867                 if (isErrorRaised(globalState)) break;
868         }
869 }
870
871 omxComputeSequence::~omxComputeSequence()
872 {
873         for (size_t cx=0; cx < clist.size(); ++cx) {
874                 delete clist[cx];
875         }
876 }
877
878 void omxComputeIterate::initFromFrontend(SEXP rObj)
879 {
880         SEXP slotValue;
881
882         super::initFromFrontend(rObj);
883
884         PROTECT(slotValue = GET_SLOT(rObj, install("maxIter")));
885         maxIter = INTEGER(slotValue)[0];
886
887         PROTECT(slotValue = GET_SLOT(rObj, install("tolerance")));
888         tolerance = REAL(slotValue)[0];
889         if (tolerance <= 0) error("tolerance must be positive");
890
891         PROTECT(slotValue = GET_SLOT(rObj, install("steps")));
892
893         for (int cx = 0; cx < length(slotValue); cx++) {
894                 SEXP step = VECTOR_ELT(slotValue, cx);
895                 SEXP s4class;
896                 PROTECT(s4class = STRING_ELT(getAttrib(step, install("class")), 0));
897                 omxCompute *compute = omxNewCompute(globalState, CHAR(s4class));
898                 compute->initFromFrontend(step);
899                 if (isErrorRaised(globalState)) break;
900                 clist.push_back(compute);
901         }
902
903         PROTECT(slotValue = GET_SLOT(rObj, install("verbose")));
904         verbose = asInteger(slotValue);
905 }
906
907 void omxComputeIterate::compute(FitContext *fc)
908 {
909         int iter = 0;
910         double prevFit = 0;
911         double mac = tolerance * 10;
912         while (1) {
913                 for (size_t cx=0; cx < clist.size(); ++cx) {
914                         FitContext *context = fc;
915                         if (fc->varGroup != clist[cx]->varGroup) {
916                                 context = new FitContext(fc, clist[cx]->varGroup);
917                         }
918                         clist[cx]->compute(context);
919                         if (context != fc) context->updateParentAndFree();
920                         if (isErrorRaised(globalState)) break;
921                 }
922                 if (fc->wanted & FF_COMPUTE_MAXABSCHANGE) {
923                         if (fc->mac < 0) {
924                                 warning("MAC estimated at %.4f; something is wrong", fc->mac);
925                                 break;
926                         } else {
927                                 mac = fc->mac;
928                                 if (verbose) mxLog("ComputeIterate: mac %.9g", mac);
929                         }
930                 }
931                 if (fc->wanted & FF_COMPUTE_FIT) {
932                         if (fc->fit == 0) {
933                                 warning("Fit estimated at 0; something is wrong");
934                                 break;
935                         }
936                         if (prevFit != 0) {
937                                 double change = prevFit - fc->fit;
938                                 if (verbose) mxLog("ComputeIterate: fit %.9g change %.9g", fc->fit, change);
939                                 mac = fabs(change);
940                         } else {
941                                 if (verbose) mxLog("ComputeIterate: initial fit %.9g", fc->fit);
942                         }
943                         prevFit = fc->fit;
944                 }
945                 if (!(fc->wanted & (FF_COMPUTE_MAXABSCHANGE | FF_COMPUTE_FIT))) {
946                         omxRaiseErrorf(globalState, "ComputeIterate: neither MAC nor fit available");
947                 }
948                 if (isErrorRaised(globalState) || ++iter > maxIter || mac < tolerance) break;
949         }
950 }
951
952 omxComputeIterate::~omxComputeIterate()
953 {
954         for (size_t cx=0; cx < clist.size(); ++cx) {
955                 delete clist[cx];
956         }
957 }
958
959 void ComputeEM::initFromFrontend(SEXP rObj)
960 {
961         recentFC = NULL;
962
963         SEXP slotValue;
964         SEXP s4class;
965
966         super::initFromFrontend(rObj);
967
968         PROTECT(slotValue = GET_SLOT(rObj, install("maxIter")));
969         maxIter = INTEGER(slotValue)[0];
970
971         PROTECT(slotValue = GET_SLOT(rObj, install("information")));
972         information = asLogical(slotValue);
973
974         PROTECT(slotValue = GET_SLOT(rObj, install("semMethod")));
975         semMethod = REAL(slotValue);
976         semMethodLen = length(slotValue);
977
978         PROTECT(slotValue = GET_SLOT(rObj, install("semDebug")));
979         semDebug = asLogical(slotValue);
980
981         PROTECT(slotValue = GET_SLOT(rObj, install("ramsay")));
982         useRamsay = asLogical(slotValue);
983
984         PROTECT(slotValue = GET_SLOT(rObj, install("tolerance")));
985         tolerance = REAL(slotValue)[0];
986         if (tolerance <= 0) error("tolerance must be positive");
987
988         PROTECT(slotValue = GET_SLOT(rObj, install("noiseTarget")));
989         noiseTarget = REAL(slotValue)[0];
990         if (noiseTarget <= 0) error("noiseTarget must be positive");
991
992         PROTECT(slotValue = GET_SLOT(rObj, install("noiseTolerance")));
993         noiseTolerance = REAL(slotValue)[0];
994         if (noiseTolerance <= 0) error("noiseTolerance must be positive");
995
996         PROTECT(slotValue = GET_SLOT(rObj, install("what")));
997         for (int wx=0; wx < length(slotValue); ++wx) {
998                 int objNum = INTEGER(slotValue)[wx];
999                 omxExpectation *expectation = globalState->expectationList[objNum];
1000                 setFreeVarGroup(expectation, varGroup);
1001                 omxCompleteExpectation(expectation);
1002                 expectations.push_back(expectation);
1003         }
1004
1005         PROTECT(slotValue = GET_SLOT(rObj, install("mstep.fit")));
1006         PROTECT(s4class = STRING_ELT(getAttrib(slotValue, install("class")), 0));
1007         fit1 = omxNewCompute(globalState, CHAR(s4class));
1008         fit1->initFromFrontend(slotValue);
1009
1010         PROTECT(slotValue = GET_SLOT(rObj, install("fit")));
1011         PROTECT(s4class = STRING_ELT(getAttrib(slotValue, install("class")), 0));
1012         fit2 = omxNewCompute(globalState, CHAR(s4class));
1013         fit2->initFromFrontend(slotValue);
1014
1015         PROTECT(slotValue = GET_SLOT(rObj, install("verbose")));
1016         verbose = asInteger(slotValue);
1017
1018         semTolerance = sqrt(tolerance);  // override needed?
1019 }
1020
1021 void ComputeEM::setExpectationContext(const char *context)
1022 {
1023         for (size_t wx=0; wx < expectations.size(); ++wx) {
1024                 omxExpectation *expectation = expectations[wx];
1025                 if (verbose >= 4) mxLog("ComputeEM: expectation[%lu] %s context %s", wx, expectation->name, context);
1026                 omxExpectationCompute(expectation, context);
1027         }
1028 }
1029
1030 void ComputeEM::probeEM(FitContext *fc, int vx, double offset, std::vector<double> *rijWork)
1031 {
1032         const int freeVarsEM = (int) fit1->varGroup->vars.size();
1033         const size_t freeVars = fc->varGroup->vars.size();
1034         const int base = paramHistLen[vx] * freeVarsEM;
1035         probeOffset[vx * maxHistLen + paramHistLen[vx]] = offset;
1036         paramHistLen[vx] += 1;
1037         memcpy(fc->est, optimum.data(), sizeof(double) * freeVars);
1038         FitContext *emfc = new FitContext(fc, fit1->varGroup);
1039
1040         double popt = optimum[emfc->mapToParent[vx]];
1041         double starting = popt + offset;
1042
1043         if (verbose >= 3) mxLog("ComputeEM: probe %d of param %d offset %.6f",
1044                                 paramHistLen[vx], vx, offset);
1045
1046         emfc->est[vx] = starting;
1047         emfc->copyParamToModel(globalState);
1048         fit1->compute(emfc);
1049
1050         for (int v1=0; v1 < freeVarsEM; ++v1) {
1051                 double got = (emfc->est[v1] - optimum[emfc->mapToParent[v1]]) / offset;
1052                 (*rijWork)[base + v1] = got;
1053         }
1054         //pda(rij.data() + base, 1, freeVarsEM);
1055         delete emfc;
1056         ++semProbeCount;
1057 }
1058
1059 void ComputeEM::recordDiff(int v1, std::vector<double> &rijWork,
1060                            double *stdDiff, bool *mengOK)
1061 {
1062         const int freeVarsEM = (int) fit1->varGroup->vars.size();
1063         int h1 = paramHistLen[v1]-2;
1064         int h2 = paramHistLen[v1]-1;
1065         double *rij1 = rijWork.data() + h1 * freeVarsEM;
1066         double *rij2 = rijWork.data() + h2 * freeVarsEM;
1067         double diff = 0;
1068         *mengOK = true;
1069         for (int v2=0; v2 < freeVarsEM; ++v2) {
1070                 double diff1 = fabs(rij1[v2] - rij2[v2]);
1071                 if (diff1 >= semTolerance) *mengOK = false;
1072                 diff += diff1;
1073         }
1074         double p1 = probeOffset[v1 * maxHistLen + h1];
1075         double p2 = probeOffset[v1 * maxHistLen + h2];
1076         double dist = fabs(p1 - p2);
1077         if (dist < tolerance/4) error("SEM: invalid probe offset distance %.9f", dist);
1078         *stdDiff = diff / (freeVarsEM * dist);
1079         diffWork[v1 * maxHistLen + h1] = *stdDiff;
1080         if (verbose >= 2) mxLog("ComputeEM: (%f,%f) width %f mengOK %d diff %f stdDiff %f",
1081                                 p1, p2, dist, *mengOK, diff, *stdDiff);
1082 }
1083
1084 void ComputeEM::compute(FitContext *fc)
1085 {
1086         int totalMstepIter = 0;
1087         int iter = 0;
1088         double prevFit = 0;
1089         double mac = tolerance * 10;
1090         bool converged = false;
1091         const size_t freeVars = fc->varGroup->vars.size();
1092         const int freeVarsEM = (int) fit1->varGroup->vars.size();
1093         bool in_middle = false;
1094         maxHistLen = 0;
1095         semProbeCount = 0;
1096
1097         OMXZERO(fc->flavor, freeVars);
1098
1099         FitContext *tmp = new FitContext(fc, fit1->varGroup);
1100         for (int vx=0; vx < freeVarsEM; ++vx) {
1101                 fc->flavor[tmp->mapToParent[vx]] = 1;
1102         }
1103         tmp->updateParentAndFree();
1104
1105         ramsay.push_back(new Ramsay1975(fc, int(ramsay.size()), 0, verbose, -1.25)); // other param
1106         ramsay.push_back(new Ramsay1975(fc, int(ramsay.size()), 0, verbose, -1));    // EM param
1107
1108         if (verbose >= 1) mxLog("ComputeEM: Welcome, tolerance=%g ramsay=%d info=%d flavors=%ld",
1109                                 tolerance, useRamsay, information, ramsay.size());
1110
1111         while (1) {
1112                 setExpectationContext("EM");
1113
1114                 if (recentFC) delete recentFC;
1115                 recentFC = new FitContext(fc, fit1->varGroup);
1116                 fit1->compute(recentFC);
1117                 if (recentFC->inform == INFORM_ITERATION_LIMIT) {
1118                         fc->inform = INFORM_ITERATION_LIMIT;
1119                         omxRaiseErrorf(globalState, "ComputeEM: iteration limited reached");
1120                         break;
1121                 }
1122                 mstepIter = recentFC->iterations;
1123                 recentFC->updateParent();
1124
1125                 setExpectationContext("");
1126
1127                 {
1128                         FitContext *context = fc;
1129                         if (fc->varGroup != fit2->varGroup) {
1130                                 context = new FitContext(fc, fit2->varGroup);
1131                         }
1132
1133                         // For IFA, PREOPTIMIZE updates latent distribution parameters
1134                         omxFitFunction *ff2 = fit2->getFitFunction();
1135                         if (ff2) omxFitFunctionCompute(ff2, FF_COMPUTE_PREOPTIMIZE, context);
1136
1137                         if (!useRamsay) {
1138                                 fc->maybeCopyParamToModel(globalState);
1139                         } else {
1140                                 context->updateParent();
1141
1142                                 bool wantRestart;
1143                                 if (iter > 3 && iter % 3 == 0) {
1144                                         for (size_t rx=0; rx < ramsay.size(); ++rx) {
1145                                                 ramsay[rx]->recalibrate(&wantRestart);
1146                                         }
1147                                 }
1148                                 for (size_t rx=0; rx < ramsay.size(); ++rx) {
1149                                         ramsay[rx]->apply();
1150                                 }
1151                                 fc->copyParamToModel(globalState);
1152                         }
1153
1154                         fit2->compute(context);
1155                         if (context != fc) context->updateParentAndFree();
1156                 }
1157
1158                 totalMstepIter += mstepIter;
1159
1160                 if (!(fc->wanted & FF_COMPUTE_FIT)) {
1161                         omxRaiseErrorf(globalState, "ComputeEM: fit not available");
1162                         break;
1163                 }
1164                 if (fc->fit == 0) {
1165                         omxRaiseErrorf(globalState, "Fit estimated at 0; something is wrong");
1166                         break;
1167                 }
1168                 double change = 0;
1169                 if (prevFit != 0) {
1170                         change = prevFit - fc->fit;
1171                         if (0 < change && change < MIDDLE_START) in_middle = true;
1172                         if (verbose >= 2) mxLog("ComputeEM[%d]: msteps %d fit %.9g change %.9g",
1173                                                 iter, mstepIter, fc->fit, change);
1174                         mac = fabs(change);
1175                 } else {
1176                         if (verbose >= 2) mxLog("ComputeEM: msteps %d initial fit %.9g",
1177                                                 mstepIter, fc->fit);
1178                 }
1179
1180                 prevFit = fc->fit;
1181                 converged = mac < tolerance;
1182                 if (isErrorRaised(globalState) || ++iter > maxIter || converged) break;
1183
1184                 // && change > MIDDLE_END
1185                 if (in_middle) estHistory.push_back(recentFC->take(FF_COMPUTE_ESTIMATE));
1186         }
1187
1188         fc->wanted = FF_COMPUTE_FIT | FF_COMPUTE_ESTIMATE;
1189         bestFit = fc->fit;
1190         if (verbose >= 1) mxLog("ComputeEM: cycles %d/%d total mstep %d fit %f",
1191                                 iter, maxIter,totalMstepIter, bestFit);
1192
1193         if (!converged || !information) return;
1194
1195         if (verbose >= 1) mxLog("ComputeEM: tolerance=%f semTolerance=%f noiseTarget=%f",
1196                                 tolerance, semTolerance, noiseTarget);
1197
1198         // what about latent distribution parameters? TODO
1199
1200         recentFC->fixHessianSymmetry(FF_COMPUTE_IHESSIAN);
1201         double *ihess = recentFC->take(FF_COMPUTE_IHESSIAN);
1202
1203         optimum.resize(freeVars);
1204         memcpy(optimum.data(), fc->est, sizeof(double) * freeVars);
1205
1206         if (semMethodLen == 0 || (semMethodLen==1 && semMethod[0] == 1)) {
1207                 maxHistLen = 4;
1208         } else if (semMethodLen==1 && semMethod[0] == 0) {
1209                 maxHistLen = estHistory.size();
1210         } else {
1211                 maxHistLen = semMethodLen;
1212         }
1213
1214         probeOffset.resize(maxHistLen * freeVarsEM);
1215         diffWork.resize(maxHistLen * freeVarsEM);
1216         paramHistLen.assign(freeVarsEM, 0);
1217
1218         omxBuffer<double> rij(freeVarsEM * freeVarsEM);
1219         setExpectationContext("EM");
1220
1221         for (int v1=0; v1 < freeVarsEM; ++v1) {
1222                 std::vector<double> rijWork(freeVarsEM * maxHistLen);
1223                 int pick = 0;
1224                 if (semMethodLen == 0 || (semMethodLen==1 && semMethod[0] == 1)) {
1225                         const double stepSize = tolerance;
1226
1227                         double offset1 = tolerance * 400;
1228                         double sign = 1;
1229                         if (estHistory.size()) {
1230                                 int hpick = 0;
1231                                 double popt = optimum[recentFC->mapToParent[v1]];
1232                                 sign = (popt < estHistory[hpick][v1])? 1 : -1;
1233                                 offset1 = fabs(estHistory[hpick][v1] - popt);
1234                                 if (offset1 < 10 * tolerance) offset1 = 10 * tolerance;
1235                         }
1236
1237                         probeEM(fc, v1, sign * offset1, &rijWork);
1238                         double offset2 = offset1 + stepSize;
1239                         probeEM(fc, v1, sign * offset2, &rijWork);
1240                         double diff;
1241                         bool mengOK;
1242                         recordDiff(v1, rijWork, &diff, &mengOK);
1243                         double midOffset = (offset1 + offset2) / 2;
1244
1245                         if (!(noiseTarget/noiseTolerance < diff && diff < noiseTarget*noiseTolerance)) {
1246                                 double coef = diff * midOffset * midOffset;
1247                                 offset1 = sqrt(coef/(noiseTarget * 1.05));
1248                                 probeEM(fc, v1, sign * offset1, &rijWork);
1249                                 if (semDebug) {
1250                                         offset2 = offset1 + stepSize;
1251                                         probeEM(fc, v1, sign * offset2, &rijWork);
1252                                         recordDiff(v1, rijWork, &diff, &mengOK);
1253                                 }
1254                                 pick = 2;
1255                         }
1256                 } else if (semMethodLen==1 && semMethod[0] == 0) {
1257                         if (!estHistory.size()) {
1258                                 if (verbose >= 1) mxLog("ComputeEM: no history available;"
1259                                                         " Tian, Cai, Thissen, Xin (2013) SEM requires convergence history");
1260                                 return;
1261                         }
1262                         for (size_t hx=0; hx < estHistory.size(); ++hx) {
1263                                 if (hx && fabs(estHistory[hx-1][v1] - estHistory[hx][v1]) < tolerance) break;
1264                                 double popt = optimum[recentFC->mapToParent[v1]];
1265                                 double offset1 = estHistory[hx][v1] - popt;
1266                                 probeEM(fc, v1, offset1, &rijWork);
1267                                 if (hx == 0) continue;
1268                                 pick = hx;
1269                                 double diff;
1270                                 bool mengOK;
1271                                 recordDiff(v1, rijWork, &diff, &mengOK);
1272                                 if (mengOK) break;
1273                         }
1274                 } else {
1275                         double sign = 1;
1276                         if (estHistory.size()) {
1277                                 int hpick = 0;
1278                                 double popt = optimum[recentFC->mapToParent[v1]];
1279                                 sign = (popt < estHistory[hpick][v1])? 1 : -1;
1280                         }
1281                         for (int hx=0; hx < semMethodLen; ++hx) {
1282                                 probeEM(fc, v1, sign * semMethod[hx], &rijWork);
1283                                 if (hx == 0) continue;
1284                                 double diff;
1285                                 bool mengOK;
1286                                 recordDiff(v1, rijWork, &diff, &mengOK);
1287                         }
1288                 }
1289
1290                 memcpy(rij.data() + v1 * freeVarsEM, rijWork.data() + pick*freeVarsEM, sizeof(double) * freeVarsEM);
1291                 if (verbose >= 2) mxLog("ComputeEM: param %d converged in %d probes",
1292                                         v1, paramHistLen[v1]);
1293         }
1294
1295         memcpy(fc->est, optimum.data(), sizeof(double) * freeVars);
1296         fc->copyParamToModel(globalState);
1297
1298         //pda(rij.data(), freeVarsEM, freeVarsEM);
1299
1300         // rij = I-rij
1301         for (int v1=0; v1 < freeVarsEM; ++v1) {
1302                 for (int v2=0; v2 < freeVarsEM; ++v2) {
1303                         int cell = v1 * freeVarsEM + v2;
1304                         double entry = rij[cell];
1305                         if (v1 == v2) entry = 1 - entry;
1306                         else entry = -entry;
1307                         rij[cell] = entry;
1308                 }
1309         }
1310         // make symmetric
1311         for (int v1=1; v1 < freeVarsEM; ++v1) {
1312                 for (int v2=0; v2 < v1; ++v2) {
1313                         int c1 = v1 * freeVarsEM + v2;
1314                         int c2 = v2 * freeVarsEM + v1;
1315                         double mean = (rij[c1] + rij[c2])/2;
1316                         rij[c1] = mean;
1317                         rij[c2] = mean;
1318                 }
1319         }
1320
1321         //mxLog("symm");
1322         //pda(rij.data(), freeVarsEM, freeVarsEM);
1323
1324         //pda(ihess, freeVarsEM, freeVarsEM);
1325
1326         // ihess = ihess %*% rij^{-1}
1327         if (0) {
1328                 omxBuffer<int> ipiv(freeVarsEM);
1329                 int info;
1330                 F77_CALL(dgesv)(&freeVarsEM, &freeVarsEM, rij.data(), &freeVarsEM,
1331                                 ipiv.data(), ihess, &freeVarsEM, &info);
1332                 if (info < 0) error("dgesv %d", info);
1333                 if (info > 0) {
1334                         if (verbose >= 1) mxLog("ComputeEM: EM map is not positive definite %d", info);
1335                         return;
1336                 }
1337         } else {
1338                 char uplo = 'U';
1339                 omxBuffer<int> ipiv(freeVarsEM);
1340                 int info;
1341                 double worksize;
1342                 int lwork = -1;
1343                 F77_CALL(dsysv)(&uplo, &freeVarsEM, &freeVarsEM, rij.data(), &freeVarsEM,
1344                                 ipiv.data(), ihess, &freeVarsEM, &worksize, &lwork, &info);
1345                 lwork = worksize;
1346                 omxBuffer<double> work(lwork);
1347                 F77_CALL(dsysv)(&uplo, &freeVarsEM, &freeVarsEM, rij.data(), &freeVarsEM,
1348                                 ipiv.data(), ihess, &freeVarsEM, work.data(), &lwork, &info);
1349                 if (info < 0) error("dsysv %d", info);
1350                 if (info > 0) {
1351                         if (verbose >= 1) mxLog("ComputeEM: Hessian from EM map is exactly singular %d", info);
1352                         return;
1353                 }
1354         }
1355
1356         for (int v1=0; v1 < freeVarsEM; ++v1) {
1357                 for (int v2=0; v2 <= v1; ++v2) {
1358                         fc->ihess[recentFC->mapToParent[v1] * freeVars + recentFC->mapToParent[v2]] =
1359                                 ihess[v1 * freeVarsEM + v2];
1360                 }
1361         }
1362         if (verbose >= 1) mxLog("ComputeEM: %d probes used to estimate Hessian", semProbeCount);
1363
1364         fc->wanted |= FF_COMPUTE_IHESSIAN;
1365         //pda(ihess, freeVarsEM, freeVarsEM);
1366
1367         delete [] ihess;
1368 }
1369
1370 void ComputeEM::collectResults(FitContext *fc, LocalComputeResult *lcr, MxRList *out)
1371 {
1372         super::collectResults(fc, lcr, out);
1373
1374         std::vector< omxCompute* > clist(2);
1375         clist[0] = fit1;
1376         clist[1] = fit2;
1377
1378         collectResultsHelper(fc, clist, lcr, out);
1379 }
1380
1381 void ComputeEM::reportResults(FitContext *fc, MxRList *slots, MxRList *)
1382 {
1383         slots->push_back(std::make_pair(mkChar("semProbeCount"),
1384                                         ScalarInteger(semProbeCount)));
1385
1386         size_t numFree = fc->varGroup->vars.size();
1387         if (!numFree) return;
1388
1389         if (semDebug) {
1390                 const int freeVarsEM = (int) fit1->varGroup->vars.size();
1391
1392                 SEXP Rpo;
1393                 PROTECT(Rpo = allocMatrix(REALSXP, maxHistLen, freeVarsEM));
1394                 memcpy(REAL(Rpo), probeOffset.data(), sizeof(double) * maxHistLen * freeVarsEM);
1395                 slots->push_back(std::make_pair(mkChar("probeOffset"), Rpo));
1396
1397                 SEXP Rdiff;
1398                 PROTECT(Rdiff = allocMatrix(REALSXP, maxHistLen, freeVarsEM));
1399                 memcpy(REAL(Rdiff), diffWork.data(), sizeof(double) * maxHistLen * freeVarsEM);
1400                 slots->push_back(std::make_pair(mkChar("semDiff"), Rdiff));
1401
1402                 SEXP Rphl;
1403                 PROTECT(Rphl = allocVector(INTSXP, freeVarsEM));
1404                 memcpy(INTEGER(Rphl), paramHistLen.data(), sizeof(int) * freeVarsEM);
1405                 slots->push_back(std::make_pair(mkChar("paramHistLen"), Rphl));
1406         }
1407 }
1408
1409 double ComputeEM::getOptimizerStatus()
1410 {
1411         // for backward compatibility, not indended to work generally
1412         return NA_REAL;
1413 }
1414
1415 ComputeEM::~ComputeEM()
1416 {
1417         for (size_t rx=0; rx < ramsay.size(); ++rx) {
1418                 delete ramsay[rx];
1419         }
1420         ramsay.clear();
1421
1422         delete fit1;
1423         delete fit2;
1424
1425         for (size_t hx=0; hx < estHistory.size(); ++hx) {
1426                 delete [] estHistory[hx];
1427         }
1428         estHistory.clear();
1429         if (recentFC) delete recentFC;
1430 }
1431
1432 void omxComputeOnce::initFromFrontend(SEXP rObj)
1433 {
1434         super::initFromFrontend(rObj);
1435
1436         SEXP slotValue;
1437         PROTECT(slotValue = GET_SLOT(rObj, install("what")));
1438         for (int wx=0; wx < length(slotValue); ++wx) {
1439                 int objNum = INTEGER(slotValue)[wx];
1440                 if (objNum >= 0) {
1441                         omxMatrix *algebra = globalState->algebraList[objNum];
1442                         if (algebra->fitFunction) {
1443                                 setFreeVarGroup(algebra->fitFunction, varGroup);
1444                                 omxCompleteFitFunction(algebra);
1445                         }
1446                         algebras.push_back(algebra);
1447                 } else {
1448                         omxExpectation *expectation = globalState->expectationList[~objNum];
1449                         setFreeVarGroup(expectation, varGroup);
1450                         omxCompleteExpectation(expectation);
1451                         expectations.push_back(expectation);
1452                 }
1453         }
1454
1455         PROTECT(slotValue = GET_SLOT(rObj, install("verbose")));
1456         verbose = asInteger(slotValue);
1457
1458         context = "";
1459
1460         PROTECT(slotValue = GET_SLOT(rObj, install("context")));
1461         if (length(slotValue) == 0) {
1462                 // OK
1463         } else if (length(slotValue) == 1) {
1464                 SEXP elem;
1465                 PROTECT(elem = STRING_ELT(slotValue, 0));
1466                 context = CHAR(elem);
1467         }
1468
1469         PROTECT(slotValue = GET_SLOT(rObj, install("maxAbsChange")));
1470         mac = asLogical(slotValue);
1471
1472         PROTECT(slotValue = GET_SLOT(rObj, install("fit")));
1473         fit = asLogical(slotValue);
1474
1475         PROTECT(slotValue = GET_SLOT(rObj, install("gradient")));
1476         gradient = asLogical(slotValue);
1477
1478         PROTECT(slotValue = GET_SLOT(rObj, install("hessian")));
1479         hessian = asLogical(slotValue);
1480
1481         PROTECT(slotValue = GET_SLOT(rObj, install("information")));
1482         infoMat = asLogical(slotValue);
1483
1484         if (hessian && infoMat) error("Cannot compute the Hessian and Fisher Information matrix simultaneously");
1485
1486         if (infoMat) {
1487                 const char *iMethod = "";
1488                 PROTECT(slotValue = GET_SLOT(rObj, install("info.method")));
1489                 if (length(slotValue) == 0) {
1490                         // OK
1491                 } else if (length(slotValue) == 1) {
1492                         SEXP elem;
1493                         PROTECT(elem = STRING_ELT(slotValue, 0));
1494                         iMethod = CHAR(elem);
1495                 }
1496
1497                 if (strcmp(iMethod, "sandwich")==0) {
1498                         infoMethod = INFO_METHOD_SANDWICH;
1499                 } else if (strcmp(iMethod, "meat")==0) {
1500                         infoMethod = INFO_METHOD_MEAT;
1501                 } else if (strcmp(iMethod, "bread")==0) {
1502                         infoMethod = INFO_METHOD_BREAD;
1503                 } else {
1504                         error("Unknown information matrix estimation method '%s'", iMethod);
1505                 }
1506         }
1507
1508         PROTECT(slotValue = GET_SLOT(rObj, install("ihessian")));
1509         ihessian = asLogical(slotValue);
1510
1511         PROTECT(slotValue = GET_SLOT(rObj, install("hgprod")));
1512         hgprod = asLogical(slotValue);
1513
1514         if (algebras.size() == 1 && algebras[0]->fitFunction) {
1515                 omxFitFunction *ff = algebras[0]->fitFunction;
1516                 if (gradient && !ff->gradientAvailable) {
1517                         error("Gradient requested but not available");
1518                 }
1519                 if ((hessian || ihessian || hgprod) && !ff->hessianAvailable) {
1520                         // add a separate flag for hgprod TODO
1521                         error("Hessian requested but not available");
1522                 }
1523                 // add check for information TODO
1524         }
1525 }
1526
1527 omxFitFunction *omxComputeOnce::getFitFunction()
1528 {
1529         if (algebras.size() == 1 && algebras[0]->fitFunction) {
1530                 return algebras[0]->fitFunction;
1531         } else {
1532                 return NULL;
1533         }
1534 }
1535
1536 void omxComputeOnce::compute(FitContext *fc)
1537 {
1538         if (algebras.size()) {
1539                 int want = 0;
1540                 size_t numParam = fc->varGroup->vars.size();
1541                 if (mac) {
1542                         want |= FF_COMPUTE_MAXABSCHANGE;
1543                         fc->mac = 0;
1544                 }
1545                 if (fit) {
1546                         want |= FF_COMPUTE_FIT;
1547                         fc->fit = 0;
1548                 }
1549                 if (gradient) {
1550                         want |= FF_COMPUTE_GRADIENT;
1551                         OMXZERO(fc->grad, numParam);
1552                 }
1553                 if (hessian) {
1554                         want |= FF_COMPUTE_HESSIAN;
1555                         OMXZERO(fc->hess, numParam * numParam);
1556                 }
1557                 if (infoMat) {
1558                         want |= FF_COMPUTE_INFO;
1559                         fc->infoMethod = infoMethod;
1560                         fc->preInfo();
1561                 }
1562                 if (ihessian) {
1563                         want |= FF_COMPUTE_IHESSIAN;
1564                         OMXZERO(fc->ihess, numParam * numParam);
1565                 }
1566                 if (hgprod) {
1567                         want |= FF_COMPUTE_HGPROD;
1568                         fc->hgProd.resize(0);
1569                 }
1570                 if (!want) return;
1571
1572                 for (size_t wx=0; wx < algebras.size(); ++wx) {
1573                         omxMatrix *algebra = algebras[wx];
1574                         if (algebra->fitFunction) {
1575                                 if (verbose) mxLog("ComputeOnce: fit %p want %d",
1576                                                    algebra->fitFunction, want);
1577
1578                                 omxFitFunctionCompute(algebra->fitFunction, FF_COMPUTE_PREOPTIMIZE, fc);
1579                                 fc->maybeCopyParamToModel(globalState);
1580
1581                                 omxFitFunctionCompute(algebra->fitFunction, want, fc);
1582                                 fc->fit = algebra->data[0];
1583                                 if (infoMat) {
1584                                         fc->postInfo();
1585                                 }
1586                                 fc->fixHessianSymmetry(want);
1587                         } else {
1588                                 if (verbose) mxLog("ComputeOnce: algebra %p", algebra);
1589                                 omxForceCompute(algebra);
1590                         }
1591                 }
1592         } else if (expectations.size()) {
1593                 for (size_t wx=0; wx < expectations.size(); ++wx) {
1594                         omxExpectation *expectation = expectations[wx];
1595                         if (verbose) mxLog("ComputeOnce: expectation[%lu] %p context %s", wx, expectation, context);
1596                         omxExpectationCompute(expectation, context);
1597                 }
1598         }
1599 }
1600
1601 void omxComputeOnce::reportResults(FitContext *fc, MxRList *slots, MxRList *out)
1602 {
1603         if (algebras.size()==0 || algebras[0]->fitFunction == NULL) return;
1604
1605         omxMatrix *algebra = algebras[0];
1606         omxPopulateFitFunction(algebra, out);
1607 }
1608
1609 void ComputeStandardError::reportResults(FitContext *fc, MxRList *slots, MxRList *)
1610 {
1611         if (isErrorRaised(globalState)) return;
1612
1613         int numParams = int(fc->varGroup->vars.size());
1614
1615         if (!(fc->wanted & (FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN))) {
1616                 return;
1617         }
1618
1619         if (!(fc->wanted & FF_COMPUTE_IHESSIAN)) {
1620                 // Populate upper triangle
1621                 for(int i = 0; i < numParams; i++) {
1622                         for(int j = 0; j <= i; j++) {
1623                                 fc->ihess[i*numParams+j] = fc->hess[i*numParams+j];
1624                         }
1625                 }
1626
1627                 Matrix wmat(fc->ihess, numParams, numParams);
1628                 InvertSymmetricIndef(wmat, 'U');
1629                 fc->fixHessianSymmetry(FF_COMPUTE_IHESSIAN, true);
1630                 fc->wanted |= FF_COMPUTE_IHESSIAN;
1631         }
1632
1633         // This function calculates the standard errors from the Hessian matrix
1634         // sqrt(diag(solve(hessian)))
1635
1636         fc->allocStderrs();
1637         for(int i = 0; i < numParams; i++) {
1638                 double got = fc->ihess[i * numParams + i];
1639                 if (got <= 0) continue;
1640                 fc->stderrs[i] = sqrt(got);
1641         }
1642 }
1643
1644 void ComputeConditionNumber::reportResults(FitContext *fc, MxRList *slots, MxRList *)
1645 {
1646         if (isErrorRaised(globalState)) return;
1647
1648         int numParams = int(fc->varGroup->vars.size());
1649
1650         if (!(fc->wanted & (FF_COMPUTE_HESSIAN | FF_COMPUTE_IHESSIAN))) {
1651                 return;
1652         }
1653
1654         if (!(fc->wanted & FF_COMPUTE_HESSIAN)) {
1655                 // Populate upper triangle
1656                 for(int i = 0; i < numParams; i++) {
1657                         for(int j = 0; j <= i; j++) {
1658                                 fc->hess[i*numParams+j] = fc->ihess[i*numParams+j];
1659                         }
1660                 }
1661
1662                 Matrix wmat(fc->hess, numParams, numParams);
1663                 InvertSymmetricIndef(wmat, 'U');
1664                 fc->fixHessianSymmetry(FF_COMPUTE_HESSIAN, true);
1665                 fc->wanted |= FF_COMPUTE_HESSIAN;
1666         }
1667
1668         omxBuffer<double> hessWork(numParams * numParams);
1669         memcpy(hessWork.data(), fc->hess, sizeof(double) * numParams * numParams);
1670
1671         char jobz = 'N';
1672         char range = 'A';
1673         char uplo = 'U';
1674         double abstol = 0;
1675         int m;
1676         omxBuffer<double> w(numParams);
1677         double optWork;
1678         int lwork = -1;
1679         omxBuffer<int> iwork(5 * numParams);
1680         int info;
1681         double realIgn = 0;
1682         int intIgn = 0;
1683         F77_CALL(dsyevx)(&jobz, &range, &uplo, &numParams, hessWork.data(),
1684                          &numParams, &realIgn, &realIgn, &intIgn, &intIgn, &abstol, &m, w.data(),
1685                          NULL, &numParams, &optWork, &lwork, iwork.data(), NULL, &info);
1686
1687         lwork = optWork;
1688         omxBuffer<double> work(lwork);
1689         F77_CALL(dsyevx)(&jobz, &range, &uplo, &numParams, hessWork.data(),
1690                          &numParams, &realIgn, &realIgn, &intIgn, &intIgn, &abstol, &m, w.data(),
1691                          NULL, &numParams, work.data(), &lwork, iwork.data(), NULL, &info);
1692         if (info != 0) error("dsyevx %d", info);
1693
1694         double got = w[numParams-1] / w[0];
1695         if (isfinite(got)) fc->hessCondNum = got;
1696 }