Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • #31
    Hi Choonjoo Lee Sorry I thought the compressed QR was the same as Stata's. It is not. It is Rao's based on QR chunks. I know Stata uses compressed QR but not Rao's formula.
    So this is a genuinely new technique. It may not be quicker or more accurate than Stata's, but nonetheless it is different.
    Cheers,
    Matt

    Comment


    • #32
      Thanks, Matt. One brief clarification for readers: the Rao-based completion and the compressed group QR example are separate calculations, and I am not claiming a new method.
      I’m glad the examples were useful. Perhaps we can leave the public discussion here and continue any further technical details by private message.
      Best wishes,

      Comment


      • #33
        I tried out a few more ways of making K. Both are not very fast but make sparse K. reml8 uses an LP algorithm and takes 20 sec for n = 1000, whereas reml11 uses transportation matrix and takes 2 sec (the formula needs to be changed to K' rather than K). These won't catch QR which took 1msec for 1000 obs. Anyway for interest here they are. reml8.do reml11.do

        Comment


        • #34
          Hi Matt Piercy ,

          I tried both attachments on a simulated random-intercept dataset with 1,000 observations in 200 groups of five, using one processor in Stata/MP 16.1. Building K took about 7 ms for reml8 and 0.65 ms for reml11. A full likelihood evaluation took about 779 ms and 741 ms, respectively. The time in your post could cover a different part of the calculation. Were the 20 s, 2 s, and 1 ms timings for building K alone?

          For the intercept-plus-one-x case in reml8, the first pivot is the first observation and the second is the first observation farthest from it in x. Filling the contrast coefficients directly gave the same K to numerical precision and took about 0.55 ms.

          For both constructions, K is fixed during optimization. With contrasts in the rows of K, I cached A = KK', B = (KZ)(KZ)', and h = Ky. At each evaluation, a Cholesky factor of C = se2*A + su2*B gives both log(det(C)) and the quadratic term from a triangular solve. The correction log(det(X'X)) - log(det(A)) keeps the likelihood on the same scale as the attachments. Taking logs of the Cholesky diagonals also avoids forming an ordinary determinant, which overflowed at one variance pair in this experiment.

          With that change, each evaluation took about 78 ms for either basis, after about 0.08 s of preparation. The likelihoods agreed with the originals within 1e-6 at the timed variance pair. On the same simulated data, the earlier group-compressed QR example took about 0.016 ms per evaluation after 0.5 ms of preparation. The cached reml8 and group QR fits both agreed with mixed, reml and took about 4.3 s and 4 ms respectively, excluding preparation. The group QR timing is for evaluating the likelihood, while your QR timing may be for constructing K.

          One detail about reml11: for x = (1, 2, 2, 3)', the two adjacent-triple contrasts are identical, so K has rank 1 when it needs rank 2. The code below checks that the selected contrasts give a positive-definite KK'. Both choices use row-oriented contrasts, so the reml8 option gives the transpose of your original K.

          Code:
          clear all
          set more off
          
          input double y x id
          10 1 1
          12 2 1
          11 3 1
          20 1 2
          22 2 2
          21 3 2
          30 1 3
          31 2 3
          33 3 3
          end
          
          mata:
          struct mp_reml_cache {
              real matrix A, B
              real colvector h
              real scalar constant
          }
          
          real matrix mp_lp_rows(real colvector x)
          {
              real scalar n, j, r
              real colvector dx, ix
              real matrix K
          
              n = rows(x)
              dx = x :- x[1]
              assert(n>2 & max(abs(dx))>0)
              ix = selectindex(abs(dx):==max(abs(dx)))
              j = ix[1]
              ix = selectindex(((1::n):!=1) :& ((1::n):!=j))
          
              K = J(n-2,n,0)
              K[.,j] = -dx[ix]/dx[j]
              K[.,1] = -1 :- K[.,j]
              for (r=1; r<=n-2; r++) K[r,ix[r]] = 1
              return(K)
          }
          
          real matrix mp_adjacent_rows(real colvector x)
          {
              real scalar n, i
              real matrix K
          
              n = rows(x)
              K = J(n-2,n,0)
              for (i=1; i<=n-2; i++) {
                  K[i,i]   = x[i+2]-x[i+1]
                  K[i,i+1] = x[i]-x[i+2]
                  K[i,i+2] = x[i+1]-x[i]
              }
              return(K)
          }
          
          struct mp_reml_cache scalar mp_prepare(real matrix K, real matrix X,
              real colvector y, real matrix Z)
          {
              struct mp_reml_cache scalar cache
              real matrix L, KZ, F, R
              real rowvector tau
          
              cache.A = cross(K',K')
              L = cholesky(cache.A)
              if (hasmissing(L) | any(diagonal(L):<=0)) {
                  errprintf("The contrast rows do not give a positive-definite KK'.\n")
                  _error(3498)
              }
              KZ = K*Z
              cache.B = cross(KZ',KZ')
              cache.h = K*y
              hqrd(X,F,tau,R)
              cache.constant = rows(K)*ln(2*pi()) +
                  2*sum(ln(abs(diagonal(R)))) - 2*sum(ln(diagonal(L)))
              return(cache)
          }
          
          void mp_reml_eval(real scalar todo, real rowvector b,
              struct mp_reml_cache scalar cache, real scalar f,
              real rowvector g, real matrix H)
          {
              real matrix L
              real colvector z
          
              L = cholesky(exp(b[2])*cache.A + exp(b[1])*cache.B)
              z = solvelower(L,cache.h)
              f = .5*(cache.constant + 2*sum(ln(diagonal(L))) + quadcross(z,z))
          }
          
          real rowvector mp_fit(struct mp_reml_cache scalar cache)
          {
              transmorphic S
              real rowvector b
          
              S = optimize_init()
              optimize_init_evaluator(S,&mp_reml_eval())
              optimize_init_evaluatortype(S,"d0")
              optimize_init_argument(S,1,cache)
              optimize_init_params(S,ln((10,1)))
              optimize_init_which(S,"min")
              optimize_init_tracelevel(S,"none")
              optimize_init_conv_ptol(S,1e-10)
              optimize_init_conv_vtol(S,1e-12)
              b = optimize(S)
              assert(optimize_result_converged(S))
              return((exp(b),-optimize_result_value(S)))
          }
          
          x = st_data(.,"x")
          y = st_data(.,"y")
          id = st_data(.,"id")
          X = (J(rows(x),1,1),x)
          levels = uniqrows(sort(id,1))
          Z = J(rows(id),rows(levels),0)
          for (j=1; j<=rows(levels); j++) Z[.,j] = (id:==levels[j])
          
          printf("                 su2          se2        REML ll\n")
          lp = mp_fit(mp_prepare(mp_lp_rows(x),X,y,Z))
          adj = mp_fit(mp_prepare(mp_adjacent_rows(x),X,y,Z))
          printf("Direct LP   %12.6f %12.6f %14.9f\n", lp[1], lp[2], lp[3])
          printf("Adjacent    %12.6f %12.6f %14.9f\n", adj[1], adj[2], adj[3])
          end
          
          mixed y x || id:, reml variance
          Best wishes,

          Comment


          • #35
            I also tried using the sparsity in your adjacent-triple construction. With observations ordered by group, each contrast uses three consecutive observations. In the example with five observations per group, the contrast covariance has at most six subdiagonals. Storing only that band and factoring it directly in Mata brought the reml11 evaluation from 77.4 ms to 3.65 ms, with about 15 ms of preparation. Across five variance pairs, the largest absolute difference from the group QR log likelihood was about 2.4e-7. These are per-evaluation timings on the same simulated data.

            Code:
            clear all
            set more off
            
            input double y x id
            10 1 1
            12 2 1
            11 3 1
            20 1 2
            22 2 2
            21 3 2
            30 1 3
            31 2 3
            33 3 3
            end
            
            mata:
            struct mp_reml_cache {
                real matrix A, B
                real colvector h
                real scalar constant
            }
            
            real matrix mp_lp_rows(real colvector x)
            {
                real scalar n, j, r
                real colvector dx, ix
                real matrix K
            
                n = rows(x)
                dx = x :- x[1]
                assert(n>2 & max(abs(dx))>0)
                ix = selectindex(abs(dx):==max(abs(dx)))
                j = ix[1]
                ix = selectindex(((1::n):!=1) :& ((1::n):!=j))
            
                K = J(n-2,n,0)
                K[.,j] = -dx[ix]/dx[j]
                K[.,1] = -1 :- K[.,j]
                for (r=1; r<=n-2; r++) K[r,ix[r]] = 1
                return(K)
            }
            
            real matrix mp_adjacent_rows(real colvector x)
            {
                real scalar n, i
                real matrix K
            
                n = rows(x)
                K = J(n-2,n,0)
                for (i=1; i<=n-2; i++) {
                    K[i,i]   = x[i+2]-x[i+1]
                    K[i,i+1] = x[i]-x[i+2]
                    K[i,i+2] = x[i+1]-x[i]
                }
                return(K)
            }
            
            struct mp_reml_cache scalar mp_prepare(real matrix K, real matrix X,
                real colvector y, real matrix Z)
            {
                struct mp_reml_cache scalar cache
                real matrix L, KZ, F, R
                real rowvector tau
            
                cache.A = cross(K',K')
                L = cholesky(cache.A)
                if (hasmissing(L) | any(diagonal(L):<=0)) {
                    errprintf("The contrast rows do not give a positive-definite KK'.\n")
                    _error(3498)
                }
                KZ = K*Z
                cache.B = cross(KZ',KZ')
                cache.h = K*y
                hqrd(X,F,tau,R)
                cache.constant = rows(K)*ln(2*pi()) +
                    2*sum(ln(abs(diagonal(R)))) - 2*sum(ln(diagonal(L)))
                return(cache)
            }
            
            void mp_reml_eval(real scalar todo, real rowvector b,
                struct mp_reml_cache scalar cache, real scalar f,
                real rowvector g, real matrix H)
            {
                real matrix L
                real colvector z
            
                L = cholesky(exp(b[2])*cache.A + exp(b[1])*cache.B)
                z = solvelower(L,cache.h)
                f = .5*(cache.constant + 2*sum(ln(diagonal(L))) + quadcross(z,z))
            }
            
            real rowvector mp_fit(struct mp_reml_cache scalar cache)
            {
                transmorphic S
                real rowvector b
            
                S = optimize_init()
                optimize_init_evaluator(S,&mp_reml_eval())
                optimize_init_evaluatortype(S,"d0")
                optimize_init_argument(S,1,cache)
                optimize_init_params(S,ln((10,1)))
                optimize_init_which(S,"min")
                optimize_init_tracelevel(S,"none")
                optimize_init_conv_ptol(S,1e-10)
                optimize_init_conv_vtol(S,1e-12)
                b = optimize(S)
                assert(optimize_result_converged(S))
                return((exp(b),-optimize_result_value(S)))
            }
            
            x = st_data(.,"x")
            y = st_data(.,"y")
            id = st_data(.,"id")
            X = (J(rows(x),1,1),x)
            levels = uniqrows(sort(id,1))
            Z = J(rows(id),rows(levels),0)
            for (j=1; j<=rows(levels); j++) Z[.,j] = (id:==levels[j])
            
            printf("                 su2          se2        REML ll\n")
            lp = mp_fit(mp_prepare(mp_lp_rows(x),X,y,Z))
            adj = mp_fit(mp_prepare(mp_adjacent_rows(x),X,y,Z))
            printf("Direct LP   %12.6f %12.6f %14.9f\n", lp[1], lp[2], lp[3])
            printf("Adjacent    %12.6f %12.6f %14.9f\n", adj[1], adj[2], adj[3])
            end
            
            mixed y x || id:, reml variance
            The code above illustrates the cached dense calculation. I'd be interested in whether your construction suggests a way to reduce the work further, perhaps by choosing contrasts that give a narrower band.

            Best wishes,

            Comment


            • #36
              A short follow-up on reml11. I wanted to see how much of the timing gap came from the amount of work in the likelihood calculation and how much came from the implementation. I exported the same cached band matrices and contrast vector from Mata and ran the same banded Cholesky recurrence in compiled C.

              On the 1,000-observation example with 200 groups of five, the time per REML likelihood evaluation was about 3.72 ms for the Mata band loop, 0.025 ms for the C band loop, and 0.016 ms for the group-compressed QR. The C and Mata band calculations produced the same log likelihood to 12 decimal places at the timed variance pair. The C figure is CPU time and the Stata figures are elapsed time. The timings exclude preparation, file I/O, and optimizer overhead.

              The comparison puts the C version and Stata's built-in QR routine in a similar range on this example. Group size still changes the work each method does. With 1,000 observations, increasing the group size from five to 25 widened the band from six to 26 subdiagonals, while the group QR input went from 203 to 43 rows. I timed the C version on the five-per-group case.

              Below is the C evaluation kernel from the benchmark. The loader populated a and b with the lower bands of KK' and (KZ)(KZ)', h with Ky, and constant with the variance-independent part of the REML criterion. In the band arrays, entry [i][d] stores the element in row i and column i-d. The benchmark fixed the dimensions. A reusable version could take the number of contrasts and band width as arguments, prepare the inputs once for each dataset, and use the same compiled routine for each variance pair. That still requires independent contrast rows and a positive-definite contrast covariance.

              Code:
              #include <math.h>
              
              enum { n=998, width=6, stride=width+1 };
              static double a[n][stride], b[n][stride], h[n], constant;
              
              static double evaluate(double su, double se)
              {
                  double l[n][stride], z[n], logdiag=0, ss=0;
                  for (int i=0; i<n; ++i) {
                      int start=i>width ? i-width : 0;
                      double r=h[i];
                      for (int j=start; j<=i; ++j) {
                          int d=i-j;
                          double entry=se*a[i][d]+su*b[i][d];
                          for (int k=start; k<j; ++k)
                              entry-=l[i][i-k]*l[j][j-k];
                          if (i==j) {
                              if (entry<=0) return NAN;
                              l[i][0]=sqrt(entry);
                          } else {
                              l[i][d]=entry/l[j][0];
                              r-=l[i][d]*z[j];
                          }
                      }
                      z[i]=r/l[i][0];
                      ss+=z[i]*z[i];
                      logdiag+=log(l[i][0]);
                  }
                  return -.5*(constant+2*logdiag+ss);
              }
              Do you see a way to adapt your adjacent-triple construction to keep the band narrow as the groups get larger?

              Best wishes,

              Comment


              • #37
                Hi Choonjoo Lee Nice work again. I got the timing for running the whole mata ll block in stata, not just compiling K. I used rnormal() to get the 1000 obs. I also got a small time for making K in reml11 but reml8 was longer. The trick is to avoid making V^-1, which you have done. Copilot tells me that although K starts sparse, it doesn't stay that way because of the calculations, and ends up being about 25% 0's. I have just started learning C mostly as a way of better understanding mata. All those times you have quoted are all very fast. I would be interested to see your full plugin C if you are willing to share it. I don't have an answer to your question about keeping the bandwidth narrow for bigger groups. Thanks, Matt

                Comment


                • #38
                  Hi Matt Piercy ,

                  Thanks for clarifying that your timings covered the whole Mata likelihood block. Here's a Stata plugin built around the banded Cholesky loop in #36, with a do-file that calls it from Mata's optimize().

                  The plugin forms the adjacent-triple contrasts from reml11 after grouping the observations by ID, keeping the original order within each group. It builds the lower bands of A = KK' and B = (KZ)(KZ)' and the vector h = Ky once per fit. Each likelihood call then factors se2*A + su2*B and uses a triangular solve. If the largest group has g observations, the lower band has at most g+1 subdiagonals. K still has at most three nonzero entries in each row. The products and the Cholesky factor can be denser within the band.

                  The example fits one numeric covariate plus an intercept and one random intercept for a numeric group ID. The optimizer works on the log-variance scale, so the fit is intended for positive variance components. The setup stops if the adjacent contrasts are numerically rank deficient. The 0.025 ms in #36 timed the C calculation loop alone. The complete fit also takes time to prepare the bands, call the plugin and run optimize().

                  Save the two source blocks below as reml_band.c and reml_band.do. Download stplugin.c and stplugin.h from StataCorp's plugin documentation into the same directory. Build the plugin for the architecture of your Stata installation.

                  On macOS, run the following in Terminal. The StataCorp page also gives the commands for a universal build.

                  Code:
                  clang -std=c99 -O2 -bundle -DSYSTEM=APPLEMAC stplugin.c reml_band.c -o reml_band.plugin
                  On Linux, use the following.

                  Code:
                  gcc -std=c99 -O2 -shared -fPIC -DSYSTEM=OPUNIX stplugin.c reml_band.c -lm -o reml_band.plugin
                  On Windows, use the DLL instructions on the StataCorp page with reml_band.c in place of hello.c, and name the resulting file reml_band.plugin. I ran the example on Stata/MP 16.1 for Apple Silicon.

                  Save this block as reml_band.c.

                  Code:
                  #include <float.h>
                  #include <math.h>
                  #include <stdint.h>
                  #include <stdlib.h>
                  #include <string.h>
                  #include "stplugin.h"
                  
                  struct observation { double y, x, id; };
                  struct contrast { double weight[3], group_weight[3]; };
                  
                  static struct {
                      size_t n, width;
                      double *a, *b, *h, *l, *z;
                      double constant;
                  } cache;
                  
                  static void release(void)
                  {
                      free(cache.a);
                      free(cache.b);
                      free(cache.h);
                      free(cache.l);
                      free(cache.z);
                      memset(&cache, 0, sizeof cache);
                  }
                  
                  /* In row i, offset d stores column i-d. Without a quadratic term,
                     check the rank of K by factoring A = KK'. */
                  static int factor(double su2, double se2, int solve,
                                    double *logdet, double *quadratic)
                  {
                      size_t stride = cache.width + 1;
                      *logdet = *quadratic = 0;
                  
                      for (size_t i = 0; i < cache.n; ++i) {
                          size_t first = i > cache.width ? i - cache.width : 0;
                          size_t row = i * stride;
                          double rhs = solve ? cache.h[i] : 0;
                          for (size_t j = first; j <= i; ++j) {
                              size_t d = i - j;
                              size_t other = j * stride;
                              double entry = se2 * cache.a[row+d] + su2 * cache.b[row+d];
                              for (size_t k = first; k < j; ++k)
                                  entry -= cache.l[row+i-k] * cache.l[other+j-k];
                              if (j == i) {
                                  double floor = solve ? 0 : 64 * DBL_EPSILON * cache.a[row];
                                  if (!isfinite(entry) || entry <= floor)
                                      return 0;
                                  cache.l[row] = sqrt(entry);
                              } else {
                                  cache.l[row+d] = entry / cache.l[other];
                                  if (solve)
                                      rhs -= cache.l[row+d] * cache.z[j];
                              }
                          }
                          *logdet += 2 * log(cache.l[row]);
                          if (solve) {
                              cache.z[i] = rhs / cache.l[row];
                              *quadratic += cache.z[i] * cache.z[i];
                          }
                      }
                      return isfinite(*logdet) && isfinite(*quadratic);
                  }
                  
                  static ST_retcode prepare(const struct observation *data, size_t n)
                  {
                      double mean = 0, ss = 0;
                      size_t biggest = 1, run = 1, groups = 1;
                      for (size_t i = 0; i < n; ++i) {
                          if (i && data[i].id < data[i-1].id) {
                              SF_error("Sort the estimation sample by numeric group ID first.\n");
                              return 198;
                          }
                          if (i && data[i].id != data[i-1].id)
                              ++groups;
                          run = i && data[i].id == data[i-1].id ? run + 1 : 1;
                          if (run > biggest)
                              biggest = run;
                  
                          /* det(X'X) = n * sum((x - mean(x))^2), with X = (1, x). */
                          double shifted = data[i].x - data[0].x;
                          double delta = shifted - mean;
                          mean += delta / (i + 1);
                          ss += delta * (shifted - mean);
                      }
                      if (groups == 1 || biggest == 1) {
                          SF_error("Use multiple groups with repeated observations in at least one group.\n");
                          return 498;
                      }
                      if (!isfinite(ss) || ss <= 0) {
                          SF_error("The covariate must vary and give a finite sum of squares.\n");
                          return 498;
                      }
                  
                      cache.n = n - 2;
                      /* Triples overlap across at most two extra positions in the ordering. */
                      cache.width = biggest + 1 < cache.n ? biggest + 1 : cache.n - 1;
                      size_t stride = cache.width + 1;
                      if (cache.n > SIZE_MAX / sizeof(double) / stride ||
                          cache.n > SIZE_MAX / sizeof(struct contrast))
                          return 909;
                      size_t cells = cache.n * stride;
                      cache.a = calloc(cells, sizeof *cache.a);
                      cache.b = calloc(cells, sizeof *cache.b);
                      cache.h = malloc(cache.n * sizeof *cache.h);
                      cache.l = malloc(cells * sizeof *cache.l);
                      cache.z = malloc(cache.n * sizeof *cache.z);
                      struct contrast *k = malloc(cache.n * sizeof *k);
                      if (!cache.a || !cache.b || !cache.h || !cache.l || !cache.z || !k) {
                          free(k);
                          return 909;
                      }
                  
                      for (size_t i = 0; i < cache.n; ++i) {
                          double left = data[i+1].x - data[i].x;
                          double right = data[i+2].x - data[i+1].x;
                          double scale = fmax(fabs(left), fabs(right));
                          if (!isfinite(scale) || scale == 0) {
                              free(k);
                              SF_error("An adjacent triple gives a zero or nonfinite contrast.\n");
                              return 498;
                          }
                          k[i].weight[0] = right / scale;
                          k[i].weight[2] = left / scale;
                          k[i].weight[1] = -k[i].weight[0] - k[i].weight[2];
                  
                          cache.h[i] = 0;
                          for (size_t p = 0; p < 3; ++p) {
                              cache.h[i] += k[i].weight[p] * (data[i+p].y - data[i].y);
                              k[i].group_weight[p] = 0;
                              if (p && data[i+p].id == data[i+p-1].id)
                                  continue;
                              for (size_t q = p; q < 3 && data[i+p].id == data[i+q].id; ++q)
                                  k[i].group_weight[p] += k[i].weight[q];
                          }
                  
                          size_t first = i > cache.width ? i - cache.width : 0;
                          for (size_t j = first; j <= i; ++j) {
                              size_t d = i - j;
                              size_t cell = i * stride + d;
                              for (size_t p = 0; p + d < 3; ++p)
                                  cache.a[cell] += k[i].weight[p] * k[j].weight[p+d];
                              for (size_t p = 0; p < 3; ++p)
                                  for (size_t q = 0; q < 3; ++q)
                                      if (data[i+p].id == data[j+q].id)
                                          cache.b[cell] += k[i].group_weight[p] * k[j].group_weight[q];
                          }
                      }
                      free(k);
                  
                      double logdet, unused;
                      if (!factor(0, 1, 0, &logdet, &unused)) {
                          SF_error("The adjacent contrasts are numerically rank deficient.\n");
                          return 498;
                      }
                      cache.constant = cache.n * log(2 * acos(-1.0))
                                       + log((double)n) + log(ss) - logdet;
                      return 0;
                  }
                  
                  static ST_retcode load(void)
                  {
                      release();
                      if (SF_nvars() != 3)
                          return 198;
                  
                      size_t n = 0;
                      for (ST_int i = SF_in1(); i <= SF_in2(); ++i)
                          if (SF_ifobs(i))
                              ++n;
                      if (n < 4) {
                          SF_error("At least four complete observations are required.\n");
                          return 2001;
                      }
                      if (n > SIZE_MAX / sizeof(struct observation))
                          return 909;
                      struct observation *data = malloc(n * sizeof *data);
                      if (!data)
                          return 909;
                  
                      ST_retcode rc = 0;
                      size_t row = 0;
                      for (ST_int i = SF_in1(); i <= SF_in2(); ++i) {
                          if (!SF_ifobs(i))
                              continue;
                          rc = SF_vdata(1, i, &data[row].y);
                          if (!rc) rc = SF_vdata(2, i, &data[row].x);
                          if (!rc) rc = SF_vdata(3, i, &data[row].id);
                          if (rc)
                              break;
                          if (SF_is_missing(data[row].y) || SF_is_missing(data[row].x) ||
                              SF_is_missing(data[row].id)) {
                              SF_error("Pass complete observations of y, x, and ID.\n");
                              rc = 416;
                              break;
                          }
                          ++row;
                      }
                      if (!rc)
                          rc = prepare(data, n);
                      free(data);
                      if (rc)
                          release();
                      return rc;
                  }
                  
                  STDLL stata_call(int argc, char *argv[])
                  {
                      if (argc == 1 && strcmp(argv[0], "load") == 0)
                          return load();
                      if (argc == 1 && strcmp(argv[0], "free") == 0) {
                          release();
                          return 0;
                      }
                      if (argc != 4 || strcmp(argv[0], "eval") != 0)
                          return 198;
                      if (!cache.n)
                          return 498;
                  
                      double su2, se2, logdet, quadratic, ll = SV_missval;
                      ST_retcode rc = SF_scal_use(argv[1], &su2);
                      if (!rc) rc = SF_scal_use(argv[2], &se2);
                      if (rc)
                          return rc;
                      if (!SF_is_missing(su2) && !SF_is_missing(se2) &&
                          isfinite(su2) && isfinite(se2) && su2 >= 0 && se2 > 0 &&
                          factor(su2, se2, 1, &logdet, &quadratic)) {
                          double value = -0.5 * (cache.constant + logdet + quadratic);
                          if (isfinite(value) && fabs(value) < SV_missval)
                              ll = value;
                      }
                      return SF_scal_save(argv[3], ll);
                  }
                  Save this block as reml_band.do.

                  Code:
                  version 16.1
                  
                  capture program drop reml_band_plugin
                  program reml_band_plugin, plugin using("reml_band.plugin")
                  
                  capture program drop reml_band
                  capture mata: mata drop reml_band_objective()
                  capture mata: mata drop reml_band_fit()
                  
                  mata:
                  void reml_band_objective(real scalar todo, real rowvector b,
                      string rowvector names, real scalar f, real rowvector g, real matrix H)
                  {
                      st_numscalar(names[1], exp(b[1]))
                      st_numscalar(names[2], exp(b[2]))
                      stata("plugin call reml_band_plugin, eval " + invtokens(names), 1)
                      f = -st_numscalar(names[3])
                  }
                  
                  void reml_band_fit(string rowvector names, real scalar start)
                  {
                      transmorphic S
                      real rowvector b
                  
                      S = optimize_init()
                      optimize_init_evaluator(S, &reml_band_objective())
                      optimize_init_evaluatortype(S, "d0")
                      optimize_init_argument(S, 1, names)
                      optimize_init_params(S, (ln(start), ln(start)))
                      optimize_init_which(S, "min")
                      optimize_init_tracelevel(S, "none")
                      b = optimize(S)
                      if (!optimize_result_converged(S)) {
                          errprintf("REML optimization did not converge.\n")
                          _error(430)
                      }
                      st_numscalar(names[1], exp(b[1]))
                      st_numscalar(names[2], exp(b[2]))
                      st_numscalar(names[3], -optimize_result_value(S))
                  }
                  end
                  
                  program reml_band, rclass sortpreserve
                      syntax varlist(numeric min=3 max=3) [if] [in]
                      marksample touse
                      gettoken y rest : varlist
                      gettoken x id : rest
                      tempname su2 se2 ll start
                      quietly summarize `y' if `touse'
                      local n = r(N)
                      if `n' < 4 {
                          error 2001
                      }
                      if missing(r(Var)) | r(Var) <= 0 {
                          display as error "The outcome must have positive finite variance."
                          exit 498
                      }
                      scalar `start' = r(Var)/2
                  
                      sort `id', stable
                      nobreak {
                          plugin call reml_band_plugin `y' `x' `id' if `touse', load
                          capture noisily break mata: reml_band_fit( ///
                              ("`su2'", "`se2'", "`ll'"), st_numscalar("`start'"))
                          local rc = _rc
                          plugin call reml_band_plugin, free
                      }
                      if `rc' {
                          exit `rc'
                      }
                  
                      display as text "Random-intercept variance  " as result %14.8g `su2'
                      display as text "Residual variance          " as result %14.8g `se2'
                      display as text "REML log likelihood        " as result %14.9f `ll'
                      return scalar N = `n'
                      return scalar su2 = `su2'
                      return scalar se2 = `se2'
                      return scalar ll = `ll'
                  end
                  In Stata, change to the directory containing the do-file and the compiled plugin. The example below uses your nine observations. On my run the two fits gave a random-intercept variance of about 103.07, a residual variance of 0.90 and a REML log likelihood of -17.400591123.

                  Code:
                  clear
                  do reml_band.do
                  
                  input double y x id
                  10 1 1
                  12 2 1
                  11 3 1
                  20 1 2
                  22 2 2
                  21 3 2
                  30 1 3
                  31 2 3
                  33 3 3
                  end
                  
                  reml_band y x id
                  scalar band_ll = r(ll)
                  mixed y x || id:, reml variance
                  assert abs(band_ll - e(ll)) < 1e-7
                  For your own data, run reml_band with the outcome, covariate and group ID in that order. The command accepts if and in and uses complete observations. It returns the two variances and the log likelihood in r(su2), r(se2) and r(ll).

                  Best wishes,

                  Comment


                  • #39
                    Thanks Choonjoo Lee All worked. Great stuff.

                    Comment

                    Working...
                    X