Announcement

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

  • #16
    That's fantastic Choonjoo Lee. I went down the pathway of trying to get rank(K) and rank(P) to be equal and tried a constrained ginv. Copilot suggested using pinv as it has these constraints built in. Unfortunately that didn't work as the rank(K) can be lost before the inverse(KVK) is constructed. So the next suggestion was to simply use a constrained inverse on M, so that rank(M) = rank(P). That did work with the pinv. rankpinv.do

    Comment


    • #17
      Hi Matt Piercy ,

      This construction does give the usual REML P when X has full column rank and V is positive definite:

      Code:
      M = I(n)-X*invsym(X'*X)*X'
      A = M*V*M
      G = pinv(A)
      P = M*G*M
      The important change is that M retains the whole n-p-dimensional contrast space. With the earlier rank-deficient K, a required direction had already been discarded, and pinv(K'VK) could not restore it. Here pinv handles the null directions associated with X while retaining the full residual space. In exact arithmetic, G itself equals the usual P.

      I would describe pinv as the Moore-Penrose pseudoinverse rather than a constraint that forces a chosen rank. In pinv(A,r), r is the numerical rank returned by the function, not an imposed target rank.

      Your V=10*I(n) example is a useful check; in that case P=M/10. I also checked the construction with nontrivial random-intercept, general positive-definite, and heterogeneous diagonal covariance matrices, comparing P element by element with the standard V/X expression. The checks agreed to numerical precision.

      Using this P in your existing likelihood expression also gave the same REML solution for both orders of your nine observations, agreeing with mixed, reml to numerical tolerance. The restricted log likelihood was approximately -17.400591123.

      This therefore provides another non-QR route. Its computational cost is a separate question, since it forms full n-by-n matrices and uses an SVD-based pseudoinverse.

      Reference: Mata pinv().

      Comment


      • #18
        I'm not sure the pinv is the correct way. That is just what copilot tried to get me to do. In fact Rao has an algebraic expression for the Ginv in this table. I think the fifth one should work in this case.
        Click image for larger version

Name:	constrained inverse.png
Views:	1
Size:	203.0 KB
ID:	1787988

        Comment


        • #19
          try this rankrao.do

          Comment


          • #20
            Apparently this still needs a pinv/ginv

            Comment


            • #21
              Thanks, Matt Piercy . Yes, the fifth expression in the table still contains an inner g-inverse. Your V=10I example works because M/10 is the correct inverse on the residual space.

              There is also a way to avoid both pinv() and QR decomposition. Rao and Mitra's Theorem 4.9, equation (4.13), gives a regular-inverse representation. A symmetric completion using the same principle is:

              Code:
              H = X(X'X)^(-1)X'
              M = I-H
              B = MVM+H
              P = M B^(-1) M
              Here X must have full column rank and V must be positive definite. B is then positive definite: it retains MVM on the residual space and supplies the identity on the removed fixed-effect space. Thus we invert B, rather than the singular MVM. This does not require choosing rows or imposing a numerical target rank.

              For REML, we can go further and avoid constructing P or an explicit inverse of B. If B=LL' and r=My, the quadratic term is (L^(-1)r)'(L^(-1)r). The determinant identity is also needed:

              Code:
              log|V| + log|X'V^(-1)X| = log|B| + log|X'X|.
              Consequently, one Cholesky decomposition supplies both parts of the likelihood. The following complete example uses only built-in Stata/Mata facilities, tested in Stata/MP 16.1. It replaces the data in memory, so save your current data first.

              Code:
              version 16.1
              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 completed_data {
                  real matrix U,M,H
                  real colvector r
                  real scalar c
              }
              
              void completed_reml(real scalar todo, real rowvector b,
                  struct completed_data scalar D, real scalar value,
                  real rowvector gradient, real matrix Hessian)
              {
                  real matrix L
                  real colvector z
                  real rowvector v
                  v=exp(b)
                  if (hasmissing(v) | any(v:<=0)) {
                      value=.
                      return
                  }
                  L=cholesky(v[1]*D.U+v[2]*D.M+D.H)
                  if (hasmissing(L)) {
                      value=.
                      return
                  }
                  z=solvelower(L,D.r)
                  value=.5*(D.c+2*sum(ln(diagonal(L)))+quadcross(z,z))
              }
              
              void completed_run()
              {
              struct completed_data scalar D
              real colvector y,id,levels
              real matrix X,Z,Sxx,F
              real rowvector b
              real scalar n,p,j
              transmorphic S
              y=st_data(.,"y")
              X=(J(rows(y),1,1),st_data(.,"x"))
              id=st_data(.,"id")
              n=rows(X)
              p=cols(X)
              assert(n>p & rank(X)==p & !hasmissing((y,X,id)))
              levels=uniqrows(sort(id,1))
              Z=J(n,rows(levels),0)
              for (j=1;j<=rows(levels);j++) {
                  Z[,j]=(id:==levels[j])
              }
              Sxx=quadcross(X,X)
              D.H=X*cholinv(Sxx)*X'
              D.M=I(n)-D.H
              F=D.M*Z
              D.U=F*F'
              D.r=D.M*y
              D.c=(n-p)*ln(2*pi())+2*sum(ln(diagonal(cholesky(Sxx))))
              
              S=optimize_init()
              optimize_init_evaluator(S,&completed_reml())
              optimize_init_evaluatortype(S,"d0")
              optimize_init_argument(S,1,D)
              optimize_init_params(S,ln((10,1)))
              optimize_init_which(S,"min")
              optimize_init_conv_ptol(S,1e-10)
              optimize_init_conv_vtol(S,1e-12)
              optimize_init_conv_maxiter(S,200)
              optimize_init_tracelevel(S,"none")
              b=optimize(S)
              assert(optimize_result_converged(S))
              st_numscalar("completed_su2",exp(b[1]))
              st_numscalar("completed_se2",exp(b[2]))
              st_numscalar("completed_ll",-optimize_result_value(S))
              }
              completed_run()
              end
              
              display "Completed-B: su2=" %12.6f completed_su2 ///
                  "  se2=" %10.6f completed_se2 "  REML ll=" %12.6f completed_ll
              mixed y x || id:, reml variance
              assert abs(completed_su2-exp(2*_b[lns1_1_1:_cons]))<1e-3
              assert abs(completed_se2-exp(2*_b[lnsig_e:_cons]))<1e-5
              assert abs(completed_ll-e(ll))<1e-7
              display "COMPLETED_COVARIANCE_STANDALONE_EXAMPLE_PASSED"
              The completed-B result is:

              Code:
              su2 = 103.070392
              se2 =   0.900000
              REML log likelihood = -17.400591
              The assertions compare these results with mixed. I also checked the last-two-row permutation and an unbalanced example with two covariates; all three likelihood implementations (pinv, completed B, and the standard V/X expression) agreed with mixed. Across 20 generated designs and five variance pairs per design, the largest absolute likelihood difference from the standard inverse-based expression was about 9.4e-13. These are numerical equivalence checks, not a simulation of statistical coverage.

              For a small timing check, these were median milliseconds per complete likelihood evaluation, using one processor and three batches after calibration:

              Code:
              Observations   pinv + V/X determinants   Completed B   Standard V/X
                     9                  0.0139             0.0071          0.0135
                   100                  1.492              0.133           0.150
                   300                 36.125              2.109           2.109
                  1000               1295.000             84.750          85.500
              These compare complete dense likelihood paths, not isolated pinv-versus-Cholesky calls: the pinv route also calculates the usual V/X determinant terms, while completed B uses the determinant identity above. Common data preparation is excluded. The standard V/X route also uses Cholesky and triangular solves, not explicit matrix inversion. The two Cholesky routes were very similar at larger n; this is an alternative formulation, not a claim that completed B is generally fastest or faster than mixed. For the separate 103-observation unbalanced example, median optimization times were 0.103, 0.009 and 0.011 seconds respectively, excluding common preparation.

              This remains a dense n-by-n implementation for learning and checking the equations. It does not eliminate numerical conditioning problems; poorly scaled or nearly collinear X and variance parameters near the boundary need further care. The log-variance parametrization here searches strictly positive variances and does not implement a separate zero-variance boundary fit. Exploiting the random-intercept block structure would be the next step for larger data.

              Rao and Mitra, Theorem 4.9, p. 610:
              https://digicoll.lib.berkeley.edu/re...article-32.pdf
              Mata's triangular solves:
              https://www.stata.com/manuals/m-5solvelower.pdf

              Comment


              • #22
                Thanks again Choonjoo Lee. That's what I was trying to do with a lot less skill. I presume from what you are saying Stata does something very similar. Nice.

                Comment


                • #23
                  Choonjoo Lee. I just worked through you proof properly. It is very elegant and is different enough from Stata's technique to be novel. I know all the other bells and whistles aren't there, but would it be worth an email to someone on their development team?

                  Comment


                  • #24
                    Thanks, Matt. I have enjoyed working through this with you. I think continuing this investigation, while considering the existing literature and carefully assessing what the approach adds, could lead to a worthwhile contribution.

                    I hope our discussion and examples provide a useful starting point for that work. I’ll step back at this point and leave the further exploration in your hands. Best wishes with your research.

                    Comment


                    • #25
                      Just checking my understanding of your workings from Rao's formula to the REML P you gave. REML P is actually the same as T, the constrained inverse of A (which is a Ginv) or the constrained inverse of B (which is a regular inverse). It gets a bit confusing because Rao uses P in his formulas for projection matrix.
                      Click image for larger version

Name:	RaoBinv.png
Views:	1
Size:	388.4 KB
ID:	1788011

                      Comment


                      • #26
                        Thanks, Matt Piercy . Yes, the REML matrix corresponds to T. To separate the notation, let P_R denote the REML matrix and set H=X(X'X)^(-1)X', with full-rank X and positive-definite V. In the theorem you quoted, use:

                        Code:
                        Rao's projection P  -> M = I-H
                        Rao's matrix A      -> A0 = MVM
                        Rao's T             -> P_R
                        Since A0*M=A0, Rao's expression becomes

                        Code:
                        T = M(A0*M+I-M)^(-1) = M B^(-1) = M B^(-1) M = P_R,
                        where B = A0+H.
                        The distinction is that T is not the ordinary inverse of B itself:

                        Code:
                        B^(-1) = P_R+H.
                        B^(-1) retains the fixed-effect space; multiplying by M removes it. Thus we use an ordinary inverse to calculate the constrained inverse, but the two matrices are different. Here A0 denotes MVM, not V.

                        A two-observation illustration may help. Take X=(1,1)' and V=diag(1,4). Then:

                        Code:
                        H = ( 0.5   0.5 )       M = ( 0.5  -0.5 )
                            ( 0.5   0.5 )           (-0.5   0.5 )
                        
                        A0 = ( 1.25  -1.25 )    B = ( 1.75  -0.75 )
                             (-1.25   1.25 )        (-0.75   1.75 )
                        
                        B^(-1) = ( 0.7   0.3 )  T = P_R = ( 0.2  -0.2 )
                                 ( 0.3   0.7 )            (-0.2   0.2 )
                        Their difference is H. T has rank 1 and removes the common-mean direction, whereas B^(-1) has rank 2 and preserves it. Even though B is invertible, its inverse constrained to the residual space is M B^(-1) M, not the unrestricted B^(-1).

                        For y=(0,1)', y'Ty=0.2 but y'B^(-1)y=0.7. Using r=My restores the correct quadratic: r'B^(-1)r=0.2. This is why the previous likelihood code used r=My.

                        Here is a complete built-in Stata/Mata check, tested in Stata/MP 16.1. It only uses local Mata matrices and leaves Stata's data in memory unchanged. This is a fixed-matrix illustration, not an estimation example.

                        Code:
                        version 16.1
                        /* Matrix illustration only. Does not clear or replace Stata's data. */
                        capture mata: mata drop rao_notation_example_20261109()
                        mata:
                        void rao_notation_example_20261109()
                        {
                            real matrix X,V,H,M,A0,B,Binv,T,Pref,Trao
                            real colvector y,r
                            real scalar tolerance
                        
                            tolerance=1e-12
                            X=(1\1)
                            V=diag((1\4))
                            H=X*invsym(X'*X)*X'
                            M=I(2)-H
                            A0=M*V*M
                            B=A0+H
                            Binv=cholinv(B)
                            T=M*Binv*M
                        
                            /* Rao's projection is M; his matrix A is our A0=MVM here.
                               Since A0*M=A0, the regular matrix A0*M+I-M equals B. */
                            Trao=M*cholinv(A0*M+I(2)-M)
                            Pref=invsym(V)-invsym(V)*X*invsym(X'*invsym(V)*X)*X'*invsym(V)
                        
                            assert(max(abs(T-Trao))<tolerance)
                            assert(max(abs(T-Pref))<tolerance)
                            assert(max(abs(T-pinv(A0)))<tolerance)
                            assert(max(abs(Binv-T-H))<tolerance)
                            assert(max(abs(A0*T*A0-A0))<tolerance)
                            assert(max(abs(B*T*B-B))>.1)
                            assert(rank(T)==1 & rank(Binv)==2)
                            assert(max(abs(T*X))<tolerance)
                            assert(max(abs(Binv*X-X))<tolerance)
                        
                            printf("X=(1,1)' ; V=diag(1,4)\n")
                            printf("H\n"); H
                            printf("M=I-H\n"); M
                            printf("A0=MVM\n"); A0
                            printf("B=A0+H\n"); B
                            printf("Ordinary inverse of B\n"); Binv
                            printf("T = P_REML = M*inverse(B)*M\n"); T
                            printf("rank(T)=%g; rank(inverse(B))=%g\n",rank(T),rank(Binv))
                            printf("max|inverse(B)-T-H|=%12.5g\n",max(abs(Binv-T-H)))
                        
                            y=(0\1)
                            r=M*y
                            assert(abs(quadcross(y,T*y)-.2)<tolerance)
                            assert(abs(quadcross(y,Binv*y)-.7)<tolerance)
                            assert(abs(quadcross(r,Binv*r)-quadcross(y,T*y))<tolerance)
                            printf("For y=(0,1)': y'Ty=%4.1f; y'inverse(B)y=%4.1f; r'inverse(B)r=%4.1f\n",
                                quadcross(y,T*y),quadcross(y,Binv*y),quadcross(r,Binv*r))
                            printf("RAO_NOTATION_AND_TWO_OBSERVATION_EXAMPLE_PASSED\n")
                        }
                        rao_notation_example_20261109()
                        end
                        All assertions passed. In particular, the example checks the standard REML P, Rao's substituted expression, pinv(A0), and B^(-1)=T+H. The superscript minus in the book denotes a generalized inverse; minus one denotes an ordinary inverse.

                        Comment


                        • #27
                          Cool thanks Choonjoo Lee. Yes I also thought M was P in Rao's case. Cheers, Matt

                          Comment


                          • #28
                            Hi! Matt Piercy
                            A small follow-up that may help with further testing: algebraic equivalence, numerical accuracy and computational cost are separate questions.

                            I checked seven implementations on a deliberately difficult grid: 24 observations, six unbalanced groups, seven covariate/response designs and seven variance pairs. An independent calculation using Python's standard-library Decimal arithmetic agreed at 70 and 100 digits. Comparing with that reference showed that forming the projector through X'X can fail under poor scaling or near collinearity. Centering/scaling and thin QR improved the results, although none of the implementations met the chosen error threshold on every extreme case. Very fast cached-moment formulas also suffered from subtractive cancellation.

                            For the random-intercept model, separating within-group deviations and group means allows the within part to be compressed once by QR. Later variance evaluations use the compressed factor and group means, without constructing an n-by-n covariance matrix. At n=1,000, median cached evaluation times were about 80 ms for dense completion, 1,204 ms for the pinv route and 0.013 ms for compressed group QR. At n=1,000,000 with 100,000 groups, group QR took about 9.44 ms per evaluation after 5.23 seconds of preparation.

                            These are implementation-specific timings, excluding preparation from the per-evaluation figures, not a comparison with mixed or a general ranking. All seven implementations agreed with mixed on a separate, well-conditioned 143-observation unbalanced example. The QR implementations can serve as reference comparisons even if your main interest remains a non-QR formulation.

                            There is also an exact scaling variant of the completion. For any positive tau, with H=I-M and full-rank X,

                            Code:
                            B_tau = MVM + tau*H
                            P_R = M B_tau^(-1) M
                            log|V| + log|X'V^(-1)X| = log|B_tau| - p*log(tau) + log|X'X|.
                            For V=su2*ZZ'+se2*I, choosing tau=se2 gives B_tau=su2*MZZ'M+se2*I. This removes the arbitrary unit scale on the fixed-effect space while preserving the exact REML target. It is not ridge regularization. It improved common covariance-scale stress cases here, but did not remove all difficulties with extreme variance ratios or near collinearity. The -p*log(tau) term must be retained, including when tau varies during optimization.

                            Here is a self-contained illustration of the compressed group calculation using only built-in Stata/Mata facilities. The functions use thin Householder QR; they do not construct a full Q matrix. The example replaces the data in memory, so save your current data first. It was tested in Stata/MP 16.1.

                            Code:
                            version 16.1
                            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 cg_data {
                                real matrix Rw,between
                                real colvector count
                                real scalar p,c,adjust
                            }
                            void cg_objective(real scalar todo, real rowvector b, struct cg_data scalar D,
                                real scalar value, real rowvector gradient, real matrix Hessian)
                            {
                                real rowvector v,tau
                                real matrix W,F,R
                                real colvector w,z
                                real scalar ldv,lds,q
                                v=exp(b)
                                if(hasmissing(v) | any(v:<=0)) {
                                    value=.; return
                                }
                                w=1:/sqrt(v[2]:+D.count*v[1])
                                W=(D.Rw/sqrt(v[2]) \ D.between:*(w*J(1,D.p+1,1)))
                                hqrd(W[,1..D.p],F,tau,R)
                                if(hasmissing(R) | any(abs(diagonal(R)):<=0)) {
                                    value=.; return
                                }
                                z=hqrdmultq(F,tau,W[,D.p+1],1)
                                q=quadcross(z[D.p+1..rows(z)],z[D.p+1..rows(z)])
                                lds=2*sum(ln(abs(diagonal(R))))
                                ldv=sum((D.count:-1)*ln(v[2])+ln(v[2]:+D.count*v[1]))
                                value=.5*(D.c+D.adjust+ldv+lds+q)
                            }
                            void cg_run()
                            {
                                struct cg_data scalar D
                                real colvector y,id,o
                                real matrix X,W,within,info,F,R
                                real rowvector mu,tau,b
                                real scalar n,g,j,k,m,sc
                                transmorphic S
                                y=st_data(.,"y"); X=(J(rows(y),1,1),st_data(.,"x")); id=st_data(.,"id")
                                n=rows(y); D.p=cols(X); D.c=(n-D.p)*ln(2*pi()); D.adjust=0
                                for(j=2;j<=D.p;j++) {
                                    X[,j]=X[,j]:-mean(X[,j]); sc=sqrt(quadcross(X[,j],X[,j])/n)
                                    assert(sc>0 & sc<.); X[,j]=X[,j]/sc; D.adjust=D.adjust+2*ln(sc)
                                }
                                o=order(id,1); W=(X,y); W=W[o,.]; info=panelsetup(id[o],1)
                                D.count=info[,2]-info[,1]:+1; g=rows(info)
                                within=J(n,D.p+1,.); D.between=J(g,D.p+1,.)
                                for(k=1;k<=g;k++) {
                                    j=info[k,1]; m=D.count[k]; mu=mean(W[j..j+m-1,.])
                                    within[j..j+m-1,.]=W[j..j+m-1,.]-J(m,1,1)*mu
                                    D.between[k,.]=sqrt(m)*mu
                                }
                                hqrd(within,F,tau,R); D.Rw=R
                                S=optimize_init(); optimize_init_evaluator(S,&cg_objective())
                                optimize_init_evaluatortype(S,"d0"); optimize_init_argument(S,1,D)
                                optimize_init_params(S,ln((10,1))); optimize_init_which(S,"min")
                                optimize_init_tracelevel(S,"none"); optimize_init_conv_maxiter(S,200)
                                optimize_init_conv_ptol(S,1e-10); optimize_init_conv_vtol(S,1e-12)
                                b=optimize(S); assert(optimize_result_converged(S))
                                st_numscalar("cg_su2",exp(b[1])); st_numscalar("cg_se2",exp(b[2]))
                                st_numscalar("cg_ll",-optimize_result_value(S))
                            }
                            cg_run()
                            end
                            display "Group QR: su2=" %12.6f cg_su2 " se2=" %10.6f cg_se2 " ll=" %12.6f cg_ll
                            mixed y x || id:, reml variance
                            assert abs(cg_su2-exp(2*_b[lns1_1_1:_cons]))<1e-3
                            assert abs(cg_se2-exp(2*_b[lnsig_e:_cons]))<1e-5
                            assert abs(cg_ll-e(ll))<1e-7
                            display "STANDALONE_COMPRESSED_GROUP_QR_AND_MIXED_PASSED"
                            The example gives su2 approximately 103.070392, se2 approximately 0.900000 and REML log likelihood approximately -17.400591, agreeing with mixed. It illustrates the random-intercept covariance only; arbitrary covariance structures require a different structural treatment. The exp() parametrization searches strictly positive variances and does not implement a separate zero-variance boundary fit.

                            Useful next comparisons would retain independent reference values, record failures rather than dropping them, report preparation and repeated-evaluation costs separately, and vary the number of groups as well as n. The stress grid above is not a probability sample and its threshold counts are not estimates of a general success rate or confidence-interval coverage.
                            Click image for larger version

Name:	cost.png
Views:	1
Size:	179.2 KB
ID:	1788023

                            Click image for larger version

Name:	conditioning.png
Views:	1
Size:	203.5 KB
ID:	1788024



                            Matt, I ran the code successfully on my machine. I’m sharing these preliminary comparisons and figures in case they help you identify useful directions for further investigation. They illustrate differences in numerical accuracy and computational cost across equivalent REML implementations, rather than establish novelty or an advantage over mixed.

                            The code corresponding to the graph is as follows.
                            Code:
                            version 16.1
                            clear all
                            set more off
                            set scheme s2color
                            import delimited using results/timing_summary.csv, clear
                            twoway (connected median_ms n if method==1, msymbol(O)) ///
                                (connected median_ms n if method==3, msymbol(T)) ///
                                (connected median_ms n if method==4, msymbol(D)) ///
                                (connected median_ms n if method==6, msymbol(S)) ///
                                (connected median_ms n if method==7, msymbol(Oh)), ///
                                xscale(log) yscale(log) xlabel(100 "100" 1000 "1k" 10000 "10k" 100000 "100k" 1000000 "1M") ///
                                ylabel(.01 .1 1 10 100 1000, angle(horizontal)) ///
                                xtitle("Observations (log scale)") ytitle("Milliseconds per evaluation") ///
                                title("REML: structure changes the computational cost", size(medsmall)) ///
                                legend(order(1 "Completed B: normal equations" 2 "Dense V: thin QR" ///
                                             3 "Compressed group QR" 4 "pinv + QR projection" ///
                                             5 "Scaled completion B_se") cols(2) size(small)) ///
                                note("One processor; median of 3 batches after calibration; cached evaluation only." ///
                                     "Dense methods stop at n=1,000 or 2,000; no extrapolated timings. Both axes logarithmic.", size(vsmall)) ///
                                graphregion(color(white)) name(cost, replace)
                            graph export results/cost.png, width(1800) replace
                            graph export results/cost.svg, replace
                            import delimited using results/stress_scored.csv, clear
                            keep if point==1 & inlist(design,1,3,4,5)
                            gen double epsilon=1 if design==1
                            replace epsilon=1e-4 if design==3
                            replace epsilon=1e-8 if design==4
                            replace epsilon=1e-12 if design==5
                            gen double error=max(scaled_ll_error,1e-16)
                            replace error=. if status!=0
                            twoway (connected error epsilon if method==1, sort msymbol(O)) ///
                                (connected error epsilon if method==2, sort msymbol(S)) ///
                                (connected error epsilon if method==3, sort msymbol(T)) ///
                                (connected error epsilon if method==4, sort msymbol(D)), ///
                                xscale(log reverse range(1e-13 10)) yscale(log) ///
                                xlabel(1 "Independent" 1e-4 "1e-4" 1e-8 "1e-8" 1e-12 "1e-12") ///
                                ylabel(1e-16 1e-12 1e-8 1e-4 .1, angle(horizontal) format(%9.0g)) ///
                                xtitle("epsilon in x2=x1+epsilon*z") ///
                                ytitle("Scaled absolute log-likelihood error") ///
                                title("Near collinearity: equivalent formulas differ numerically", size(medsmall)) ///
                                legend(order(1 "Completed: normal equations" 2 "Completed: scaled X + QR" ///
                                             3 "Dense V: scaled X + QR" 4 "Compressed group QR") cols(2) size(small)) ///
                                note("24 observations, 6 unbalanced groups, variances (1,1); independent 100-digit reference." ///
                                     "Error = abs(ll - reference)/(1+abs(reference)); display floor 1e-16. Failed points omitted.", size(vsmall)) ///
                                graphregion(color(white)) name(conditioning, replace)
                            graph export results/conditioning.png, width(1800) replace
                            graph export results/conditioning.svg, replace
                            display "COST_AND_CONDITIONING_FIGURES_PASSED"
                            Mata Householder QR documentation:
                            https://www.stata.com/manuals/m-5qrd.pdf
                            Last edited by Choonjoo Lee; 09 Nov 2026, 17:27.

                            Comment


                            • #29
                              Hi @Choonjoo Lee,
                              Thanks for your extra work. Great job. It looks like Stata's approach wins in terms of speed and accuracy. Probably not that surprising. They all seem very accurate and work, though, which is the interesting part for me. Despite the different approaches.
                              Cheers,
                              Matt

                              Comment


                              • #30
                                Thanks, Matt. Yes, the agreement in the well-conditioned examples is a useful check on the equivalence of the formulations.

                                One small clarification: the timing comparisons were between the demonstration implementations; mixed was used to check the estimates, rather than benchmark its speed. The stress tests also showed why numerical conditioning matters.

                                I’m glad the examples were useful. Best wishes with your further work.

                                Comment

                                Working...
                                X