Git Product home page Git Product logo

ftools's Introduction

FTOOLS: A faster Stata for large datasets

GitHub release (latest by date) GitHub Release Date GitHub commits since latest release (by date) StataMin DOI


Introduction

Some of the most common Stata commands (collapse, merge, sort, etc.) are not designed for large datasets. This package provides alternative implementations that solves this problem, speeding up these commands by 3x-10x:

collapse benchmark

Other user commands that are very useful for speeding up Stata with large datasets include:

  • gtools, a package similar to ftools but written in C. In most cases it's much faster than both ftools and the standard Stata commands, as shown in the graph above. Try it out!
  • sumup provides fast summary statistics, and includes the fasttabstat command, a faster version of tabstat.
  • egenmisc introduces the egen functions fastxtile, fastwpctile, etc. that provide much faster alternatives to xtile and pctile. Also see the fastxtile package, which provides similar functionality.
  • randomtag is a much faster alternative to sample.
  • reghdfe provides a faster alternative to xtreg and areg, as well as multi-way clustering and IV regression.
  • parallel allows for easier parallel computing in Stata (useful when running simulations, reshaping, etc.)
  • boottest, for efficiently running wild bootstraps.
  • The rangerun, runby and rangestat commands are useful for running commands and collecting statistics on rolling windows of observations.

ftools can also be used to speed up your own commands. For more information, see this presentation from the 2017 Stata Conference (slides 14 and 15 show how to create faster alternatives to unique and xmiss with only a couple lines of code). Also, see help ftools for the detailed documentation.

Details

ftools is two things:

  1. A list of Stata commands optimized for large datasets, replacing commands such as: collapse, contract, merge, egen, sort, levelsof, etc.
  2. A Mata class (Factor) that focuses on working with categorical variables. This class is what makes the above commands fast, and is also what powers reghdfe

Currently the following commands are implemented:

  • fegen group replacing egen group
  • fcollapse replacing collapse, contract and most of egen (through the , merge option)
  • join (and its wrapper fmerge) replacing merge
  • fisid replacing isid
  • flevelsof replacing levelsof
  • fsort replacing sort (although it is rarely faster than sort)

Usage

* Stata usage:
sysuse auto

fsort turn
fegen id = group(turn trunk)
fcollapse (sum) price (mean) gear, by(turn foreign) freq

* Advanced: creating the .mlib library:
ftools, compile

* Mata usage:
sysuse auto, clear
mata: F = factor("turn")
mata: F.keys, F.counts
mata: sorted_price = F.sort(st_data(., "price"))

Other features include:

  • Add your own functions to -fcollapse-
  • View the levels of each variable with mata: F.keys
  • Embed -factor()- into your own Mata program. For this, you can use F.sort() and the built-in panelsubmatrix().

Benchmarks

(see the test folder for the details of the tests and benchmarks)

egen group

Given a dataset with 20 million obs. and 5 variables, we create the following variable, and create IDs based on that:

gen long x = ceil(uniform()*5000)

Then, we compare five different variants of egen group:

Method Min Avg
egen id = group(x) 49.17 51.26
fegen id = group(x) 1.44 1.53
fegen id = group(x), method(hash0) 1.41 1.60
fegen id = group(x), method(hash1) 8.87 9.35
fegen id = group(x), method(stata) 34.73 35.43

Our variant takes roughly 3% of the time of egen group. If we were to choose a more complex hash method, it would take 18% of the time. We also report the most efficient method based in Stata (that uses bysort), which is still significantly slower than our Mata approach.

Notes:

  • The gap is larger in systems with two or less cores, and smaller in systems with many cores (because our approach does not take much advantage of multicore)
  • The gap is larger in datasets with more observations or variables.
  • The gap is larger with fewer levels

collapse

On a dataset of similar size, we ran collapse (sum) y1-y15, by(x3) where x3 takes 100 different values:

Method Time % of Collapse
collapse … , fast 81.87 100%
sumup 56.18 69%
fcollapse … , fast 38.54 47%
fcollapse … , fast pool(5) 28.32 35%
tab ... 9.39 11%

We can see that fcollapse takes roughly a third of the time of collapse (although it uses more memory when moving data from Stata to Mata). As a comparison, tabulating the data (one of the most efficient Stata operations) takes 11% of the time of collapse.

Alternatively, the pool(#) option will use very little memory (similar to collapse) at also very good speeds.

Notes:

  • The gap is larger if you want to collapse fewer variables
  • The gap is larger if you want to collapse to fewer levels
  • The gap is larger for more complex stats. (such as median)
  • compressing the by() identifiers beforehand might lead to significant improvements in speed (by allowing the use of the internal hash0 function instead of hash1).
  • In a computer with less memory, it seems pool(#) might actually be faster.

collapse: alternative benchmark

We can run a more complex query, collapsing means and medians instead of sums, also with 20mm obs.:

Method Time % of Collapse
collapse … , fast 81.06 100%
sumup 67.05 83%
fcollapse … , fast 30.93 38%
fcollapse … , fast pool(5) 33.85 42%
tab 8.06 10%

(Note: sumup might be better for medium-sized datasets, although some benchmarking is needed)

And we can see that the results are similar.

join (and fmerge)

Similar to merge but avoids sorting the datasets. It is faster than merge for datasets larger than ~ 100,000 obs., and for datasets above 1mm obs. it takes a third of the time.

Benchmark:

Method Time % of merge
merge 28.89 100%
join/fmerge 8.69 30%

fisid

Similar to isid, but allowing for if in and on the other hand not allowing for using and sort.

In very large datasets, it takes roughly a third of the time of isid.

flevelsof

Provides the same results as levelsof.

In large datasets, takes up to 20% of the time of levelsof.

fsort

At this stage, you would need a significantly large dataset (50 million+) for fsort to be faster than sort.

Method Avg. 1 Avg. 2
sort id 62.52 71.15
sort id, stable 63.74 65.72
fsort id 55.4 67.62

The table above shows the benchmark on a 50 million obs. dataset. The unstable sorting is slightly slower (col. 1) or slighlty faster (col. 2) than the fsort approach. On the other hand, a stable sort is clearly slower than fsort (which always produces a stable sort)

Installation

Stable Version

Within Stata, type:

cap ado uninstall ftools
ssc install ftools

Dev Version

With Stata 13+, type:

cap ado uninstall ftools
net install ftools, from(https://github.com/sergiocorreia/ftools/raw/master/src/)

For older versions, first download and extract the zip file, and then run

cap ado uninstall ftools
net install ftools, from(SOME_FOLDER)

Where SOME_FOLDER is the folder that contains the stata.toc and related files.

Compiling the mata library

In case of a Mata error, try typing ftools to create the Mata library (lftools.mlib).

Installing local versions

To install from a git fork, type something like:

cap ado uninstall ftools
net install ftools, from("C:/git/ftools/src")
ftools, compile

(Changing "C:/git/" to your own folder)

Dependencies

The fcollapse function requires the moremata package for some the median and percentile stats:

ssc install moremata

Users of Stata 11 and 12 need to install the boottest package:

ssc install boottest

FAQ:

"What features is this missing?"

  • You can create levels based on one or more variables, and on numeric or string variables, but not on combinations of both. Thus, you can't do something like fcollapse price, by(make foreign) because make is string and foreign is numeric. This is due to a limitation in Mata and is probably a hard restriction. As a workaround, just run something like fegen id = group(make), to create a numeric ID.
  • Support for weights is incomplete (datasets that use weights are often relatively small, so this feature has less priority)
  • Some commands could also gain large speedups (merge, reshape, etc.)
  • Since Mata is ~4 times slower than C, rewriting this in a C plugin should lead to a large speedup.

"How can this be faster than existing commands?"

Existing commands (e.g. sort) are often compiled and don't have to move data from Stata to Mata and viceversa. However, they use inefficient algorithms, so for datasets large enough, they are slower. In particular, creating identifiers can be an ~O(N) operation if we use hashes instead of sorting the data (see the help file). Similarly, once the identifiers are created, sorting other variables by these identifiers can be done as an O(N) operation instead of O(N log N).

"But I already tried to use Mata's asarray and it was much slower"

Mata's asarray() has a key problem: it is very slow with hash collisions (which you see a lot in this use case). Thus, I avoid using asarray() and instead use hash1() to create a hash table with open addressing (see a comparision between both approaches here).

Updates

  • 2.49.0 06may2022: fixed a bug in fcollapse with quantiles (p**, median, and iqr stats). ftools computes these statistics using moremata and had failed to update its function arguments as required by recent changes in moremata.

ftools's People

Contributors

reifjulian avatar sergiocorreia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ftools's Issues

parallel_map crashes on computers with slow temp folder

parallel_map runs into frequent supposed "syntax" errors that crashes the program. Changing the sleep time in line 348 from 50 to e.g. 500 solves this problem. This is important for legacy servers which, while having slow drives for the temporary files folder, still have many cores that are useful to speed up simulations.

I propose adding a [sleep(integer 50)] option in the syntax, with default 50 as is now. Should I do a pull request?

Stata 17, MP4.
Windows Server 2019.

Dict size exceeds Mata limits?

Hi Sergio,
I'm running into a dict size exceeds Mata limits error running reghdfe on a pretty large dataset, and found this error built into the ftools .ado file.

According to the Stata documentation for the release of Stata 16, though, "Mata matrices remain limited only by memory," so I was wondering if there's a remaining reason for the hard-coded limit in place here?

Thanks!

fegen group behaviour with missing grouping values

Firstly, thanks for this excellent set of programs.

. which ftools
/home/anon/ado/plus/f/ftools.ado
*! version 2.9.2 06apr2017

Suppose we have the data set:

hhid	pid
1	1
2	1
2	1
2	
3	1
3	2
4	
4	

Using egen group will return a missing group value if the grouping values have a missing value. Using fegen group does not distinguish between missing and non-missing values. So, running,

fegen group1 = group(hhid pid)
egen group2 = group(hhid pid)

produces the data set:

hhid	pid	group1	group2
1	1	1	1
2	1	2	2
2	1	2	2
2		3	
3	1	4	3
3	2	5	4
4		6	
4		6	

which may cause problems if the users program expects the same behaviour as the stata command.

Best, Andrew

error when running fsort twice

Thanks for this excellent set of programs, but when I run the commond fsort twice there was an error like this:
. sysuse auto,clear
(1978 Automobile Data)

. fsort turn

. fsort turn
st_store(): 3200 conformability error
: - function returned error
r(3200);
Why does this happen?

fcollapse with any missing weights returns all missing

Consider

clear
set obs 10
gen x = _n
gen y = 1
replace y = . if mod(_n, 3) == 0
gen g = mod(_n, 5)

Missing weights should be dropped, but instead all the results are missing

. which fcollapse
/home/mauricio/ado/plus/f/fcollapse.ado
*! version 2.24.1 15jan2018

.     preserve

.         fcollapse x [fw = y], by(g)

.         l

     +-------+
     | g   x |
     |-------|
  1. | 0   . |
  2. | 1   . |
  3. | 2   . |
  4. | 3   . |
  5. | 4   . |
     +-------+

.     restore

.     collapse x [fw = y], by(g)

.     l

     +---------+
     | g     x |
     |---------|
  1. | 0   7.5 |
  2. | 1     1 |
  3. | 2   4.5 |
  4. | 3     8 |
  5. | 4     4 |
     +---------+

join: assert that by() vars have same general type (str vs num)

EG:


key variable id1 is str5 in master but byte in using data
key variable id3 is str12 in master but int in using data
    Each key variable -- the variables on which observations are matched -- must be of the same generic type
    in the master and using datasets.  Same generic type means both numeric or both string.

fcollapse fails with string by variables (Stata 14/MP)

. sysuse auto, clear
(1978 Automobile Data)

. version 14

. fcollapse price, by(make)
      st_varvaluelabel():   181  Stata returned error
    Factor::store_keys():     -  function returned error
            f_collapse():     -  function returned error
                 <istmt>:     -  function returned error
r(181);

join does not clear sortedby macro

With the following code

set seed 42
clear
set obs 20
gen x = _n
gen r = runiform()
drop if r > 0.5
sort r
drop r
tempfile x
save "`x'"

clear
set obs 20
gen y = _n
drop if runiform() > 0.5
sort y
join, by(y=x) from("`x'")
desc
disp "`:sortedby'"
l

shows the data is sorted by y. However, this is only the case for master/matched observations, which appear first and sorted. Unmatched using observations appear last and unsorted. Ideally sortedby would get cleared after join is run if the results will not be sorted.

  • which join gives *! version 2.36.1 13feb2019
  • which ftools gives *! version 2.42.0 28dec2020

Error when merging m:1 on string variable

set obs 100
gen a = string(_n)
tempfile temp
save `temp'
fmerge m:1 a using `temp'

returns

assert_is_id():  3498  <a> do not uniquely identify obs. in the using data
                  join():     -  function returned error
                 <istmt>:     -  function returned error

Command join is unrecognised

Hi,

first of all, thanks a lot for both ftools and reghdfe! These are superb tools...

I have an issue using Stata 14 and using fmerge: I get an error r(199) stating "command join is unrecognised".
I have ftools also running on a Stata 13 version and there I have no issues.
All the best,
Glenn

fmerge: 1:1 merge, error 3498, <id1 id2> do not uniquely identify obs. in the master data

Hello,

A few times I have accidentally performed a 1:1 merge using fmerge when I should have performed a m:1 merge. I then get error 3498. However, rather than failing to merge (as would happen, I think, with the standard merge command) fmerge seems to perform a correct m:1 merge anyway. Am I correct that this happens? I wonder if this is a feature or a bug?

Thanks for your help!

join: do not copy certain chars

When copying labels/notes from -using- to -master-, avoid copying _dta[...], in particular _TStvar _TSpanel _TSdelta _TSitrvl tis iis (or maybe no _dta at all?)

Otherwise, running -join- messes up -xtset-

Support many to many join

Would it be possible to add many to many functionality in the join command that could mimic the joinby command?

fmerge error

Hi using stata 13.1 mp and facing the following error when running fmerge

Using stata 13.1mp

  is_integers_only():  3253  pk[325815,1] found where real required

              join():     -  function returned error

             <istmt>:     -  function returned error

Possible issue with fsort when clearing sort variable

In testing hashsort, I found that fsort sometimes did not give me an identical data set compared to sort, stable. I cannot replicate this from a blank session very easily, so here is the data that gives the issue:

local addr https://raw.githubusercontent.com/mcaceresb/stata-gtools
local path develop/src/github-issues/

use `addr'/`path'/fsort_share.dta
sort int1, stable
tempfile cmp
save `cmp'

use `addr'/`path'/fsort_share.dta
fsort int1
cf * using `cmp'

The result is

. cf * using `cmp'
           rsort:  1 mismatch
r(9);

I believe the issue is with Andrew Maurer's trick to clear : sortedby. I got around this by setting obs to =_N + 1, manipulating the last observation, and dropping it. This way the origina data is never altered.

improve 'ftools compile'

  • ftools xyz is treated as ftools compile instead of raising an error
  • similarly, ftools check stays silent, but ftools check, v (nonexisting option) ends up as ftools compile
  • if the ado/plus/l folder does not exist, we should try to create it before saving to it
  • the abcreg source code has a more robust variant of the ftools.ado code
  • expose ftools check on the help file

fmerge / join changes using-keys>100 to missing

Hi Sergio,

I found a rather weird bug in the fmerge/join command:

Let's say I have a numeric ID ranging from 1 to X where X>100. In the Master data, the ID is always <100 but in the Using data the ID can be > 100. The fmerge/join works, however, it will change all IDs > 100 to missing in the final data. This behavior does happen in all join into/from combinations.

I attached an example code and data.

Best,

Chris

bugexample.zip

(ftools header: *! version 2.37.0 16aug2019,
join header: *! version 2.36.1 13feb2019,
fmerge header: *! version 2.10.0 3apr2017,
stata version 15 mp,
mac osx
)

join: problems with spaces in filepath

Hi!
Join will throw an error if the filepath for your tempfiles contains spaces. This can be fixed by enclosing "form", "into" and "filename" on lines 24 and 65 of join.ado in additional quotes.

Thanks so much for ceating this great set of tools - it already saved me hours of time!

error with join

The command -join- appears to fail with the error message 3598 when the master dataset is a tempfile. See reproducible example below. I am running Stata 14.0 on mac OS X 10.13.6.

sysuse auto , clear
generate id = _n
preserve
keep id make price mpg
tempfile tmp
save "tmp'" restore keep id foreign join , into("tmp'") by(id)

data type following fcollapse

. which ftools
/home/asheph/ado/plus/f/ftools.ado
*! version 2.24.0 11jan2018

Stata's own collapse command will promote the storage type of variables. So, if I have

set obs 1000
gen byte x = 1
collapse (sum) x

then the sum x will be promoted to double with a value of 1000 returned.

With fcollapse the storage type of the returned variable x is not promoted from byte, in which case a missing value is returned.

fmerge error

I just received the following error when using fmerge. I suspect I hit some sort of memory limit.

fmerge m:1 perm using "`permutations'", assert(match) nogen
                  join():  3900  unable to allocate real <tmp>[403200000,9]
                 <istmt>:     -  function returned error
r(3900);                                                                                                     

Here's version number:

which ftools             
/home/wtownsend/ado/plus/f/ftools.ado
SMP Mon Jun 25 08:07:07 PDT 
*! version 2.24.3 24jan2018 

Here's the dofile, for context
https://pastebin.com/NixsYupi

fcollapse incorrectly parses negative weights

clear
set obs 1
gen x = 1
gen y = -1
preserve
    fcollapse (p30) p30 = x (p50) p50 = x (p70) p70 = x [fw = y]
restore, preserve
    fcollapse (p30) p30 = x (p50) p50 = x (p70) p70 = x [pw = y]
restore, preserve
    fcollapse (p30) p30 = x (p50) p50 = x (p70) p70 = x [aw = y]
restore

With collapse, all those instances throw errors. Further,

set seed 42
clear
set obs 10
gen x = _n
gen y = int(10 * rnormal())
l
preserve
    fcollapse (p10) p10 = x (p50) p50 = x (p90) p90 = x [iw = y]
    l
restore, preserve
    collapse (p10) p10 = x (p50) p50 = x (p90) p90 = x [iw = y]
    l
restore

Produces

     +-----------------+
     | p10   p50   p90 |
     |-----------------|
  1. |  10     1     1 |
     +-----------------+

vs

     +-----------------+
     | p10   p50   p90 |
     |-----------------|
  1. |   1     5    10 |

I think you are running into the same issue I did, and are forgetting to normalize the weights. For percentiles, collapse multiplies the weights by number non-missing / sum weights before computing them. This gives the right answer:

 qui sum y, meanonly
 gen ynorm = y / `r(sum)'
 fcollapse (p10) p10 = x (p50) p50 = x (p90) p90 = x [iw = ynorm]
 l

fcollapse issue with double identifier

Hi Sergio,

First - thanks very much for writing the gtools and ftools packages. Incredibly useful and a great public service!!!

I have found that with fcollapse, the results of the collapse are likely to be incorrect if the identifier is a very long double (in my example, census block identifiers). Another reminder that one should always use strings for identifiers, but I wanted to flag this issue. This issue does not show up using collapse or gcollapse.

Thanks -- Nate

Add check in panelsum() when factors are sorted

This would speed up F.sort() calls when factors are sorted in the dataset; particularly useful if we run this method a lot (e.g. reghdfe)

First, create .is_sorted

Then, intercept this loop and replace (not tested):

p[index[level] = index[level] + 1] = obs

with

p[idx = index[level] = index[level] + 1] = obs
if (is_sorted) {
    if (idx < last_idx)) is_sorted = 0 // set is_sorted = 1 before the loop
    last_idx = idx // initially set last_idx = 0
}

Also benchmark it to see if the slowdown is high (in which case we make the sort check optional and unroll the loop)

Finally, sort() and _sort() should add a line like if (is_sorted) return(data)

fmerge fails if there is a space in the path

fmerge id using "/some path with spaces/somefile" will fail due to insufficient quotes (we should quote everything that touches the -filename- local (including instances of -use-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.