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