Announcement

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

  • DEA for 9040 firms

    Hi all, I am trying to do DEA (Data Envelopment Analysis) for 9040 firms with 5 inputs and 2 outputs. STATA seems to hang when I run this model after matsize is set to maximum. Is there any other quick and efficient way to do this? I just need the efficiency score (or relative efficiency) out of the analysis.
    Last edited by Denila Jinny; 13 Mar 2018, 03:29.

  • #2
    You'll increase your chances of a helpful answer by following the FAQ on asking questions - provide Stata code in code delimiters, readable Stata output, and sample data using dataex.

    I have not used the DEA routine. We do ask that anyone using a user written routine identify the routine and where the individual found the routine. From your brief description, it is not clear whether there is a real problem or the routine is just taking a long time. When it hangs, is Stata using a lot of CPU? Are there other user-written Stata DEA routines that might do the job? I'd try the routine on a small subsample to make sure the number of firms is the problem. There are some ways to get rough ideas of estimation difficulty on DEA. You might try varying the sample size to see how solution time increases with sample size. Sometimes "hanging" just means you let it run overnight or over the weekend.

    Comment


    • #3
      To anyone coming across this question, I used rDEA in R to get efficiency scores. It just needed 2 mins to give me the output.

      Comment


      • #4
        How to get efficiency scores for 9,040 firms in Stata

        Yes, the public dea command can return one efficiency score per firm with five inputs and two outputs. Thank you for reporting your rDEA result. To give others a Stata example they can reproduce, I generated 9,040 firms and used all of them as the reference set for every firm. The timings below refer to these simulated data. The original data and the settings behind the reported two-minute R run would be needed to reproduce that result.

        Download and extract DEA-Stata 2.0.73. In a fresh Stata 16 or later session, set the working directory to the extracted folder containing ado. This version returns a diagnostic matrix with one row per firm, so check that c(max_matdim) is at least 9040. Run the block once for the model you want. The two local settings select any of the four specifications.
        DEA-Stata 2.0.73 on GitHub

        Code:
        adopath ++ "`c(pwd)'/ado"
        which dea
        display c(max_matdim)
        
        clear
        set rng mt64
        set seed 119
        set obs 9040
        generate long firm = _n
        foreach v in x1 x2 x3 x4 x5 y1 y2 {
            generate double `v' = 1 + 10*runiform()
        }
        
        local rts crs            // crs or vrs
        local orient input       // input or output
        quietly dea x1 x2 x3 x4 x5 = y1 y2, dmu(firm) rts(`rts') ///
            orientation(`orient') stage(1) engine(auto) generate(te)
        assert r(N) == 9040 & r(n_failed) == 0
        assert te > 0 & te <= 1 + 1e-7
        summarize te
        With your own data, start at the two local settings and substitute your identifier and variables in the dea line. Inputs go to the left of the equals sign and outputs to the right. stage(1) skips the separate slack-maximization step. The variable te contains the firm-level radial score.

        Choose CRS if the technology allows proportional scaling of inputs and outputs, or VRS if returns can vary with scale. Choose input orientation to ask how far inputs could contract at observed outputs, or output orientation to ask how far outputs could expand at observed inputs. This command stores the output-oriented score as 1/phi. For example, te = 0.80 means a possible 20% input reduction in the input model, or a 25% output expansion in the output model.

        All four runs returned 9,040 scores. The mean was 0.4466 for either orientation under CRS, 0.5721 for VRS input and 0.7129 for VRS output. On our Mac, the full-reference benchmark took about four minutes for either CRS model and about eighteen to nineteen minutes for VRS. With the same firms, variables and requested score, what accounts for that extra time?

        Comment


        • #5
          Where does the time go? Full-reference DEA in Stata and R

          A useful starting point is to time the same firms and then check what each command computed. R read the double-precision data saved by Stata. The three commands evaluated the same 9,040 targets against the same 9,040 reference firms, in the same order. Here are elapsed seconds for one serial call per cell on an Apple M5 Pro with 48 GB RAM, using Stata/MP 16.1 and R 4.6.0. Data import, installation and writing our comparison files were outside the timers.

          Code:
          Model          Stata dea 2.0.73   Benchmarking 0.33   rDEA 1.2-8
          CRS input               243.71               19.60        34.75
          CRS output              240.94               19.81        32.44
          VRS input             1,145.02               25.49        41.90
          VRS output            1,083.75               23.80        40.60
          For output orientation we took the reciprocal of the expansion factor returned by Benchmarking. Stata's te and rDEA's thetaOpt already use that scale. Against Stata, all 36,160 firm/model pairs per R package agreed within 1e-7.

          What the command returns. Under VRS, dea solves the requested model and then runs CRS, VRS and non-increasing returns models to calculate scale efficiency and classify returns to scale. That makes four scheduled radial evaluations per firm. The R calls requested one model each. In a separate Stata VRS output run, the profiler attributed 771 of 1,072 seconds (72%) to the scale decomposition. If both the score and the decomposition are needed, one opportunity is to reuse the main VRS score in the decomposition.
          Stata source for the VRS decomposition

          How the linear programs are solved. Stata selected the package's two-phase revised simplex in Mata. Its public source makes the LP construction, pivot selection, basis updates and recovery steps available for teaching and diagnosis. Mata compiles to bytecode. Benchmarking updates one LP object from R and calls the compiled lp_solve solver. We used FAST=TRUE for scores. rDEA sends a batch to C, where it reloads each firm's problem and calls GLPK. It also returns peer weights. Reusing the unchanged reference matrix and updating only the target coefficients is one concrete optimization to test in Mata. These timings combine model construction, solver work and returned results. Isolating a Stata/Mata engine effect would require timing the same LP formulation and outputs while changing just the backend.
          Mata per-firm solve loop
          Benchmarking LP setup and updates
          rDEA's C loop and GLPK calls

          What parallel workers can save. We split the VRS output targets into two groups of 4,520 and gave each worker all 9,040 references. On macOS, the same two blocks took 24.05 seconds sequentially and 12.60 seconds with two external R workers for Benchmarking (1.91x). For rDEA the corresponding times were 40.95 and 24.04 seconds (1.70x). Within each package the sequential and parallel two-block scores matched. The ordinary Stata and R calls in the table processed firms sequentially. Splitting the reference firms as well as the targets would change the frontier.

          What a smaller reference set can save. BuildHull first identifies a subset of firms that generates the frontier. Every firm can then be scored against that common subset. This reduces the number of reference weights in each LP. The cost of finding and checking the subset has to be included in the timing.
          Dulá (2011), An Algorithm for Data Envelopment Analysis

          For someone who needs only the efficiency scores, can we keep the Stata/Mata solver, use one worker, and bring the total time close to the R calls while reproducing every firm's full-reference score?

          Comment


          • #6
            Dear Denila Jinny
            From 9,040 reference firms to 639: reproducing the scores with sdea

            On these data, yes. With the public sdea 5.8.0 command in Stata, the VRS output model scored all 9,040 firms in about 23 seconds using one worker. A dominance check first reduced the reference candidates to 1,424. The default modified BuildHull procedure and coverage check left 639 reference firms. Each of the 9,040 firms was then evaluated against those same 639 firms using the revised simplex in Mata. The count of retained references can differ from the number of firms with an efficiency score of one.
            sdea for Stata — source, installation and examples

            To reproduce the run in Stata 16 or later, extract the sdea ZIP. Inside that folder, extract the DEA-Stata ZIP so its top-level directory sits beside load.do. Start a fresh Stata session in the folder containing load.do. The data generator uses five inputs, two outputs and seed 119, as in the full-reference example.
            Download the tested sdea 5.8.0 snapshot
            Download the required DEA-Stata 2.0.73 solver

            Code:
            do load.do
            do examples/generate_9040.do
            
            sdea y1 y2, inputs(x1 x2 x3 x4 x5) dmu(firm) method(standard) ///
                refset(buildhull) rts(vrs) orientation(output) generate(te isref drift)
            display "Firms scored: " r(N) "   Reference firms: " r(N_frame)
            assert te > 0 & te <= 1
            generate double phi = 1/te
            list firm te phi if firm == 9040, noobs
            For firm 9,040, te was 0.7215 and phi was 1.3861. At its observed inputs, the estimated frontier allows both outputs to expand proportionally by about 38.6%. The variable isref identifies a retained reference firm. Use method(standard) refset(buildhull) for this final cross-sectional score. The separate streaming method(buildhull) reports hull distance as observations arrive.

            We timed the whole sdea call twice on the same Mac, rebuilding the reference set each time. The last column is the largest absolute difference from the corresponding full-reference dea score across the 9,040 firms.

            Code:
            Model         Run 1 (s)   Run 2 (s)   Max. score difference
            CRS input        22.578      22.366                8.88e-16
            CRS output       21.914      21.829                6.66e-16
            VRS input        25.886      25.718                1.09e-11
            VRS output       23.110      23.115                1.14e-13
            All four models reproduced the full-reference scores within 1e-7, with zero full-reference retries. For CRS input, where the public dea call also skips the VRS scale decomposition, the elapsed time fell from 243.71 seconds to about 22.5 seconds. For VRS output, the corresponding serial R calls took 23.80 seconds with Benchmarking and 40.60 seconds with rDEA. The sdea timings cover reference-set construction, coverage checks and radial scoring. The 1,083.75-second public dea call also produced scale efficiency and returns-to-scale classifications. For another dataset, the gain will depend on how many reference firms the frontier requires.

            To check all four models on your own installation, run the benchmark from the same sdea folder. It regenerates the sample and compares every firm's score against the full-reference scores supplied with the repository.

            Code:
            do tests/benchmark_9040.do
            Last edited by Choonjoo Lee; Yesterday, 17:49.

            Comment


            • #7
              Scoring 9,040 firms with two Stata workers: same efficiency scores in 40.6% less time

              In my previous post, BuildHull reduced the reference set from 9,040 firms to 639. I repeated the VRS output-oriented analysis to see whether two Stata workers could shorten the remaining calculation. The median time for the whole call fell from 23.51 to 13.97 seconds. Every firm received exactly the same efficiency score as in the single-worker sdea calculation.

              I used the same 9,040 simulated firms, five inputs and two outputs. Each run built and checked the frontier once. The two workers then took 4,520 target firms each and evaluated them against the same 639 reference firms. Both used the Mata scoring function from sdea 5.8.0. An experimental Python script launched the Stata processes and collected their results. Each Stata process used one processor.
              Public sdea 5.8.0 source used for the benchmark

              I ran each configuration four times on an Apple M5 Pro with Stata/MP 16.1. The table gives median elapsed seconds. The two-worker times include startup of both workers, data transfer and collection of scores. The whole-call times also include constructing and checking the reference set.

              Code:
              VRS output                      One worker   Two workers   Speedup
              Final scoring stage (s)              19.68         10.12     1.94x
              Whole sdea call (s)                  23.51         13.97     1.68x
              I compared the scores firm by firm against both earlier calculations. Across all 9,040 firms, the largest absolute difference from the public single-worker sdea result was exactly 0. Compared with the original dea calculation using all 9,040 firms as references, the largest absolute difference was 1.14e-13, well within the 1e-7 tolerance. All eight runs retained the same 639 reference firms and completed without a full-reference retry.

              To repeat the experiment on macOS, use Stata/MP and Python 3.8 or later. Download both snapshots below and extract them into the same folder, keeping the two directory names supplied by GitHub. Save the Python block at the end of this post as benchmark.py beside those two directories. It contains the Stata and Mata routines used in the experiment.
              Download the tested sdea snapshot
              Download the tested DEA-Stata solver

              In Stata, change the working directory to the folder containing benchmark.py. Run the following line in the Command window or a do-file. Python starts the batch jobs, and each Stata worker solves its assigned firms' LPs in Mata. The benchmark uses its own simulated data and writes the timing results to a CSV. Your current Stata data stay in memory.

              Code:
              shell python3 benchmark.py
              You can also run python3 benchmark.py in a terminal from the same folder.

              The script looks for stata-mp on your PATH and then in the standard macOS Stata installation. For a custom installation, use the optional --stata argument to specify the executable. The script writes parallel_timings.csv beside benchmark.py. Each of its eight rows gives the total time, scoring time, and maximum firm-level differences from the public sdea and full-reference dea results.

              Code:
              """Reproduce the static VRS/output two-worker experiment using Stata/MP."""
              import argparse
              import hashlib
              import os
              import shlex
              import shutil
              import subprocess
              import sys
              import tempfile
              from concurrent.futures import ThreadPoolExecutor
              from pathlib import Path
              
              HERE = Path(__file__).resolve().parent
              SDEA_REVISION = "834e4073bd7a7e1db219a24b74b2a2481ad14606"
              REVISION = "ad77287466b22c3edd1ae3cc074981225c95d424"
              SDEA_HASH = "46ef7d1a63e12f8786f50ff97a4027ce77ad7af096a7f9d9662145065f6f5cb0"
              
              
              MATA_DISPATCH = r"""// Inserted into a temporary copy of the pinned sdea source, before its evaluator.
              void bench_dispatch(real matrix X, real matrix Y, real matrix rawX, real matrix rawY,
                  real colvector fr, string scalar ort, string scalar rts,
                  real colvector scores, real scalar retries)
              {
                  real scalar f, i, n, workers
                  real colvector ids, seen
                  real matrix result
                  string scalar dir
                  workers = st_numscalar("bench_workers")
                  dir = pwd()
                  unlink("inputs.bin")
                  f = fopen("inputs.bin","w")
                  fputmatrix(f,X)
                  fputmatrix(f,Y)
                  fputmatrix(f,rawX)
                  fputmatrix(f,rawY)
                  fputmatrix(f,fr)
                  fputmatrix(f,(ort,rts))
                  fclose(f)
                  unlink("workers.ok")
                  stata("shell ./dispatch " + strofreal(workers))
                  if (!fileexists("workers.ok")) _error(498,"worker run failed")
                  n = rows(X)
                  seen = J(n,1,0)
                  scores = J(n,1,.)
                  retries = 0
                  for (i=1; i<=workers; i++) {
                      f = fopen(dir+"/worker"+strofreal(i)+"/result.bin","r")
                      result = fgetmatrix(f)
                      retries = retries + fgetmatrix(f)
                      fclose(f)
                      ids = result[,1]
                      if (min(ids)<1 | max(ids)>n | rows(uniqrows(sort(ids,1)))!=rows(ids)) _error(459)
                      if (any(seen[ids]) | hasmissing(result)) _error(459)
                      seen[ids] = J(rows(ids),1,1)
                      scores[ids] = result[,2]
                  }
                  if (!all(seen)) _error(459)
              }
              """
              
              STATA_WORKER = r"""version 16
              args worker workers
              set processors 1
              adopath ++ "../core"
              quietly run "../stock.ado"
              
              mata:
              void bench_work(real scalar worker, real scalar workers)
              {
                  real scalar f, k, j, retries
                  real matrix X, Y, rawX, rawY, FX, FY, origFX, origFY
                  real colvector fr, ids, scores
                  string rowvector model
                  f = fopen("../inputs.bin","r")
                  X = fgetmatrix(f)
                  Y = fgetmatrix(f)
                  rawX = fgetmatrix(f)
                  rawY = fgetmatrix(f)
                  fr = fgetmatrix(f)
                  model = fgetmatrix(f)
                  fclose(f)
                  FX = X[fr,.]
                  FY = Y[fr,.]
                  origFX = rawX[fr,.]
                  origFY = rawY[fr,.]
                  ids = (floor((worker-1)*rows(X)/workers)+1)::floor(worker*rows(X)/workers)
                  scores = J(rows(ids),1,.)
                  retries = 0
                  for (j=1; j<=rows(ids); j++) {
                      k = ids[j]
                      scores[j] = _sdea_static_score(FX,FY,origFX,origFY,X[k,.],Y[k,.],rawX[k,.],rawY[k,.],model[1],model[2])
                      if (missing(scores[j])) {
                          retries++
                          scores[j] = _sdea_static_score(X,Y,rawX,rawY,X[k,.],Y[k,.],rawX[k,.],rawY[k,.],model[1],model[2])
                          if (missing(scores[j])) _error(430)
                      }
                  }
                  f = fopen("result.bin","w")
                  fputmatrix(f,(ids,scores))
                  fputmatrix(f,retries)
                  fclose(f)
              }
              end
              mata: bench_work(strtoreal(st_local("worker")),strtoreal(st_local("workers")))
              display "WORKER COMPLETE"
              """
              
              STATA_BENCHMARK = r"""version 16
              set more off
              set processors 1
              adopath ++ "./core"
              quietly run "stock.ado"
              quietly do generate_9040.do
              quietly sdea y1 y2, inputs(x1 x2 x3 x4 x5) dmu(firm) method(standard) ///
                  refset(buildhull) rts(vrs) orientation(output) generate(stockte stockref stockdrift)
              assert r(N)==9040 & r(N_frame)==639
              isid firm
              preserve
              quietly import delimited using "full_dea_9040.csv", clear asdouble
              keep firm vrs_out
              tempfile baseline
              quietly save `baseline'
              restore
              quietly merge 1:1 firm using `baseline', assert(match) nogen
              assert firm==_n & abs(stockte-vrs_out)<1e-7
              clear programs
              mata: mata clear
              quietly run "bench.ado"
              tempname results
              file open `results' using "timings.csv", write text replace
              file write `results' "run,workers,total_s,scoring_s,n,refs,retries,max_diff_stock,max_diff_full" _n
              local run = 0
              foreach w in 1 2 2 1 2 1 1 2 {
                  local ++run
                  scalar bench_workers = `w'
                  timer clear
                  timer on 1
                  quietly sdea y1 y2, inputs(x1 x2 x3 x4 x5) dmu(firm) method(standard) ///
                      refset(buildhull) rts(vrs) orientation(output) generate(te isref drift)
                  timer off 1
                  local retries = r(N_full_retry)
                  local refs = r(N_frame)
                  local n = r(N)
                  assert `n'==9040 & `refs'==639 & `retries'==0
                  assert te>0 & te<=1 & isref==stockref & drift==stockdrift
                  quietly generate double diff = abs(te-stockte)
                  quietly summarize diff, meanonly
                  local ds = r(max)
                  quietly replace diff = abs(te-vrs_out)
                  quietly summarize diff, meanonly
                  local df = r(max)
                  assert max(`ds',`df')<=1e-7
                  quietly timer list
                  file write `results' "`run',`w'," (r(t1)) "," (r(t2)) ",`n',`refs',`retries',`ds',`df'" _n
                  drop te isref drift diff
              }
              file close `results'
              display "BENCHMARK COMPLETE"
              """
              
              
              def run_stata(directory, dofile, arguments, marker):
                  command = [os.environ["BENCH_STATA"], "-b", "do", dofile, *arguments]
                  subprocess.run(command, cwd=directory, check=True)
                  log = (directory / (Path(dofile).stem + ".log")).read_text(errors="replace")
                  if marker not in log.splitlines():
                      raise RuntimeError("\n".join(log.splitlines()[-18:]))
              
              
              def dispatch(count):
                  root = Path.cwd()
              
                  def score(i):
                      directory = root / f"worker{i}"
                      (directory / "result.bin").unlink(missing_ok=True)
                      run_stata(directory, "worker.do", [str(i), str(count)], "WORKER COMPLETE")
              
                  with ThreadPoolExecutor(max_workers=count) as pool:
                      list(pool.map(score, range(1, count + 1)))
                  (root / "workers.ok").touch()
              
              
              def prepare(work, package, core):
                  source = (package / "ado/sdea.ado").read_bytes()
                  if hashlib.sha256(source).hexdigest() != SDEA_HASH:
                      raise ValueError("Use the sdea 5.8.0 snapshot linked in this post.")
                  (work / "stock.ado").write_bytes(source)
                  text = source.decode()
                  entry = "real rowvector _sdea_static_evaluate("
                  begin = "    scores = J(rows(X),1,.)"
                  end = "    st_store(.,member,keep)"
                  assert all(text.count(anchor) == 1 for anchor in (entry, begin, end))
                  text = text.replace(entry, MATA_DISPATCH + "\n" + entry)
                  start, stop = text.index(begin), text.index(end)
                  sequential = text[start:stop]
                  text = (text[:start] + '    stata("timer on 2")\n'
                          '    if (st_numscalar("bench_workers")==1) {\n' + sequential +
                          '    }\n    else bench_dispatch(X,Y,rawX,rawY,fr,ort,rts,scores,retries)\n'
                          '    stata("timer off 2")\n' + text[stop:])
                  (work / "bench.ado").write_text(text)
                  (work / "core").mkdir()
                  for name in ("_dea_simplex", "_dea_lpcheck", "_dea_nonte_lp", "_dea_teaudit", "_dea_recovery"):
                      shutil.copyfile(core / (name + ".ado"), work / "core" / (name + ".ado"))
                  shutil.copyfile(package / "examples/generate_9040.do", work / "generate_9040.do")
                  shutil.copyfile(package / "tests/fixtures/full_dea_9040.csv", work / "full_dea_9040.csv")
                  (work / "bench.do").write_text(STATA_BENCHMARK)
                  shutil.copyfile(__file__, work / "benchmark.py")
                  launch = work / "dispatch"
                  launch.write_text("#!/bin/sh\nexec " + shlex.quote(sys.executable) + ' benchmark.py dispatch "$@"\n')
                  launch.chmod(0o700)
                  for i in range(3):
                      directory = work if i == 0 else work / f"worker{i}"
                      directory.mkdir(exist_ok=True)
                      (directory / "profile.do").write_text(
                          f'sysdir set PERSONAL "{directory}"\nsysdir set PLUS "{directory}"\nset more off\n'
                      )
                      if i:
                          (directory / "worker.do").write_text(STATA_WORKER)
              
              
              def main():
                  parser = argparse.ArgumentParser(description=__doc__)
                  parser.add_argument("--stata", help="Stata/MP executable (optional)")
                  parser.add_argument("--package", type=Path, default=HERE / ("sdea-" + SDEA_REVISION))
                  parser.add_argument("--core", type=Path, default=HERE / ("DEA-Stata-" + REVISION) / "ado")
                  parser.add_argument("--output", type=Path, default=HERE / "parallel_timings.csv")
                  args = parser.parse_args()
                  if args.stata:
                      executable = shutil.which(os.path.expanduser(args.stata))
                  else:
                      executable = shutil.which("stata-mp")
                      if not executable:
                          apps = Path("/Applications").glob("Stata*/StataMP.app/Contents/MacOS/stata-mp")
                          executable = next((app for app in sorted(apps) if os.access(app, os.X_OK)), None)
                  if not executable:
                      parser.error("Supply the Stata/MP executable with --stata.")
                  if not (args.package / "ado/sdea.ado").is_file() or not (args.core / "_dea_simplex.ado").is_file():
                      parser.error("Extract both linked GitHub ZIPs beside this script with their original folder names.")
                  os.environ["BENCH_STATA"] = str(Path(executable).resolve())
                  with tempfile.TemporaryDirectory(prefix="sdea_workers_") as temp:
                      work = Path(temp)
                      prepare(work, args.package, args.core)
                      print("Benchmark running in", work, flush=True)
                      run_stata(work, "bench.do", [], "BENCHMARK COMPLETE")
                      shutil.copyfile(work / "timings.csv", args.output)
                      print(args.output.read_text(), end="")
              
              
              if __name__ == "__main__":
                  if sys.argv[1:2] == ["dispatch"]:
                      dispatch(int(sys.argv[2]))
                  else:
                      main()

              Comment


              • #8
                Parallel DEA directly from Stata with sdea and workers(2)

                For anyone following the question about 9,040 firms, you can now run the parallel calculation directly from a Stata do-file. The public sdea command accepts workers(2) for method(standard) refset(buildhull). The earlier experiment used Python to start the workers. This version starts two Stata/MP processes through the system shell and solves every linear program in Mata. No Python installation or add-on parallel package is required.
                sdea source and installation instructions on GitHub

                I tested the following on macOS with Stata/MP 16.1. Extract the sdea snapshot, then extract the DEA-Stata solver ZIP inside it, keeping the solver directory's original name. Set Stata's working directory to the sdea folder containing load.do. Run the example in a fresh session because the data generator replaces the data in memory. The loader should report sdea 5.9.0 and dea 2.0.73.
                Download the tested sdea snapshot
                Download the required DEA-Stata solver

                Code:
                do load.do
                do examples/generate_9040.do
                
                sdea y1 y2, inputs(x1 x2 x3 x4 x5) dmu(firm) method(standard) ///
                    refset(buildhull) rts(vrs) orientation(output) workers(2) ///
                    generate(te2 ref2 drift2)
                
                display "Workers: " r(workers) "   Firms: " r(N) "   References: " r(N_frame)
                summarize te2
                Here te2 is the output-oriented radial efficiency score, stored as the reciprocal of the output expansion factor. BuildHull selected 639 reference firms from the 9,040 simulated firms. Each worker scored 4,520 target firms against all 639 references, so both groups used the same frontier.

                On an Apple M5 Pro, the whole command took 23.586 and 23.682 seconds with one worker, and 13.823 and 13.896 seconds with two. That is about 41% less elapsed time on this sample, including the time to build and check the reference set, start the workers and collect their results.
                Timing and accuracy results for all four runs

                You can check the scores firm by firm on the same data. The default is workers(1).

                Code:
                sdea y1 y2, inputs(x1 x2 x3 x4 x5) dmu(firm) method(standard) ///
                    refset(buildhull) rts(vrs) orientation(output) workers(1) ///
                    generate(te1 ref1 drift1)
                
                assert _N == 9040
                assert !missing(te1, te2) & te1 == te2
                assert ref1 == ref2
                All 9,040 efficiency scores matched the single-worker sdea results exactly, and both runs identified the same reference firms. Compared with the original dea calculation using all 9,040 firms as references, the largest absolute score difference was 1.14e-13.

                Comment


                • #9
                  How to find and interpret an individual firm's DEA efficiency score in Stata

                  If you ran the previous sdea example, the efficiency score for each firm is already in your dataset. The option generate(te2 ref2 drift2) put the score in te2, the BuildHull reference-set indicator in ref2, and the static drift flag in drift2. To look up one firm, use its identifier. For example, list firm te2 if firm == 9040 works even after you sort the data.

                  To start from scratch, download and extract sdea. Inside its folder containing load.do, extract the DEA-Stata solver ZIP, keeping the solver directory's original name. In a fresh Stata session, set the working directory to the folder containing load.do and run the four blocks below in order. The first generates 9,040 simulated firms and replaces the data in memory. The example uses two workers on macOS with Stata/MP 16.1. For a single-worker run, change workers(2) to workers(1). If you already have firm, te2 and ref2 from the previous example in memory, start at the second block.
                  Download sdea 5.9.0
                  Download the DEA-Stata 2.0.73 solver

                  Code:
                  do load.do
                  do examples/generate_9040.do
                  sdea y1 y2, inputs(x1 x2 x3 x4 x5) dmu(firm) method(standard) ///
                      refset(buildhull) rts(vrs) orientation(output) workers(2) ///
                      generate(te2 ref2 drift2)
                  return list
                  For output orientation, sdea stores te2 as the reciprocal of the radial output expansion factor. To express the result as a percentage increase in both outputs at the firm's observed inputs, calculate 100*(1/te2 - 1).

                  Code:
                  generate double output_gain_pct = 100*(1/te2 - 1) if te2 > 0 & te2 < .
                  format te2 %9.4f
                  format output_gain_pct %9.2f
                  list firm te2 output_gain_pct if inlist(firm, 31, 9040), noobs
                  Firm 31 has a score of 1.0000 and a radial output gain of 0.00%. Firm 9040 has a score of 0.7215. Its estimated expansion factor is 1.3861, so both outputs could rise together by 38.61% at its current inputs relative to the estimated frontier. For an input-oriented run, 100*(1 - score) gives the potential proportional reduction in inputs at observed outputs.

                  Code:
                  summarize te2, detail
                  count if abs(te2 - 1) < 1e-6
                  count if ref2 == 1
                  On these data the mean of the 9,040 scores is 0.7129. The first count gives 351 firms with a radial score of one within sdea's tolerance. The second gives the 639 firms that BuildHull retained as the common reference set. To answer “How many firms are radially efficient?”, use the first count. To inspect the firms used to form the reference set, use list firm te2 if ref2 == 1. In this cross-sectional model drift2 is zero for each evaluated firm.

                  Immediately after sdea, return list also shows r(N) for the number scored, r(N_efficient) for the first count and r(N_frame) for the second. Later commands such as summarize and count overwrite those returned results. The generated variables stay in the data, so you can still look up individual scores or export one row per evaluated firm.

                  Code:
                  export delimited firm te2 output_gain_pct ref2 if !missing(te2) ///
                      using "firm_efficiency_vrs_output.csv"

                  Comment

                  Working...
                  X