licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
0.7.1
68888f0d012aae809dbbe90f5ea6e1c8c5c5f737
docs
3883
![Logo](full-logo.svg) *An [algebraic modeling](https://en.wikipedia.org/wiki/Algebraic_modeling_language) and [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation) tool in [Julia Language](https://julialang.org/), specialized for [SIMD](https://en.wikipedia.org/wiki/Single_instruction,_multiple_data) abstraction of [nonlinear programs](https://en.wikipedia.org/wiki/Nonlinear_programming).* --- | **License** | **Documentation** | **Build Status** | **Coverage** | **Citation** | |:-----------------:|:----------------:|:----------------:|:----------------:|:----------------:| | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/exanauts/ExaModels.jl/blob/main/LICENSE) | [![doc](https://img.shields.io/badge/docs-stable-blue.svg)](https://exanauts.github.io/ExaModels.jl/stable) [![doc](https://img.shields.io/badge/docs-dev-blue.svg)](https://exanauts.github.io/ExaModels.jl/dev) | [![build](https://github.com/exanauts/ExaModels.jl/actions/workflows/test.yml/badge.svg)](https://github.com/exanauts/ExaModels.jl/actions/workflows/test.yml) | [![codecov](https://codecov.io/gh/exanauts/ExaModels.jl/branch/main/graph/badge.svg?token=8ViJWBWnZt)](https://codecov.io/gh/exanauts/ExaModels.jl) | [![arXiv](https://img.shields.io/badge/arXiv-2307.16830-b31b1b.svg)](https://arxiv.org/abs/2307.16830) | ## Overview ExaModels.jl employs what we call **[SIMD](https://en.wikipedia.org/wiki/Single_instruction,_multiple_data) abstraction for [nonlinear programs](https://en.wikipedia.org/wiki/Nonlinear_programming)** (NLPs), which allows for the **preservation of the parallelizable structure** within the model equations, facilitating **efficient, parallel [reverse-mode automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation)** on the **[GPU](https://en.wikipedia.org/wiki/Graphics_processing_unit) accelerators**. ExaModels.jl is different from other algebraic modeling tools, such as [JuMP](https://github.com/jump-dev/JuMP.jl) or [AMPL](https://ampl.com/), in the following ways: - **Modeling Interface**: ExaModels.jl requires users to specify the model equations always in the form of `Generator`s. This restrictive structure allows ExaModels.jl to preserve the SIMD-compatible structure in the model equations. This unique feature distinguishes ExaModels.jl from other algebraic modeling tools. - **Performance**: ExaModels.jl compiles (via Julia's compiler) derivative evaluation codes tailored to each computation pattern. Through reverse-mode automatic differentiation using these tailored codes, ExaModels.jl achieves significantly faster derivative evaluation speeds, even when using CPU. - **Portability**: ExaModels.jl goes beyond traditional boundaries of algebraic modeling systems by **enabling derivative evaluation on GPU accelerators**. Implementation of GPU kernels is accomplished using the portable programming paradigm offered by [KernelAbstractions.jl](https://github.com/JuliaGPU/KernelAbstractions.jl). With ExaModels.jl, you can run your code on various devices, including multi-threaded CPUs, NVIDIA GPUs, AMD GPUs, and Intel GPUs. Note that Apple's Metal is currently not supported due to its lack of support for double-precision arithmetic. ## Highlight The performance comparison of ExaModels with other algebraic modeling systems for evaluating different NLP functions (obj, con, grad, jac, and hess) are shown below. Note that Hessian computations are the typical bottlenecks. ![benchmark](https://raw.githubusercontent.com/exanauts/ExaModels.jl/main/docs/src/assets/benchmark.svg) ## Supporting ExaModels.jl - Please report issues and feature requests via the [GitHub issue tracker](https://github.com/exanatus/ExaModels.jl/issues). - Questions are welcome at [GitHub discussion forum](https://github.com/exanauts/ExaModels.jl/discussions).
ExaModels
https://github.com/exanauts/ExaModels.jl.git
[ "MIT" ]
0.7.1
68888f0d012aae809dbbe90f5ea6e1c8c5c5f737
docs
51
# ExaModels ```@autodocs Modules = [ExaModels] ```
ExaModels
https://github.com/exanauts/ExaModels.jl.git
[ "MIT" ]
0.7.1
68888f0d012aae809dbbe90f5ea6e1c8c5c5f737
docs
2493
# Developing Extensions ExaModels.jl's API only uses simple julia funcitons, and thus, implementing the extensions is straightforward. Below, we suggest a good practice for implementing an extension package. Let's say that we want to implement an extension package for the example problem in [Getting Started](@ref guide). An extension package may look like: ``` Root ├───Project.toml ├── src │ └── LuksanVlcekModels.jl └── test └── runtest.jl ``` Each of the files containing ```toml # Project.toml name = "LuksanVlcekModels" uuid = "0c5951a0-f777-487f-ad29-fac2b9a21bf1" authors = ["Sungho Shin <[email protected]>"] version = "0.1.0" [deps] ExaModels = "1037b233-b668-4ce9-9b63-f9f681f55dd2" [extras] NLPModelsIpopt = "f4238b75-b362-5c4c-b852-0801c9a21d71" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" [targets] test = ["Test", "NLPModelsIpopt"] ``` ```julia # src/LuksanVlcekModels.jl module LuksanVlcekModels import ExaModels function luksan_vlcek_obj(x,i) return 100*(x[i-1]^2-x[i])^2+(x[i-1]-1)^2 end function luksan_vlcek_con(x,i) return 3x[i+1]^3+2*x[i+2]-5+sin(x[i+1]-x[i+2])sin(x[i+1]+x[i+2])+4x[i+1]-x[i]exp(x[i]-x[i+1])-3 end function luksan_vlcek_x0(i) return mod(i,2)==1 ? -1.2 : 1.0 end function luksan_vlcek_model(N; backend = nothing) c = ExaModels.ExaCore(backend) x = ExaModels.variable( c, N; start = (luksan_vlcek_x0(i) for i=1:N) ) ExaModels.constraint( c, luksan_vlcek_con(x,i) for i in 1:N-2) ExaModels.objective(c, luksan_vlcek_obj(x,i) for i in 2:N) return ExaModels.ExaModel(c) # returns the model end export luksan_vlcek_model end # module LuksanVlcekModels ``` ```julia # test/runtest.jl using Test, LuksanVlcekModels, NLPModelsIpopt @testset "LuksanVlcekModelsTest" begin m = luksan_vlcek_model(10) result = ipopt(m) @test result.status == :first_order @test result.solution ≈ [ -0.9505563573613093 0.9139008176388945 0.9890905176644905 0.9985592422681151 0.9998087408802769 0.9999745932450963 0.9999966246997642 0.9999995512524277 0.999999944919307 0.999999930070643 ] @test result.multipliers ≈ [ 4.1358568305002255 -1.876494903703342 -0.06556333356358675 -0.021931863018312875 -0.0019537261317119302 -0.00032910445671233547 -3.8788212776372465e-5 -7.376592164341867e-6 ] end ```
ExaModels
https://github.com/exanauts/ExaModels.jl.git
[ "MIT" ]
0.7.1
68888f0d012aae809dbbe90f5ea6e1c8c5c5f737
docs
6346
# Introduction Welcome to the documentation of [ExaModels.jl](https://github.com/sshin23/ExaModels.jl) !!! note ExaModels runs on julia `VERSION ≥ v"1.9"` !!! warning **Please help us improve ExaModels and this documentation!** ExaModels is in the early stage of development, and you may encounter unintended behaviors or missing documentations. If you find anything is not working as intended or documentation is missing, please [open issues](https://github.com/sshin/ExaModels.jl/issues) or [pull requests](https://github.com/sshin/ExaModels.jl/pulls) or start [discussions](https://github.com/sshin/ExaModels.jl/discussions). ## What is ExaModels.jl? ExaModels.jl is an [algebraic modeling](https://en.wikipedia.org/wiki/Algebraic_modeling_language) and [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation) tool in [Julia Language](https://julialang.org/), specialized for [SIMD](https://en.wikipedia.org/wiki/Single_instruction,_multiple_data) abstraction of [nonlinear programs](https://en.wikipedia.org/wiki/Nonlinear_programming). ExaModels.jl employs what we call [SIMD](https://en.wikipedia.org/wiki/Single_instruction,_multiple_data) abstraction for [nonlinear programs](https://en.wikipedia.org/wiki/Nonlinear_programming) (NLPs), which allows for the preservation of the parallelizable structure within the model equations, facilitating efficient [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation) either on the single-thread CPUs, multi-threaded CPUs, as well as [GPU accelerators](https://en.wikipedia.org/wiki/Graphics_processing_unit). More details about SIMD abstraction can be found [here](@ref simd). ## Key differences from other algebraic modeling tools ExaModels.jl is different from other algebraic modeling tools, such as [JuMP](https://github.com/jump-dev/JuMP.jl) or [AMPL](https://ampl.com/), in the following ways: - **Modeling Interface**: ExaModels.jl requires users to specify the model equations always in the form of `Generator`s. This restrictive structure allows ExaModels.jl to preserve the SIMD-compatible structure in the model equations. This unique feature distinguishes ExaModels.jl from other algebraic modeling tools. - **Performance**: ExaModels.jl compiles (via Julia's compiler) derivative evaluation codes tailored to each computation pattern. Through reverse-mode automatic differentiation using these tailored codes, ExaModels.jl achieves significantly faster derivative evaluation speeds, even when using CPU. - **Portability**: ExaModels.jl goes beyond traditional boundaries of algebraic modeling systems by **enabling derivative evaluation on GPU accelerators**. Implementation of GPU kernels is accomplished using the portable programming paradigm offered by [KernelAbstractions.jl](https://github.com/JuliaGPU/KernelAbstractions.jl). With ExaModels.jl, you can run your code on various devices, including multi-threaded CPUs, NVIDIA GPUs, AMD GPUs, and Intel GPUs. Note that Apple's Metal is currently not supported due to its lack of support for double-precision arithmetic. Thus, ExaModels.jl shines when your model has - nonlinear objective and constraints; - a large number of variables and constraints; - highly repetitive structure; - sparse Hessian and Jacobian. These features are often exhibited in optimization problems associated with first-principle physics-based models. Primary examples include optimal control problems formulated with direct subscription method [biegler2010nonlinear](@cite) and network system optimization problems, such as optimal power flow [coffrin2018powermodels](@cite) and gas network control/estimation problems. ## Performance Highlights ExaModels.jl significantly enhances the performance of derivative evaluations for nonlinear optimization problems that can benefit from SIMD abstraction. Recent benchmark results demonstrate this notable improvement. Notably, when solving the AC OPF problem for a 9241 bus system, derivative evaluation using ExaModels.jl on GPUs can be up to two orders of magnitude faster compared to JuMP or AMPL. Some benchmark results are available below. The following problems are used for benchmarking: - [LuksanVlcek problem](@ref guide) - [Quadrotor control problem](@ref quad) - [Distillation column control problem](@ref distillation) - [AC optimal power flow problem](@ref opf) ![benchmark](./assets/benchmark.svg) ## Supported Solvers ExaModels can be used with any solver that can handle `NLPModel` data type, but several callbacks are not currently implemented, and cause some errors. Currently, it is tested with the following solvers: - [Ipopt](https://github.com/JuliaSmoothOptimizers/NLPModelsIpopt.jl) (via [NLPModelsIpopt.jl](https://github.com/JuliaSmoothOptimizers/NLPModelsIpopt.jl)) - [MadNLP.jl](https://github.com/MadNLP/MadNLP.jl) ## Documentation Structure This documentation is structured in the following way. - The remainder of this page highlights several key aspects of ExaModels.jl. - The mathematical abstraction---SIMD abstraction of nonlinear programming---of ExaModels.jl is discussed in [Mathematical Abstraction page](@ref simd). - The step-by-step tutorial of using ExaModels.jl can be found in [Tutorial page](@ref guide). - This documentation does not intend to discuss the engineering behind the implementation of ExaModels.jl. Some high-level idea is discussed in [a recent publication](https://arxiv.org/abs/2307.16830), but the full details of the engineering behind it will be discussed in the future publications. ## Citing ExaModels.jl If you use ExaModels.jl in your research, we would greatly appreciate your citing this [preprint](https://arxiv.org/abs/2307.16830). ```bibtex @misc{shin2023accelerating, title={Accelerating Optimal Power Flow with {GPU}s: {SIMD} Abstraction of Nonlinear Programs and Condensed-Space Interior-Point Methods}, author={Sungho Shin and Fran{\c{c}}ois Pacaud and Mihai Anitescu}, year={2023}, eprint={2307.16830}, archivePrefix={arXiv}, primaryClass={math.OC} } ``` ## Supporting ExaModels.jl - Please report issues and feature requests via the [GitHub issue tracker](https://github.com/sshin/ExaModels.jl/issues). - Questions are welcome at [GitHub discussion forum](https://github.com/sshin23/ExaModels.jl/discussions).
ExaModels
https://github.com/exanauts/ExaModels.jl.git
[ "MIT" ]
0.7.1
68888f0d012aae809dbbe90f5ea6e1c8c5c5f737
docs
35
# References ```@bibliography ```
ExaModels
https://github.com/exanauts/ExaModels.jl.git
[ "MIT" ]
0.7.1
68888f0d012aae809dbbe90f5ea6e1c8c5c5f737
docs
2974
# [SIMD Abstraction](@id simd) In this page, we explain what SIMD abstraction of nonlinear program is, and why it can be beneficial for scalable optimization of large-scale optimization problems. More discussion can be found in our [paper](https://arxiv.org/abs/2307.16830). ## What is SIMD abstraction? The mathematical statement of the problem formulation is as follows. ```math \begin{aligned} \min_{x^\flat\leq x \leq x^\sharp} & \sum_{l\in[L]}\sum_{i\in [I_l]} f^{(l)}(x; p^{(l)}_i)\\ \text{s.t.}\; &\left[g^{(m)}(x; q_j)\right]_{j\in [J_m]} +\sum_{n\in [N_m]}\sum_{k\in [K_n]}h^{(n)}(x; s^{(n)}_{k}) =0,\quad \forall m\in[M] \end{aligned} ``` where $f^{(\ell)}(\cdot,\cdot)$, $g^{(m)}(\cdot,\cdot)$, and $h^{(n)}(\cdot,\cdot)$ are twice differentiable functions with respect to the first argument, whereas $\{\{p^{(k)}_i\}_{i\in [N_k]}\}_{k\in[K]}$, $\{\{q^{(k)}_{i}\}_{i\in [M_l]}\}_{m\in[M]}$, and $\{\{\{s^{(n)}_{k}\}_{k\in[K_n]}\}_{n\in[N_m]}\}_{m\in[M]}$ are problem data, which can either be discrete or continuous. It is also assumed that our functions $f^{(l)}(\cdot,\cdot)$, $g^{(m)}(\cdot,\cdot)$, and $h^{(n)}(\cdot,\cdot)$ can be expressed with computational graphs of moderate length. ## Why SIMD abstraction? Many physics-based models, such as AC OPF, have a highly repetitive structure. One of the manifestations of it is that the mathematical statement of the model is concise, even if the practical model may contain millions of variables and constraints. This is possible due to the use of repetition over a certain index and data sets. For example, it suffices to use 15 computational patterns to fully specify the AC OPF model. These patterns arise from (1) generation cost, (2) reference bus voltage angle constraint, (3-6) active and reactive power flow (from and to), (7) voltage angle difference constraint, (8-9) apparent power flow limits (from and to), (10-11) power balance equations, (12-13) generators' contributions to the power balance equations, and (14-15) in/out flows contributions to the power balance equations. However, such repetitive structure is not well exploited in the standard NLP modeling paradigms. In fact, without the SIMD abstraction, it is difficult for the AD package to detect the parallelizable structure within the model, as it will require the full inspection of the computational graph over all expressions. By preserving the repetitive structures in the model, the repetitive structure can be directly available in AD implementation. Using the multiple dispatch feature of Julia, ExaModels.jl generates highly efficient derivative computation code, specifically compiled for each computational pattern in the model. These derivative evaluation codes can be run over the data in various GPU array formats, and implemented via array and kernel programming in Julia Language. In turn, ExaModels.jl has the capability to efficiently evaluate first and second-order derivatives using GPU accelerators.
ExaModels
https://github.com/exanauts/ExaModels.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
1611
using Documenter using DiffinDiffs using DocumenterCitations using StatsProcedures using Vcov bib = CitationBibliography(joinpath(@__DIR__, "../paper/paper.bib"), style=:authoryear) makedocs( modules = [DiffinDiffsBase, InteractionWeightedDIDs], format = Documenter.HTML( assets = ["assets/favicon.ico"], canonical = "https://JuliaDiffinDiffs.github.io/DiffinDiffs.jl/stable/", prettyurls = get(ENV, "CI", nothing) == "true", collapselevel = 2, ansicolor = true ), sitename = "DiffinDiffs.jl", authors = "Junyuan Chen", pages = [ "Home" => "index.md", "Manual" => [ "Getting Started" => "man/getting-started.md" ], "Library" => [ "Treatment Types" => "lib/treatments.md", "Parallel Types" => "lib/parallels.md", "Formula Terms" => "lib/terms.md", "Estimators" => "lib/estimators.md", "Inference" => "lib/inference.md", "Procedures" => "lib/procedures.md", "Results" => "lib/results.md", "Tables" => "lib/tables.md", "Panel Operations" => "lib/panel.md", "ScaledArrays" => "lib/ScaledArrays.md", "StatsProcedures" => "lib/StatsProcedures.md" ], "About" => [ "References" => "about/references.md", "License" => "about/license.md" ] ], workdir = joinpath(@__DIR__, ".."), doctest = false, plugins = [bib] ) deploydocs( repo = "github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git", devbranch = "master" )
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
1287
using Luxor function logo(s) full_radius = 99*s/100 Δ = full_radius/180 sethue(Luxor.julia_purple) sector(O+(-20Δ,0), 60Δ, 90Δ, -π/2, π/2, :fill) sethue(Luxor.julia_red) sector(O+(-20Δ,0), 0, 40Δ, -π/2, π/2, :fill) sethue(Luxor.julia_green) box(Point(-55Δ,0), 30Δ, 180Δ, :fill) sethue(Luxor.julia_blue) poly(Point.([(-40Δ,90Δ),(-40Δ,60Δ),(-20Δ,60Δ)]), :fill, close=true) poly(Point.([(-40Δ,-90Δ),(-40Δ,-60Δ),(-20Δ,-60Δ)]), :fill, close=true) end function drawlogo(s, fname) Drawing(s, s, fname) origin() logo(s) finish() end function drawbanner(w, h, fname) Drawing(w, h, fname) origin() table = Table([h], [h, w - h]) @layer begin translate(table[1]) logo(h) end @layer begin translate(table[2]) sethue("black") fontface("Julius Sans One") fontsize(h/2.35) text("iffinDiffs.jl", O+(-h/9,0), halign=:center, valign=:middle) fontface("Montserrat") fontsize(h/10.5) text("A suite of Julia packages for difference-in-differences", O+(-h/10,h/2.5), halign=:center, valign=:middle) end finish() end drawlogo(120, "../assets/logo.svg") drawlogo(420, "../assets/logo.png") drawbanner(350, 100, "../assets/banner.svg")
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
3662
# Generate example datasets as compressed CSV files # See data/README.md for the sources of the input data files # To regenerate the .csv.gz files: # 1) Have all input files ready in the data folder # 2) Instantiate the package environment for data/src # 3) Run this script and call `make()` with the root folder as working directory using CSV, CodecBzip2, CodecZlib, DataFrames, DataValues, RData, ReadStat function _to_array(d::DataValueArray{T}) where T a = Array{T}(undef, size(d)) hasmissing = false @inbounds for i in eachindex(d) v = d[i] if hasvalue(v) a[i] = v.value elseif !hasmissing a = convert(Array{Union{T,Missing}}, a) hasmissing = true a[i] = missing else a[i] = missing end end return a end function _get_columns(data::ReadStatDataFrame, names::Vector{Symbol}) lookup = Dict(data.headers.=>keys(data.headers)) cols = Vector{AbstractVector}(undef, length(names)) for (i, n) in enumerate(names) col = data.data[lookup[n]] cols[i] = _to_array(col) end return cols end # The steps for preparing data follow Sun and Abraham (2020) function hrs() raw = read_dta("data/HRS_long.dta") names = [:hhidpn, :wave, :wave_hosp, :evt_time, :oop_spend, :riearnsemp, :rwthh, :male, :spouse, :white, :black, :hispanic, :age_hosp] cols = _get_columns(raw, names) df = dropmissing!(DataFrame(cols, names), [:wave, :age_hosp, :evt_time]) df = df[(df.wave.>=7).&(df.age_hosp.<=59), :] # Must count wave after the above selection transform!(groupby(df, :hhidpn), nrow=>:nwave, :evt_time => minimum => :evt_time) df = df[(df.nwave.==5).&(df.evt_time.<0), :] transform!(groupby(df, :hhidpn), :wave_hosp => minimum∘skipmissing => :wave_hosp) select!(df, Not([:nwave, :evt_time, :age_hosp])) for n in (:male, :spouse, :white, :black, :hispanic) df[!, n] .= ifelse.(df[!, n].==100, 1, 0) end for n in propertynames(df) if !(n in (:oop_spend, :riearnsemp, :wrthh)) df[!, n] .= convert(Array{Int}, df[!, n]) end end # Replace the original hh index with enumeration ids = IdDict{Int,Int}() hhidpn = df.hhidpn newid = 0 for i in 1:length(hhidpn) oldid = hhidpn[i] id = get(ids, oldid, 0) if id === 0 newid += 1 ids[oldid] = newid hhidpn[i] = newid else hhidpn[i] = id end end open(GzipCompressorStream, "data/hrs.csv.gz", "w") do stream CSV.write(stream, df) end end # Produce a subset of nsw_long from the DRDID R package function nsw() df = DataFrame(CSV.File("data/ec675_nsw.tab", delim='\t')) df = df[(isequal.(df.treated, 0)).|(df.sample.==2), Not([:dwincl, :early_ra])] df.experimental = ifelse.(ismissing.(df.treated), 0, 1) select!(df, Not([:treated, :sample])) df.id = 1:nrow(df) # Convert the data to long format df = stack(df, [:re75, :re78]) df.year = ifelse.(df.variable.=="re75", 1975, 1978) select!(df, Not(:variable)) rename!(df, :value=>:re) sort!(df, :id) open(GzipCompressorStream, "data/nsw.csv.gz", "w") do stream CSV.write(stream, df) end end # Convert mpdta from the did R package to csv format function mpdta() df = load("data/mpdta.rda")["mpdta"] df.first_treat = convert(Vector{Int}, df.first_treat) select!(df, Not(:treat)) open(GzipCompressorStream, "data/mpdta.csv.gz", "w") do stream CSV.write(stream, df) end end function make() hrs() nsw() mpdta() end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
3394
module DiffinDiffsBase using Base: @propagate_inbounds using CSV using CodecZlib: GzipDecompressorStream using DataAPI using DataAPI: refarray, refpool, invrefpool using Dates: Period, TimeType using LinearAlgebra: Diagonal using Missings: allowmissing, disallowmissing using PooledArrays: _label using PrettyTables: pretty_table using Reexport using StatsAPI: stderror using StatsBase: CoefTable, Weights, uweights using StatsFuns: normccdf, norminvcdf, tdistccdf, tdistinvcdf @reexport using StatsModels using StatsModels: Schema @reexport using StatsProcedures using StatsProcedures: ≊, _args_kwargs, _parse! using StructArrays: StructArray using Tables using Tables: AbstractColumns, istable, columnnames, getcolumn import Base: ==, +, -, *, isless, show, parent, view, diff import Base: eltype, firstindex, lastindex, getindex, iterate, length import Missings: allowmissing, disallowmissing import StatsAPI: coef, vcov, confint, nobs, dof_residual, responsename, coefnames, weights, coeftable import StatsModels: concrete_term, schema, termvars, lag, lead import StatsProcedures: required, default, transformed, combinedargs, copyargs, _show_args # Reexport objects from StatsAPI and StatsBase export coef, vcov, stderror, confint, nobs, dof_residual, responsename, coefnames, weights, coeftable export RotatingTimeValue, rotatingtime, RotatingTimeArray, VecColumnTable, VecColsRow, subcolumns, apply, apply_and!, apply_and, TableIndexedMatrix, ScaledArray, ScaledVector, ScaledMatrix, scale, align, TreatmentSharpness, SharpDesign, sharp, AbstractTreatment, DynamicTreatment, dynamic, ParallelCondition, Unconditional, unconditional, CovariateConditional, ParallelStrength, Exact, exact, Approximate, AbstractParallel, UnspecifiedParallel, unspecifiedpr, TrendParallel, TrendOrUnspecifiedPR, NeverTreatedParallel, nevertreated, NotYetTreatedParallel, notyettreated, istreated, istreated!, TermSet, termset, TreatmentTerm, treat, findcell, cellrows, settime, aligntime, PanelStructure, setpanel, findlag!, findlead!, ilag!, ilead!, diff!, diff, CheckData, GroupTreatintterms, GroupXterms, GroupContrasts, CheckVars, GroupSample, MakeWeights, DiffinDiffsEstimator, DefaultDID, did, didspec, @did, AbstractDIDResult, DIDResult, AggregatedDIDResult, vce, treatment, outcomename, treatnames, treatcells, ntreatcoef, treatcoef, treatvcov, coefinds, ncovariate, agg, SubDIDResult, TransformedDIDResult, TransSubDIDResult, lincom, rescale, ExportFormat, StataPostHDF, getexportformat, setexportformat!, post! include("tables.jl") include("utils.jl") include("time.jl") include("ScaledArrays.jl") include("treatments.jl") include("parallels.jl") include("terms.jl") include("operations.jl") include("procedures.jl") include("did.jl") end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
10755
const DEFAULT_REF_TYPE = Int32 # A wrapper only used for resolving method ambiguity when constructing ScaledArray mutable struct RefArray{R} a::R end """ ScaledArray{T,R,N,RA,P} <: AbstractArray{T,N} Array type that stores data as indices of a range. # Fields - `refs::RA<:AbstractArray{R,N}`: an array of indices. - `pool::P<:AbstractRange`: a range that covers all possible values stored by the array. - `invpool::Dict{T,R}`: a map from array elements to indices of `pool`. """ mutable struct ScaledArray{T,R,N,RA,P} <: AbstractArray{T,N} refs::RA pool::P invpool::Dict{T,R} function ScaledArray{T,R,N,RA,P}(rs::RefArray{RA}, pool::P, invpool::Dict{T,R}) where {T, R, N, RA<:AbstractArray{R, N}, P<:AbstractRange} eltype(P) == nonmissingtype(T) || throw(ArgumentError( "expect element type of pool being $(nonmissingtype(T)); got $(eltype(P))")) return new{T,R,N,RA,P}(rs.a, pool, invpool) end end ScaledArray(rs::RefArray{RA}, pool::P, invpool::Dict{T,R}) where {T,R,RA<:AbstractArray{R},P} = ScaledArray{T,R,ndims(RA),RA,P}(rs, pool, invpool) const ScaledVector{T,R} = ScaledArray{T,R,1} const ScaledMatrix{T,R} = ScaledArray{T,R,2} const ScaledArrOrSub{T,R,N,RA,P} = Union{ScaledArray{T,R,N,RA,P}, SubArray{<:Any, <:Any, <:ScaledArray{T,R,N,RA,P}}} """ scale(sa::ScaledArrOrSub) Return the step size of the `pool` of `sa`. """ scale(sa::ScaledArrOrSub) = step(DataAPI.refpool(sa)) Base.size(sa::ScaledArray) = size(sa.refs) Base.IndexStyle(::Type{<:ScaledArray{T,R,N,RA}}) where {T,R,N,RA} = IndexStyle(RA) function _validmin(min, xmin, isstart::Bool) if min === nothing min = xmin elseif min > xmin str = isstart ? "start =" : "stop =" throw(ArgumentError("$str $min is greater than the allowed minimum element $xmin")) end return min end function _validmax(max, xmax, isstart::Bool) if max === nothing max = xmax elseif max < xmax str = isstart ? "start =" : "stop =" throw(ArgumentError("$str $max is smaller than the allowed maximum element $xmax")) end return max end function validpool(x::AbstractArray, T::Type, start, step, stop, usepool::Bool) step === nothing && throw(ArgumentError("step cannot be nothing")) pool = DataAPI.refpool(x) xs = skipmissing(usepool && pool !== nothing ? pool : x) xmin, xmax = extrema(xs) applicable(+, xmin, step) || throw(ArgumentError( "step of type $(typeof(step)) does not match array with element type $(eltype(x))")) if xmin + step > xmin start = _validmin(start, xmin, true) stop = _validmax(stop, xmax, false) elseif xmin + step < xmin start = _validmax(start, xmax, true) stop = _validmin(stop, xmin, false) else throw(ArgumentError("step cannot be zero")) end start = convert(T, start) stop = convert(T, stop) return start:step:stop end function _scaledlabel!(labels::AbstractArray, invpool::Dict, xs::AbstractArray, start, step) z = zero(valtype(invpool)) @inbounds for (i, x) in zip(eachindex(labels), xs) lbl = get(invpool, x, z) if lbl !== z labels[i] = lbl elseif ismissing(x) labels[i] = z invpool[x] = z else r = start:step:x lbl = length(r) labels[i] = lbl invpool[x] = lbl end end end function scaledlabel(xs::AbstractArray, stepsize, R::Type=DEFAULT_REF_TYPE, T::Type=eltype(xs); start=nothing, stop=nothing, usepool::Bool=true) pool = validpool(xs, T, start, stepsize, stop, usepool) T = Missing <: T ? Union{eltype(pool), Missing} : eltype(pool) start = first(pool) stepsize = step(pool) if R <: Integer while typemax(R) < length(pool) R = widen(R) end end # Array types with customized indexing could cause problems labels = similar(Array{R}, axes(xs)) invpool = Dict{T,R}() _scaledlabel!(labels, invpool, xs, start, stepsize) return labels, pool, invpool end function ScaledArray(x::AbstractArray, reftype::Type, xtype::Type, start, step, stop, usepool::Bool=true) refs, pool, invpool = scaledlabel(x, step, reftype, xtype; start=start, stop=stop, usepool=usepool) return ScaledArray(RefArray(refs), pool, invpool) end function ScaledArray(sa::ScaledArray, reftype::Type, xtype::Type, start, step, stop, usepool::Bool=true) if step !== nothing && step != scale(sa) refs, pool, invpool = scaledlabel(sa, step, reftype, xtype; start=start, stop=stop, usepool=usepool) return ScaledArray(RefArray(refs), pool, invpool) else step = scale(sa) pool = validpool(sa, xtype, start, step, stop, usepool) T = Missing <: xtype ? Union{eltype(pool), Missing} : eltype(pool) refs = similar(sa.refs, reftype) invpool = Dict{T, reftype}() start0 = first(sa.pool) start = first(pool) stop = last(pool) if start == start0 copy!(refs, sa.refs) copy!(invpool, sa.invpool) elseif start < start0 && start < stop || start > start0 && start > stop offset = length(start:step:start0) - 1 refs .= sa.refs .+ offset for (k, v) in sa.invpool invpool[k] = v + offset end else offset = length(start0:step:start) - 1 refs .= sa.refs .- offset for (k, v) in sa.invpool invpool[k] = v - offset end end return ScaledArray(RefArray(refs), pool, invpool) end end """ ScaledArray(x::AbstractArray, start, step[, stop]; reftype=Int32, usepool=true) ScaledArray(x::AbstractArray, step; reftype=Int32, start, stop, usepool=true) Construct a `ScaledArray` from `x` given the `step` size. If `start` or `stop` is not specified, it will be chosen based on the extrema of `x`. # Keywords - `reftype::Type=Int32`: the element type of field `refs`. - `usepool::Bool=true`: find extrema of `x` based on `DataAPI.refpool`. """ ScaledArray(x::AbstractArray, start, step, stop=nothing; reftype::Type=DEFAULT_REF_TYPE, xtype::Type=eltype(x), usepool::Bool=true) = ScaledArray(x, reftype, xtype, start, step, stop, usepool) ScaledArray(sa::ScaledArray, start, step, stop=nothing; reftype::Type=eltype(refarray(sa)), xtype::Type=eltype(sa), usepool::Bool=true) = ScaledArray(sa, reftype, xtype, start, step, stop, usepool) ScaledArray(x::AbstractArray, step; reftype::Type=DEFAULT_REF_TYPE, start=nothing, stop=nothing, xtype::Type=eltype(x), usepool::Bool=true) = ScaledArray(x, reftype, xtype, start, step, stop, usepool) ScaledArray(sa::ScaledArray, step=nothing; reftype::Type=eltype(refarray(sa)), start=nothing, stop=nothing, xtype::Type=eltype(sa), usepool::Bool=true) = ScaledArray(sa, reftype, xtype, start, step, stop, usepool) Base.similar(sa::ScaledArrOrSub{T,R}, dims::Dims=size(sa)) where {T,R} = ScaledArray(RefArray(ones(R, dims)), DataAPI.refpool(sa), Dict{T,R}()) Base.similar(sa::ScaledArrOrSub, dims::Int...) = similar(sa, dims) """ align(xs::AbstractArray, sa::ScaledArrOrSub) Convert `xs` into a [`ScaledArray`](@ref) with a `pool` that has the same first element and step size as the `pool` from `sa`. """ function align(xs::AbstractArray, sa::ScaledArrOrSub) pool = DataAPI.refpool(sa) invpool = DataAPI.invrefpool(sa) step = scale(sa) xmin, xmax = extrema(xs) start = first(pool) stop = last(pool) start < stop && xmin < start && throw(ArgumentError( "the minimum of xs $xmin is smaller than the minimum of pool $start")) start > stop && xmax > start && throw(ArgumentError( "the maximum of xs $xmax is greater than the maximum of pool $start")) refs = similar(DataAPI.refarray(sa), size(xs)) _scaledlabel!(refs, invpool, xs, start, step) return ScaledArray(RefArray(refs), pool, invpool) end DataAPI.refarray(sa::ScaledArray) = sa.refs DataAPI.refvalue(sa::ScaledArray, n::Integer) = getindex(DataAPI.refpool(sa), n) DataAPI.refpool(sa::ScaledArray) = sa.pool DataAPI.invrefpool(sa::ScaledArray) = sa.invpool DataAPI.refarray(ssa::SubArray{<:Any, <:Any, <:ScaledArray}) = view(parent(ssa).refs, ssa.indices...) DataAPI.refvalue(ssa::SubArray{<:Any, <:Any, <:ScaledArray}, n::Integer) = DataAPI.refvalue(parent(ssa), n) DataAPI.refpool(ssa::SubArray{<:Any, <:Any, <:ScaledArray}) = DataAPI.refpool(parent(ssa)) DataAPI.invrefpool(ssa::SubArray{<:Any, <:Any, <:ScaledArray}) = DataAPI.invrefpool(parent(ssa)) @inline function Base.getindex(sa::ScaledArray, i::Int) refs = DataAPI.refarray(sa) @boundscheck checkbounds(refs, i) @inbounds n = refs[i] iszero(n) && return missing pool = DataAPI.refpool(sa) @boundscheck checkbounds(pool, n) return @inbounds pool[n] end Base.@propagate_inbounds function Base.getindex(sa::ScaledArrOrSub, I::AbstractVector) newrefs = DataAPI.refarray(sa)[I] pool = DataAPI.refpool(sa) invpool = DataAPI.invrefpool(sa) return ScaledArray(RefArray(newrefs), pool, invpool) end Base.@propagate_inbounds function Base.setindex!(sa::ScaledArray, val, ind::Int) invpool = DataAPI.invrefpool(sa) n = get(invpool, val, nothing) if n === nothing pool = DataAPI.refpool(sa) r = first(pool):step(pool):val last(r) > last(pool) && (sa.pool = r) n = length(r) invpool[val] = n end refs = DataAPI.refarray(sa) refs[ind] = n return sa end Base.@propagate_inbounds function Base.setindex!(sa::ScaledArray, ::Missing, ind::Int) refs = DataAPI.refarray(sa) z = zero(eltype(refs)) invpool = DataAPI.invrefpool(sa) invpool[missing] = z refs[ind] = z return sa end allowmissing(sa::ScaledArray{T,R}) where {T,R} = ScaledArray(RefArray(sa.refs), sa.pool, convert(Dict{Union{T,Missing},R}, sa.invpool)) function disallowmissing(sa::ScaledArray{T,R}) where {T,R} T1 = nonmissingtype(T) any(x->iszero(x), sa.refs) && throw(ArgumentError("cannot convert missing to $T1")) delete!(sa.invpool, missing) return ScaledArray(RefArray(sa.refs), sa.pool, convert(Dict{T1,R}, sa.invpool)) end function Base.:(==)(x::ScaledArrOrSub, y::ScaledArrOrSub) size(x) == size(y) || return false first(DataAPI.refpool(x)) == first(DataAPI.refpool(y)) && scale(x) == scale(y) && return DataAPI.refarray(x) == DataAPI.refarray(y) eq = true for (p, q) in zip(x, y) # missing could arise veq = p == q isequal(veq, false) && return false eq &= veq end return eq end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
32927
""" DiffinDiffsEstimator{A,T} <: AbstractStatsProcedure{A,T} Specify the estimation procedure for difference-in-differences. """ struct DiffinDiffsEstimator{A,T} <: AbstractStatsProcedure{A,T} end """ DefaultDID <: DiffinDiffsEstimator Default difference-in-differences estimator selected based on the context. """ const DefaultDID = DiffinDiffsEstimator{:DefaultDID, Tuple{}} _key(::Type{<:DiffinDiffsEstimator}) = :d _key(::AbstractString) = :name _key(::AbstractTreatment) = :tr _key(::AbstractParallel) = :pr _key(::Any) = throw(ArgumentError("unacceptable positional arguments")) function _totermset!(args::Dict{Symbol,Any}, s::Symbol) if haskey(args, s) && !(args[s] isa TermSet) arg = args[s] args[s] = arg isa Symbol ? termset(arg) : termset(arg...) end end """ parse_didargs!(args::Vector{Any}, kwargs::Dict{Symbol,Any}) Return a `Dict` that is suitable for being passed to [`valid_didargs`](@ref) for further processing. Any [`TreatmentTerm`](@ref) in `args` is decomposed. Any collection of terms is converted to `TermSet`. Keys are assigned to all positional arguments based on their types. An optional `name` for [`StatsSpec`](@ref) can be included in `args` as a string. The order of positional arguments is irrelevant. This function is required for `@specset` to work properly. """ function parse_didargs!(args::Vector{Any}, kwargs::Dict{Symbol,Any}) for arg in args if arg isa TreatmentTerm kwargs[_key(arg.tr)] = arg.tr kwargs[_key(arg.pr)] = arg.pr kwargs[:treatname] = arg.sym else kwargs[_key(arg)] = arg end end foreach(n->_totermset!(kwargs, n), (:treatintterms, :xterms)) return kwargs end """ valid_didargs(args::Dict{Symbol,Any}) Return a tuple of objects that can be accepted by the constructor of [`StatsSpec`](@ref). If no [`DiffinDiffsEstimator`](@ref) is found in `args`, try to select one based on other information. This function is required for `@specset` to work properly. """ function valid_didargs(args::Dict{Symbol,Any}) if haskey(args, :tr) && haskey(args, :pr) d = pop!(args, :d, DefaultDID) return valid_didargs(d, args[:tr], args[:pr], args) else throw(ArgumentError("not all required arguments are specified")) end end valid_didargs(d::Type{<:DiffinDiffsEstimator}, tr::AbstractTreatment, pr::AbstractParallel, ::Dict{Symbol,Any}) = error(d.instance, " is not implemented for $(typeof(tr)) and $(typeof(pr))") """ didspec(args...; kwargs...) Construct a [`StatsSpec`](@ref) for difference-in-differences with the specified arguments. """ function didspec(args...; kwargs...) args = Any[args...] kwargs = Dict{Symbol,Any}(kwargs...) return didspec(args, kwargs) end didspec(args::Vector{Any}, kwargs::Dict{Symbol,Any}) = StatsSpec(valid_didargs(parse_didargs!(args, kwargs))...) function _show_args(io::IO, sp::StatsSpec{<:DiffinDiffsEstimator}) if haskey(sp.args, :tr) || haskey(sp.args, :pr) print(io, ":") haskey(sp.args, :tr) && print(io, "\n ", sp.args[:tr]) haskey(sp.args, :pr) && print(io, "\n ", sp.args[:pr]) end end function did(args...; verbose::Bool=false, keep=nothing, keepall::Bool=false, kwargs...) args = Any[args...] kwargs = Dict{Symbol,Any}(kwargs...) sp = didspec(args, kwargs) return sp(verbose=verbose, keep=keep, keepall=keepall) end """ @did [option option=val ...] "name" args... kwargs... Conduct difference-in-differences estimation with the specified arguments. The order of the arguments is irrelevant. # Arguments - `[option option=val ...]`: optional settings for @did including keyword arguments passed to an instance of [`StatsSpec`](@ref). - `name::AbstractString`: an optional name for the [`StatsSpec`](@ref). - `args... kwargs...`: a list of arguments to be processed by [`parse_didargs!`](@ref) and [`valid_didargs`](@ref). # Notes When expanded outside [`@specset`](@ref), a [`StatsSpec`](@ref) is constructed and then estimated by calling this instance. Options for [`StatsSpec`] can be provided in a bracket `[...]` as the first argument after `@did` with each option separated by white space. For options that take a Boolean value, specifying the name of the option is enough for setting the value to be true. By default, only a result object that is a subtype of [`DIDResult`](@ref) is returned. When expanded inside [`@specset`](@ref), `@did` informs [`@specset`](@ref) the methods for processing the arguments. Any option specified in the bracket is ignored. Options for the behavior of `@did` can be provided in a bracket `[...]` as the first argument with each option separated by white space. For options that take a Boolean value, specifying the name of the option is enough for setting the value to be true. The following options are available for altering the behavior of `@did`: - `noproceed::Bool=false`: return the constructed [`StatsSpec`](@ref) without conducting the procedure. - `verbose::Bool=false`: print the name of each step when it is called. - `keep=nothing`: names (of type `Symbol`) of additional objects to be returned. - `keepall::Bool=false`: return all objects generated by procedures along with arguments from the [`StatsSpec`](@ref)s. - `pause::Int=0`: break the iteration over [`StatsStep`](@ref)s after finishing the specified number of steps (for debugging). """ macro did(args...) nargs = length(args) options = :(Dict{Symbol, Any}()) noproceed = false didargs = () if nargs > 0 op = args[1] if op isa Expr && op.head in (:vect, :hcat, :vcat) noproceed = _parse!(options, op.args) nargs > 1 && (didargs = args[2:end]) else didargs = args end end dargs, dkwargs = _args_kwargs(didargs) if noproceed return :(StatsSpec(valid_didargs(parse_didargs!($(esc(dargs)), $(esc(dkwargs))))...)) else return :(StatsSpec(valid_didargs(parse_didargs!($(esc(dargs)), $(esc(dkwargs))))...)(; $(esc(options))...)) end end """ AbstractDIDResult{TR<:AbstractTreatment} <: StatisticalModel Interface supertype for all types that collect estimation results for difference-in-differences with treatment of type `TR`. # Interface definition | Required method | Default definition | Brief description | |:---|:---|:---| | `coef(r)` | `r.coef` | Vector of point estimates for all coefficients including covariates | | `vcov(r)` | `r.vcov` | Variance-covariance matrix for estimates in `coef` | | `vce(r)` | `r.vce` | Covariance estimator | | `confint(r)` | Based on t or normal distribution | Confidence interval for estimates in `coef` | | `treatment(r)` | `r.tr` | Treatment specification | | `nobs(r)` | `r.nobs` | Number of observations (table rows) involved in estimation | | `outcomename(r)` | `r.yname` | Name of the outcome variable | | `coefnames(r)` | `r.coefnames` | Names (`Vector{String}`) of all coefficients including covariates | | `treatcells(r)` | `r.treatcells` | `Tables.jl`-compatible tabular description of treatment coefficients in the order of `coefnames` (without covariates) | | `weights(r)` | `r.weights` | Name of the column containing sample weights (if specified) | | `ntreatcoef(r)` | `size(treatcells(r), 1)` | Number of treatment coefficients | | `treatcoef(r)` | `view(coef(r), 1:ntreatcoef(r))` | A view of treatment coefficients | | `treatvcov(r)` | `(N = ntreatcoef(r); view(vcov(r), 1:N, 1:N))` | A view of variance-covariance matrix for treatment coefficients | | `treatnames(r)` | `coefnames(r)[1:ntreatcoef(r)]` | Names (`Vector{String}`) of treatment coefficients | | **Optional methods** | | | | `parent(r)` | `r.parent` or `r` | Result object from which `r` is generated | | `dof_residual(r)` | `r.dof_residual` or `nothing` | Residual degrees of freedom | | `responsename(r)` | `outcomename(r)` | Name of the outcome variable | | `coefinds(r)` | `r.coefinds` or `nothing` | Lookup table (`Dict{String,Int}`) from `coefnames` to integer indices (for retrieving estimates by name) | | `ncovariate(r)` | `length(coef(r)) - ntreatcoef(r)` | Number of covariate coefficients | """ abstract type AbstractDIDResult{TR<:AbstractTreatment} <: StatisticalModel end """ DIDResult{TR} <: AbstractDIDResult{TR} Supertype for all types that collect estimation results directly obtained from [`DiffinDiffsEstimator`](@ref) with treatment of type `TR`. """ abstract type DIDResult{TR} <: AbstractDIDResult{TR} end """ AggregatedDIDResult{TR,P<:DIDResult} <: AbstractDIDResult{TR} Supertype for all types that collect estimation results aggregated from a [`DIDResult`](@ref) of type `P` with treatment of type `TR`. """ abstract type AggregatedDIDResult{TR,P<:DIDResult} <: AbstractDIDResult{TR} end """ coef(r::AbstractDIDResult) Return the vector of point estimates for all coefficients. """ coef(r::AbstractDIDResult) = r.coef """ coef(r::AbstractDIDResult, name::String) coef(r::AbstractDIDResult, name::Symbol) coef(r::AbstractDIDResult, i::Int) coef(r::AbstractDIDResult, inds) Retrieve a point estimate by name (as in `coefnames`) or integer index. Return a vector of estimates if an iterable collection of names or integers are specified. Indexing by name requires the method [`coefinds(r)`](@ref). See also [`AbstractDIDResult`](@ref). """ coef(r::AbstractDIDResult, name::String) = coef(r)[coefinds(r)[name]] coef(r::AbstractDIDResult, name::Symbol) = coef(r, string(name)) coef(r::AbstractDIDResult, i::Int) = coef(r)[i] coef(r::AbstractDIDResult, inds) = [coef(r, ind) for ind in inds] """ coef(r::AbstractDIDResult, bys::Pair...) Return a vector of point estimates for treatment coefficients selected based on the specified functions that return either `true` or `false`. Depending on the argument(s) accepted by a function `f`, it is specified with argument `bys` as either `column_index => f` or `column_indices => f` where `column_index` is either a `Symbol` or `Int` for a column in [`treatcells`](@ref) and `column_indices` is an iterable collection of such indices for multiple columns. `f` is applied elementwise to each specified column to obtain a `BitVector` for selecting coefficients. If multiple `Pair`s are provided, the results are combined into one `BitVector` through bit-wise `and`. !!! note This method only selects estimates for treatment coefficients. Covariates are not taken into account. """ @inline function coef(r::AbstractDIDResult, bys::Pair...) inds = apply_and(treatcells(r), bys...) return treatcoef(r)[inds] end """ vcov(r::AbstractDIDResult) Return the variance-covariance matrix for all coefficient estimates. """ vcov(r::AbstractDIDResult) = r.vcov """ vcov(r::AbstractDIDResult, name1::Union{String, Symbol}, name2::Union{String, Symbol}=name1) vcov(r::AbstractDIDResult, i::Int, j::Int=i) vcov(r::AbstractDIDResult, inds) Retrieve the covariance between two coefficients by name (as in `coefnames`) or integer index. Return the variance if only one name or index is specified. Return a variance-covariance matrix for selected coefficients if an iterable collection of names or integers are specified. Indexing by name requires the method [`coefinds(r)`](@ref). See also [`AbstractDIDResult`](@ref). """ vcov(r::AbstractDIDResult, i::Int, j::Int=i) = vcov(r)[i,j] function vcov(r::AbstractDIDResult, name1::Union{String, Symbol}, name2::Union{String, Symbol}=name1) cfinds = coefinds(r) return vcov(r)[cfinds[string(name1)], cfinds[string(name2)]] end function vcov(r::AbstractDIDResult, inds) cfinds = coefinds(r) # inds needs to be one-dimensional for the output to be a matrix inds = [i isa Int ? i : cfinds[string(i)] for i in inds][:] return vcov(r)[inds, inds] end """ vcov(r::AbstractDIDResult, bys::Pair...) Return a variance-covariance matrix for treatment coefficients selected based on the specified functions that return either `true` or `false`. Depending on the argument(s) accepted by a function `f`, it is specified with argument `bys` as either `column_index => f` or `column_indices => f` where `column_index` is either a `Symbol` or `Int` for a column in [`treatcells`](@ref) and `column_indices` is an iterable collection of such indices for multiple columns. `f` is applied elementwise to each specified column to obtain a `BitVector` for selecting coefficients. If multiple `Pair`s are provided, the results are combined into one `BitVector` through bit-wise `and`. !!! note This method only selects estimates for treatment coefficients. Covariates are not taken into account. """ @inline function vcov(r::AbstractDIDResult, bys::Pair...) inds = apply_and(treatcells(r), bys...) return treatvcov(r)[inds, inds] end """ vce(r::AbstractDIDResult) Return the covariance estimator used to estimate variance-covariance matrix. """ vce(r::AbstractDIDResult) = r.vce """ confint(r::AbstractDIDResult; level::Real=0.95) Return a confidence interval for each coefficient estimate. The returned object is of type `Tuple{Vector{Float64}, Vector{Float64}}` where the first vector collects the lower bounds for all intervals and the second one collects the upper bounds. """ function confint(r::AbstractDIDResult; level::Real=0.95) dofr = dof_residual(r) if dofr === nothing scale = norminvcdf(1 - (1 - level) / 2) else scale = tdistinvcdf(dofr, 1 - (1 - level) / 2) end se = stderror(r) return coef(r) .- scale .* se, coef(r) .+ scale .* se end """ treatment(r::AbstractDIDResult) Return the treatment specification. """ treatment(r::AbstractDIDResult) = r.tr """ nobs(r::AbstractDIDResult) Return the number of observations (table rows) involved in estimation. """ nobs(r::AbstractDIDResult) = r.nobs """ outcomename(r::AbstractDIDResult) Return the name of outcome variable generated by `StatsModels.coefnames`. See also [`responsename`](@ref). """ outcomename(r::AbstractDIDResult) = r.yname """ coefnames(r::AbstractDIDResult) Return a vector of coefficient names. """ coefnames(r::AbstractDIDResult) = r.coefnames """ treatcells(r::AbstractDIDResult) Return a `Tables.jl`-compatible tabular description of treatment coefficients in the order of coefnames (without covariates). """ treatcells(r::AbstractDIDResult) = r.treatcells """ weights(r::AbstractDIDResult) Return the column name of the weight variable. Return `nothing` if `weights` is not specified for estimation. """ weights(r::AbstractDIDResult) = r.weightname """ ntreatcoef(r::AbstractDIDResult) Return the number of treatment coefficients. """ ntreatcoef(r::AbstractDIDResult) = size(treatcells(r), 1) """ treatcoef(r::AbstractDIDResult) Return a view of treatment coefficients. """ treatcoef(r::AbstractDIDResult) = view(coef(r), 1:ntreatcoef(r)) """ treatvcov(r::AbstractDIDResult) Return a view of variance-covariance matrix for treatment coefficients. """ treatvcov(r::AbstractDIDResult) = (N = ntreatcoef(r); view(vcov(r), 1:N, 1:N)) """ treatnames(r::AbstractDIDResult) Return a vector of names for treatment coefficients. """ treatnames(r::AbstractDIDResult) = coefnames(r)[1:ntreatcoef(r)] """ parent(r::AbstractDIDResult) Return the `AbstractDIDResult` from which `r` is generated. """ parent(r::AbstractDIDResult) = hasfield(typeof(r), :parent) ? r.parent : r """ dof_residual(r::AbstractDIDResult) Return the residual degrees of freedom. """ dof_residual(r::AbstractDIDResult) = hasfield(typeof(r), :dof_residual) ? r.dof_residual : nothing """ responsename(r::AbstractDIDResult) Return the name of outcome variable generated by `StatsModels.coefnames`. This method is an alias of [`outcomename`](@ref). """ responsename(r::AbstractDIDResult) = outcomename(r) """ coefinds(r::AbstractDIDResult) Return the map from coefficient names to integer indices for retrieving estimates by name. """ coefinds(r::AbstractDIDResult) = hasfield(typeof(r), :coefinds) ? r.coefinds : nothing """ ncovariate(r::AbstractDIDResult) Return the number of covariate coefficients. """ ncovariate(r::AbstractDIDResult) = length(coef(r)) - ntreatcoef(r) """ agg(r::DIDResult) Aggregate difference-in-differences estimates and return a subtype of [`AggregatedDIDResult`](@ref). The implementation depends on the type of `r`. """ agg(r::DIDResult) = error("agg is not implemented for $(typeof(r))") function coeftable(r::AbstractDIDResult; level::Real=0.95) cf = coef(r) se = stderror(r) ts = cf ./ se dofr = dof_residual(r) if dofr === nothing pv = 2 .* normccdf.(abs.(ts)) tname = "z" else pv = 2 .* tdistccdf.(dofr, abs.(ts)) tname = "t" end cil, ciu = confint(r, level=level) cnames = coefnames(r) levstr = isinteger(level*100) ? string(Integer(level*100)) : string(level*100) return CoefTable(Vector[cf, se, ts, pv, cil, ciu], ["Estimate", "Std. Error", tname, "Pr(>|$tname|)", "Lower $levstr%", "Upper $levstr%"], ["$(cnames[i])" for i = 1:length(cf)], 4, 3) end show(io::IO, r::AbstractDIDResult) = show(io, coeftable(r)) """ _treatnames(treatcells) Generate names for treatment coefficients. Assume `treatcells` is compatible with the `Tables.jl` interface. """ function _treatnames(treatcells) cols = columnnames(treatcells) ncol = length(cols) # Assume treatcells has at least one column c1 = cols[1] names = Ref(string(c1, ": ")).*string.(getcolumn(treatcells, c1)) if ncol > 1 for i in 2:ncol ci = cols[i] names .*= Ref(string(" & ", ci, ": ")).*string.(getcolumn(treatcells, ci)) end end return names end # Helper functions that parse the bys option for agg function _parse_bycells!(bycols::Vector, cells::VecColumnTable, by::Pair{Symbol}) lookup = getfield(cells, :lookup) _parse_bycells!(bycols, cells, lookup[by[1]]=>by[2]) end function _parse_bycells!(bycols::Vector, cells::VecColumnTable, by::Pair{Int}) if by[2] isa Function bycols[by[1]] = apply(cells, by[1]=>by[2]) else bycols[by[1]] = apply(cells, by[2][1]=>by[2][2]) end end function _parse_bycells!(bycols::Vector, cells::VecColumnTable, bys) eltype(bys) <: Pair || throw(ArgumentError("unaccepted type of bys")) for by in bys _parse_bycells!(bycols, cells, by) end end _parse_bycells!(bycols::Vector, cells::VecColumnTable, bys::Nothing) = nothing # Helper function for _parse_subset function _fill_x!(r::AbstractDIDResult, inds::BitVector) nx = ncovariate(r) nx > 0 && push!(inds, (false for i in 1:nx)...) end # Helper functions for handling subset option that may involves Pairs _parse_subset(r::AbstractDIDResult, by::Pair, fill_x::Bool) = (inds = apply_and(treatcells(r), by); fill_x && _fill_x!(r, inds); return inds) function _parse_subset(r::AbstractDIDResult, inds, fill_x::Bool) eltype(inds) <: Pair || return inds inds = apply_and(treatcells(r), inds...) fill_x && _fill_x!(r, inds) return inds end _parse_subset(r::AbstractDIDResult, ::Colon, fill_x::Bool) = fill_x ? (1:length(coef(r))) : 1:ntreatcoef(r) # Count number of elements selected by indices `inds` _nselected(inds) = eltype(inds) == Bool ? sum(inds) : length(inds) _nselected(::Colon) = throw(ArgumentError("cannot accept Colon (:)")) """ treatindex(ntcoef::Int, I) Extract indices referencing the treatment coefficients from `I` based on the total number of treatment coefficients `ntcoef`. """ treatindex(ntcoef::Int, ::Colon) = 1:ntcoef treatindex(ntcoef::Int, i::Real) = i<=ntcoef ? i : 1:0 treatindex(ntcoef::Int, I::AbstractVector{<:Real}) = view(I, I.<=ntcoef) treatindex(ntcoef::Int, I::AbstractVector{Bool}) = view(I, 1:ntcoef) treatindex(ntcoef::Int, i) = throw(ArgumentError("invalid index of type $(typeof(i))")) """ checktreatindex(inds, tinds) Check whether all indices for treatment coefficients `tinds` are positioned before any other index in `inds`. This is required to be true for methods such as `treatcoef` and `treatvcov` to work properly. If the test fails, an `ArgumentError` exception is thrown. """ function checktreatindex(inds::AbstractVector{<:Real}, tinds) length(tinds) == length(union(tinds, inds[1:length(tinds)])) || throw(ArgumentError("indices for treatment coefficients must come first")) end checktreatindex(inds::AbstractVector{Bool}, tinds) = true checktreatindex(inds, tinds) = true """ SubDIDResult{TR,P<:AbstractDIDResult,I,TI} <: AbstractDIDResult{TR} A view into a DID result of type `P` with indices for all coefficients of type `I` and indices for treatment coefficients of type `TI`. See also [`view(r::AbstractDIDResult, inds)`](@ref). """ struct SubDIDResult{TR,P<:AbstractDIDResult,I,TI} <: AbstractDIDResult{TR} parent::P inds::I treatinds::TI coefinds::Dict{String,Int} end @propagate_inbounds function SubDIDResult(p::AbstractDIDResult{TR}, inds) where {TR} @boundscheck if !checkindex(Bool, axes(coef(p), 1), inds) throw(BoundsError(p, inds)) end tinds = treatindex(ntreatcoef(p), inds) checktreatindex(inds, tinds) cnames = view(coefnames(p), inds) cfinds = Dict{String,Int}(n=>i for (i,n) in enumerate(cnames)) return SubDIDResult{TR, typeof(p), typeof(inds), typeof(tinds)}(p, inds, tinds, cfinds) end """ view(r::AbstractDIDResult, inds) Return a [`SubDIDResult`](@ref) that lazily references elements from `r` at the given index or indices `inds` without constructing a copied subset. """ @propagate_inbounds view(r::AbstractDIDResult, inds) = SubDIDResult(r, inds) coef(r::SubDIDResult) = view(coef(parent(r)), r.inds) vcov(r::SubDIDResult) = view(vcov(parent(r)), r.inds, r.inds) vce(r::SubDIDResult) = vce(parent(r)) treatment(r::SubDIDResult) = treatment(parent(r)) nobs(r::SubDIDResult) = nobs(parent(r)) outcomename(r::SubDIDResult) = outcomename(parent(r)) coefnames(r::SubDIDResult) = view(coefnames(parent(r)), r.inds) treatcells(r::SubDIDResult) = view(treatcells(parent(r)), r.treatinds) weights(r::SubDIDResult) = weights(parent(r)) ntreatcoef(r::SubDIDResult) = _nselected(r.treatinds) treatcoef(r::SubDIDResult) = view(treatcoef(parent(r)), r.treatinds) treatvcov(r::SubDIDResult) = view(treatvcov(parent(r)), r.treatinds, r.treatinds) treatnames(r::SubDIDResult) = view(treatnames(parent(r)), r.treatinds) dof_residual(r::SubDIDResult) = dof_residual(parent(r)) responsename(r::SubDIDResult) = responsename(parent(r)) """ TransformedDIDResult{TR,P,M} <: AbstractDIDResult{TR} Estimation results obtained from a linear transformation of all coefficient estimates from [`DIDResult`](@ref). See also [`TransSubDIDResult`](@ref), [`lincom`](@ref) and [`rescale`](@ref). # Parameters - `P`: type of the result that is transformed. - `M`: type of the matrix representing the linear transformation. """ struct TransformedDIDResult{TR,P,M} <: AbstractDIDResult{TR} parent::P linmap::M coef::Vector{Float64} vcov::Matrix{Float64} function TransformedDIDResult(r::AbstractDIDResult{TR}, linmap::AbstractMatrix{<:Real}, cf::Vector{Float64}, v::Matrix{Float64}) where {TR} return new{TR, typeof(r), typeof(linmap)}(r, linmap, cf, v) end end """ TransSubDIDResult{TR,P,M,I,TI} <: AbstractDIDResult{TR} Estimation results obtained from a linear transformation of a subset of coefficient estimates from [`DIDResult`](@ref). See also [`TransformedDIDResult`](@ref), [`lincom`](@ref) and [`rescale`](@ref). # Parameters - `P`: type of the result that is transformed. - `M`: type of the matrix representing the linear transformation. - `I`: type of indices for all coefficients. - `TI`: type of indices for treatment coefficients. """ struct TransSubDIDResult{TR,P,M,I,TI} <: AbstractDIDResult{TR} parent::P linmap::M coef::Vector{Float64} vcov::Matrix{Float64} inds::I treatinds::TI coefinds::Dict{String,Int} function TransSubDIDResult(r::AbstractDIDResult{TR}, linmap::AbstractMatrix{<:Real}, cf::Vector{Float64}, v::Matrix{Float64}, inds) where {TR} if !checkindex(Bool, axes(coef(r), 1), inds) throw(BoundsError(r, inds)) end tinds = treatindex(ntreatcoef(r), inds) checktreatindex(inds, tinds) cnames = view(coefnames(r), inds) cfinds = Dict{String,Int}(n=>i for (i,n) in enumerate(cnames)) return new{TR, typeof(r), typeof(linmap), typeof(inds), typeof(tinds)}( r, linmap, cf, v, inds, tinds, cfinds) end end const TransOrTransSub{TR} = Union{TransformedDIDResult{TR}, TransSubDIDResult{TR}} vce(r::TransOrTransSub) = vce(parent(r)) treatment(r::TransOrTransSub) = treatment(parent(r)) nobs(r::TransOrTransSub) = nobs(parent(r)) outcomename(r::TransOrTransSub) = outcomename(parent(r)) coefnames(r::TransformedDIDResult) = coefnames(parent(r)) coefnames(r::TransSubDIDResult) = view(coefnames(parent(r)), r.inds) treatcells(r::TransformedDIDResult) = treatcells(parent(r)) treatcells(r::TransSubDIDResult) = view(treatcells(parent(r)), r.treatinds) weights(r::TransOrTransSub) = weights(parent(r)) ntreatcoef(r::TransformedDIDResult) = ntreatcoef(parent(r)) ntreatcoef(r::TransSubDIDResult) = _nselected(r.treatinds) treatnames(r::TransformedDIDResult) = treatnames(parent(r)) treatnames(r::TransSubDIDResult) = view(treatnames(parent(r)), r.treatinds) dof_residual(r::TransOrTransSub) = dof_residual(parent(r)) responsename(r::TransOrTransSub) = responsename(parent(r)) coefinds(r::TransformedDIDResult) = coefinds(parent(r)) """ lincom(r::AbstractDIDResult, linmap::AbstractMatrix{<:Real}, subset=nothing) Linearly transform the coefficient estimates from DID result `r` through a matrix `linmap`. The number of columns of `linmap` must match the total number of coefficients from `r`. If `linmap` is not square (with fewer rows than columns), `subset` must be specified with indices representing coefficients that remain after the transformation. See also [`rescale`](@ref). """ function lincom(r::AbstractDIDResult, linmap::AbstractMatrix{<:Real}, subset::Nothing=nothing) nr, nc = size(linmap) length(coef(r)) == nc || throw(DimensionMismatch("linmap must have $(length(coef(r))) columns")) nr == nc || throw(ArgumentError("subset must be specified if linmap is not square")) cf = linmap * coef(r) v = linmap * vcov(r) * linmap' return TransformedDIDResult(r, linmap, cf, v) end function lincom(r::AbstractDIDResult, linmap::AbstractMatrix{<:Real}, subset) inds = _parse_subset(r, subset, true) nr, nc = size(linmap) length(coef(r)) == nc || throw(DimensionMismatch("linmap must have $(length(coef(r))) columns")) _nselected(inds) == nr || throw(ArgumentError("subset must select $nr elements")) cf = linmap * coef(r) v = linmap * vcov(r) * linmap' return TransSubDIDResult(r, linmap, cf, v, inds) end """ rescale(r::AbstractDIDResult, scale::AbstractVector{<:Real}, subset=nothing) rescale(r::AbstractDIDResult, by::Pair, subset=nothing) Rescale the coefficient estimates from DID result `r`. The order of elements in `scale` must match the order of coefficients. If the length of `scale` is smaller than the total number of coefficient, `subset` must be specified with indices representing coefficients that remain after the transformation. Alternatively, if `by` is specified in the same way for [`apply`](@ref), the scales can be computed based on values in [`treatcells(r)`](@ref). In this case, only treatment coefficients are transformed even if `subset` is not specified. See [`lincom`](@ref) for more general transformation. """ function rescale(r::AbstractDIDResult, scale::AbstractVector{<:Real}, subset::Nothing=nothing) N0 = length(coef(r)) N1 = length(scale) N0 == N1 || throw(ArgumentError( "subset must be specified if scale does not have $N0 elements")) cf = scale .* coef(r) v = Matrix{Float64}(undef, N0, N0) pv = vcov(r) @inbounds for j in 1:N0 for i in 1:N0 v[i, j] = scale[i]*scale[j]*pv[i, j] end end return TransformedDIDResult(r, Diagonal(scale), cf, v) end function rescale(r::AbstractDIDResult, scale::AbstractVector{<:Real}, subset) inds = _parse_subset(r, subset, true) N = length(scale) _nselected(inds) == N || throw(ArgumentError("subset must select $N elements")) cf = scale .* view(coef(r), inds) v = Matrix{Float64}(undef, N, N) pv = view(vcov(r), inds, inds) @inbounds for j in 1:N for i in 1:N v[i, j] = scale[i]*scale[j]*pv[i, j] end end return TransSubDIDResult(r, Diagonal(scale), cf, v, inds) end rescale(r::AbstractDIDResult, by::Pair, subset::Nothing=nothing) = rescale(r, apply(treatcells(r), by), 1:ntreatcoef(r)) function rescale(r::AbstractDIDResult, by::Pair, subset) inds = _parse_subset(r, subset, true) tinds = treatindex(ntreatcoef(r), inds) return rescale(r, apply(view(treatcells(r), tinds), by), inds) end """ ExportFormat Supertype for all types representing the format for exporting an [`AbstractDIDResult`](@ref). """ abstract type ExportFormat end """ StataPostHDF <: ExportFormat Export an [`AbstractDIDResult`](@ref) for Stata module [`posthdf`](https://github.com/junyuan-chen/posthdf). """ struct StataPostHDF <: ExportFormat end const DefaultExportFormat = ExportFormat[StataPostHDF()] """ getexportformat() Return the default [`ExportFormat`](@ref) for [`post!`](@ref). """ getexportformat() = DefaultExportFormat[1] """ setexportformat!(format::ExportFormat) Set the default [`ExportFormat`](@ref) for [`post!`](@ref). """ setexportformat!(format::ExportFormat) = (DefaultExportFormat[1] = format) """ post!(f, r; kwargs...) Export result `r` in a default [`ExportFormat`](@ref). The default format can be retrieved via [`getexportformat`](@ref) and modified via [`setexportformat!`](@ref). The keyword arguments that can be accepted depend on the format and the type of `r`. """ post!(f, r; kwargs...) = post!(f, getexportformat(), r; kwargs...) _statafield(v::Symbol) = string(v) _statafield(v::Union{Real, String, Vector{<:Real}, Vector{String}, Matrix{<:Real}}) = v _statafield(v::Vector{Symbol}) = string.(v) _statafield(::Nothing) = "" _statafield(v) = nothing function _postfields!(f, r::AbstractDIDResult, fields::AbstractVector{<:Union{Symbol, Pair{String,Symbol}}}) for k in fields if k isa Symbol s = string(k) n = k else s, n = k end v = _statafield(getfield(r, n)) v === nothing && throw(ArgumentError( "Field $n has a type that cannot be posted via posthdf")) f[s] = v end end _postat!(f, r::AbstractDIDResult, at) = nothing _postat!(f, r::AbstractDIDResult, at::AbstractVector) = (f["at"] = at) _postat!(f, r::AbstractDIDResult{<:DynamicTreatment}, at::Bool) = at && (f["at"] = treatcells(r).rel) """ post!(f, ::StataPostHDF, r::AbstractDIDResult; kwargs...) Export result `r` for Stata module [`posthdf`](https://github.com/junyuan-chen/posthdf). A subset of field values from `r` are placed in `f` by setting key-value pairs, where `f` can be either an `HDF5.Group` or any object that can be indexed by strings. # Keywords - `model::String=repr(typeof(r))`: name of the model. - `fields::Union{AbstractVector{<:Union{Symbol, Pair{String,Symbol}}}, Nothing}=nothing`: additional fields to be exported; alternative names can be specified with `Pair`s. - `at::Union{AbstractVector{<:Real}, Bool, Nothing}=nothing`: post the `at` vector in Stata. """ function post!(f, ::StataPostHDF, r::AbstractDIDResult; model::String=repr(typeof(r)), fields::Union{AbstractVector{<:Union{Symbol, Pair{String,Symbol}}}, Nothing}=nothing, at::Union{AbstractVector{<:Real}, Bool, Nothing}=nothing) f["model"] = model f["b"] = coef(r) f["V"] = vcov(r) f["vce"] = repr(vce(r)) f["N"] = nobs(r) f["depvar"] = string(outcomename(r)) f["coefnames"] = convert(AbstractVector{String}, coefnames(r)) f["weights"] = (w = weights(r); w === nothing ? "" : string(w)) f["ntreatcoef"] = ntreatcoef(r) dofr = dof_residual(r) dofr === nothing || (f["df_r"] = dofr) fields === nothing || _postfields!(f, r, fields) if at !== nothing pat = _postat!(f, r, at) pat === nothing && throw(ArgumentError( "Keyword argument `at` of type $(typeof(at)) is not accepted.")) pat == false || length(pat) != length(coef(r)) && throw(ArgumentError( "The length of at ($(length(pat))) does not match the length of b ($(length(coef(r))))")) end return f end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
16548
# A variant of SplitApplyCombine.groupfind using IdDict instead of Dictionaries.Dictionary function _groupfind(container) T = keytype(container) inds = IdDict{eltype(container), Vector{T}}() @inbounds for i in keys(container) push!(get!(Vector{T}, inds, container[i]), i) end return inds end function _refs_pool(col::AbstractArray, reftype::Type{<:Integer}=UInt32) refs = refarray(col) pool = refpool(col) labeled = pool !== nothing if !labeled refs, invpool, pool = _label(col, eltype(col), reftype) end return refs, pool, labeled end # Obtain unique labels for row-wise pairs of values from a1 and a2 when mult is large enough function _mult!(a1::AbstractArray, a2::AbstractArray, mult) z = zero(eltype(a1)) @inbounds for i in eachindex(a1) x1 = a1[i] x2 = a2[i] # Handle missing values represented by zeros if iszero(x1) || iszero(x2) a1[i] = z else a1[i] += mult * (x2 - 1) end end end """ findcell(cols::VecColumnTable) findcell(names, data, esample=Colon()) Group the row indices of a collection of data columns so that the combination of row values from these columns are the same within each group. Instead of directly providing the relevant portions of columns as [`VecColumnTable`](@ref)``, one may specify the `names` of columns from `data` of any `Tables.jl`-compatible table type over selected rows indicated by `esample`. Note that unless `esample` covers all rows of `data`, the row indices are those for the subsample selected based on `esample` rather than those for the full `data`. # Returns - `IdDict{Tuple, Vector{Int}}`: a map from unique row values to row indices. """ function findcell(cols::VecColumnTable) ncol = size(cols, 2) isempty(cols) && throw(ArgumentError("no data column is found")) refs, pool, labeled = _refs_pool(cols[1]) mult = length(pool) if ncol > 1 # Make a copy to be used as cache labeled && (refs = copy(refs)) @inbounds for n in 2:ncol refsn, pool, labeled = _refs_pool(cols[n]) multn = length(pool) _mult!(refs, refsn, mult) mult = mult * multn end end return _groupfind(refs) end findcell(names, data, esample=Colon()) = findcell(subcolumns(data, names, esample)) """ cellrows(cols::VecColumnTable, refrows::IdDict) A utility function for processing the object `refrows` returned by [`findcell`](@ref). Unique row values from `cols` corresponding to the keys in `refrows` are sorted lexicographically and stored as rows in a new `VecColumnTable`. Groups of row indices from the values of `refrows` are permuted to match the order of row values and collected in a `Vector`. # Returns - `cells::VecColumnTable`: unique row values from columns in `cols`. - `rows::Vector{Vector{Int}}`: row indices for each combination. """ function cellrows(cols::VecColumnTable, refrows::IdDict) isempty(refrows) && throw(ArgumentError("refrows is empty")) isempty(cols) && throw(ArgumentError("no data column is found")) ncol = length(cols) ncell = length(refrows) rows = Vector{Vector{Int}}(undef, ncell) columns = Vector{AbstractVector}(undef, ncol) for i in 1:ncol c = cols[i] if typeof(c) <: Union{ScaledArrOrSub, RotatingTimeArray} columns[i] = similar(c, ncell) else columns[i] = Vector{eltype(c)}(undef, ncell) end end refs = Vector{keytype(refrows)}(undef, ncell) r = 0 @inbounds for (k, v) in refrows r += 1 row1 = v[1] refs[r] = k for c in 1:ncol columns[c][r] = cols[c][row1] end end cells = VecColumnTable(columns, _names(cols), _lookup(cols)) p = sortperm(cells) # Replace each column of cells with a new one in the sorted order @inbounds for i in 1:ncol columns[i] = cells[i][p] end # Collect rows in the same order as cells @inbounds for i in 1:ncell rows[i] = refrows[refs[p[i]]] end return cells, rows end """ settime(time::AbstractArray, step; start, stop, reftype, rotation) Convert a column of time values to a [`ScaledArray`](@ref) for representing discretized time periods of uniform length. If `rotation` is specified (time values belong to multiple rotation groups), a [`RotatingTimeArray`](@ref) is returned with the `time` field being a [`ScaledArray`](@ref). The returned array ensures well-defined time intervals for operations involving relative time (such as [`lag`](@ref) and [`diff`](@ref)). See also [`aligntime`](@ref). # Arguments - `time::AbstractArray`: the array containing time values. - `step=nothing`: the length of each time interval; try `step=one(eltype(time))` if not specified. # Keywords - `start=nothing`: the first element of the `pool` of the returned [`ScaledArray`](@ref). - `stop=nothing`: the last element of the `pool` of the returned [`ScaledArray`](@ref). - `reftype::Type{<:Signed}=Int32`: the element type of the reference values for the [`ScaledArray`](@ref). - `rotation=nothing`: rotation groups in a rotating sampling design. """ function settime(time::AbstractArray, step=nothing; start=nothing, stop=nothing, reftype::Type{<:Signed}=Int32, rotation=nothing) T = eltype(time) T <: ValidTimeType && !(T <: RotatingTimeValue) || throw(ArgumentError("unaccepted element type $T from time column")) step === nothing && (step = one(T)) time = ScaledArray(time, start, step, stop; reftype=reftype) rotation === nothing || (time = RotatingTimeArray(rotation, time)) return time end """ aligntime(col::AbstractArray, time::ScaledArrOrSub) aligntime(col::AbstractArray, time::RotatingTimeArray) aligntime(data, colname::Union{Symbol,Integer}, timename::Union{Symbol,Integer}) Convert a column of time values `col` to a [`ScaledArray`](@ref) with a `pool` that has the same first element and step size as the `pool` from the [`ScaledArray`](@ref) `time`. If `time` is a [`RotatingTimeArray`](@ref) with the `time` field being a [`ScaledArray`](@ref), the returned array is also a [`RotatingTimeArray`](@ref) with the `time` field being the converted [`ScaledArray`](@ref). Alternative, the arrays may be specified with a `Tables.jl`-compatible `data` table and column indices `colname` and `timename`. See also [`settime`](@ref). This is useful for representing all discretized time periods with the same scale so that the underlying reference values returned by `DataAPI.refarray` can be directly comparable across the columns. """ aligntime(col::AbstractArray, time::ScaledArrOrSub) = align(col, time) aligntime(col::AbstractArray, time::RotatingTimeArray) = RotatingTimeArray(time.rotation, align(col, time.time)) aligntime(col::RotatingTimeArray, time::RotatingTimeArray) = RotatingTimeArray(time.rotation, align(col.time, time.time)) function aligntime(data, colname::Union{Symbol,Integer}, timename::Union{Symbol,Integer}) checktable(data) return aligntime(getcolumn(data, colname), getcolumn(data, timename)) end """ PanelStructure{R<:Signed, IP<:AbstractVector, TP<:AbstractVector} Panel data structure defined by unique combinations of unit ids and time periods. It contains the information required for certain operations such as [`lag`](@ref) and [`diff`](@ref). See also [`setpanel`](@ref). # Fields - `refs::Vector{R}`: reference values that allow obtaining time gaps by taking differences. - `invrefs::Dict{R, Int}`: inverse map from `refs` to indices. - `idpool::IP`: unique unit ids. - `timepool::TP`: sorted unique time periods. - `laginds::Dict{Int, Vector{Int}}`: a map from lag distances to vectors of indices of lagged values. """ struct PanelStructure{R<:Signed, IP<:AbstractVector, TP<:AbstractVector} refs::Vector{R} invrefs::Dict{R, Int} idpool::IP timepool::TP laginds::Dict{Int, Vector{Int}} function PanelStructure(refs::Vector{R}, idpool::IP, timepool::TP, laginds::Dict=Dict{Int, Vector{Int}}()) where {R,IP,TP} invrefs = Dict{R, Int}(ref=>i for (i, ref) in enumerate(refs)) return new{R,IP,TP}(refs, invrefs, idpool, timepool, laginds) end end """ setpanel(data, idname, timename; step, reftype, rotation) setpanel(id::AbstractArray, time::AbstractArray; step, reftype, rotation) Declare a [`PanelStructure`](@ref) which is required for certain operations such as [`lag`](@ref) and [`diff`](@ref). Unit IDs and time values can be provided either as a table containing the relevant columns or as arrays. `timestep` must be specified unless the `time` array is a [`ScaledArray`](@ref) that is returned by [`settime`](@ref). # Arguments - `data`: a `Tables.jl`-compatible data table. - `idname::Union{Symbol,Integer}`: the name of the column in `data` that contains unit IDs. - `timename::Union{Symbol,Integer}`: the name of the column in `data` that contains time values. - `id::AbstractArray`: the array containing unit IDs (only needed for the alternative method). - `time::AbstractArray`: the array containing time values (only needed for the alternative method). # Keywords - `step=nothing`: the length of each time interval; try `step=one(eltype(time))` if not specified. - `reftype::Type{<:Signed}=Int32`: the element type of the reference values for [`PanelStructure`](@ref). - `rotation=nothing`: rotation groups in a rotating sampling design; use [`RotatingTimeValue`](@ref)s as reference values. !!! note If the underlying data used to create the [`PanelStructure`](@ref) are modified. The changes will not be reflected in the existing instances of [`PanelStructure`](@ref). A new instance needs to be created with `setpanel`. """ function setpanel(id::AbstractArray, time::AbstractArray; step=nothing, reftype::Type{<:Signed}=Int32, rotation=nothing) eltype(time) <: ValidTimeType || throw(ArgumentError("unaccepted element type $(eltype(time)) from time column")) length(id) == length(time) || throw(DimensionMismatch( "id has length $(length(id)) while time has length $(length(time))")) refs, idpool, labeled = _refs_pool(id) labeled && (refs = copy(refs); idpool = copy(idpool)) time = settime(time, step; reftype=reftype, rotation=rotation) trefs = refarray(time) tpool = refpool(time) # Multiply 2 to create enough gaps between id groups for the largest possible lead/lag mult = 2 * length(tpool) _mult!(trefs, refs, mult) return PanelStructure(trefs, idpool, tpool) end function setpanel(data, idname::Union{Symbol,Integer}, timename::Union{Symbol,Integer}; step=nothing, reftype::Type{<:Signed}=Int32) checktable(data) return setpanel(getcolumn(data, idname), getcolumn(data, timename); step=step, reftype=reftype) end show(io::IO, ::PanelStructure) = print(io, "Panel Structure") function show(io::IO, ::MIME"text/plain", panel::PanelStructure) println(io, "Panel Structure:") println(IOContext(io, :limit=>true, :displaysize=>(1, 80)), " idpool: ", panel.idpool) println(IOContext(io, :limit=>true, :displaysize=>(1, 80)), " timepool: ", panel.timepool) print(IOContext(io, :limit=>true, :displaysize=>(1, 80)), " laginds: ", panel.laginds) end """ findlag!(panel::PanelStructure, l::Integer=1) Construct a vector of indices of the `l`th lagged values for all id-time combinations of `panel` and save the result in `panel.laginds`. If a lagged value does not exist, its index is filled with 0. See also [`ilag!`](@ref). """ function findlag!(panel::PanelStructure, l::Integer=1) abs(l) < length(panel.timepool) || throw(ArgumentError("|l| must be smaller than $(length(panel.timepool)); got $l")) refs = panel.refs invrefs = panel.invrefs T = eltype(refs) inds = Vector{Int}(undef, size(refs)) l = convert(T, l) z = zero(T) @inbounds for i in keys(refs) ref = refs[i] inds[i] = get(invrefs, ref-l, z) end panel.laginds[l] = inds return inds end """ findlead!(panel::PanelStructure, l::Integer=1) Construct a vector of indices of the `l`th lead values for all id-time combinations of `panel` and save the result in `panel.laginds`. If a lead value does not exist, its index is filled with 0. See also [`ilead!`](@ref). """ findlead!(panel::PanelStructure, l::Integer=1) = findlag!(panel, -l) """ ilag!(panel::PanelStructure, l::Integer=1) Return a vector of indices of the `l`th lagged values for all id-time combinations of `panel`. The indices are retrieved from `panel` if they have been collected before. Otherwise, they are created by calling [`findlag!`](@ref). See also [`ilead!`](@ref). """ function ilag!(panel::PanelStructure, l::Integer=1) il = get(panel.laginds, l, nothing) return il === nothing ? findlag!(panel, l) : il end """ ilead!(panel::PanelStructure, l::Integer=1) Return a vector of indices of the `l`th lead values for all id-time combinations of `panel`. The indices are retrieved from `panel` if they have been collected before. Otherwise, they are created by calling [`findlead!`](@ref). See also [`ilag!`](@ref). """ ilead!(panel::PanelStructure, l::Integer=1) = ilag!(panel, -l) """ lag(panel::PanelStructure, v::AbstractArray, l::Integer=1; default=missing) Return a vector of `l`th lagged values of `v` with missing values filled with `default`. The `panel` structure is respected. See also [`ilag!`](@ref) and [`lead`](@ref). """ function lag(panel::PanelStructure, v::AbstractArray, l::Integer=1; default=missing) length(v) == length(panel.refs) || throw(DimensionMismatch( "v has length $(length(v)) while expecting $(length(panel.refs))")) inds = ilag!(panel, l) out = default === missing ? similar(v, Union{eltype(v), Missing}) : similar(v) @inbounds for i in 1:length(v) out[i] = inds[i] == 0 ? default : v[inds[i]] end return out end """ lead(panel::PanelStructure, v::AbstractArray, l::Integer=1; default=missing) Return a vector of `l`th lead values of `v` with missing values filled with `default`. The `panel` structure is respected. See also [`ilead!`](@ref) and [`lag`](@ref). """ lead(panel::PanelStructure, v::AbstractArray, l::Integer=1; default=missing) = lag(panel, v, -l, default=default) function _diff!(dest::AbstractArray, v::AbstractArray, inds::AbstractArray, default) @inbounds for i in 1:length(v) dest[i] = inds[i] == 0 ? default : v[i] - v[inds[i]] end end """ diff!(dest::AbstractArray, panel::PanelStructure, v::AbstractArray; kwargs...) Take the differences of `v` within observations for each unit in `panel` and store the result in `dest`. By default, it calculates the first differences. See also [`diff`](@ref). # Keywords - `order::Integer=1`: the order of differences to be taken. - `l::Integer=1`: the time interval between each pair of observations. - `default=missing`: default values for indices where the differences do not exist. """ function diff!(dest::AbstractArray, panel::PanelStructure, v::AbstractArray; order::Integer=1, l::Integer=1, default=missing) length(dest) == length(v) || throw(DimensionMismatch( "dest has length $(length(dest)) while v has length $(length(v))")) 0 < order < length(panel.timepool) || throw(ArgumentError( "order must be between 0 and $(length(panel.timepool)); got $order")) inds = get(panel.laginds, l, nothing) inds === nothing && (inds = findlag!(panel, l)) _diff!(dest, v, inds, default) if order > 1 cache = similar(dest) for i in 2:order copy!(cache, dest) _diff!(dest, cache, inds, default) end end return dest end """ diff(panel::PanelStructure, v::AbstractArray; kwargs...) Return the differences of `v` within observations for each unit in `panel`. By default, it calculates the first differences. See also [`diff!`](@ref). # Keywords - `order::Integer=1`: the order of differences to be taken. - `l::Integer=1`: the time interval between each pair of observations. - `default=missing`: default values for indices where the differences do not exist. """ function diff(panel::PanelStructure, v::AbstractArray; order::Integer=1, l::Integer=1, default=missing) out = default === missing ? similar(v, Union{eltype(v), Missing}) : similar(v) diff!(out, panel, v, order=order, l=l, default=default) return out end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
11159
""" ParallelCondition Supertype for all types imposing conditions of parallel. """ abstract type ParallelCondition end @fieldequal ParallelCondition """ Unconditional <: ParallelCondition Assume some notion of parallel holds without conditions. """ struct Unconditional <: ParallelCondition end show(io::IO, ::Unconditional) = get(io, :compact, false) ? print(io, "U") : print(io, "Unconditional") """ unconditional() Alias for [`Unconditional()`](@ref). """ unconditional() = Unconditional() """ CovariateConditional <: ParallelCondition Supertype for all types assuming some notion of parallel holds after conditioning on covariates. """ abstract type CovariateConditional <: ParallelCondition end """ ParallelStrength Supertype for all types specifying the strength of parallel. """ abstract type ParallelStrength end """ Exact <: ParallelStrength Assume some notion of parallel holds exactly. """ struct Exact <: ParallelStrength end show(io::IO, ::Exact) = get(io, :compact, false) ? print(io, "P") : print(io, "Parallel") """ exact() Alias for [`Exact()`](@ref). """ exact() = Exact() """ Approximate <: ParallelStrength Supertype for all types assuming some notion of parallel holds approximately. """ abstract type Approximate <: ParallelStrength end """ AbstractParallel{C<:ParallelCondition, S<:ParallelStrength} Supertype for all parallel types. """ abstract type AbstractParallel{C<:ParallelCondition, S<:ParallelStrength} end @fieldequal AbstractParallel """ UnspecifiedParallel{C,S} <: AbstractParallel{C,S} A parallel trends assumption (PTA) without explicitly specified relations across treatment groups. See also [`unspecifiedpr`](@ref). With this parallel type, operations for complying with a PTA are suppressed. This is useful, for example, when the user-provided regressors and sample restrictions need to be accepted without any PTA-specific alteration. # Fields - `c::C`: an instance of [`ParallelCondition`](@ref). - `s::S`: an instance of [`ParallelStrength`](@ref). """ struct UnspecifiedParallel{C,S} <: AbstractParallel{C,S} c::C s::S function UnspecifiedParallel(c::ParallelCondition=Unconditional(), s::ParallelStrength=Exact()) return new{typeof(c),typeof(s)}(c, s) end end """ unspecifiedpr(c::ParallelCondition=Unconditional(), s::ParallelStrength=Exact()) Construct an [`UnspecifiedParallel`](@ref) with fields set by the arguments. This is an alias of the inner constructor of [`UnspecifiedParallel`](@ref). """ unspecifiedpr(c::ParallelCondition=Unconditional(), s::ParallelStrength=Exact()) = UnspecifiedParallel(c, s) show(io::IO, pr::UnspecifiedParallel) = print(IOContext(io, :compact=>true), "Unspecified{", pr.c, ",", pr.s, "}") function show(io::IO, ::MIME"text/plain", pr::UnspecifiedParallel) print(io, pr.s, " among unspecified treatment groups") pr.c isa Unconditional || print(io, ":\n ", pr.c) end """ TrendParallel{C,S} <: AbstractParallel{C,S} Supertype for all parallel types that assume a parallel trends assumption holds over all the relevant time periods. """ abstract type TrendParallel{C,S} <: AbstractParallel{C,S} end """ TrendOrUnspecifiedPR{C,S} Union type of [`TrendParallel{C,S}`](@ref) and [`UnspecifiedParallel{C,S}`](@ref). """ const TrendOrUnspecifiedPR{C,S} = Union{TrendParallel{C,S}, UnspecifiedParallel{C,S}} """ istreated(pr::TrendParallel, x) Test whether `x` represents the treatment time for a group of units that are not treated. See also [`istreated!`](@ref). """ function istreated end """ istreated!(out::AbstractVector{Bool}, pr::TrendParallel, x::AbstractArray) For each element in `x`, test whether it represents the treatment time for a group of units that are not treated and save the result in `out`. See also [`istreated`](@ref). """ function istreated! end """ NeverTreatedParallel{C,S} <: TrendParallel{C,S} Assume a parallel trends assumption holds between any group that received the treatment during the sample periods and a group that did not receive any treatment in any sample period. See also [`nevertreated`](@ref). # Fields - `e::Tuple{Vararg{ValidTimeType}}`: group indices for units that did not receive any treatment. - `c::C`: an instance of [`ParallelCondition`](@ref). - `s::S`: an instance of [`ParallelStrength`](@ref). """ struct NeverTreatedParallel{C,S} <: TrendParallel{C,S} e::Tuple{Vararg{ValidTimeType}} c::C s::S function NeverTreatedParallel(e, c::ParallelCondition, s::ParallelStrength) e = applicable(iterate, e) ? (unique!(sort!([e...]))...,) : (e,) isempty(e) && error("field `e` cannot be empty") return new{typeof(c),typeof(s)}(e, c, s) end end istreated(pr::NeverTreatedParallel, x) = !(x in pr.e) function istreated!(out::AbstractVector{Bool}, pr::NeverTreatedParallel, x::AbstractArray{<:Union{ValidTimeType, Missing}}) e = Set(pr.e) out .= .!(x .∈ Ref(e)) end function istreated!(out::AbstractVector{Bool}, pr::NeverTreatedParallel, x::ScaledArray{<:Union{ValidTimeType, Missing}}) refs = refarray(x) invpool = invrefpool(x) e = Set(invpool[c] for c in pr.e if haskey(invpool, c)) out .= .!(refs .∈ Ref(e)) end show(io::IO, pr::NeverTreatedParallel) = print(IOContext(io, :compact=>true), "NeverTreated{", pr.c, ",", pr.s, "}", length(pr.e)==1 ? string("(", pr.e[1], ")") : pr.e) function show(io::IO, ::MIME"text/plain", pr::NeverTreatedParallel) println(io, pr.s, " trends with any never-treated group:") print(io, " Never-treated groups: ", join(string.(pr.e), ", ")) pr.c isa Unconditional || print(io, "\n ", pr.c) end """ nevertreated(e, c::ParallelCondition, s::ParallelStrength) nevertreated(e; c=Unconditional(), s=Exact()) Construct a [`NeverTreatedParallel`](@ref) with fields set by the arguments. By default, `c` is set as [`Unconditional()`](@ref) and `s` is set as [`Exact()`](@ref). When working with `@formula`, a wrapper method of `nevertreated` calls this method. # Examples ```jldoctest; setup = :(using DiffinDiffsBase) julia> nevertreated(-1) Parallel trends with any never-treated group: Never-treated groups: -1 julia> typeof(nevertreated(-1)) NeverTreatedParallel{Unconditional,Exact} julia> nevertreated([-1, 0]) Parallel trends with any never-treated group: Never-treated groups: -1, 0 julia> nevertreated([-1, 0]) == nevertreated(-1:0) == nevertreated(Set([-1, 0])) true ``` """ nevertreated(e, c::ParallelCondition, s::ParallelStrength) = NeverTreatedParallel(e, c, s) nevertreated(e; c::ParallelCondition=Unconditional(), s::ParallelStrength=Exact()) = NeverTreatedParallel(e, c, s) """ NotYetTreatedParallel{C,S} <: TrendParallel{C,S} Assume a parallel trends assumption holds between any group that received the treatment relatively early and any group that received the treatment relatively late (or never receved). See also [`notyettreated`](@ref). # Fields - `e::Tuple{Vararg{ValidTimeType}}`: group indices for units that received the treatment relatively late. - `ecut::Tuple{Vararg{ValidTimeType}}`: user-specified period(s) when units in a group in `e` started to receive treatment or show anticipation effects. - `c::C`: an instance of [`ParallelCondition`](@ref). - `s::S`: an instance of [`ParallelStrength`](@ref). !!! note `ecut` could be different from `minimum(e)` if - never-treated groups are included and use indices with smaller values; - the sample has a rotating panel structure with periods overlapping with some others. """ struct NotYetTreatedParallel{C,S} <: TrendParallel{C,S} e::Tuple{Vararg{ValidTimeType}} ecut::Tuple{Vararg{ValidTimeType}} c::C s::S function NotYetTreatedParallel(e, ecut, c::ParallelCondition, s::ParallelStrength) e = applicable(iterate, e) ? (unique!(sort!([e...]))...,) : (e,) isempty(e) && throw(ArgumentError("field e cannot be empty")) ecut = applicable(iterate, ecut) ? (unique!(sort!([ecut...]))...,) : (ecut,) isempty(ecut) && throw(ArgumentError("field ecut cannot be empty")) eltype(e) == eltype(ecut) || throw(ArgumentError("e and ecut must have the same element type")) return new{typeof(c), typeof(s)}(e, ecut, c, s) end end istreated(pr::NotYetTreatedParallel, x) = !(x in pr.e) function istreated!(out::AbstractVector{Bool}, pr::NotYetTreatedParallel, x::AbstractArray{<:Union{ValidTimeType, Missing}}) e = Set(pr.e) out .= .!(x .∈ Ref(e)) end function istreated!(out::AbstractVector{Bool}, pr::NotYetTreatedParallel, x::ScaledArray{<:Union{ValidTimeType, Missing}}) refs = refarray(x) invpool = invrefpool(x) e = Set(invpool[c] for c in pr.e if haskey(invpool, c)) out .= .!(refs .∈ Ref(e)) end show(io::IO, pr::NotYetTreatedParallel) = print(IOContext(io, :compact=>true), "NotYetTreated{", pr.c, ",", pr.s, "}", length(pr.e)==1 ? string("(", pr.e[1], ")") : pr.e) function show(io::IO, ::MIME"text/plain", pr::NotYetTreatedParallel) println(io, pr.s, " trends with any not-yet-treated group:") println(io, " Not-yet-treated groups: ", join(string.(pr.e), ", ")) print(io, " Treated since: ", join(string.(pr.ecut), ", ")) pr.c isa Unconditional || print(io, "\n ", pr.c) end """ notyettreated(e, ecut, c::ParallelCondition, s::ParallelStrength) notyettreated(e, ecut=e; c=Unconditional(), s=Exact()) Construct a [`NotYetTreatedParallel`](@ref) with fields set by the arguments. By default, `c` is set as [`Unconditional()`](@ref) and `s` is set as [`Exact()`](@ref). When working with `@formula`, a wrapper method of `notyettreated` calls this method. # Examples ```jldoctest; setup = :(using DiffinDiffsBase) julia> notyettreated(5) Parallel trends with any not-yet-treated group: Not-yet-treated groups: 5 Treated since: 5 julia> typeof(notyettreated(5)) NotYetTreatedParallel{Unconditional,Exact} julia> notyettreated([-1, 5, 6], 5) Parallel trends with any not-yet-treated group: Not-yet-treated groups: -1, 5, 6 Treated since: 5 julia> notyettreated([4, 5, 6], [4, 5, 6]) Parallel trends with any not-yet-treated group: Not-yet-treated groups: 4, 5, 6 Treated since: 4, 5, 6 ``` """ notyettreated(e, ecut, c::ParallelCondition, s::ParallelStrength) = NotYetTreatedParallel(e, ecut, c, s) notyettreated(e, ecut=e; c::ParallelCondition=Unconditional(), s::ParallelStrength=Exact()) = NotYetTreatedParallel(e, ecut, c, s) termvars(c::ParallelCondition) = error("StatsModels.termvars is not defined for $(typeof(c))") termvars(::Unconditional) = Symbol[] termvars(s::ParallelStrength) = error("StatsModels.termvars is not defined for $(typeof(s))") termvars(::Exact) = Symbol[] termvars(pr::AbstractParallel) = error("StatsModels.termvars is not defined for $(typeof(pr))") termvars(pr::UnspecifiedParallel) = union(termvars(pr.c), termvars(pr.s)) termvars(pr::NeverTreatedParallel) = union(termvars(pr.c), termvars(pr.s)) termvars(pr::NotYetTreatedParallel) = union(termvars(pr.c), termvars(pr.s))
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
11691
""" checkdata!(args...) Check `data` is `Tables.AbstractColumns`-compatible and find valid rows for options `subset` and `weightname`. See also [`CheckData`](@ref). """ function checkdata!(data, subset::Union{BitVector, Nothing}, weightname::Union{Symbol, Nothing}) checktable(data) nrow = Tables.rowcount(data) if subset !== nothing length(subset) == nrow || throw(DimensionMismatch( "data contain $(nrow) rows while subset has $(length(subset)) elements")) # Do not modify subset in-place esample = copy(subset) else esample = trues(nrow) end # A cache that makes updating BitVector (esample or tr_rows) faster # See https://github.com/JuliaData/DataFrames.jl/pull/2726 aux = BitVector(undef, nrow) if weightname !== nothing colweights = getcolumn(data, weightname) if Missing <: eltype(colweights) aux .= .!ismissing.(colweights) esample .&= aux end aux[esample] .= view(colweights, esample) .> 0 esample[esample] .&= view(aux, esample) end sum(esample) == 0 && error("no nonmissing data") return (esample=esample, aux=aux) end """ CheckData <: StatsStep Call [`DiffinDiffsBase.checkdata!`](@ref) for some preliminary checks of the input data. """ const CheckData = StatsStep{:CheckData, typeof(checkdata!), true} required(::CheckData) = (:data,) default(::CheckData) = (subset=nothing, weightname=nothing) """ grouptreatintterms(treatintterms) Return the argument without change for allowing later comparisons based on object-id. See also [`GroupTreatintterms`](@ref). """ grouptreatintterms(treatintterms::TermSet) = (treatintterms=treatintterms,) """ GroupTreatintterms <: StatsStep Call [`DiffinDiffsBase.grouptreatintterms`](@ref) to obtain one of the instances of `treatintterms` that have been grouped by equality (`hash`) for allowing later comparisons based on object-id. This step is only useful when working with [`@specset`](@ref) and [`proceed`](@ref). """ const GroupTreatintterms = StatsStep{:GroupTreatintterms, typeof(grouptreatintterms), false} default(::GroupTreatintterms) = (treatintterms=TermSet(),) """ groupxterms(xterms) Return the argument without change for allowing later comparisons based on object-id. See also [`GroupXterms`](@ref). """ groupxterms(xterms::TermSet) = (xterms=xterms,) """ GroupXterms <: StatsStep Call [`DiffinDiffsBase.groupxterms`](@ref) to obtain one of the instances of `xterms` that have been grouped by equality (`hash`) for allowing later comparisons based on object-id. This step is only useful when working with [`@specset`](@ref) and [`proceed`](@ref). """ const GroupXterms = StatsStep{:GroupXterms, typeof(groupxterms), false} default(::GroupXterms) = (xterms=TermSet(),) """ groupcontrasts(contrasts) Return the argument without change for allowing later comparisons based on object-id. See also [`GroupContrasts`](@ref). """ groupcontrasts(contrasts::Union{Dict{Symbol,Any},Nothing}) = (contrasts=contrasts,) """ GroupContrasts <: StatsStep Call [`DiffinDiffsBase.groupcontrasts`](@ref) to obtain one of the instances of `contrasts` that have been grouped by equality (`hash`) for allowing later comparisons based on object-id. This step is only useful when working with [`@specset`](@ref) and [`proceed`](@ref). """ const GroupContrasts = StatsStep{:GroupContrasts, typeof(groupcontrasts), false} default(::GroupContrasts) = (contrasts=nothing,) function _checkscales(col1::AbstractArray, col2::AbstractArray, treatvars::Vector{Symbol}) if col1 isa ScaledArrOrSub || col2 isa ScaledArrOrSub col1 isa ScaledArrOrSub && col2 isa ScaledArrOrSub || throw(ArgumentError("time fields in both columns $(treatvars[1]) and $(treatvars[2]) must be ScaledArrays; see settime and aligntime")) first(DataAPI.refpool(col1)) == first(DataAPI.refpool(col2)) && scale(col1) == scale(col2) || throw(ArgumentError( "time fields in columns $(treatvars[1]) and $(treatvars[2]) are not aligned; see aligntime")) else eltype(col1) <: Integer || throw(ArgumentError( "columns $(treatvars[1]) and $(treatvars[2]) must be stored in ScaledArrays; see settime and aligntime")) end end function checktreatvars(::DynamicTreatment{SharpDesign}, pr::TrendOrUnspecifiedPR{Unconditional}, treatvars::Vector{Symbol}, data) # treatvars should be cohort and time variables col1 = getcolumn(data, treatvars[1]) col2 = getcolumn(data, treatvars[2]) T1 = nonmissingtype(eltype(col1)) T2 = nonmissingtype(eltype(col2)) T1 == T2 || throw(ArgumentError( "nonmissing elements from columns $(treatvars[1]) and $(treatvars[2]) have different types $T1 and $T2")) T1 <: ValidTimeType || throw(ArgumentError("column $(treatvars[1]) has unaccepted element type $(T1)")) if pr isa TrendParallel eltype(pr.e) == T1 || throw(ArgumentError("element type $(eltype(pr.e)) of control cohorts from $pr does not match element type $T1 from data; expect $T1")) end if T1 <: RotatingTimeValue col1 isa RotatingTimeArray && col2 isa RotatingTimeArray || throw(ArgumentError("columns $(treatvars[1]) and $(treatvars[2]) must be RotatingTimeArrays; see settime")) _checkscales(col1.time, col2.time, treatvars) else _checkscales(col1, col2, treatvars) end end function _overlaptime(tr::DynamicTreatment, esample::BitVector, tr_rows::BitVector, data) timeref = refarray(getcolumn(data, tr.time)) control_time = Set(view(timeref, .!tr_rows.&esample)) treated_time = Set(view(timeref, tr_rows.&esample)) return intersect(control_time, treated_time), control_time, treated_time end function overlap!(esample::BitVector, tr_rows::BitVector, aux::BitVector, tr::DynamicTreatment, ::NeverTreatedParallel{Unconditional}, treatname::Symbol, data) overlap_time, control_time, treated_time = _overlaptime(tr, esample, tr_rows, data) if !(length(control_time)==length(treated_time)==length(overlap_time)) aux[esample] .= view(refarray(getcolumn(data, tr.time)), esample) .∈ (overlap_time,) esample[esample] .&= view(aux, esample) end tr_rows .&= esample end function overlap!(esample::BitVector, tr_rows::BitVector, aux::BitVector, tr::DynamicTreatment, pr::NotYetTreatedParallel{Unconditional}, treatname::Symbol, data) timecol = getcolumn(data, tr.time) # First exclude cohorts not suitable for comparisons if !(eltype(timecol) <: RotatingTimeValue) invpool = invrefpool(timecol) e = invpool === nothing ? Set(pr.e) : Set(invpool[c] for c in pr.e) ecut = invpool === nothing ? pr.ecut[1] : invpool[pr.ecut[1]] isvalidcohort = x -> x < ecut || x in e else invpool = invrefpool(timecol.time) if invpool === nothing e = Set(pr.e) ecut = IdDict(e.rotation=>e.time for e in pr.ecut) else e = Set(RotatingTimeValue(c.rotation, invpool[c.time]) for c in pr.e) ecut = IdDict(e.rotation=>invpool[e.time] for e in pr.ecut) end isvalidcohort = x -> x.time < ecut[x.rotation] || x in e end aux[esample] .= isvalidcohort.(view(refarray(getcolumn(data, treatname)), esample)) esample[esample] .&= view(aux, esample) # Check overlaps among the remaining cohorts only overlap_time, _c, _t = _overlaptime(tr, esample, tr_rows, data) if !(eltype(timecol) <: RotatingTimeValue) filter!(x -> x < ecut, overlap_time) else filter!(x -> x.time < ecut[x.rotation], overlap_time) end aux[esample] .= view(refarray(timecol), esample) .∈ (overlap_time,) esample[esample] .&= view(aux, esample) tr_rows .&= esample end overlap!(esample::BitVector, tr_rows::BitVector, aux::BitVector, tr::DynamicTreatment, pr::UnspecifiedParallel{Unconditional}, treatname::Symbol, data) = nothing """ checkvars!(args...) Exclude rows with missing data or violate the overlap condition and find rows with data from treated units. See also [`CheckVars`](@ref). """ function checkvars!(data, pr::AbstractParallel, yterm::AbstractTerm, treatname::Symbol, esample::BitVector, aux::BitVector, treatintterms::TermSet, xterms::TermSet, ::Type, @nospecialize(trvars::Tuple), tr::AbstractTreatment) # Do not check eltype of treatintterms treatvars = union([treatname], trvars, termvars(pr)) checktreatvars(tr, pr, treatvars, data) allvars = union(treatvars, termvars(yterm), termvars(xterms)) for v in allvars col = getcolumn(data, v) if Missing <: eltype(col) aux .= .!ismissing.(col) esample .&= aux end end # Values of treatintterms from untreated units are ignored tr_rows = copy(esample) if !(pr isa UnspecifiedParallel) istreated!(view(aux, esample), pr, view(getcolumn(data, treatname), esample)) tr_rows[esample] .&= view(aux, esample) end treatintvars = termvars(treatintterms) for v in treatintvars col = getcolumn(data, v) if Missing <: eltype(col) aux[tr_rows] .= .!ismissing.(view(col, tr_rows)) esample[tr_rows] .&= view(aux, tr_rows) end end isempty(treatintvars) || (tr_rows[tr_rows] .&= view(esample, tr_rows)) overlap!(esample, tr_rows, aux, tr, pr, treatname, data) sum(esample) == 0 && error("no nonmissing data") return (esample=esample, tr_rows=tr_rows::BitVector) end """ CheckVars <: StatsStep Call [`DiffinDiffsBase.checkvars!`](@ref) to exclude invalid rows for relevant variables. """ const CheckVars = StatsStep{:CheckVars, typeof(checkvars!), true} required(::CheckVars) = (:data, :pr, :yterm, :treatname, :esample, :aux, :treatintterms, :xterms) transformed(::CheckVars, @nospecialize(nt::NamedTuple)) = (typeof(nt.tr), (termvars(nt.tr)...,)) combinedargs(step::CheckVars, allntargs) = combinedargs(step, allntargs, typeof(allntargs[1].tr)) combinedargs(::CheckVars, allntargs, ::Type{DynamicTreatment{SharpDesign}}) = (allntargs[1].tr,) copyargs(::CheckVars) = (5,) """ groupsample(esample) Return the argument without change for allowing later comparisons based on object-id. See also [`GroupSample`](@ref). """ groupsample(esample::BitVector) = (esample=esample,) """ GroupSample <: StatsStep Call [`DiffinDiffsBase.groupsample`](@ref) to obtain one of the instances of `esample` that have been grouped by equality (`hash`) for allowing later comparisons based on object-id. This step is only useful when working with [`@specset`](@ref) and [`proceed`](@ref). """ const GroupSample = StatsStep{:GroupSample, typeof(groupsample), false} required(::GroupSample) = (:esample,) """ makeweights(args...) Construct a generic `Weights` vector. See also [`MakeWeights`](@ref). """ function makeweights(data, esample::BitVector, weightname::Symbol) weights = Weights(convert(Vector{Float64}, view(getcolumn(data, weightname), esample))) all(isfinite, weights) || error("data column $weightname contain not-a-number values") return (weights=weights,) end function makeweights(data, esample::BitVector, weightname::Nothing) weights = uweights(sum(esample)) return (weights=weights,) end """ MakeWeights <: StatsStep Call [`DiffinDiffsBase.makeweights`](@ref) to create a generic `Weights` vector. """ const MakeWeights = StatsStep{:MakeWeights, typeof(makeweights), true} required(::MakeWeights) = (:data, :esample) default(::MakeWeights) = (weightname=nothing,)
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
13209
""" VecColumnTable <: AbstractColumns A `Tables.jl`-compatible column table that stores data as `Vector{AbstractVector}` and column names as `Vector{Symbol}`. Retrieving columns by column names is achieved with a `Dict{Symbol,Int}` that maps names to indices. This table type is designed for retrieving and iterating dynamically generated columns for which specialization on names and order of columns are not desired. It is not intended to be directly constructed for interactive usage. """ struct VecColumnTable <: AbstractColumns columns::Vector{AbstractVector} names::Vector{Symbol} lookup::Dict{Symbol,Int} function VecColumnTable(columns::Vector{AbstractVector}, names::Vector{Symbol}, lookup::Dict{Symbol,Int}) # Assume Symbols in names and lookup match length(columns) == length(names) == length(lookup) || throw(ArgumentError("arguments do not share the same length")) return new(columns, names, lookup) end end function VecColumnTable(columns::Vector{AbstractVector}, names::Vector{Symbol}) lookup = Dict{Symbol,Int}(names.=>keys(names)) return VecColumnTable(columns, names, lookup) end function VecColumnTable(data, subset=nothing) Tables.istable(data) || throw(ArgumentError("input data is not `Tables.jl`-compatible")) names = collect(Tables.columnnames(data)) ncol = length(names) columns = Vector{AbstractVector}(undef, ncol) cols = Tables.columns(data) if subset === nothing @inbounds for i in keys(names) columns[i] = Tables.getcolumn(cols, i) end else @inbounds for i in keys(names) columns[i] = view(Tables.getcolumn(cols, i), subset) end end return VecColumnTable(columns, names) end function VecColumnTable(cols::VecColumnTable, subset=nothing) subset === nothing && return cols columns = similar(_columns(cols)) @inbounds for i in keys(columns) columns[i] = view(cols[i], subset) end return VecColumnTable(columns, _names(cols), _lookup(cols)) end _columns(cols::VecColumnTable) = getfield(cols, :columns) _names(cols::VecColumnTable) = getfield(cols, :names) _lookup(cols::VecColumnTable) = getfield(cols, :lookup) ncol(cols::VecColumnTable) = length(_names(cols)) nrow(cols::VecColumnTable) = ncol(cols) > 0 ? length(_columns(cols)[1])::Int : 0 Base.size(cols::VecColumnTable) = (nrow(cols), ncol(cols)) function Base.size(cols::VecColumnTable, i::Integer) if i == 1 nrow(cols) elseif i == 2 ncol(cols) else throw(ArgumentError("VecColumnTable only have two dimensions")) end end Base.length(cols::VecColumnTable) = ncol(cols) Base.isempty(cols::VecColumnTable) = size(cols, 1) == 0 || size(cols, 2) == 0 @inline function Base.getindex(cols::VecColumnTable, i::Int) @boundscheck if !checkindex(Bool, axes(_columns(cols), 1), i) throw(BoundsError(cols, i)) end @inbounds return _columns(cols)[i] end @inline Base.getindex(cols::VecColumnTable, n::Symbol) = cols[_lookup(cols)[n]] @inline Base.getindex(cols::VecColumnTable, ns::AbstractArray{Symbol}) = map(n->cols[n], ns) @inline Base.getindex(cols::VecColumnTable, ::Colon) = _columns(cols)[:] @inline function Base.getindex(cols::VecColumnTable, I) @boundscheck if !checkindex(Bool, axes(_columns(cols), 1), I) throw(BoundsError(cols, I)) end @inbounds return _columns(cols)[I] end Base.values(cols::VecColumnTable) = _columns(cols) Base.haskey(cols::VecColumnTable, key::Symbol) = haskey(_lookup(cols), key) Base.haskey(cols::VecColumnTable, i::Int) = 0 < i <= length(_names(cols)) function Base.:(==)(x::VecColumnTable, y::VecColumnTable) size(x) == size(y) || return false _names(x) == _names(y) || return false eq = true for i in 1:size(x, 2) # missing could arise coleq = x[i] == y[i] isequal(coleq, false) && return false eq &= coleq end return eq end Base.view(cols::VecColumnTable, I) = VecColumnTable(cols, I) Base.show(io::IO, cols::VecColumnTable) = print(io, nrow(cols), '×', ncol(cols), " VecColumnTable") function Base.show(io::IO, ::MIME"text/plain", cols::VecColumnTable) show(io, cols) if ncol(cols) > 0 && nrow(cols) > 0 println(io, ':') nr, nc = displaysize(io) pretty_table(IOContext(io, :limit=>true, :displaysize=>(nr-3, nc)), cols, vlines=1:1, hlines=1:1, show_row_number=true, show_omitted_cell_summary=false, newline_at_end=false, vcrop_mode=:middle) end end Base.summary(cols::VecColumnTable) = string(nrow(cols), '×', ncol(cols), ' ', nameof(typeof(cols))) Base.summary(io::IO, cols::VecColumnTable) = print(io, summary(cols)) Tables.getcolumn(cols::VecColumnTable, i::Int) = cols[i] Tables.getcolumn(cols::VecColumnTable, n::Symbol) = cols[n] Tables.columnnames(cols::VecColumnTable) = _names(cols) Tables.schema(cols::VecColumnTable) = Tables.Schema{(_names(cols)...,), Tuple{(eltype(col) for col in _columns(cols))...}}() Tables.materializer(::VecColumnTable) = VecColumnTable Tables.columnindex(cols::VecColumnTable, n::Symbol) = _lookup(cols)[n] Tables.columntype(cols::VecColumnTable, n::Symbol) = eltype(cols[n]) Tables.rowcount(cols::VecColumnTable) = nrow(cols) """ subcolumns(data, names, rows=Colon(); nomissing=true) Construct a [`VecColumnTable`](@ref) from `data` using columns specified with `names` over selected `rows`. By default, columns are converted to drop support for missing values. When possible, resulting columns share memory with original columns. """ function subcolumns(data, names, rows=Colon(); nomissing=true) Tables.istable(data) || throw(ArgumentError("input data is not `Tables.jl`-compatible")) names = names isa Vector{Symbol} ? names : Symbol[names...] ncol = length(names) columns = Vector{AbstractVector}(undef, ncol) lookup = Dict{Symbol,Int}() @inbounds for i in keys(names) col = view(Tables.getcolumn(data, names[i]), rows) nomissing && (col = disallowmissing(col)) columns[i] = col lookup[names[i]] = i end return VecColumnTable(columns, names, lookup) end subcolumns(data, names::Symbol, rows=Colon(); nomissing=true) = subcolumns(data, [names], rows, nomissing=nomissing) const VecColsRow = Tables.ColumnsRow{VecColumnTable} ncol(r::VecColsRow) = length(r) _rowhash(cols::Tuple{AbstractVector}, r::Int, h::UInt=zero(UInt))::UInt = hash(cols[1][r], h) function _rowhash(cols::Tuple{Vararg{AbstractVector}}, r::Int, h::UInt=zero(UInt))::UInt h = hash(cols[1][r], h) _rowhash(Base.tail(cols), r, h) end # hash is implemented following DataFrames.DataFrameRow for getting unique row values # Column names are not taken into account Base.hash(r::VecColsRow, h::UInt=zero(UInt)) = _rowhash(ntuple(c->Tables.getcolumns(r)[c], ncol(r)), Tables.getrow(r), h) # Column names are not taken into account function Base.isequal(r1::VecColsRow, r2::VecColsRow) length(r1) == length(r2) || return false return all(((a, b),) -> isequal(a, b), zip(r1, r2)) end # Column names are not taken into account function Base.isless(r1::VecColsRow, r2::VecColsRow) length(r1) == length(r2) || throw(ArgumentError("compared VecColsRow do not have the same length")) for (a, b) in zip(r1, r2) isequal(a, b) || return isless(a, b) end return false end Base.sortperm(cols::VecColumnTable; @nospecialize(kwargs...)) = sortperm(collect(Tables.rows(cols)); kwargs...) # names and lookup are not copied function Base.sort(cols::VecColumnTable; @nospecialize(kwargs...)) p = sortperm(cols; kwargs...) columns = similar(_columns(cols)) i = 0 @inbounds for col in cols i += 1 columns[i] = col[p] end return VecColumnTable(columns, _names(cols), _lookup(cols)) end function Base.sort!(cols::VecColumnTable; @nospecialize(kwargs...)) p = sortperm(cols; kwargs...) @inbounds for col in cols col .= col[p] end end """ apply(d, by::Pair) Apply a function elementwise to the specified column(s) in a `Tables.jl`-compatible table `d` and return the result. Depending on the argument(s) accepted by a function `f`, it is specified with argument `by` as either `column_index => f` or `column_indices => f` where `column_index` is either a `Symbol` or `Int` for a column in `d` and `column_indices` is an iterable collection of such indices for multiple columns. `f` is applied elementwise to each specified column to obtain an array of returned values. """ apply(d, by::Pair{Symbol,<:Function}) = map(by[2], Tables.getcolumn(d, by[1])) apply(d, @nospecialize(by::Pair)) = map(by[2], (Tables.getcolumn(d, c) for c in by[1])...) """ apply_and!(inds::BitVector, d, by::Pair) apply_and!(inds::BitVector, d, bys::Pair...) Apply a function that returns `true` or `false` elementwise to the specified column(s) in a `Tables.jl`-compatible table `d` and then update the elements in `inds` through bitwise `and` with the returned array. If an array instead of a function is provided, elementwise equality (`==`) comparison is applied between the column and the array. See also [`apply_and`](@ref). The way a function is specified is the same as how it is done with [`apply`](@ref). If multiple `Pair`s are provided, `inds` are updated for each returned array through bitwise `and`. """ function apply_and!(inds::BitVector, d, by::Pair{Symbol,<:Function}) aux = map(by[2], Tables.getcolumn(d, by[1])) inds .&= aux return inds end function apply_and!(inds::BitVector, d, @nospecialize(by::Pair)) if by[2] isa Function aux = map(by[2], (Tables.getcolumn(d, c) for c in by[1])...) else aux = Tables.getcolumn(d, by[1]).==by[2] end inds .&= aux return inds end function apply_and!(inds::BitVector, d, @nospecialize(bys::Pair...)) for by in bys apply_and!(inds, d, by) end return inds end """ apply_and(d, by::Pair) apply_and(d, bys::Pair...) Apply a function that returns `true` or `false` elementwise to the specified column(s) in a `Tables.jl`-compatible table `d` and return the result. If an array instead of a function is provided, elementwise equality (`==`) comparison is applied between the column and the array. See also [`apply_and!`](@ref). The way a function is specified is the same as how it is done with [`apply`](@ref). If multiple `Pair`s are provided, the returned array is obtained by combining arrays returned by each function through bitwise `and`. """ apply_and(d, by::Pair{Symbol,<:Any}) = Tables.getcolumn(d, by[1]).==by[2] function apply_and(d, by::Pair{Symbol,<:Function}) src = Tables.getcolumn(d, by[1]) out = similar(BitArray, size(src)) map!(by[2], out, src) return out end function apply_and(d, @nospecialize(by::Pair)) if by[2] isa Function src = ((Tables.getcolumn(d, c) for c in by[1])...,) out = similar(BitArray, size(src[1])) map!(by[2], out, src...) return out else return Tables.getcolumn(d, by[1]).==by[2] end end function apply_and(d, @nospecialize(bys::Pair...)) inds = apply_and(d, bys[1]) apply_and!(inds, d, bys[2:end]...) return inds end _parse_subset(cols::VecColumnTable, by::Pair) = (inds = apply_and(cols, by); return inds) function _parse_subset(cols::VecColumnTable, inds) eltype(inds) <: Pair || return inds inds = apply_and(cols, inds...) return inds end _parse_subset(::VecColumnTable, ::Colon) = Colon() """ TableIndexedMatrix{T,M,R,C} <: AbstractMatrix{T} Matrix with row and column indices that can be selected based on row values in a `Tables.jl`-compatible table respectively. This is useful when how elements are stored into the matrix are determined by the rows of the tables. # Parameters - `T`: element type of the matrix. - `M`: type of the matrix. - `R`: type of the table paired with the row indices. - `C`: type of the table paired with the column indices. # Fields - `m::M`: the matrix that stores the elements. - `r::R`: a table with the same number of rows with `m`. - `c::C`: a table of which the number of rows is equal to the number of columns of `m`. """ struct TableIndexedMatrix{T,M,R,C} <: AbstractMatrix{T} m::M r::R c::C function TableIndexedMatrix(m::AbstractMatrix, r, c) Tables.istable(r) || throw(ArgumentError("r is not `Tables.jl`-compatible")) Tables.istable(c) || throw(ArgumentError("c is not `Tables.jl`-compatible")) size(m, 1) == Tables.rowcount(r) || throw(DimensionMismatch("m and r do not have the same number of rows")) size(m, 2) == Tables.rowcount(c) || throw(DimensionMismatch( "the number of columns of m does not match the number of rows of c")) return new{eltype(m), typeof(m), typeof(r), typeof(c)}(m, r, c) end end Base.size(tm::TableIndexedMatrix) = size(tm.m) Base.getindex(tm::TableIndexedMatrix, i) = tm.m[i] Base.getindex(tm::TableIndexedMatrix, i, j) = tm.m[i,j] Base.IndexStyle(::Type{<:TableIndexedMatrix{T,M}}) where {T,M} = IndexStyle(M)
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
4514
""" TermSet <: AbstractSet{AbstractTerm} Wrapped `Set{AbstractTerm}` that specifies a collection of terms. Commonly used methods for `Set` work in the same way for `TermSet`. Compared with `StatsModels.TermOrTerms`, it does not maintain order of terms but is more suitable for dynamically constructed terms. """ struct TermSet <: AbstractSet{AbstractTerm} terms::Set{AbstractTerm} TermSet(set::Set{AbstractTerm}) = new(set) end """ TermSet([itr]) TermSet(ts::Union{Int, Symbol, AbstractTerm}...) Construct a [`TermSet`](@ref) from a collection of terms. Instead of passing an iterable collection, one may pass the terms as arguments directly. In the latter case, any `Int` or `Symbol` will be converted to a `Term`. See also [`termset`](@ref), which is an alias for the constructor. """ TermSet() = TermSet(Set{AbstractTerm}()) TermSet(ts) = TermSet(Set{AbstractTerm}(ts)) TermSet(ts::Union{Int, Symbol, AbstractTerm}...) = TermSet(Set{AbstractTerm}(t isa AbstractTerm ? t : term(t) for t in ts)) """ termset([itr]) termset(ts::Union{Int, Symbol, AbstractTerm}...) Construct a [`TermSet`](@ref) from a collection of terms. Instead of passing an iterable collection, one may pass the terms as arguments directly. In the latter case, any `Int` or `Symbol` will be converted to a `Term`. """ termset() = TermSet(Set{AbstractTerm}()) termset(ts) = TermSet(Set{AbstractTerm}(ts)) termset(ts::Union{Int, Symbol, AbstractTerm}...) = TermSet(Set{AbstractTerm}(t isa AbstractTerm ? t : term(t) for t in ts)) Base.isempty(ts::TermSet) = isempty(ts.terms) Base.length(ts::TermSet) = length(ts.terms) Base.in(x, ts::TermSet) = in(x, ts.terms) Base.push!(ts::TermSet, x) = push!(ts.terms, x) Base.pop!(ts::TermSet, x) = pop!(ts.terms, x) Base.pop!(ts::TermSet, x, default) = pop!(ts.terms, x, default) Base.delete!(ts::TermSet, x) = delete!(ts.terms, x) Base.empty!(ts::TermSet) = empty!(ts.terms) Base.eltype(::Type{TermSet}) = AbstractTerm Base.iterate(ts::TermSet, i...) = iterate(ts.terms, i...) Base.emptymutable(::TermSet, ::Type{<:AbstractTerm}) = termset() const Terms{N} = NTuple{N, AbstractTerm} where N ==(@nospecialize(a::Terms), @nospecialize(b::Terms)) = length(a)==length(b) && all(t->t in b, a) ==(@nospecialize(a::InteractionTerm), @nospecialize(b::InteractionTerm)) = a.terms==b.terms """ TreatmentTerm{T<:AbstractTreatment} <: AbstractTerm A term that contains specifications on treatment and parallel trends assumption. See also [`treat`](@ref). # Fields - `sym::Symbol`: the column name of data representing treatment status. - `tr::T`: a treatment type that specifies the causal parameters of interest. - `pr::P`: a parallel type that specifies the parallel trends assumption. """ struct TreatmentTerm{T<:AbstractTreatment,P<:AbstractParallel} <: AbstractTerm sym::Symbol tr::T pr::P end """ treat(s::Symbol, t::AbstractTreatment, p::AbstractParallel) Construct a [`TreatmentTerm`](@ref) with fields set by the arguments. """ treat(s::Symbol, t::AbstractTreatment, p::AbstractParallel) = TreatmentTerm(s, t, p) isintercept(t::AbstractTerm) = t in (InterceptTerm{true}(), ConstantTerm(1)) isomitsintercept(t::AbstractTerm) = t in (InterceptTerm{false}(), ConstantTerm(0), ConstantTerm(-1)) """ parse_intercept(ts::TermSet) Remove any `ConstantTerm` or `InterceptTerm` and return Boolean values indicating whether terms explictly requiring including/excluding the intercept exist. This function is useful for obtaining a unique way of specifying the intercept before going through the `schema`--`apply_schema` pipeline defined in `StatsModels`. """ function parse_intercept!(ts::TermSet) hasintercept = false hasomitsintercept = false for t in ts if isintercept(t) delete!(ts, t) hasintercept = true end if isomitsintercept(t) delete!(ts, t) hasomitsintercept = true end end return hasintercept, hasomitsintercept end schema(ts::TermSet, data, hints=nothing) = Schema(t=>concrete_term(t, VecColumnTable(data), hints) for t in ts) concrete_term(t::Term, dt::VecColumnTable, hint) = concrete_term(t, getproperty(dt, t.sym), hint) concrete_term(t::Term, dt::VecColumnTable, hints::Dict{Symbol}) = concrete_term(t, getproperty(dt, t.sym), get(hints, t.sym, nothing)) concrete_term(::Term, ::VecColumnTable, hint::AbstractTerm) = hint termvars(ts::TermSet) = mapreduce(termvars, union, ts, init=Symbol[])
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
4715
""" RotatingTimeValue{R, T} A wrapper around a time value for distinguishing potentially different rotation group it could belong to in a rotating sampling design. See also [`rotatingtime`](@ref) and [`settime`](@ref). # Fields - `rotation::R`: a rotation group in a rotating sampling design. - `time::T`: a time value belonged to the rotation group. """ struct RotatingTimeValue{R, T} rotation::R time::T end RotatingTimeValue(::Type{RotatingTimeValue{R,T}}, rotation, time) where {R,T} = RotatingTimeValue(convert(R, rotation), convert(T, time)) """ rotatingtime(rotation, time) Construct [`RotatingTimeValue`](@ref)s from `rotation` and `time`. This method simply broadcasts the default constructor over the arguments. """ rotatingtime(rotation, time) = RotatingTimeValue.(rotation, time) # Compare time first isless(x::RotatingTimeValue, y::RotatingTimeValue) = isequal(x.time, y.time) ? isless(x.rotation, y.rotation) : isless(x.time, y.time) isless(x::RotatingTimeValue, y) = isless(x.time, y) isless(x, y::RotatingTimeValue) = isless(x, y.time) isless(::RotatingTimeValue, ::Missing) = true isless(::Missing, ::RotatingTimeValue) = false Base.isequal(x::RotatingTimeValue, y::RotatingTimeValue) = isequal(x.rotation, y.rotation) && isequal(x.time, y.time) function ==(x::RotatingTimeValue, y::RotatingTimeValue) req = x.rotation == y.rotation isequal(req, missing) && return missing teq = x.time == y.time isequal(teq, missing) && return missing return req && teq end ==(x::RotatingTimeValue, y) = x.time == y ==(x, y::RotatingTimeValue) = x == y.time ==(::RotatingTimeValue, ::Missing) = missing ==(::Missing, ::RotatingTimeValue) = missing Base.zero(::Type{RotatingTimeValue{R,T}}) where {R,T} = RotatingTimeValue(zero(R), zero(T)) Base.iszero(x::RotatingTimeValue) = iszero(x.time) Base.one(::Type{RotatingTimeValue{R,T}}) where {R,T} = RotatingTimeValue(one(R), one(T)) Base.isone(x::RotatingTimeValue) = isone(x.time) Base.convert(::Type{RotatingTimeValue{R,T}}, x::RotatingTimeValue) where {R,T} = RotatingTimeValue(convert(R, x.rotation), convert(T, x.time)) Base.nonmissingtype(::Type{RotatingTimeValue{R,T}}) where {R,T} = RotatingTimeValue{nonmissingtype(R), nonmissingtype(T)} Base.iterate(x::RotatingTimeValue) = (x, nothing) Base.iterate(x::RotatingTimeValue, ::Any) = nothing Base.length(x::RotatingTimeValue) = 1 show(io::IO, x::RotatingTimeValue) = print(io, x.rotation, '_', x.time) function show(io::IO, ::MIME"text/plain", x::RotatingTimeValue) println(io, typeof(x), ':') println(io, " rotation: ", x.rotation) print(io, " time: ", x.time) end """ RotatingTimeArray{T<:RotatingTimeValue,N,C,I} <: AbstractArray{T,N} Array type for [`RotatingTimeValue`](@ref)s that stores the field values `rotation` and `time` in two arrays for efficiency. The two arrays that hold the field values for all elements can be accessed as properties. """ struct RotatingTimeArray{T<:RotatingTimeValue,N,C,I} <: AbstractArray{T,N} a::StructArray{T,N,C,I} RotatingTimeArray(a::StructArray{T,N,C,I}) where {T,N,C,I} = new{T,N,C,I}(a) end """ RotatingTimeArray(rotation::AbstractArray, time::AbstractArray) Construct a [`RotatingTimeValue`](@ref) from arrays of `rotation` and `time`. """ function RotatingTimeArray(rotation::AbstractArray, time::AbstractArray) a = StructArray{RotatingTimeValue{eltype(rotation), eltype(time)}}((rotation, time)) return RotatingTimeArray(a) end _getarray(a::RotatingTimeArray) = getfield(a, :a) Base.size(a::RotatingTimeArray) = size(_getarray(a)) Base.IndexStyle(::Type{<:RotatingTimeArray{<:Any,<:Any,<:Any,I}}) where I = I === Int ? IndexLinear() : IndexCartesian() Base.@propagate_inbounds Base.getindex(a::RotatingTimeArray, i::Int) = _getarray(a)[i] Base.@propagate_inbounds Base.getindex(a::RotatingTimeArray, I) = RotatingTimeArray(_getarray(a).rotation[I], _getarray(a).time[I]) Base.@propagate_inbounds Base.setindex!(a::RotatingTimeArray, v, i::Int) = setindex!(_getarray(a), v, i) Base.@propagate_inbounds Base.setindex!(a::RotatingTimeArray, v, I) = setindex!(_getarray(a), v, I) @inline Base.view(a::RotatingTimeArray, I...) = RotatingTimeArray(view(_getarray(a), I...)) Base.similar(a::RotatingTimeArray, dims::Dims=size(a)) = RotatingTimeArray(similar(_getarray(a), dims)) Base.similar(a::RotatingTimeArray, dims::Int...) = similar(a, dims) Base.getproperty(a::RotatingTimeArray, n::Symbol) = getproperty(_getarray(a), n) DataAPI.refarray(a::RotatingTimeArray) = RotatingTimeArray(DataAPI.refarray(a.rotation), DataAPI.refarray(a.time)) const ValidTimeType = Union{Signed, TimeType, Period, RotatingTimeValue}
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
2946
""" TreatmentSharpness Supertype for all types specifying the sharpness of treatment. """ abstract type TreatmentSharpness end @fieldequal TreatmentSharpness """ SharpDesign <: TreatmentSharpness Assume identical treatment within each treatment group. """ struct SharpDesign <: TreatmentSharpness end show(io::IO, ::SharpDesign) = get(io, :compact, false) ? print(io, "S") : print(io, "Sharp") """ sharp() Alias for [`SharpDesign()`](@ref). """ sharp() = SharpDesign() """ AbstractTreatment Supertype for all treatment types. """ abstract type AbstractTreatment end @fieldequal AbstractTreatment """ DynamicTreatment{S<:TreatmentSharpness} <: AbstractTreatment Specify an absorbing binary treatment with effects allowed to evolve over time. See also [`dynamic`](@ref). # Fields - `time::Symbol`: column name of data representing calendar time. - `exc::Tuple{Vararg{Int}}`: excluded relative time. - `s::S`: an instance of [`TreatmentSharpness`](@ref). """ struct DynamicTreatment{S<:TreatmentSharpness} <: AbstractTreatment time::Symbol exc::Tuple{Vararg{Int}} s::S function DynamicTreatment(time::Symbol, exc, s::TreatmentSharpness) exc = exc !== nothing ? (unique!(sort!([exc...]))...,) : () return new{typeof(s)}(time, exc, s) end end show(io::IO, tr::DynamicTreatment) = print(IOContext(io, :compact=>true), "Dynamic{", tr.s, "}", length(tr.exc)==1 ? string("(", tr.exc[1], ")") : tr.exc) function show(io::IO, ::MIME"text/plain", tr::DynamicTreatment) println(io, tr.s, " dynamic treatment:") println(io, " column name of time variable: ", tr.time) print(io, " excluded relative time: ", isempty(tr.exc) ? "none" : join(string.(tr.exc), ", ")) end """ dynamic(time::Symbol, exc, s::TreatmentSharpness=sharp()) Construct a [`DynamicTreatment`](@ref) with fields set by the arguments. By default, `s` is set as [`SharpDesign`](@ref). When working with `@formula`, a wrapper method of `dynamic` calls this method. # Examples ```jldoctest; setup = :(using DiffinDiffsBase) julia> dynamic(:month, -1) Sharp dynamic treatment: column name of time variable: month excluded relative time: -1 julia> typeof(dynamic(:month, -1)) DynamicTreatment{SharpDesign} julia> dynamic(:month, -3:-1) Sharp dynamic treatment: column name of time variable: month excluded relative time: -3, -2, -1 julia> dynamic(:month, [-2,-1], sharp()) Sharp dynamic treatment: column name of time variable: month excluded relative time: -2, -1 ``` """ dynamic(time::Symbol, exc, s::TreatmentSharpness=sharp()) = DynamicTreatment(time, exc, s) termvars(s::TreatmentSharpness) = error("StatsModels.termvars is not defined for $(typeof(s))") termvars(::SharpDesign) = Symbol[] termvars(tr::AbstractTreatment) = error("StatsModels.termvars is not defined for $(typeof(tr))") termvars(tr::DynamicTreatment) = [tr.time, termvars(tr.s)...]
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
1416
""" @fieldequal Supertype Define a method of `==` for all subtypes of `Supertype` such that `==` returns true if two instances have the same field values. """ macro fieldequal(Supertype) return esc(quote function ==(x::T, y::T) where T <: $Supertype f = fieldnames(T) getfield.(Ref(x),f) == getfield.(Ref(y),f) end end) end """ exampledata() Return the names of available example datasets. """ exampledata() = (:hrs, :nsw, :mpdta) """ exampledata(name::Union{Symbol,String}) Return a `CSV.File` containing the example dataset with the specified `name`. """ function exampledata(name::Union{Symbol,String}) Symbol(name) in exampledata() || throw(ArgumentError("example dataset $(name) does not exist")) path = (@__DIR__)*"/../data/$(name).csv.gz" cols = open(path) |> GzipDecompressorStream |> read |> CSV.File |> VecColumnTable # Avoid customized index type for columns from CSV.File for i in 1:ncol(cols) col = _columns(cols)[i] _columns(cols)[i] = convert(Vector, col) end return cols end # Check whether the input data is a column table function checktable(data) istable(data) || throw(ArgumentError("data of type $(typeof(data)) is not `Tables.jl`-compatible")) Tables.columnaccess(data) || throw(ArgumentError("data of type $(typeof(data)) is not a column table")) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
5399
using DiffinDiffsBase: RefArray, validpool, scaledlabel @testset "ScaledArray" begin refs = repeat(1:5, outer=2) pool = Date(1):Year(1):Date(5) invpool = Dict(p=>i for (i, p) in enumerate(pool)) sa = ScaledArray(RefArray(refs), pool, invpool) ssa = view(sa, 3:5) @test sa.refs === refs @test scale(sa) == Year(1) @test scale(ssa) == Year(1) @test size(sa) == (10,) @test IndexStyle(typeof(sa)) == IndexLinear() x = 1:10 @test validpool(x, Int, 10, -1, nothing, true) == 10:-1:1 @test_throws ArgumentError validpool(x, Int, 1, -1, 10, true) p = PooledArray(x) p[1] = 2 p[10] = 9 @test validpool(p, Int, nothing, 1, nothing, true) == 1:10 @test_throws ArgumentError validpool(p, Int, 2, 1, 9, true) @test validpool(p, Int, 2, 1, nothing, false) == 2:9 @test_throws ArgumentError validpool(p, Int, 2, 1, 8, false) s = ScaledArray(1.0:2.0:9.0, 1.0, 2, 10) ss = validpool(s, Float64, 1, 2, 9, true) @test ss == 1.0:2.0:9.0 @test eltype(ss) == Float64 @test_throws ArgumentError validpool(1:5, Int, 1, nothing, 1, true) @test_throws ArgumentError validpool(1:5, Int, 1, Year(1), 1, true) @test_throws ArgumentError validpool(1:5, Int, 1, 0, 1, true) sa1 = ScaledArray(p, 2, usepool=false) @test sa1.refs == [1, repeat(1:4, inner=2)..., 4] @test sa1.pool == 2:2:9 @test sa1 != sa sa2 = ScaledArray(sa1, 2, 1, 10) @test sa2.refs == [1, repeat(1:2:7, inner=2)..., 7] @test sa2.pool == 2:10 @test sa2 == sa1 sa3 = ScaledArray(sa2, reftype=Int16, start=0, stop=8, usepool=false) @test sa3.refs == [3, repeat(3:2:9, inner=2)..., 9] @test eltype(sa3.refs) == Int16 @test sa3.pool == 0:8 @test sa3 == sa2 sa4 = ScaledArray(sa3, start=2, stop=8, usepool=false) @test sa4.refs == [1, repeat(1:2:7, inner=2)..., 7] @test sa4.pool == 2:8 @test sa4 == sa3 sa5 = ScaledArray(sa4, usepool=false) @test sa5.refs == sa4.refs @test sa5.refs !== sa4.refs sa6 = ScaledArray([missing, 1, 2], 1) @test eltype(sa6) == Union{Int,Missing} @test sa6.refs == 0:2 @test eltype(sa6.refs) == Int32 @test ismissing(sa6[1]) @test_throws ArgumentError ScaledArray(sa5, stop=7, usepool=false) @test_throws ArgumentError ScaledArray(RefArray(1:3), 1.0:0.5:3.0, Dict{Int,Int}()) @test similar(sa, 4) == ScaledArray(RefArray(ones(Int, 4)), sa.pool, Dict{Date,Int}()) @test similar(sa, (4,)) == similar(view(sa, 1:5), 4) == similar(sa, 4) xs = Date(5):Year(-1):Date(1) sa1 = align(xs, sa) @test sa1.pool == pool xs = Date(0):Year(1):Date(4) @test_throws ArgumentError align(xs, sa) sa1 = ScaledArray(sa, Year(-1)) xs = Date(2):Year(1):Date(6) @test_throws ArgumentError align(xs, sa1) @test refarray(sa) === sa.refs @test refvalue(sa, 1) == Date(1) @test refpool(sa) === sa.pool @test invrefpool(sa) === sa.invpool @test refarray(ssa) == view(sa.refs, 3:5) @test refvalue(ssa, 1) == Date(1) @test refpool(ssa) === sa.pool @test invrefpool(ssa) === sa.invpool @test ssa == sa[3:5] @test sa[1] == Date(1) @test sa[1:2] == sa[[1,2]] == sa[(1:10).<3] == Date.(1:2) @test sa[1:2] isa ScaledArray @test ssa[1:2] isa ScaledArray sa[1] = Date(10) @test sa[1] == Date(10) sa[1:2] .= Date(100) @test sa[1:2] == [Date(100), Date(100)] @test last(sa.pool) == Date(100) @test_throws MethodError sa[1] = missing sa = allowmissing(sa) sa[1] = missing @test ismissing(sa[1]) @test_throws ArgumentError disallowmissing(sa) sa[1] = Date(1) sa = disallowmissing(sa) @test eltype(sa) == Date end @testset "scaledlabel" begin x = Date.(10:-2:0) pl = Date(-1):Year(1):Date(11) refs, pool, invpool = scaledlabel(x, Year(1), start=Date(-1), stop=Date(11)) @test refs == 12:-2:2 @test eltype(refs) == Int32 @test pool == pl pl = Date(0):Year(2):Date(10) ip = Dict(p=>i for (i, p) in enumerate(pl)) refs, pool, invpool = scaledlabel(x, Year(2), Int16) @test refs == 6:-1:1 @test eltype(refs) == Int16 @test pool == pl @test invpool == ip @test valtype(invpool) == Int16 x = ScaledArray(RefArray(refs), Date(0):Year(2):Date(10), invpool) refs1, pool1, invpool1 = scaledlabel(x, Year(2)) @test refs1 == x.refs && refs1 !== x.refs @test eltype(refs1) == Int32 @test pool1 == x.pool @test invpool1 == x.invpool && invpool1 !== x.invpool refs1, pool1, invpool1 = scaledlabel(x, Year(2), Int16) @test refs1 == 6:-1:1 @test eltype(refs1) == Int16 @test pool1 == pl @test invpool1 == ip @test valtype(invpool1) == Int16 refs1, pool1, invpool1 = scaledlabel(x, Year(1), start=Date(-1), stop=Date(11)) @test refs1 == 12:-2:2 @test pool1 == Date(-1):Year(1):Date(11) refs, pool, invpool = scaledlabel(1.0:200.0, 1, Int8, Int) @test refs == 1:200 @test eltype(refs) == Int16 @test pool == 1:200 @test eltype(pool) == Int @test invpool == Dict(i=>Int(i) for i in 1.0:200.0) refs, pool, invpool = scaledlabel(1:typemax(Int16), 1, Int8) @test refs == 1:typemax(Int16) @test eltype(refs) == Int16 @test valtype(invpool) == Int16 refs, pool, invpool = scaledlabel([missing, 1, 2], 1) @test refs == 0:2 @test eltype(refs) == Int32 end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
21371
const testterm = treat(:g, TR, PR) function valid_didargs(d::Type{TestDID}, ::AbstractTreatment, ::AbstractParallel, args::Dict{Symbol,Any}) name = get(args, :name, "") ns = (setdiff([keys(args)...], [:name, :d])...,) args = NamedTuple{ns}(map(n->args[n], ns)) return name, d, args end @testset "DiffinDiffsEstimator" begin d = DefaultDID() @test length(d) == 0 @test eltype(d) == StatsStep @test_throws BoundsError d[1] @test collect(d) == StatsStep[] @test iterate(d) === nothing d = TestDID() @test length(d) == 2 @test eltype(d) == StatsStep @test d[1] == TestStep() @test d[1:2] == [TestStep(), TestNextStep()] @test d[[2,1]] == [TestNextStep(), TestStep()] @test_throws BoundsError d[3] @test_throws MethodError d[:a] @test collect(d) == StatsStep[TestStep(), TestNextStep()] @test iterate(d) == (TestStep(), 2) @test iterate(d, 2) === (TestNextStep(), 3) @test iterate(d, 3) === nothing end @testset "parse_didargs!" begin args = Dict{Symbol,Any}(:xterms=>(term(:x),), :treatintterms=>:z) _totermset!(args, :xterms) @test args[:xterms] == TermSet(term(:x)) _totermset!(args, :treatintterms) @test args[:treatintterms] == TermSet(term(:z)) @test parse_didargs!(Any["test"], Dict{Symbol,Any}()) == Dict{Symbol,Any}(:name=>"test") args = parse_didargs!([TestDID, TR, PR], Dict{Symbol,Any}(:a=>1, :b=>2)) @test args == Dict{Symbol,Any}(pairs((d=TestDID, tr=TR, pr=PR, a=1, b=2))) args = parse_didargs!(["test", testterm, TestDID], Dict{Symbol,Any}()) @test args == Dict{Symbol,Any}(pairs((d=TestDID, tr=TR, pr=PR, name="test", treatname=:g))) @test_throws ArgumentError parse_didargs!(['a', :a, 1], Dict{Symbol,Any}()) @test parse_didargs!(Any[TestDID, DefaultDID], Dict{Symbol,Any}()) == Dict{Symbol,Any}(:d=>DefaultDID) end @testset "valid_didargs" begin arg = Dict{Symbol,Any}(pairs((d=TestDID, tr=TR, pr=PR))) @test valid_didargs(arg) == ("", TestDID, (tr=TR, pr=PR)) arg = Dict{Symbol,Any}(pairs((name="name", d=TestDID, tr=TR, pr=PR))) @test valid_didargs(arg) == ("name", TestDID, (tr=TR, pr=PR)) arg = Dict{Symbol,Any}(pairs((d=TestDID, tr=TR, a=1))) @test_throws ArgumentError valid_didargs(arg) arg = Dict{Symbol,Any}(pairs((tr=TR, pr=PR))) @test_throws ErrorException valid_didargs(arg) arg = Dict{Symbol,Any}(pairs((d=NotImplemented, tr=TR, pr=PR))) @test_throws ErrorException valid_didargs(arg) end @testset "StatsSpec" begin @testset "== ≊" begin sp1 = StatsSpec("", DefaultDID, NamedTuple()) sp2 = StatsSpec("", DefaultDID, NamedTuple()) @test sp1 == sp2 @test sp1 ≊ sp2 sp1 = StatsSpec("", DefaultDID, (tr=TR, pr=PR, a=1, b=2)) sp2 = StatsSpec("", DefaultDID, (pr=PR, tr=TR, b=2, a=1)) @test sp1 != sp2 @test sp1 ≊ sp2 sp2 = StatsSpec("", DefaultDID, (tr=TR, pr=PR, a=1.0, b=2.0)) @test sp1 == sp2 @test sp1 ≊ sp2 sp2 = StatsSpec("", DefaultDID, (tr=TR, pr=PR, a=1, b=2, c=3)) @test !(sp1 ≊ sp2) sp2 = StatsSpec("", DefaultDID, (tr=TR, pr=PR, a=1, b=1)) @test !(sp1 ≊ sp2) end @testset "show" begin sp = StatsSpec("", DefaultDID, NamedTuple()) @test sprint(show, sp) == "unnamed" @test sprint(show, MIME("text/plain"), sp) == "unnamed (StatsSpec for DefaultDID)" sp = StatsSpec("name", DefaultDID, NamedTuple()) @test sprint(show, sp) == "name" @test sprint(show, MIME("text/plain"), sp) == "name (StatsSpec for DefaultDID)" sp = StatsSpec("", TestDID, (tr=dynamic(:time,-1), pr=nevertreated(-1))) @test sprint(show, sp) == "unnamed" @test sprint(show, MIME("text/plain"), sp) == """ unnamed (StatsSpec for TestDID): Dynamic{S}(-1) NeverTreated{U,P}(-1)""" sp = StatsSpec("", TestDID, (tr=dynamic(:time,-1),)) @test sprint(show, sp) == "unnamed" @test sprint(show, MIME("text/plain"), sp) == """ unnamed (StatsSpec for TestDID): Dynamic{S}(-1)""" sp = StatsSpec("name", TestDID, (pr=notyettreated(-1),)) @test sprint(show, sp) == "name" @test sprint(show, MIME("text/plain"), sp) == """ name (StatsSpec for TestDID): NotYetTreated{U,P}(-1)""" end end @testset "didspec @did" begin @test_throws ArgumentError @did [noproceed] @test_throws ArgumentError didspec() sp0 = StatsSpec("", TestDID, (tr=TR, pr=PR, a=1, b=2)) sp1 = didspec(TestDID, TR, PR, a=1, b=2) @test sp1 ≊ sp0 @test sp0 ≊ @did [noproceed] TR a=1 b=2 PR TestDID sp2 = StatsSpec("name", TestDID, (tr=TR, pr=PR, a=1, b=2)) sp3 = didspec("name", TR, PR, TestDID, b=2, a=1) @test sp2 ≊ sp1 @test sp3 ≊ sp2 @test sp3 ≊ @did [noproceed] TR PR TestDID "name" b=2 a=1 sp4 = StatsSpec("name", TestDID, (tr=TR, pr=PR, treatname=:g)) sp5 = didspec(TestDID, testterm) @test sp5 ≊ sp4 @test sp4 ≊ @did [noproceed] TestDID testterm "name" sp6 = StatsSpec("", TestDID, (tr=TR, pr=PR, yterm=term(:y), treatname=:g, treatintterms=TermSet(term(:z)), xterms=TermSet(term(:x)))) @test sp6 ≊ @did [noproceed] TestDID yterm=term(:y) testterm treatintterms=:z xterms=:x end @testset "did @did" begin r = result(TestDID, NamedTuple()).result d0 = @did TestDID TR PR d1 = @did PR TR TestDID @test d0 == r @test d1 == d0 @test did(TestDID, TR, PR) == r @test did(PR, TR, TestDID) == r d = @did [keepall] TestDID testterm @test d ≊ (tr=TR, pr=PR, treatname=:g, str=sprint(show, TR), spr=sprint(show, PR), next="next"*sprint(show, TR), result=r) @test did(TestDID, testterm; keepall=true) == d d0 = @did [keepall] TestDID yterm=term(:y) testterm treatintterms=() xterms=() @test d0 ≊ merge(d, (yterm=term(:y), treatintterms=TermSet(), xterms=TermSet())) d0 = @did [keepall] TestDID yterm=term(:y) testterm treatintterms=:z xterms=:x @test d0 ≊ merge(d, (yterm=term(:y), treatintterms=TermSet(term(:z)), xterms=TermSet(term(:x)))) d = @did [keep=:treatname] TestDID testterm @test d ≊ (treatname=:g, result=r) @test did(TestDID, testterm; keep=:treatname) == d d = @did [keep=[:treatname,:tr]] TestDID testterm @test d ≊ (treatname=:g, tr=TR, result=r) @test did(TestDID, testterm; keep=[:treatname,:tr]) == d @test_throws ArgumentError @did TestDID @test_throws ArgumentError did(TestDID) @test_throws ArgumentError @did TestDID TR @test_throws ArgumentError did(TestDID, TR) @test_throws ArgumentError @did TestDID TR PR 1 @test_throws ArgumentError did(TestDID, TR, PR, 1) @test_throws ErrorException @did NotImplemented TR PR @test_throws ErrorException did(NotImplemented, TR, PR) @test_throws ArgumentError @did [keep] TestDID testterm @test_throws ArgumentError did(TestDID, testterm, keep=true) @test_throws ArgumentError @did [keep=1] TestDID testterm @test_throws ArgumentError did(TestDID, testterm, keep=1) @test_throws ArgumentError @did [keep="treatname"] TestDID testterm @test_throws ArgumentError did(TestDID, testterm, keep="treatname") end @testset "@specset @did" begin s = @specset [noproceed] begin @did TestDID TR PR end @test s == [didspec(TestDID, TR, PR)] @test proceed(s) == [@did TestDID TR PR] s = @specset [noproceed] begin @did TestDID TR PR @did PR TR TestDID end @test s == StatsSpec[didspec(TestDID, TR, PR), didspec(PR, TR, TestDID)] s = @specset [noproceed] DefaultDID PR a=1 begin @did TR PR TestDID a=2 @did TR TestDID end @test s[1] ≊ didspec(TestDID, TR, PR; a=2) @test s[2] ≊ didspec(TestDID, TR, PR; a=1) s = @specset [noproceed] DefaultDID PR begin @did [keep=:treatname verbose] TestDID testterm end @test s[1] ≊ didspec(TestDID, TR, PR; treatname=:g) s = @specset [noproceed] for i in 1:2 @did "name"*"$i" TestDID TR PR a=i end @test s[1] ≊ didspec("name1", TestDID, TR, PR; a=1) @test s[2] ≊ didspec("name2", TestDID, TR, PR; a=2) s = @specset [noproceed] DefaultDID PR a=1 begin @did "name" TR PR TestDID a=0 for i in 1:2 @did "name"*"$i" TR TestDID a=i end end @test s[1] ≊ didspec("name", TestDID, TR, PR; a=0) @test s[2] ≊ didspec("name1", TestDID, TR, PR; a=1) @test s[3] ≊ didspec("name2", TestDID, TR, PR; a=2) end @testset "DIDResult" begin r = TestResult(2, 2) @test coef(r) == r.coef @test coef(r, 1) == 1 @test coef(r, "rel: 1 & c: 1") == 1 @test coef(r, :c5) == 5 @test coef(r, 1:2) == [1.0, 2.0] @test coef(r, 5:-1:3) == [5.0, 4.0, 3.0] @test coef(r, (1, :c5, "rel: 1 & c: 1")) == [1.0, 5.0, 1.0] @test coef(r, [1 "rel: 1 & c: 1" :c5]) == [1.0 1.0 5.0] @test coef(r, :rel=>x->x==1) == [1.0, 2.0] @test coef(r, :rel=>x->x==1, :c=>x->x==1) == [1.0] @test coef(r, (:rel, :c)=>(x, y)->x==1) == [1.0, 2.0] @test vcov(r) == r.vcov @test vcov(r, 1) == 1 @test vcov(r, 1, 2) == 2 @test vcov(r, "rel: 1 & c: 1") == 1 @test vcov(r, :c5) == 25 @test vcov(r, "rel: 1 & c: 1", :c5) == 5 @test vcov(r, 1:2) == r.vcov[1:2, 1:2] @test vcov(r, 5:-1:3) == r.vcov[5:-1:3, 5:-1:3] @test vcov(r, (1, :c5, "rel: 1 & c: 1")) == r.vcov[[1,5,1], [1,5,1]] @test vcov(r, [1 :c5 "rel: 1 & c: 1"]) == r.vcov[[1,5,1], [1,5,1]] @test vcov(r, :rel=>x->x==1) == r.vcov[[1,2], [1,2]] @test vcov(r, :rel=>x->x==1, :c=>x->x==1) == reshape([1.0], 1, 1) @test vcov(r, (:rel, :c)=>(x, y)->x==1) == r.vcov[[1,2], [1,2]] @test vce(r) === nothing cfint = confint(r) @test length(cfint) == 2 @test all(cfint[1] + cfint[2] .≈ 2 * coef(r)) @test treatment(r) === TR @test nobs(r) == 6 @test outcomename(r) == "y" @test coefnames(r) == r.coefnames @test treatcells(r) == r.treatcells @test weights(r) == :w @test ntreatcoef(r) == 4 @test treatcoef(r) == r.coef[1:4] @test treatvcov(r) == r.vcov[1:4, 1:4] @test treatnames(r) == r.coefnames[1:4] @test parent(r) === r @test dof_residual(r) == 5 @test responsename(r) == "y" @test coefinds(r) == r.coefinds @test ncovariate(r) == 2 @test_throws ErrorException agg(r) w = VERSION < v"1.6.0" ? " " : "" @test sprint(show, r) == """ ───────────────────────────────────────────────────────────────────────── Estimate Std. Error t Pr(>|t|) Lower 95% Upper 95% ───────────────────────────────────────────────────────────────────────── rel: 1 & c: 1 1.0 1.0 1.00 0.3632 -1.57058 3.57058 rel: 1 & c: 2 2.0 2.0 1.00 0.3632 -3.14116 7.14116 rel: 2 & c: 1 3.0 3.0 1.00 0.3632 -4.71175 10.7117$w rel: 2 & c: 2 4.0 4.0 1.00 0.3632 -6.28233 14.2823$w c5 5.0 5.0 1.00 0.3632 -7.85291 17.8529$w c6 6.0 6.0 1.00 0.3632 -9.42349 21.4235$w ─────────────────────────────────────────────────────────────────────────""" r = TestResultBARE(2, 2) @test dof_residual(r) === nothing @test coefinds(r) === nothing w = VERSION < v"1.6.0" ? " " : "" @test sprint(show, r) == """ ───────────────────────────────────────────────────────────────────────── Estimate Std. Error z Pr(>|z|) Lower 95% Upper 95% ───────────────────────────────────────────────────────────────────────── rel: 1 & c: 1 1.0 1.0 1.00 0.3173 -0.959964 2.95996 rel: 1 & c: 2 2.0 2.0 1.00 0.3173 -1.91993 5.91993 rel: 2 & c: 1 3.0 3.0 1.00 0.3173 -2.87989 8.87989 rel: 2 & c: 2 4.0 4.0 1.00 0.3173 -3.83986 11.8399$w ─────────────────────────────────────────────────────────────────────────""" end @testset "_treatnames" begin t = VecColumnTable((rel=[1, 2],)) @test _treatnames(t) == ["rel: 1", "rel: 2"] r = TestResult(2, 2) @test _treatnames(r.treatcells) == ["rel: $a & c: $b" for a in 1:2 for b in 1:2] end @testset "_parse_bycells!" begin cells = VecColumnTable((rel=repeat(1:2, inner=2), c=repeat(1:2, outer=2))) bycols = copy(getfield(cells, :columns)) _parse_bycells!(bycols, cells, :rel=>isodd) @test bycols[1] == isodd.(cells.rel) @test bycols[2] === cells.c bycols = copy(getfield(cells, :columns)) _parse_bycells!(bycols, cells, :rel=>:c=>isodd) @test bycols[1] == isodd.(cells.c) @test bycols[2] === cells.c bycols = copy(getfield(cells, :columns)) _parse_bycells!(bycols, cells, (:rel=>1=>isodd, 2=>1=>isodd)) @test bycols[1] == isodd.(cells.rel) @test bycols[2] == isodd.(cells.rel) bycols = copy(getfield(cells, :columns)) _parse_bycells!(bycols, cells, nothing) @test bycols[1] == cells.rel @test bycols[2] == cells.c @test_throws ArgumentError _parse_bycells!(bycols, cells, (:rel,)) end @testset "_parse_subset _nselected" begin r = TestResult(2, 2) @test _parse_subset(r, 1:4, true) == 1:4 @test _parse_subset(r, collect(1:4), true) == 1:4 @test _parse_subset(r, trues(4), true) == trues(4) @test _parse_subset(r, :rel=>isodd, true) == ((1:6) .< 3) @test _parse_subset(r, :rel=>isodd, false) == ((1:4) .< 3) @test _parse_subset(r, (:rel=>isodd, :c=>isodd), true) == ((1:6) .< 2) @test _parse_subset(r, (:rel=>isodd, :c=>isodd), false) == ((1:4) .<2) @test _parse_subset(r, :, false) == 1:4 @test _parse_subset(r, :, true) == 1:6 @test _nselected(1:10) == 10 @test _nselected(collect(1:10)) == 10 @test _nselected(isodd.(1:10)) == 5 @test _nselected([true, false]) == 1 @test_throws ArgumentError _nselected(:) end @testset "treatindex checktreatindex" begin @test treatindex(10, :) == 1:10 @test treatindex(10, 1) == 1 @test length(treatindex(10, 11)) == 0 @test treatindex(10, 1:5) == 1:5 @test treatindex(10, collect(1:20)) == 1:10 @test treatindex(10, isodd.(1:20)) == isodd.(1:10) @test_throws ArgumentError treatindex(10, :a) @test checktreatindex([3,2,1,5,4], [1,2,3]) @test checktreatindex(1:10, 1:5) @test_throws ArgumentError checktreatindex([3,2,1,5,4], [3,5]) @test_throws ArgumentError checktreatindex(10:-1:1, 1:5) @test checktreatindex(trues(10), trues(5)) @test checktreatindex(:, 1:5) @test checktreatindex(5, 1:0) end @testset "SubDIDResult" begin r = TestResult(2, 2) sr = view(r, :) @test coef(sr) == coef(r) @test vcov(sr) == vcov(r) @test vce(sr) === nothing @test treatment(sr) === TR @test nobs(sr) == nobs(r) @test outcomename(sr) == outcomename(r) @test coefnames(sr) == coefnames(r) @test treatcells(sr) == treatcells(r) @test weights(sr) == weights(r) @test ntreatcoef(sr) == ntreatcoef(r) @test treatcoef(sr) == treatcoef(r) @test treatvcov(sr) == treatvcov(r) @test treatnames(sr) == treatnames(r) @test parent(sr) === r @test dof_residual(sr) == dof_residual(r) @test responsename(sr) == responsename(r) @test coefinds(sr) == coefinds(r) @test ncovariate(sr) == 2 sr = view(r, isodd.(1:6)) @test coef(sr) == coef(r)[[1,3,5]] @test vcov(sr) == vcov(r)[[1,3,5],[1,3,5]] @test vce(sr) === nothing @test treatment(sr) === TR @test nobs(sr) == nobs(r) @test outcomename(sr) == outcomename(r) @test coefnames(sr) == coefnames(r)[[1,3,5]] @test treatcells(sr) == view(treatcells(r), [1,3]) @test weights(sr) == weights(r) @test ntreatcoef(sr) == 2 @test treatcoef(sr) == treatcoef(r)[[1,3]] @test treatvcov(sr) == treatvcov(r)[[1,3],[1,3]] @test treatnames(sr) == treatnames(r)[[1,3]] @test parent(sr) === r @test dof_residual(sr) == dof_residual(r) @test responsename(sr) == responsename(r) @test coefinds(sr) == Dict("rel: 1 & c: 1"=>1, "rel: 2 & c: 1"=>2, "c5"=>3) @test ncovariate(sr) == 1 @test_throws BoundsError view(r, 1:7) @test_throws ArgumentError view(r, [6,1]) end @testset "TransformedDIDResult" begin r = TestResult(2, 2) m = reshape(1:36, 6, 6) tr = TransformedDIDResult(r, m, copy(r.coef), copy(r.vcov)) @test coef(tr) === tr.coef @test vcov(tr) === tr.vcov @test vce(tr) === nothing @test treatment(tr) === TR @test nobs(tr) == nobs(r) @test outcomename(tr) == outcomename(r) @test coefnames(tr) === coefnames(r) @test treatcells(tr) === treatcells(r) @test weights(tr) == weights(r) @test ntreatcoef(tr) == 4 @test treatcoef(tr) == tr.coef[1:4] @test treatvcov(tr) == tr.vcov[1:4,1:4] @test treatnames(tr) == treatnames(r) @test parent(tr) === r @test dof_residual(tr) == dof_residual(r) @test responsename(tr) == responsename(r) @test coefinds(tr) === coefinds(r) @test ncovariate(tr) == 2 end @testset "TransSubDIDResult" begin r = TestResult(2, 2) m = reshape(1:18, 3, 6) inds = [2,1,6] tr = TransSubDIDResult(r, m, r.coef[inds], r.vcov[inds, inds], inds) @test coef(tr) === tr.coef @test vcov(tr) === tr.vcov @test vce(tr) === nothing @test treatment(tr) === TR @test nobs(tr) == nobs(r) @test outcomename(tr) == outcomename(r) @test coefnames(tr) == coefnames(r)[inds] @test treatcells(tr) == view(treatcells(r), 2:-1:1) @test weights(tr) == weights(r) @test ntreatcoef(tr) == 2 @test treatcoef(tr) == tr.coef[1:2] @test treatvcov(tr) == tr.vcov[1:2,1:2] @test treatnames(tr) == treatnames(r)[2:-1:1] @test parent(tr) === r @test dof_residual(tr) == dof_residual(r) @test responsename(tr) == responsename(r) @test coefinds(tr) === tr.coefinds @test ncovariate(tr) == 1 @test_throws BoundsError TransSubDIDResult(r, m, r.coef[1:2], r.vcov[1:2,1:2], 1:7) @test_throws ArgumentError TransSubDIDResult(r, m, r.coef[1:2], r.vcov[1:2,1:2], [6,1]) end @testset "lincom" begin r = TestResult(2, 2) m = reshape(1:36, 6, 6) tr = lincom(r, m) @test coef(tr) == m * r.coef @test vcov(tr) == m * r.vcov * m' tr = lincom(r, m, nothing) @test coef(tr) == m * r.coef @test vcov(tr) == m * r.vcov * m' @test tr isa TransformedDIDResult m = reshape(1:18, 3, 6) inds = [1,2,6] tr = lincom(r, m, inds) @test coef(tr) == m * r.coef @test vcov(tr) == m * r.vcov * m' m1 = reshape(1:15, 3, 5) @test_throws DimensionMismatch lincom(r, m1) @test_throws DimensionMismatch lincom(r, m1, 1:3) @test_throws ArgumentError lincom(r, m) @test_throws ArgumentError lincom(r, m, 1:6) end @testset "rescale" begin r = TestResult(2, 2) scale = fill(2, 6) m = Diagonal(scale) tr = rescale(r, scale) @test coef(tr) == m * r.coef @test vcov(tr) == m * r.vcov * m' tr = rescale(r, scale, nothing) @test coef(tr) == m * r.coef @test vcov(tr) == m * r.vcov * m' @test tr isa TransformedDIDResult scale = fill(2, 3) m = Diagonal(scale) inds = [1,2,6] tr = rescale(r, scale, inds) @test coef(tr) == m * r.coef[inds] @test vcov(tr) == m * r.vcov[inds,inds] * m' tr = rescale(r, :rel=>identity) @test coef(tr) == r.treatcells.rel.*r.coef[1:4] m = Diagonal(r.treatcells.rel) @test vcov(tr) == m * r.vcov[1:4,1:4] * m' tr = rescale(r, :rel=>identity, 1:3) @test coef(tr) == r.treatcells.rel[1:3].*r.coef[1:3] m = Diagonal(r.treatcells.rel[1:3]) @test vcov(tr) == m * r.vcov[1:3,1:3] * m' end @testset "post!" begin @test getexportformat() == DefaultExportFormat[1] setexportformat!(StataPostHDF()) @test DefaultExportFormat[1] == StataPostHDF() f = Dict{String,Any}() r = TestResult(2, 2) post!(f, r) @test f["model"] == "TestResult{TestTreatment}" @test f["b"] == coef(r) @test f["V"] == vcov(r) @test f["vce"] == "nothing" @test f["N"] == nobs(r) @test f["depvar"] == "y" @test f["coefnames"][1] == "rel: 1 & c: 1" @test f["weights"] == "w" @test f["ntreatcoef"] == 4 f = Dict{String,Any}() fds = Union{Symbol, Pair{String,Symbol}}[Symbol("extra$i") for i in 1:8] fds[1] = "e1"=>:extra1 post!(f, StataPostHDF(), r, model="test", fields=fds, at=1:6) @test f["e1"] == 1 @test f["extra2"] == "a" @test f["extra3"] == "a" @test f["extra4"] == [1.0] @test f["extra5"] == ["a"] @test f["extra6"] == [1.0 2.0] @test f["extra7"] == ["a"] @test f["extra8"] == "" f = Dict{String,Any}() @test_throws ArgumentError post!(f, StataPostHDF(), r, fields=[:extra9]) f = Dict{String,Any}() @test_throws ArgumentError post!(f, StataPostHDF(), r, at=false) f = Dict{String,Any}() @test_throws ArgumentError post!(f, StataPostHDF(), r, at=1:2) r1 = TestResultBARE(2, 2) f = Dict{String,Any}() post!(f, StataPostHDF(), r1, at=true) @test f["at"] == treatcells(r1).rel f = Dict{String,Any}() post!(f, StataPostHDF(), r1, at=false) @test !haskey(f, "at") end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
7014
@testset "_mult!" begin a = collect(0:5) b = collect(1:6) _mult!(a, b, 6) @test a == 0:7:35 end @testset "findcell" begin hrs = exampledata("hrs") @test_throws ArgumentError findcell((), hrs) @test_throws ArgumentError findcell((:wave,), hrs, falses(size(hrs, 1))) rows = findcell((:wave,), hrs) @test length(rows) == 5 @test rows[UInt32(5)] == findall(x->x==7, hrs.wave) df = DataFrame(hrs) df.wave = PooledArray(df.wave) @test findcell((:wave,), df) == rows esample = hrs.wave.!=11 rows = findcell((:wave, :wave_hosp), hrs, esample) @test length(rows) == 16 @test rows[one(UInt32)] == intersect(findall(x->x==10, view(hrs.wave, esample)), findall(x->x==10, view(hrs.wave_hosp, esample))) rows = findcell((:wave, :wave_hosp, :male), hrs) @test length(rows) == 40 end @testset "cellrows" begin hrs = exampledata("hrs") cols0 = subcolumns(hrs, (:wave, :wave_hosp), falses(size(hrs, 1))) cols = subcolumns(hrs, (:wave, :wave_hosp)) rows_dict0 = IdDict{UInt32, Vector{Int}}() @test_throws ArgumentError cellrows(cols, rows_dict0) rows_dict = findcell(cols) @test_throws ArgumentError cellrows(cols0, rows_dict) cells, rows = cellrows(cols, rows_dict) @test length(cells[1]) == length(rows) == 20 @test Tables.matrix(cells) == sortslices(unique(hcat(hrs.wave, hrs.wave_hosp), dims=1), dims=1) @test propertynames(cells) == [:wave, :wave_hosp] @test rows[1] == intersect(findall(x->x==7, hrs.wave), findall(x->x==8, hrs.wave_hosp)) df = DataFrame(hrs) df.wave = ScaledArray(hrs.wave, 1) df.wave_hosp = ScaledArray(hrs.wave_hosp, 1) cols1 = subcolumns(df, (:wave, :wave_hosp)) cells1, rows1 = cellrows(cols1, rows_dict) @test rows1 == rows @test cells1 == cells @test cells1.wave isa ScaledArray @test cells1.wave_hosp isa ScaledArray rot = ones(size(df, 1)) df.wave = RotatingTimeArray(rot, hrs.wave) df.wave_hosp = RotatingTimeArray(rot, hrs.wave_hosp) cols2 = subcolumns(df, (:wave, :wave_hosp)) cells2, rows2 = cellrows(cols2, rows_dict) @test rows2 == rows @test cells2 == cells @test cells2.wave isa RotatingTimeArray @test cells2.wave_hosp isa RotatingTimeArray end @testset "settime aligntime" begin hrs = exampledata("hrs") t = settime(hrs.wave, 2, reftype=Int16) @test eltype(refarray(t)) == Int16 @test sort!(unique(refarray(t))) == 1:3 t = settime(hrs.wave, 0.5) @test eltype(t) == Float64 rot = isodd.(hrs.wave) t = settime(hrs.wave, rotation=rot) @test eltype(t) == RotatingTimeValue{Bool, eltype(hrs.wave)} @test refpool(t) === nothing @test eltype(refarray(t.time)) == Int32 @test t.rotation == rot @test t.time == hrs.wave df = DataFrame(hrs) df.wave1 = Date.(df.wave) t = settime(df.wave1, Year(1)) @test t == df.wave1 @test t.pool == Date(7):Year(1):Date(11) t = settime(df.wave1, Year(1), rotation=rot) @test eltype(t) == RotatingTimeValue{Bool, eltype(df.wave1)} @test eltype(refarray(t.time)) == Int32 @test t.time isa ScaledArray df.t1 = settime(df.wave, 1) df.t2 = settime(df.wave, 2) t = aligntime(df, :t2, :t1) @test t == df.t2 @test t.pool == df.t1.pool @test t.invpool == df.t1.invpool df.t2 = settime(df.wave, start=0, stop=20) t = aligntime(df, :t2, :t1) @test t == df.t2 @test t.pool == df.t1.pool t1 = settime(df.wave1, Year(1), rotation=rot) t2 = settime(df.wave1, Year(1), start=Date(5)) t = aligntime(t2, t1) @test t == t1 @test t.time.pool == t1.time.pool t2 = settime(df.wave1, Year(1), start=Date(5), rotation=rot) t = aligntime(t2, t1) @test t == t1 @test t.time.pool == t1.time.pool end @testset "PanelStructure" begin hrs = exampledata("hrs") N = size(hrs, 1) panel = setpanel(hrs, :hhidpn, :wave) @test length(unique(panel.refs)) == N inidbounds = view(hrs.hhidpn, 2:N) .== view(hrs.hhidpn, 1:N-1) @test view(diff(panel.refs), inidbounds) == view(diff(hrs.wave), inidbounds) @test length(panel.idpool) == 656 @test panel.timepool == 7:11 panel1 = setpanel(hrs, :hhidpn, :wave, step=0.5, reftype=Int) @test view(diff(panel1.refs), inidbounds) == 2 .* view(diff(hrs.wave), inidbounds) @test panel1.timepool == 7.0:0.5:11.0 @test eltype(panel1.refs) == Int @test_throws ArgumentError setpanel(hrs, :hhidpn, :oop_spend) @test_throws DimensionMismatch setpanel(hrs.hhidpn, 1:100) @test sprint(show, panel) == "Panel Structure" t = VERSION < v"1.6.0" ? "Array{Int64,1}" : " Vector{Int64}" @test sprint(show, MIME("text/plain"), panel) == """ Panel Structure: idpool: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 … 647, 648, 649, 650, 651, 652, 653, 654, 655, 656] timepool: 7:1:11 laginds: Dict{Int64,$t}()""" lags = findlag!(panel) @test sprint(show, MIME("text/plain"), panel) == """ Panel Structure: idpool: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 … 647, 648, 649, 650, 651, 652, 653, 654, 655, 656] timepool: 7:1:11 laginds: Dict(1 => [4, 5, 1, 2, 0, 7, 0, 10, 8, 6 … 0, 3275, 3271, 3273, 3274, 3279, 3280, 3277, 3278, 0])""" leads = findlead!(panel, -1) @test leads == leads @test_throws ArgumentError findlag!(panel, 5) @test ilag!(panel) === panel.laginds[1] @test ilag!(panel, 2) === panel.laginds[2] @test ilead!(panel) === panel.laginds[-1] l1 = lag(panel, hrs.wave) @test view(l1, hrs.wave.!=7) == view(hrs.wave, hrs.wave.!=7) .- 1 @test all(ismissing, view(l1, hrs.wave.==7)) l2 = lag(panel, hrs.wave, 2, default=-1) @test view(l2, hrs.wave.>=9) == view(hrs.wave, hrs.wave.>=9) .- 2 @test all(x->x==-1, view(l2, hrs.wave.<9)) @test eltype(l2) == Int l_2 = lead(panel, hrs.wave, 2, default=-1.0) @test view(l_2, hrs.wave.<=9) == view(hrs.wave, hrs.wave.<=9) .+ 2 @test all(x->x==-1, view(l_2, hrs.wave.>9)) @test eltype(l_2) == Int @test_throws DimensionMismatch lag(panel, 1:10) d1 = diff(panel, hrs.wave) @test all(x->x==1, view(d1, hrs.wave.!=7)) @test all(ismissing, view(d1, hrs.wave.==7)) d2 = diff(panel, hrs.wave, l=2, default=-1) @test all(x->x==2, view(d2, hrs.wave.>=9)) @test all(x->x==-1, view(d2, hrs.wave.<9)) @test eltype(d2) == Int d_2 = diff(panel, hrs.wave, l=-2, default=-1.0) @test all(x->x==-2, view(d_2, hrs.wave.<=9)) @test all(x->x==-1, view(d_2, hrs.wave.>9)) @test eltype(d_2) == Int d2 = diff(panel, hrs.wave, order=2) @test all(x->x==0, view(d2, hrs.wave.>=9)) @test all(ismissing, view(d2, hrs.wave.<9)) d2 = diff(panel, hrs.wave, order=2, l=2) @test all(x->x==0, view(d2, hrs.wave.==11)) @test all(ismissing, view(d2, hrs.wave.!=11)) @test_throws ArgumentError diff(panel, hrs.wave, l=5) @test_throws ArgumentError diff(panel, hrs.wave, order=5) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
6418
@testset "singletons" begin @testset "alias" begin @test unconditional() == Unconditional() @test exact() == Exact() end @testset "show" begin @test sprint(show, Unconditional()) == "Unconditional" @test sprintcompact(Unconditional()) == "U" @test sprint(show, Exact()) == "Parallel" @test sprintcompact(Exact()) == "P" end end @testset "unspecifiedpr" begin us = UnspecifiedParallel() @test unspecifiedpr() === us @test unspecifiedpr(Unconditional()) === us @test unspecifiedpr(Unconditional(), Exact()) === us @test sprint(show, us) == "Unspecified{U,P}" @test sprint(show, MIME("text/plain"), us) == "Parallel among unspecified treatment groups" end @testset "nevertreated" begin nt0 = NeverTreatedParallel([0], Unconditional(), Exact()) nt0y = NeverTreatedParallel(Date(0), Unconditional(), Exact()) nt1 = NeverTreatedParallel([0,1], Unconditional(), Exact()) nt1y = NeverTreatedParallel([Date(0), Date(1)], Unconditional(), Exact()) @testset "inner constructor" begin @test NeverTreatedParallel([1,1,0], Unconditional(), Exact()) == nt1 @test_throws ErrorException NeverTreatedParallel([], Unconditional(), Exact()) @test_throws MethodError NeverTreatedParallel([-0.5], Unconditional(), Exact()) end @testset "without @formula" begin @test nevertreated(0) == nt0 @test nevertreated([0,1]) == nt1 @test nevertreated(0:1) == nt1 @test nevertreated(Set([0,1])) == nt1 @test nevertreated([0,1,1]) == nt1 @test nevertreated(Date(0)) == nt0y @test nevertreated((Date(0), Date(1))) == nt1y @test nevertreated(0, Unconditional(), Exact()) == nt0 @test nevertreated(0, c=Unconditional(), s=Exact()) == nt0 @test nevertreated([0,1], Unconditional(), Exact()) == nt1 @test nevertreated([0,1], c=Unconditional(), s=Exact()) == nt1 end @testset "show" begin @test sprint(show, nt0) == "NeverTreated{U,P}(0)" @test sprint(show, MIME("text/plain"), nt0) == """ Parallel trends with any never-treated group: Never-treated groups: 0""" @test sprint(show, nt1) == "NeverTreated{U,P}(0, 1)" @test sprint(show, MIME("text/plain"), nt1) == """ Parallel trends with any never-treated group: Never-treated groups: 0, 1""" end end @testset "notyettreated" begin ny0 = NotYetTreatedParallel([0], [0], Unconditional(), Exact()) ny0y = NotYetTreatedParallel(Date(0), Date(0), Unconditional(), Exact()) ny1 = NotYetTreatedParallel([0,1], [0], Unconditional(), Exact()) ny1y = NotYetTreatedParallel([Date(0), Date(1)], [Date(0)], Unconditional(), Exact()) ny2 = NotYetTreatedParallel([0,1], [0], Unconditional(), Exact()) ny3 = NotYetTreatedParallel([0,1], [0,1], Unconditional(), Exact()) @testset "inner constructor" begin @test NotYetTreatedParallel([1,1,0], [1,0,0], Unconditional(), Exact()) == ny3 @test_throws ArgumentError NotYetTreatedParallel([0], [], Unconditional(), Exact()) @test_throws ArgumentError NotYetTreatedParallel([], [0], Unconditional(), Exact()) @test_throws ArgumentError NotYetTreatedParallel([-0.5], [-1], Unconditional(), Exact()) end @testset "without @formula" begin @test notyettreated(0) == ny0 @test notyettreated([0,1], 0) == ny1 @test notyettreated(0:1, (0,)) == ny2 @test notyettreated(Set([0,1]), 0:1) == ny3 @test notyettreated([0,1,1], [0,1,1]) == ny3 @test notyettreated(Date(0)) == ny0y @test notyettreated((Date(0), Date(1)), Date(0)) == ny1y @test notyettreated(0, 0, Unconditional(), Exact()) == ny0 @test notyettreated(0, c=Unconditional(), s=Exact()) == ny0 @test notyettreated([0,1], [0], Unconditional(), Exact()) == ny1 @test notyettreated([0,1], 0, c=Unconditional(), s=Exact()) == ny1 end @testset "show" begin @test sprint(show, ny0) == "NotYetTreated{U,P}(0)" @test sprint(show, MIME("text/plain"), ny0) == """ Parallel trends with any not-yet-treated group: Not-yet-treated groups: 0 Treated since: 0""" @test sprint(show, ny1) == "NotYetTreated{U,P}(0, 1)" @test sprint(show, MIME("text/plain"), ny1) == """ Parallel trends with any not-yet-treated group: Not-yet-treated groups: 0, 1 Treated since: 0""" @test sprint(show, ny2) == "NotYetTreated{U,P}(0, 1)" @test sprint(show, MIME("text/plain"), ny2) == """ Parallel trends with any not-yet-treated group: Not-yet-treated groups: 0, 1 Treated since: 0""" @test sprint(show, ny3) == "NotYetTreated{U,P}(0, 1)" @test sprint(show, MIME("text/plain"), ny3) == """ Parallel trends with any not-yet-treated group: Not-yet-treated groups: 0, 1 Treated since: 0, 1""" end end @testset "istreated istreated!" begin nt = nevertreated(-1) @test istreated(nt, -1) == false @test istreated(nt, 0) out = BitVector(undef, 3) x = [1, -1, missing] @test istreated!(out, nt, x) == [true, false, true] x = ScaledArray([1, -1, missing], 1) @test istreated!(out, nt, x) == [true, false, true] x = ScaledArray([1, 0, missing], 1) @test istreated!(out, nt, x) == [true, true, true] ny = notyettreated(5) @test istreated(ny, 5) == false @test istreated(ny, 4) ny = notyettreated(5, 4) @test istreated(ny, 4) out = BitVector(undef, 3) x = [1, 5, missing] @test istreated!(out, ny, x) == [true, false, true] x = ScaledArray([1, 5, missing], 1) @test istreated!(out, ny, x) == [true, false, true] x = ScaledArray([1, 0, missing], 1) @test istreated!(out, ny, x) == [true, true, true] end @testset "termvars" begin @test termvars(Unconditional()) == Symbol[] @test termvars(Exact()) == Symbol[] @test termvars(unspecifiedpr()) == Symbol[] @test termvars(nevertreated(-1)) == Symbol[] @test termvars(notyettreated(5)) == Symbol[] @test_throws ErrorException termvars(TestParaCondition()) @test_throws ErrorException termvars(TestParaStrength()) @test_throws ErrorException termvars(PR) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
12488
@testset "CheckData" begin @testset "checkdata!" begin hrs = exampledata("hrs") nt = (data=hrs, subset=nothing, weightname=nothing) ret = checkdata!(nt...) @test ret.esample == trues(size(hrs,1)) ismale = hrs.male.==1 nt = merge(nt, (weightname=:rwthh, subset=ismale)) ret = checkdata!(nt...) @test ret.esample == ismale @test ret.esample !== ismale df = DataFrame(hrs) allowmissing!(df, :rwthh) df.rwthh[1] = missing nt = merge(nt, (data=df, subset=nothing)) ret = checkdata!(nt...) @test ret.esample == (hrs.rwthh.>0) .& (.!ismissing.(df.rwthh)) nt = merge(nt, (data=rand(10,10),)) @test_throws ArgumentError checkdata!(nt...) nt = merge(nt, (data=[(a=1, b=2), (a=1, b=2)],)) @test_throws ArgumentError checkdata!(nt...) nt = merge(nt, (data=hrs, subset=BitArray(hrs.male[1:100]))) @test_throws DimensionMismatch checkdata!(nt...) nt = merge(nt, (subset=falses(size(hrs,1)),)) @test_throws ErrorException checkdata!(nt...) end @testset "StatsStep" begin @test sprint(show, CheckData()) == "CheckData" @test sprint(show, MIME("text/plain"), CheckData()) == "CheckData (StatsStep that calls DiffinDiffsBase.checkdata!)" @test _f(CheckData()) == checkdata! hrs = exampledata("hrs") nt = (data=hrs, subset=nothing, weightname=nothing) ret = CheckData()(nt) @test ret.esample == trues(size(hrs,1)) @test ret.aux isa BitVector @test_throws ErrorException CheckData()() end end @testset "GroupTreatintterms" begin @testset "grouptreatintterms" begin nt = (treatintterms=TermSet(),) @test grouptreatintterms(nt...) == nt end @testset "StatsStep" begin @test sprint(show, GroupTreatintterms()) == "GroupTreatintterms" @test sprint(show, MIME("text/plain"), GroupTreatintterms()) == "GroupTreatintterms (StatsStep that calls DiffinDiffsBase.grouptreatintterms)" @test _byid(SharedStatsStep(GroupTreatintterms(),1)) == false nt = (treatintterms=TermSet(),) @test GroupTreatintterms()() == nt end end @testset "GroupXterms" begin @testset "groupxterms" begin nt = (xterms=TermSet(term(:x)),) @test groupxterms(nt...) == nt end @testset "StatsStep" begin @test sprint(show, GroupXterms()) == "GroupXterms" @test sprint(show, MIME("text/plain"), GroupXterms()) == "GroupXterms (StatsStep that calls DiffinDiffsBase.groupxterms)" @test _byid(SharedStatsStep(GroupXterms(), 1)) == false nt = (xterms=TermSet(),) @test GroupXterms()() == nt end end @testset "GroupContrasts" begin @testset "groupcontrasts" begin nt = (contrasts=Dict{Symbol,Any}(),) @test groupcontrasts(nt...) == nt end @testset "StatsStep" begin @test sprint(show, GroupContrasts()) == "GroupContrasts" @test sprint(show, MIME("text/plain"), GroupContrasts()) == "GroupContrasts (StatsStep that calls DiffinDiffsBase.groupcontrasts)" @test _byid(SharedStatsStep(GroupContrasts(), 1)) == false nt = (contrasts=nothing,) @test GroupContrasts()() == nt end end @testset "CheckVars" begin @testset "checkvars!" begin hrs = exampledata("hrs") N = size(hrs,1) us = unspecifiedpr() tr = dynamic(:wave, -1) nt = (data=hrs, pr=us, yterm=term(:oop_spend), treatname=:wave_hosp, esample=trues(N), aux=BitVector(undef, N), treatintterms=TermSet(), xterms=TermSet(), tytr=typeof(tr), trvars=(termvars(tr)...,), tr=tr) @test checkvars!(nt...) == (esample=trues(N), tr_rows=trues(N)) nt = merge(nt, (pr=nevertreated(11),)) @test checkvars!(nt...) == (esample=trues(N), tr_rows=hrs.wave_hosp.!=11) nt = merge(nt, (pr=notyettreated(11),)) @test checkvars!(nt...) == (esample=hrs.wave.!=11, tr_rows=(hrs.wave_hosp.!=11).&(hrs.wave.!=11)) nt = merge(nt, (pr=notyettreated(11, 10), esample=trues(N))) @test checkvars!(nt...) == (esample=.!(hrs.wave_hosp.∈(10,)).& .!(hrs.wave.∈((10,11),)), tr_rows=(.!(hrs.wave_hosp.∈((10,11),)).& .!(hrs.wave.∈((10,11),)))) nt = merge(nt, (pr=notyettreated(10), esample=.!((hrs.wave_hosp.==10).&(hrs.wave.==9)))) @test checkvars!(nt...) == (esample=(hrs.wave.<9).&(hrs.wave_hosp.<=10), tr_rows=(hrs.wave.<9).&(hrs.wave_hosp.<=9)) nt = merge(nt, (pr=us, treatintterms=TermSet(term(:male)), xterms=TermSet(term(:white)), esample=trues(N))) @test checkvars!(nt...) == (esample=trues(N), tr_rows=trues(N)) nt = merge(nt, (pr=nevertreated(11), treatintterms=TermSet(term(:male)), xterms=TermSet(term(:white)), esample=trues(N))) @test checkvars!(nt...) == (esample=trues(N), tr_rows=hrs.wave_hosp.!=11) df = DataFrame(hrs) allowmissing!(df, :male) df.male .= ifelse.(hrs.wave_hosp.==11, missing, df.male) nt = merge(nt, (data=df, pr=us, esample=trues(N))) @test checkvars!(nt...) == (esample=hrs.wave_hosp.!=11, tr_rows=hrs.wave_hosp.!=11) df.male .= ifelse.(hrs.wave_hosp.==10, missing, hrs.male) nt = merge(nt, (esample=trues(N),)) @test checkvars!(nt...) == (esample=hrs.wave_hosp.!=10, tr_rows=hrs.wave_hosp.!=10) df.male .= ifelse.(hrs.wave_hosp.==11, missing, hrs.male) nt = merge(nt, (pr=nevertreated(11), esample=trues(N))) @test checkvars!(nt...) == (esample=trues(N), tr_rows=hrs.wave_hosp.!=11) df.male .= ifelse.(hrs.wave_hosp.==10, missing, df.male) @test checkvars!(nt...) == (esample=hrs.wave_hosp.!=10, tr_rows=hrs.wave_hosp.∈((8,9),)) df.white = ifelse.(hrs.wave_hosp.==9, missing, df.white.+0.5) ret = (esample=hrs.wave_hosp.∈((8,11),), tr_rows=hrs.wave_hosp.==8) @test checkvars!(nt...) == ret df.wave_hosp = Date.(df.wave_hosp) @test_throws ArgumentError checkvars!(nt...) df.wave = Date.(df.wave) @test_throws ArgumentError checkvars!(nt...) nt = merge(nt, (pr=nevertreated(Date(11)),)) @test_throws ArgumentError checkvars!(nt...) df.wave = settime(df.wave, Year(1)) df.wave_hosp = settime(df.wave_hosp, Year(1)) @test_throws ArgumentError checkvars!(nt...) df.wave_hosp = aligntime(df, :wave_hosp, :wave) @test checkvars!(nt...) == ret nt = merge(nt, (pr=notyettreated(Date(11)), esample=trues(N))) ret = checkvars!(nt...) @test ret == (esample=(df.wave_hosp.∈((Date(8),Date(11)),)).&(df.wave.!=Date(11)), tr_rows=(df.wave_hosp.==Date(8)).&(df.wave.!=Date(11))) allowmissing!(df, :wave) df[:,:wave] .= ifelse.((df.wave_hosp.==Date(8)).&(df.wave.∈((Date(7), Date(8)),)), missing, df.wave) nt = merge(nt, (esample=trues(N), pr=nevertreated(Date(11)))) ret = checkvars!(nt...) @test ret.esample == (df.wave_hosp.∈((Date(8),Date(11)),)).& (.!(hrs.wave.∈((7,8),))) @test ret.tr_rows == ret.esample.&(df.wave_hosp.!=Date(11)) nt = merge(nt, (esample=trues(N), pr=notyettreated(Date(11)))) ret = checkvars!(nt...) @test ret.esample == (df.wave_hosp.∈((Date(8),Date(11)),)).& (hrs.wave.∈((9,10),)) @test ret.tr_rows == ret.esample.&(df.wave_hosp.!=Date(11)) df = DataFrame(hrs) rot = ifelse.(isodd.(df.hhidpn), 1, 2) df.wave_hosp = rotatingtime(rot, df.wave_hosp) df.wave = rotatingtime(rot, df.wave) e = rotatingtime((1,2), 11) nt = merge(nt, (data=df, pr=nevertreated(e), treatintterms=TermSet(), xterms=TermSet(), esample=trues(N))) # Check RotatingTimeArray @test_throws ArgumentError checkvars!(nt...) df.wave_hosp = settime(hrs.wave_hosp, rotation=rot) df.wave = settime(hrs.wave, rotation=rot) # Check aligntime @test_throws ArgumentError checkvars!(nt...) df.wave_hosp = aligntime(df.wave_hosp, df.wave) ret1 = checkvars!(nt...) @test ret1 == (esample=trues(N), tr_rows=hrs.wave_hosp.!=11) df.wave_hosp = settime(hrs.wave_hosp, start=7, rotation=ones(N)) df.wave = settime(hrs.wave, rotation=ones(N)) # Check the match of field type of pr.e @test_throws ArgumentError checkvars!(nt...) df.wave_hosp = settime(hrs.wave_hosp, start=7, rotation=ones(Int, N)) df.wave = settime(hrs.wave, rotation=ones(Int, N)) nt = merge(nt, (esample=trues(N), pr=notyettreated(e),)) ret2 = checkvars!(nt...) @test ret2 == (esample=hrs.wave.!=11, tr_rows=(hrs.wave_hosp.!=11).&(hrs.wave.!=11)) # RotatingTimeArray with time field of type Array df.wave_hosp = RotatingTimeArray(rot, hrs.wave_hosp) df.wave = RotatingTimeArray(rot, hrs.wave) e = rotatingtime((1,2), (10,11)) nt = merge(nt, (esample=trues(N), pr=notyettreated(e))) ret3 = checkvars!(nt...) ret3e = (hrs.wave.!=11).&(.!((hrs.wave.==10).&(rot.==1))).& (.!((hrs.wave_hosp.==11).&(rot.==1))) @test ret3 == (esample=ret3e, tr_rows=ret3e.& (hrs.wave_hosp.!=11).&(.!((hrs.wave_hosp.==10).&(rot.==1)))) df.wave = settime(Date.(hrs.wave), Year(1), rotation=rot) df.wave_hosp = settime(Date.(hrs.wave_hosp), Year(1), start=Date(7), rotation=rot) e = rotatingtime((1,2), Date(11)) nt = merge(nt, (esample=trues(N), pr=nevertreated(e))) @test checkvars!(nt...) == ret1 nt = merge(nt, (esample=trues(N), pr=notyettreated(e),)) @test checkvars!(nt...) == ret2 end @testset "StatsStep" begin @test sprint(show, CheckVars()) == "CheckVars" @test sprint(show, MIME("text/plain"), CheckVars()) == "CheckVars (StatsStep that calls DiffinDiffsBase.checkvars!)" @test _f(CheckVars()) == checkvars! hrs = exampledata("hrs") N = size(hrs,1) nt = (data=hrs, tr=dynamic(:wave, -1), pr=nevertreated(11), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=TermSet(), xterms=TermSet(), esample=trues(N), aux=BitVector(undef, N)) gargs = groupargs(CheckVars(), nt) @test gargs[copyargs(CheckVars())...] == nt.esample @test CheckVars()(nt) == merge(nt, (esample=trues(N), tr_rows=hrs.wave_hosp.!=11)) nt = (data=hrs, tr=dynamic(:wave, -1), pr=nevertreated(11), yterm=term(:oop_spend), treatname=:wave_hosp, esample=trues(N), aux=BitVector(undef, N), treatintterms=TermSet(), xterms=TermSet()) @test CheckVars()(nt) == merge(nt, (esample=trues(N), tr_rows=hrs.wave_hosp.!=11)) @test_throws ErrorException CheckVars()() end end @testset "GroupSample" begin @testset "groupsample" begin nt = (esample=trues(3),) @test groupsample(nt...) == nt end @testset "StatsStep" begin @test sprint(show, GroupSample()) == "GroupSample" @test sprint(show, MIME("text/plain"), GroupSample()) == "GroupSample (StatsStep that calls DiffinDiffsBase.groupsample)" @test _byid(SharedStatsStep(GroupSample(), 1)) == false nt = (esample=trues(3),) @test GroupSample()(nt) == nt end end @testset "MakeWeights" begin @testset "makeweights" begin hrs = exampledata("hrs") nt = (data=hrs, esample=trues(size(hrs,1)), weightname=nothing) r = makeweights(nt...) @test r.weights isa UnitWeights && sum(r.weights) == size(hrs,1) nt = merge(nt, (weightname=:rwthh,)) r = makeweights(nt...) @test r.weights isa Weights && sum(r.weights) == sum(hrs.rwthh) end @testset "StatsStep" begin @test sprint(show, MakeWeights()) == "MakeWeights" @test sprint(show, MIME("text/plain"), MakeWeights()) == "MakeWeights (StatsStep that calls DiffinDiffsBase.makeweights)" @test _f(MakeWeights()) == makeweights hrs = exampledata("hrs") nt = (data=hrs, esample=trues(size(hrs,1))) r = MakeWeights()(nt) @test r.weights isa UnitWeights && sum(r.weights) == size(hrs,1) end end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
1237
using Test using DiffinDiffsBase using DataAPI: refarray, refvalue, refpool, invrefpool using DataFrames using Dates: Date, Year using DiffinDiffsBase: @fieldequal, exampledata, checktable, isintercept, isomitsintercept, parse_intercept!, ncol, nrow, _mult!, checkdata!, grouptreatintterms, groupxterms, groupcontrasts, checkvars!, groupsample, makeweights, _totermset!, parse_didargs!, _treatnames, _parse_bycells!, _parse_subset, _nselected, treatindex, checktreatindex, DefaultExportFormat using LinearAlgebra: Diagonal using Missings: allowmissing, disallowmissing using PooledArrays: PooledArray using StatsBase: Weights, UnitWeights using StatsModels: termvars using StatsProcedures: _f, _byid, groupargs, copyargs, pool, ≊ using Tables: table import Base: ==, show import DiffinDiffsBase: valid_didargs import StatsProcedures: required, result include("testutils.jl") const tests = [ "tables", "utils", "time", "ScaledArrays", "terms", "treatments", "parallels", "operations", "procedures", "did" ] printstyled("Running tests:\n", color=:blue, bold=true) @time for test in tests include("$test.jl") println("\033[1m\033[32mPASSED\033[0m: $(test)") end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
8564
@testset "VecColumnTable" begin hrs = DataFrame(exampledata("hrs")) cols = VecColumnTable(AbstractVector[], Symbol[], Dict{Symbol,Int}()) cols1 = VecColumnTable(AbstractVector[], Symbol[]) @test cols1 == cols cols2 = VecColumnTable(cols1) @test cols2 === cols1 cols3 = VecColumnTable(DataFrame()) @test cols3 == cols @test size(cols) == (0, 0) @test length(cols) == 0 @test isempty(cols) @test_throws BoundsError cols[1] @test_throws ArgumentError size(cols, 3) @test sprint(show, MIME("text/plain"), cols) == "0×0 VecColumnTable" cols = VecColumnTable(AbstractVector[[]], Symbol[:a], Dict{Symbol,Int}(:a=>1)) @test size(cols) == (0, 1) @test length(cols) == 1 @test isempty(cols) @test sprint(show, MIME("text/plain"), cols) == "0×1 VecColumnTable" cols = VecColumnTable((wave=hrs.wave,)) @test size(cols) == (3280, 1) rows = collect(Tables.rows(cols)) @test hash(rows[2]) == hash(rows[6]) @test isequal(rows[2], rows[6]) @test !isequal(rows[1], rows[2]) @test isless(rows[1], rows[3]) @test !isless(rows[1], rows[2]) cols = VecColumnTable(AbstractVector[hrs.wave, hrs.oop_spend], [:wave, :oop_spend], Dict(:wave=>1, :oop_spend=>2)) cols1 = VecColumnTable(AbstractVector[hrs.wave, hrs.oop_spend], [:wave, :oop_spend]) @test cols1 == cols @test nrow(cols) == 3280 @test ncol(cols) == 2 @test size(cols) == (3280, 2) @test length(cols) == 2 @test isempty(cols) === false cols2 = VecColumnTable(hrs) @test size(cols2) == (3280, 11) cols3 = VecColumnTable(cols2) @test cols3 === cols2 esample = hrs.wave.==7 cols3 = VecColumnTable(hrs, esample) @test size(cols3) == (sum(esample), 11) cols4 = VecColumnTable(cols2, esample) @test cols4 == cols3 @test VecColumnTable(cols2, :) == view(cols2, :) == cols2 @test VecColumnTable(cols2, 1:3280) == view(cols2, 1:3280) == cols2 @test VecColumnTable(cols2, [2,1]) == view(cols2, [2,1]) @test cols[1] === hrs.wave @test cols[:] == cols[1:2] == cols[[1,2]] == cols[trues(2)] == [hrs.wave, hrs.oop_spend] @test cols[:wave] === cols[1] @test cols[[:oop_spend, :wave]] == [hrs.oop_spend, hrs.wave] @test_throws ArgumentError cols[[1, :oop_spend]] @test_throws BoundsError cols[1:3] @test propertynames(cols) == [:wave, :oop_spend] @test cols.wave === cols[1] @test keys(cols) == [:wave, :oop_spend] @test values(cols) == [hrs.wave, hrs.oop_spend] @test haskey(cols, :wave) @test haskey(cols, 1) @test get(cols, :wave, nothing) == cols[1] @test get(cols, :none, nothing) === nothing @test [col for col in cols] == cols[:] @test cols == deepcopy(cols) @test sprint(show, cols) == "3280×2 VecColumnTable" @test sprint(show, MIME("text/plain"), cols, context=:displaysize=>(18,80)) == """ 3280×2 VecColumnTable: Row │ wave oop_spend │ Int64 Float64 ──────┼────────────────── 1 │ 10 6532.91 2 │ 8 1326.93 3 │ 11 1050.33 4 │ 9 979.418 5 │ 7 5498.68 ⋮ │ ⋮ ⋮ 3276 │ 11 3020.78 3277 │ 8 2632.0 3278 │ 9 657.34 3279 │ 10 782.795 3280 │ 7 4182.39""" @test summary(cols) == "3280×2 VecColumnTable" @test sprint(summary, cols) == "3280×2 VecColumnTable" @test Tables.istable(typeof(cols)) @test Tables.columnaccess(typeof(cols)) @test Tables.columns(cols) === cols @test Tables.getcolumn(cols, 1) === cols[1] @test Tables.getcolumn(cols, :wave) === cols[1] @test Tables.columnnames(cols) == [:wave, :oop_spend] @test Tables.schema(cols) == Tables.Schema{(:wave, :oop_spend), Tuple{Int, Float64}}() @test Tables.materializer(cols) == VecColumnTable @test Tables.columnindex(cols, :wave) == 1 @test Tables.columntype(cols, :wave) == Int @test Tables.rowcount(cols) == 3280 @test eltype(Tables.rows(cols)) == VecColsRow rows0 = collect(Tables.rows(cols)) @test ncol(rows0[1]) == 2 @test hash(rows0[2]) != hash(rows0[6]) @test isequal(rows0[1], rows0[1]) @test isequal(rows0[1], rows0[2]) == false @test isless(rows0[2], rows0[1]) # Same data but different parent tables rows1 = collect(Tables.rows(cols1)) @test hash(rows0[1]) == hash(rows1[1]) @test isequal(rows0[1], rows1[1]) @test isless(rows0[2], rows1[1]) # Rows do not have the same length @test !isequal(rows[1], rows0[1]) @test_throws ArgumentError isless(rows[1], rows0[1]) cols2 = VecColumnTable((wave=hrs.wave, male=hrs.male)) rows2 = collect(Tables.rows(cols2)) @test hash(rows2[2]) == hash(rows2[6]) @test isequal(rows2[2], rows2[6]) # Different column names but otherwise the same table cols3 = VecColumnTable((wave1=hrs.wave, oop_spend1=hrs.oop_spend)) rows3 = collect(Tables.rows(cols3)) @test hash(rows0[2]) == hash(rows3[2]) @test isequal(rows0[2], rows3[2]) @test isless(rows0[2], rows3[1]) df = DataFrame(hrs) @test sortperm(cols) == sortperm(rows0) == sortperm(df, [:wave, :oop_spend]) cols_sorted = sort(cols) df_sorted = sort(df, [:wave, :oop_spend]) @test cols_sorted.oop_spend == df_sorted.oop_spend sort!(cols) @test cols.oop_spend == df_sorted.oop_spend end @testset "subcolumns" begin hrs = exampledata("hrs") df = DataFrame(hrs) allowmissing!(df) cols = subcolumns(df, []) @test size(cols) == (0, 0) @test isempty(cols) cols = subcolumns(df, :wave, falses(size(df,1))) @test size(cols) == (0, 1) @test isempty(cols) @test cols.wave == cols[:wave] == cols[1] == Int[] cols = subcolumns(df, :wave) @test cols.wave == hrs.wave @test eltype(cols.wave) == Int @test size(cols) == (3280, 1) cols = subcolumns(df, :wave, nomissing=false) @test cols.wave == hrs.wave @test eltype(cols.wave) == Union{Int, Missing} df[:,:male] .= ifelse.(df.wave.==11, missing, df.male) @test_throws MethodError subcolumns(df, :male) cols = subcolumns(df, :male, df.wave.!=11) @test cols.male == hrs.male[hrs.wave.!=11] @test eltype(cols.male) == Int cols = subcolumns(df, (:wave, :male), df.wave.!=11) @test cols.wave == hrs.wave[hrs.wave.!=11] @test eltype(cols.wave) == Int @test subcolumns(df, [:wave, :male], df.wave.!=11) == cols end @testset "apply apply_and" begin cols = VecColumnTable((a=collect(1:10), b=collect(2:11))) @test apply(cols, :a=>identity) == cols.a @test apply(cols, 2=>identity) == cols.b @test apply(cols, (:a,2)=>(x,y)->x+y) == cols.a .+ cols.b r = apply(cols, (:a,)=>isodd) @test r == isodd.(cols.a) @test r isa Vector{Bool} @test_throws MethodError apply(cols, :a=>identity, :b=>identity) inds = trues(10) apply_and!(inds, cols, :a=>isodd) @test inds == isodd.(cols.a) inds = trues(10) apply_and!(inds, cols, [1,:b]=>(x,y)->isodd(x)&&isodd(y)) @test inds == falses(10) inds = trues(10) apply_and!(inds, cols, :a=>isodd, :a=>isodd) @test inds == isodd.(cols.a) inds = trues(10) @test all(apply_and!(inds, cols, :a=>cols.a)) inds = trues(10) @test all(.!(apply_and!(inds, cols, 2=>cols.a))) inds = trues(10) apply_and!(inds, cols, :a=>isodd, 2=>isodd) @test inds == falses(10) @test all(apply_and(cols, :a=>cols.a)) r = apply_and(cols, :a=>isodd) @test r == isodd.(cols.a) @test r isa BitArray @test all(apply_and(cols, 2=>cols.b)) @test apply_and(cols, :a=>isodd, 2=>isodd) == falses(10) end @testset "_parse_subset" begin cols = VecColumnTable((a=collect(1:10), b=collect(2:11))) @test _parse_subset(cols, :a=>isodd) == isodd.(cols.a) inds = trues(2) @test _parse_subset(cols, inds) === inds @test _parse_subset(cols, (:a=>isodd, 2=>isodd)) == falses(10) @test _parse_subset(cols, :) === Colon() end @testset "TableIndexedMatrix" begin m = reshape(1:100, 10, 10) r = VecColumnTable((a=collect(1:10),)) c = VecColumnTable((b=collect(1:10),)) tm = TableIndexedMatrix(m, r, c) @test size(tm) == size(m) @test tm[1] == 1 @test tm[1, 1] == 1 @test IndexStyle(typeof(tm)) == IndexLinear() @test_throws ArgumentError TableIndexedMatrix(m, 1:10, c) r1 = VecColumnTable((a=collect(1:11),)) @test_throws DimensionMismatch TableIndexedMatrix(m, r1, c) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
2993
const t0 = TreatmentTerm(:g, TestTreatment(:t, 0), TestParallel(0)) const t1 = treat(:g, TestTreatment(:t, 0), TestParallel(0)) const t2 = treat(:g, TestTreatment(:t, 1), TestParallel(0)) const t3 = treat(:g, TestTreatment(:t, 0), TestParallel(1)) @testset "TermSet" begin @test TermSet() == termset() @test TermSet([term(:a)]) == termset([term(:a)]) == TermSet(Set{AbstractTerm}([term(:a)])) @test TermSet(1, :a, term(:a)) == termset(1, :a, term(:a)) == TermSet(Set{AbstractTerm}([term(1), term(:a)])) ts0 = TermSet() @test isempty(ts0) @test length(ts0) == 0 ts1 = TermSet(term(:a)) @test isempty(ts1) == false @test length(ts1) == 1 @test term(:a) in ts1 @test push!(ts0, term(:a)) == ts1 @test pop!(ts0, term(:a)) == term(:a) @test isempty(ts0) @test pop!(ts0, term(:a), 0) === 0 delete!(ts1, term(:a)) @test ts1 == ts0 ts1 = TermSet(term(:a)) @test empty!(ts1) == ts0 @test eltype(TermSet) == AbstractTerm ts1 = TermSet(term(:a)) @test iterate(ts1)[1] == term(:a) @test Base.emptymutable(ts1) == ts0 end @testset "==" begin @test term(:x) + term(:y) == term(:y) + term(:x) @test term(:x) + term(:y) + term(:y) == term(:y) + term(:x) + term(:x) @test term(:x) & term(:y) == term(:y) & term(:x) @test term(:x) & term(:y) + term(:y) & term(:x) == term(:y) & term(:x) @test term(:x) & term(:y) + term(:z) == term(:z) + term(:y) & term(:x) @test lag(term(:x),1) & term(:z) == term(:z) & lag(term(:x),1) end @testset "treat" begin @test t1 == t0 @test t2 != t0 @test t3 != t0 end @testset "parse_intercept!" begin @test isintercept(term(1)) @test isomitsintercept(term(0)) @test isomitsintercept(term(-1)) @test parse_intercept!(TermSet()) == (false, false) @test parse_intercept!(TermSet(term(:x))) == (false, false) ts = TermSet(term(1)) @test parse_intercept!(ts) == (true, false) @test isempty(ts) ts = TermSet((term(0), term(-1))) @test parse_intercept!(ts) == (false, true) @test isempty(ts) ts = TermSet((term(1), term(0), term(:x))) @test parse_intercept!(ts) == (true, true) @test collect(ts) == [term(:x)] end @testset "schema" begin hrs = exampledata("hrs") sc = schema(termset(:wave, :oop_spend), hrs) @test sc[term(:wave)] isa ContinuousTerm @test sc[term(:oop_spend)] isa ContinuousTerm sc = schema(termset(:wave, :oop_spend), hrs, Dict(:wave=>CategoricalTerm)) @test sc[term(:wave)] isa CategoricalTerm @test sc[term(:oop_spend)] isa ContinuousTerm cols = VecColumnTable(hrs) @test concrete_term(term(:wave), cols, nothing) isa ContinuousTerm @test concrete_term(term(:wave), cols, Dict(:wave=>CategoricalTerm)) isa CategoricalTerm @test concrete_term(term(:wave), cols, term(:wave)) isa Term @test termvars(termset()) == Symbol[] @test termvars(termset(:wave, :oop_spend)) in ([:wave, :oop_spend], [:oop_spend, :wave]) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
3051
# Define simple generic types and methods for testing sprintcompact(x) = sprint(show, x; context=:compact=>true) struct TestSharpness <: TreatmentSharpness end struct TestParaCondition <: ParallelCondition end struct TestParaStrength <: ParallelStrength end struct TestTreatment <: AbstractTreatment time::Symbol ref::Int end ttreat(time::Term, ref::ConstantTerm) = TestTreatment(time.sym, ref.n) struct TestParallel{C,S} <: AbstractParallel{C,S} e::Int end TestParallel(e::Int) = TestParallel{ParallelCondition,ParallelStrength}(e) tpara(c::ConstantTerm) = TestParallel{ParallelCondition,ParallelStrength}(c.n) teststep(tr::AbstractTreatment, pr::AbstractParallel) = (str=sprint(show, tr), spr=sprint(show, pr)) const TestStep = StatsStep{:TestStep, typeof(teststep), true} required(::TestStep) = (:tr, :pr) testnextstep(::AbstractTreatment, str::String) = (next="next"*str,) const TestNextStep = StatsStep{:TestNextStep, typeof(testnextstep), true} required(::TestNextStep) = (:tr, :str) const TestDID = DiffinDiffsEstimator{:TestDID, Tuple{TestStep,TestNextStep}} const NotImplemented = DiffinDiffsEstimator{:NotImplemented, Tuple{}} const TR = TestTreatment(:t, 0) const PR = TestParallel(0) struct TestResult{TR} <: DIDResult{TR} coef::Vector{Float64} vcov::Matrix{Float64} vce::Nothing tr::AbstractTreatment nobs::Int dof_residual::Int yname::String coefnames::Vector{String} coefinds::Dict{String, Int} treatcells::VecColumnTable weightname::Symbol extra1::Int extra2::Symbol extra3::String extra4::Vector{Float64} extra5::Vector{String} extra6::Matrix{Float64} extra7::Vector{Symbol} extra8::Nothing extra9::Array{Float64,3} end @fieldequal TestResult function TestResult(n1::Int, n2::Int) N = n1*(n2+1) coef = collect(Float64, 1:N) tr = TR tnames = ["rel: $a & c: $b" for a in 1:n1 for b in 1:n2] cnames = vcat(tnames, ["c"*string(i) for i in n1*n2+1:N]) cinds = Dict(cnames .=> 1:N) tcells = VecColumnTable((rel=repeat(1:n1, inner=n2), c=repeat(1:n2, outer=n1))) return TestResult{typeof(tr)}(coef, coef.*coef', nothing, tr, N, N-1, "y", cnames, cinds, tcells, :w, 1, :a, "a", [1.0], ["a"], [1.0 2.0], [:a], nothing, ones(1,1,1)) end struct TestResultBARE{TR} <: DIDResult{TR} coef::Vector{Float64} vcov::Matrix{Float64} vce::Nothing tr::AbstractTreatment nobs::Int yname::String coefnames::Vector{String} treatcells::VecColumnTable weightname::Symbol end @fieldequal TestResultBARE function TestResultBARE(n1::Int, n2::Int) N = n1*n2 coef = collect(Float64, 1:N) tr = dynamic(:time, (-1,)) tnames = ["rel: $a & c: $b" for a in 1:n1 for b in 1:n2] tcells = VecColumnTable((rel=repeat(1:n1, inner=n2), c=repeat(1:n2, outer=n1))) return TestResultBARE{typeof(tr)}(coef, coef.*coef', nothing, tr, N, "y", tnames, tcells, :w) end function result(::Type{TestDID}, nt::NamedTuple) return merge(nt, (result=TestResult(2, 2),)) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
2732
@testset "RotatingTimeValue" begin rt0 = RotatingTimeValue(1, Date(1)) rt1 = RotatingTimeValue(1.0, Date(1)) @test RotatingTimeValue(typeof(rt0), 1.0, Date(1)) === rt0 @test rotatingtime(1.0, Date(1)) == rt1 rot = repeat(5:-1:1, inner=5) time = repeat(1:5, outer=5) rt = rotatingtime(rot, time) @test eltype(rt) == RotatingTimeValue{Int, Int} @test getfield.(rt, :rotation) == rot @test getfield.(rt, :time) == time @test isless(rt[1], rt[2]) @test isless(rt[6], rt[1]) @test isless(rt[1], rt[7]) @test isless(rt[1], 2.0) @test isless(1, rt[2]) @test isless(rt[1], missing) @test !isless(missing, rt[1]) @test isequal(rt[1], RotatingTimeValue(5, 1)) @test rt[1] == RotatingTimeValue(Int32(5), Int32(1)) @test isequal(rt[1] == RotatingTimeValue(missing, 1), missing) @test isequal(rt[1] == RotatingTimeValue(5, missing), missing) @test isequal(rt[1] == RotatingTimeValue(1, missing), missing) @test rt[1] == 1 @test 1 == rt[1] @test isequal(rt[1] == missing, missing) @test isequal(missing == rt[1], missing) @test zero(typeof(rt[1])) === RotatingTimeValue(0, 0) @test iszero(RotatingTimeValue(1, 0)) @test !iszero(RotatingTimeValue(0, 1)) @test one(typeof(rt[1])) === RotatingTimeValue(1, 1) @test isone(RotatingTimeValue(1, 1)) @test !isone(RotatingTimeValue(1, 0)) @test convert(typeof(rt[1]), RotatingTimeValue(Int32(5), Int32(1))) === RotatingTimeValue(5, 1) @test nonmissingtype(RotatingTimeValue{Union{Int,Missing}, Union{Int,Missing}}) == RotatingTimeValue{Int, Int} @test iterate(rt1) == (rt1, nothing) @test iterate(rt1, 1) === nothing @test length(rt1) == 1 @test sprint(show, rt[1]) == "5_1" w = VERSION < v"1.6.0" ? "" : " " @test sprint(show, MIME("text/plain"), rt[1]) == """ RotatingTimeValue{Int64,$(w)Int64}: rotation: 5 time: 1""" end @testset "RotatingTimeArray" begin rot = collect(1:5) time = collect(1.0:5.0) a = RotatingTimeArray(rot, time) @test eltype(a) == RotatingTimeValue{Int, Float64} @test size(a) == (5,) @test IndexStyle(typeof(a)) == IndexLinear() @test a[1] == RotatingTimeValue(1, 1.0) @test a[5:-1:1] == RotatingTimeArray(rot[5:-1:1], time[5:-1:1]) a[1] = RotatingTimeValue(2, 2.0) @test a[1] == RotatingTimeValue(2, 2.0) a[1:2] = a[3:4] @test a[1:2] == a[3:4] v = view(a, 2:4) @test v isa RotatingTimeArray @test v == a[2:4] @test typeof(similar(a)) == typeof(a) @test size(similar(a, 3)) == (3,) @test v.rotation == rot[2:4] @test v.time == time[2:4] @test refarray(a).rotation == rot end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
2179
@testset "singletons" begin @testset "alias" begin @test sharp() == SharpDesign() end @testset "show" begin @test sprint(show, SharpDesign()) == "Sharp" @test sprintcompact(SharpDesign()) == "S" end end @testset "dynamic" begin dt0 = DynamicTreatment(:month, nothing, SharpDesign()) dt1 = DynamicTreatment(:month, -1, SharpDesign()) dt2 = DynamicTreatment(:month, [-2,-1], SharpDesign()) @testset "inner constructor" begin @test DynamicTreatment(:month, [], SharpDesign()) == dt0 @test DynamicTreatment(:month, [-1], SharpDesign()) == dt1 @test DynamicTreatment(:month, [-1,-1,-2], SharpDesign()) == dt2 @test DynamicTreatment(:month, [-1.0], SharpDesign()) == dt1 @test_throws InexactError DynamicTreatment(:month, [-1.5], SharpDesign()) end @testset "without @formula" begin @test dynamic(:month, nothing) == dt0 @test dynamic(:month, []) == dt0 @test dynamic(:month, -1) == dt1 @test dynamic(:month, [-1], sharp()) == dt1 @test dynamic(:month, -2:-1) == dt2 @test dynamic(:month, Set([-1,-2]), sharp()) == dt2 end @testset "show" begin @test sprint(show, dt0) == "Dynamic{S}()" @test sprint(show, MIME("text/plain"), dt0) == """ Sharp dynamic treatment: column name of time variable: month excluded relative time: none""" @test sprint(show, dt1) == "Dynamic{S}(-1)" @test sprint(show, MIME("text/plain"), dt1) == """ Sharp dynamic treatment: column name of time variable: month excluded relative time: -1""" @test sprint(show, dt2) == "Dynamic{S}(-2, -1)" @test sprint(show, MIME("text/plain"), dt2) == """ Sharp dynamic treatment: column name of time variable: month excluded relative time: -2, -1""" end end @testset "termvars" begin @test termvars(sharp()) == Symbol[] @test termvars(dynamic(:month, -1)) == [:month] @test_throws ErrorException termvars(TestSharpness()) @test_throws ErrorException termvars(TR) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
424
@testset "exampledata" begin @test exampledata() == (:hrs, :nsw, :mpdta) hrs = exampledata("hrs") @test size(hrs) == (3280, 11) @test hrs[1] isa Vector @test size(exampledata(:nsw)) == (32834, 11) @test size(exampledata(:mpdta)) == (2500, 5) end @testset "checktable" begin @test_throws ArgumentError checktable(rand(3,3)) @test_throws ArgumentError checktable([(a=1, b=2), (a=1, b=2)]) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
1491
module InteractionWeightedDIDs using Base: Callable using DataAPI: refarray using FixedEffectModels: FixedEffectTerm, fe, fesymbol, _multiply, basis!, invsym!, isnested, nunique using FixedEffects using LinearAlgebra: Symmetric, diag, mul! using Reexport using StatsBase: AbstractWeights, CovarianceEstimator, UnitWeights, PValue, TestStat, NoQuote using StatsFuns: fdistccdf using StatsModels: coefnames using Tables using Tables: getcolumn, columnnames using Vcov @reexport using DiffinDiffsBase using DiffinDiffsBase: ValidTimeType, termvars, isintercept, parse_intercept!, _groupfind, _treatnames, _parse_bycells!, _parse_subset using DiffinDiffsBase.StatsProcedures: _count! import Base: show import DiffinDiffsBase: valid_didargs, vce, treatment, nobs, outcomename, weights, treatnames, dof_residual, agg, post! import DiffinDiffsBase.StatsProcedures: required, default, transformed, combinedargs, copyargs, result, prerequisites import FixedEffectModels: has_fe export Vcov, fe export CheckVcov, ParseFEterms, GroupFEterms, MakeFEs, CheckFEs, MakeFESolver, MakeYXCols, MakeTreatCols, SolveLeastSquares, EstVcov, SolveLeastSquaresWeights, RegressionBasedDID, Reg, RegressionBasedDIDResult, has_fe, AggregatedRegDIDResult, has_lsweights, ContrastResult, contrast include("utils.jl") include("procedures.jl") include("did.jl") end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
24177
""" RegressionBasedDID <: DiffinDiffsEstimator Estimation procedure for regression-based difference-in-differences. A `StatsSpec` for this procedure accepts the following arguments: | Key | Type restriction | Default value | Description | |:---|:---|:---|:---| | `data` | | | A `Tables.jl`-compatible data table | | `tr` | `DynamicTreatment{SharpDesign}` | | Treatment specification | | `pr` | `TrendOrUnspecifiedPR{Unconditional,Exact}` | | Parallel trend assumption | | `yterm` | `AbstractTerm` | | A term for outcome variable | | `treatname` | `Symbol` | | Column name for the variable representing treatment time | | `subset` | `Union{BitVector,Nothing}` | `nothing` | Rows from `data` to be used for estimation | | `weightname` | `Union{Symbol,Nothing}` | `nothing` | Column name of the sample weight variable | | `vce` | `Vcov.CovarianceEstimator` | `Vcov.CovarianceEstimator` | Variance-covariance estimator | | `treatintterms` | `TermSet` | `TermSet()` | Terms interacted with the treatment indicators | | `xterms` | `TermSet` | `TermSet()` | Terms for covariates and fixed effects | | `contrasts` | `Union{Dict{Symbol,Any},Nothing}` | `nothing` | Contrast coding to be processed by `StatsModels.jl` | | `drop_singletons` | `Bool` | `true` | Drop singleton observations for fixed effects | | `nfethreads` | `Int` | `Threads.nthreads()` | Number of threads to be used for solving fixed effects | | `fetol` | `Float64` | `1e-8` | Tolerance level for the fixed effect solver | | `femaxiter` | `Int` | `10000` | Maximum number of iterations allowed for the fixed effect solver | | `cohortinteracted` | `Bool` | `true` | Interact treatment indicators by treatment time | | `solvelsweights` | `Bool` | `false` | Solve the cell-level least-square weights with default cell partition | | `lswtnames` | Iterable of `Symbol`s | `tuple()` | Column names from `treatcells` defining the cell partition used for solving least-square weights | """ const RegressionBasedDID = DiffinDiffsEstimator{:RegressionBasedDID, Tuple{CheckData, GroupTreatintterms, GroupXterms, GroupContrasts, CheckVcov, CheckVars, GroupSample, ParseFEterms, GroupFEterms, MakeFEs, CheckFEs, MakeWeights, MakeFESolver, MakeYXCols, MakeTreatCols, SolveLeastSquares, EstVcov, SolveLeastSquaresWeights}} """ Reg <: DiffinDiffsEstimator Alias for [`RegressionBasedDID`](@ref). """ const Reg = RegressionBasedDID function valid_didargs(d::Type{Reg}, ::DynamicTreatment{SharpDesign}, ::TrendOrUnspecifiedPR{Unconditional,Exact}, args::Dict{Symbol,Any}) name = get(args, :name, "")::String treatintterms = haskey(args, :treatintterms) ? args[:treatintterms] : TermSet() xterms = haskey(args, :xterms) ? args[:xterms] : TermSet() solvelsweights = haskey(args, :lswtnames) || get(args, :solvelsweights, false)::Bool ntargs = (data=args[:data], tr=args[:tr]::DynamicTreatment{SharpDesign}, pr=args[:pr]::TrendOrUnspecifiedPR{Unconditional,Exact}, yterm=args[:yterm]::AbstractTerm, treatname=args[:treatname]::Symbol, subset=get(args, :subset, nothing)::Union{BitVector,Nothing}, weightname=get(args, :weightname, nothing)::Union{Symbol,Nothing}, vce=get(args, :vce, Vcov.RobustCovariance())::Vcov.CovarianceEstimator, treatintterms=treatintterms::TermSet, xterms=xterms::TermSet, contrasts=get(args, :contrasts, nothing)::Union{Dict{Symbol,Any},Nothing}, drop_singletons=get(args, :drop_singletons, true)::Bool, nfethreads=get(args, :nfethreads, Threads.nthreads())::Int, fetol=get(args, :fetol, 1e-8)::Float64, femaxiter=get(args, :femaxiter, 10000)::Int, cohortinteracted=get(args, :cohortinteracted, true)::Bool, solvelsweights=solvelsweights::Bool, lswtnames=get(args, :lswtnames, ())) return name, d, ntargs end prerequisites(::Reg, ::CheckData) = () prerequisites(::Reg, ::GroupTreatintterms) = () prerequisites(::Reg, ::GroupXterms) = () prerequisites(::Reg, ::GroupContrasts) = () prerequisites(::Reg, ::CheckVcov) = (CheckData(),) prerequisites(::Reg, ::CheckVars) = (CheckData(), GroupTreatintterms(), GroupXterms()) prerequisites(::Reg, ::GroupSample) = (CheckVcov(), CheckVars()) prerequisites(::Reg, ::ParseFEterms) = (GroupXterms(),) prerequisites(::Reg, ::GroupFEterms) = (ParseFEterms(),) prerequisites(::Reg, ::MakeFEs) = (GroupSample(), GroupFEterms()) prerequisites(::Reg, ::CheckFEs) = (MakeFEs(),) prerequisites(::Reg, ::MakeWeights) = (CheckFEs(),) prerequisites(::Reg, ::MakeFESolver) = (MakeWeights(),) prerequisites(::Reg, ::MakeYXCols) = (MakeFESolver(), GroupContrasts()) prerequisites(::Reg, ::MakeTreatCols) = (MakeFESolver(),) prerequisites(::Reg, ::SolveLeastSquares) = (MakeYXCols(), MakeTreatCols()) prerequisites(::Reg, ::EstVcov) = (SolveLeastSquares(),) prerequisites(::Reg, ::SolveLeastSquaresWeights) = (SolveLeastSquares(),) """ RegressionBasedDIDResult{TR,CohortInteracted,Haslsweights} <: DIDResult{TR} Estimation results from regression-based difference-in-differences. # Fields - `coef::Vector{Float64}`: coefficient estimates. - `vcov::Matrix{Float64}`: variance-covariance matrix for the estimates. - `vce::CovarianceEstimator`: variance-covariance estiamtor. - `tr::TR`: treatment specification. - `pr::AbstractParallel`: parallel trend assumption. - `treatweights::Vector{Float64}`: total sample weights from observations for which the corresponding treatment indicator takes one. - `treatcounts::Vector{Int}`: total number of observations for which the corresponding treatment indicator takes one. - `esample::BitVector`: indicator for the rows from `data` involved in estimation. - `nobs::Int`: number of observations involved in estimation. - `dof_residual::Int`: residual degree of freedom. - `F::Float64`: F-statistic for overall significance of regression model. - `p::Float64`: p-value corresponding to the F-statistic. - `yname::String`: name of the outcome variable. - `coefnames::Vector{String}`: coefficient names. - `coefinds::Dict{String, Int}`: a map from `coefnames` to integer indices for retrieving estimates by name. - `treatcells::VecColumnTable`: a tabular description of cells where a treatment indicator takes one. - `treatname::Symbol`: column name for the variable representing treatment time. - `yxterms::Dict{AbstractTerm, AbstractTerm}`: a map from all specified terms to concrete terms. - `yterm::AbstractTerm`: the specified term for outcome variable. - `xterms::Vector{AbstractTerm}`: the specified terms for covariates and fixed effects. - `contrasts::Union{Dict{Symbol, Any}, Nothing}`: contrast coding to be processed by `StatsModels.jl`. - `weightname::Union{Symbol, Nothing}`: column name of the sample weight variable. - `fenames::Vector{String}`: names of the fixed effects. - `nfeiterations::Union{Int, Nothing}`: number of iterations for the fixed effect solver to reach convergence. - `feconverged::Union{Bool, Nothing}`: whether the fixed effect solver has converged. - `nfesingledropped::Int`: number of singleton observations for fixed effects that have been dropped. - `lsweights::Union{TableIndexedMatrix, Nothing}`: cell-level least-square weights. - `cellymeans::Union{Vector{Float64}, Nothing}`: cell-level averages of the outcome variable. - `cellweights::Union{Vector{Float64}, Nothing}`: total sample weights for each cell. - `cellcounts::Union{Vector{Int}, Nothing}`: number of observations for each cell. """ struct RegressionBasedDIDResult{TR,CohortInteracted,Haslsweights} <: DIDResult{TR} coef::Vector{Float64} vcov::Matrix{Float64} vce::CovarianceEstimator tr::TR pr::AbstractParallel treatweights::Vector{Float64} treatcounts::Vector{Int} esample::BitVector nobs::Int dof_residual::Int F::Float64 p::Float64 yname::String coefnames::Vector{String} coefinds::Dict{String, Int} treatcells::VecColumnTable treatname::Symbol yxterms::Dict{AbstractTerm, AbstractTerm} yterm::AbstractTerm xterms::Vector{AbstractTerm} contrasts::Union{Dict{Symbol, Any}, Nothing} weightname::Union{Symbol, Nothing} fenames::Vector{String} nfeiterations::Union{Int, Nothing} feconverged::Union{Bool, Nothing} nfesingledropped::Int lsweights::Union{TableIndexedMatrix{Float64, Matrix{Float64}, VecColumnTable, VecColumnTable}, Nothing} cellymeans::Union{Vector{Float64}, Nothing} cellweights::Union{Vector{Float64}, Nothing} cellcounts::Union{Vector{Int}, Nothing} end function result(::Type{Reg}, @nospecialize(nt::NamedTuple)) yterm = nt.yxterms[nt.yterm] yname = coefnames(yterm) cnames = _treatnames(nt.treatcells) cnames = append!(cnames, coefnames.(nt.xterms))[nt.basiscols] coefinds = Dict(cnames .=> 1:length(cnames)) didresult = RegressionBasedDIDResult{typeof(nt.tr), nt.cohortinteracted, nt.lsweights!==nothing}( nt.coef, nt.vcov_mat, nt.vce, nt.tr, nt.pr, nt.treatweights, nt.treatcounts, nt.esample, sum(nt.esample), nt.dof_resid, nt.F, nt.p, yname, cnames, coefinds, nt.treatcells, nt.treatname, nt.yxterms, yterm, nt.xterms, nt.contrasts, nt.weightname, nt.fenames, nt.nfeiterations, nt.feconverged, nt.nsingle, nt.lsweights, nt.cellymeans, nt.cellweights, nt.cellcounts) return merge(nt, (result=didresult,)) end """ has_fe(r::RegressionBasedDIDResult) Test whether any fixed effect is involved in regression. """ has_fe(r::RegressionBasedDIDResult) = !isempty(r.fenames) _top_info(r::RegressionBasedDIDResult) = ( "Number of obs" => nobs(r), "Degrees of freedom" => nobs(r) - dof_residual(r), "F-statistic" => TestStat(r.F), "p-value" => PValue(r.p) ) _nunique(t, s::Symbol) = length(unique(getproperty(t, s))) _excluded_rel_str(tr::DynamicTreatment) = isempty(tr.exc) ? "none" : join(string.(tr.exc), " ") _treat_info(r::RegressionBasedDIDResult{<:DynamicTreatment, true}) = ( "Number of cohorts" => _nunique(r.treatcells, r.treatname), "Interactions within cohorts" => length(columnnames(r.treatcells)) - 2, "Relative time periods" => _nunique(r.treatcells, :rel), "Excluded periods" => NoQuote(_excluded_rel_str(r.tr)) ) _treat_info(r::RegressionBasedDIDResult{<:DynamicTreatment, false}) = ( "Relative time periods" => _nunique(r.treatcells, :rel), "Excluded periods" => NoQuote(_excluded_rel_str(r.tr)) ) _treat_spec(r::RegressionBasedDIDResult{DynamicTreatment{SharpDesign}, true}) = "Cohort-interacted sharp dynamic specification" _treat_spec(r::RegressionBasedDIDResult{DynamicTreatment{SharpDesign}, false}) = "Sharp dynamic specification" _fe_info(r::RegressionBasedDIDResult) = ( "Converged" => r.feconverged, "Singletons dropped" => r.nfesingledropped ) show(io::IO, ::RegressionBasedDIDResult) = print(io, "Regression-based DID result") function show(io::IO, ::MIME"text/plain", r::RegressionBasedDIDResult; totalwidth::Int=70, interwidth::Int=4+mod(totalwidth,2)) halfwidth = div(totalwidth-interwidth, 2) top_info = _top_info(r) fe_info = has_fe(r) ? _fe_info(r) : () tr_info = _treat_info(r) blocks = (top_info, tr_info, fe_info) fes = has_fe(r) ? join(string.(r.fenames), " ") : "none" fetitle = string("Fixed effects: ", fes) blocktitles = ("Summary of results: Regression-based DID", _treat_spec(r), fetitle[1:min(totalwidth,length(fetitle))]) for (ib, b) in enumerate(blocks) println(io, repeat('─', totalwidth)) println(io, blocktitles[ib]) if !isempty(b) # Print line between block title and block content println(io, repeat('─', totalwidth)) for (i, e) in enumerate(b) print(io, e[1], ':') print(io, lpad(e[2], halfwidth - length(e[1]) - 1)) print(io, isodd(i) ? repeat(' ', interwidth) : '\n') end end end print(io, repeat('─', totalwidth)) end """ AggregatedRegDIDResult{TR,Haslsweights,P<:RegressionBasedDIDResult,I} <: AggregatedDIDResult{TR,P} Estimation results aggregated from a [`RegressionBasedDIDResult`](@ref). See also [`agg`](@ref). # Fields - `parent::P`: the [`RegressionBasedDIDResult`](@ref) from which the results are generated. - `inds::I`: indices of the coefficient estimates from `parent` used to generate the results. - `coef::Vector{Float64}`: coefficient estimates. - `vcov::Matrix{Float64}`: variance-covariance matrix for the estimates. - `coefweights::Matrix{Float64}`: coefficient weights used to aggregate the coefficient estimates from `parent`. - `treatweights::Vector{Float64}`: sum of `treatweights` from `parent` over combined `treatcells`. - `treatcounts::Vector{Int}`: sum of `treatcounts` from `parent` over combined `treatcells`. - `coefnames::Vector{String}`: coefficient names. - `coefinds::Dict{String, Int}`: a map from `coefnames` to integer indices for retrieving estimates by name. - `treatcells::VecColumnTable`: cells combined from the `treatcells` from `parent`. - `lsweights::Union{TableIndexedMatrix, Nothing}`: cell-level least-square weights. - `cellymeans::Union{Vector{Float64}, Nothing}`: cell-level averages of the outcome variable. - `cellweights::Union{Vector{Float64}, Nothing}`: total sample weights for each cell. - `cellcounts::Union{Vector{Int}, Nothing}`: number of observations for each cell. """ struct AggregatedRegDIDResult{TR,Haslsweights,P<:RegressionBasedDIDResult,I} <: AggregatedDIDResult{TR,P} parent::P inds::I coef::Vector{Float64} vcov::Matrix{Float64} coefweights::Matrix{Float64} treatweights::Vector{Float64} treatcounts::Vector{Int} coefnames::Vector{String} coefinds::Dict{String, Int} treatcells::VecColumnTable lsweights::Union{TableIndexedMatrix{Float64, Matrix{Float64}, VecColumnTable, VecColumnTable}, Nothing} cellymeans::Union{Vector{Float64}, Nothing} cellweights::Union{Vector{Float64}, Nothing} cellcounts::Union{Vector{Int}, Nothing} end """ agg(r::RegressionBasedDIDResult{<:DynamicTreatment}, names=nothing; kwargs...) Aggregate coefficient estimates from `r` by values taken by the columns from `r.treatcells` indexed by `names` with weights proportional to `treatweights` within each relative time. # Keywords - `bys=nothing`: columnwise transformations over `r.treatcells` before grouping by `names`. - `subset=nothing`: subset of treatment coefficients used for aggregation. """ function agg(r::RegressionBasedDIDResult{<:DynamicTreatment}, names=nothing; bys=nothing, subset=nothing) inds = subset === nothing ? Colon() : _parse_subset(r, subset, false) bycells = view(treatcells(r), inds) isempty(bycells) && throw(ArgumentError( "No coefficient left for aggregation after taking the subset")) _parse_bycells!(getfield(bycells, :columns), bycells, bys) names === nothing || (bycells = subcolumns(bycells, names, nomissing=false)) tcells, rows = cellrows(bycells, findcell(bycells)) ncell = length(rows) pcf = view(treatcoef(r), inds) cweights = zeros(length(pcf), ncell) ptreatweights = view(r.treatweights, inds) ptreatcounts = view(r.treatcounts, inds) # Ensure the weights for each relative time always sum up to one rels = view(r.treatcells.rel, inds) for (i, rs) in enumerate(rows) if length(rs) > 1 relgroups = _groupfind(view(rels, rs)) for ids in values(relgroups) if length(ids) > 1 cwts = view(ptreatweights, view(rs, ids)) cweights[view(rs, ids), i] .= cwts ./ sum(cwts) else cweights[rs[ids[1]], i] = 1.0 end end else cweights[rs[1], i] = 1.0 end end cf = cweights' * pcf v = cweights' * view(treatvcov(r), inds, inds) * cweights treatweights = [sum(ptreatweights[rows[i]]) for i in 1:ncell] treatcounts = [sum(ptreatcounts[rows[i]]) for i in 1:ncell] cnames = _treatnames(tcells) coefinds = Dict(cnames .=> keys(cnames)) if r.lsweights === nothing lswt = nothing else lswtmat = view(r.lsweights.m, :, inds) * cweights lswt = TableIndexedMatrix(lswtmat, r.lsweights.r, tcells) end return AggregatedRegDIDResult{typeof(r.tr), lswt!==nothing, typeof(r), typeof(inds)}( r, inds, cf, v, cweights, treatweights, treatcounts, cnames, coefinds, tcells, lswt, r.cellymeans, r.cellweights, r.cellcounts) end vce(r::AggregatedRegDIDResult) = vce(parent(r)) treatment(r::AggregatedRegDIDResult) = treatment(parent(r)) nobs(r::AggregatedRegDIDResult) = nobs(parent(r)) outcomename(r::AggregatedRegDIDResult) = outcomename(parent(r)) weights(r::AggregatedRegDIDResult) = weights(parent(r)) treatnames(r::AggregatedRegDIDResult) = coefnames(r) dof_residual(r::AggregatedRegDIDResult) = dof_residual(parent(r)) """ RegDIDResultOrAgg{TR,Haslsweights} Union type of [`RegressionBasedDIDResult`](@ref) and [`AggregatedRegDIDResult`](@ref). """ const RegDIDResultOrAgg{TR,Haslsweights} = Union{RegressionBasedDIDResult{TR,<:Any,Haslsweights}, AggregatedRegDIDResult{TR,Haslsweights}} """ has_lsweights(r::RegDIDResultOrAgg) Test whether `r` contains computed least-sqaure weights (`r.lsweights!==nothing`). """ has_lsweights(::RegDIDResultOrAgg{TR,H}) where {TR,H} = H """ ContrastResult{T,M,R,C} <: AbstractMatrix{T} Matrix type that holds least-square weights obtained from one or more [`RegDIDResultOrAgg`](@ref)s computed over the same set of cells and cell-level averages. See also [`contrast`](@ref). The least-square weights are stored in a `Matrix` that can be retrieved with property name `:m`, where the weights for each treatment coefficient are stored columnwise starting from the second column and the first column contains the cell-level averages of outcome variable. The indices for cells can be accessed with property name `:r`; and indices for identifying the coefficients can be accessed with property name `:c`. The [`RegDIDResultOrAgg`](@ref)s used to generate the `ContrastResult` can be accessed by calling `parent`. """ struct ContrastResult{T,M,R,C} <: AbstractMatrix{T} rs::Vector{RegDIDResultOrAgg} m::TableIndexedMatrix{T,M,R,C} function ContrastResult(rs::Vector{RegDIDResultOrAgg}, m::TableIndexedMatrix{T,M,R,C}) where {T,M,R,C} cnames = columnnames(m.c) cnames[1]==:iresult && cnames[2]==:icoef && cnames[3]==:name || throw(ArgumentError( "Table paired with column indices has unaccepted column names")) return new{T,M,R,C}(rs, m) end end _getmat(cr::ContrastResult) = getfield(cr, :m) Base.size(cr::ContrastResult) = size(_getmat(cr)) Base.getindex(cr::ContrastResult, i) = _getmat(cr)[i] Base.getindex(cr::ContrastResult, i, j) = _getmat(cr)[i,j] Base.IndexStyle(::Type{<:ContrastResult{T,M}}) where {T,M} = IndexStyle(M) Base.getproperty(cr::ContrastResult, n::Symbol) = getproperty(_getmat(cr), n) Base.parent(cr::ContrastResult) = getfield(cr, :rs) """ contrast(r1::RegDIDResultOrAgg, rs::RegDIDResultOrAgg...; kwargs) Construct a [`ContrastResult`](@ref) by collecting the computed least-square weights from each of the [`RegDIDResultOrAgg`](@ref). # Keywords - `subset=nothing`: indices for cells to be included (rows in output). - `coefs=nothing`: indices for coefficients from each result to be included (columns in output). """ function contrast(r1::RegDIDResultOrAgg, rs::RegDIDResultOrAgg...; subset=nothing, coefs=nothing) has_lsweights(r1) && all(r->has_lsweights(r), rs) || throw(ArgumentError( "Results must contain computed least-sqaure weights")) ri = r1.lsweights.r rinds = subset === nothing ? Colon() : _parse_subset(ri, subset) # Make a copy to avoid accidentally overwriting cells for DIDResult ri = deepcopy(view(ri, rinds)) dcoefs = coefs === nothing ? NamedTuple() : IdDict{Int,Any}(coefs) rs = RegDIDResultOrAgg[r1, rs...] m = Vector{Array}(undef, length(rs)+1) m[1] = view(r1.cellymeans, rinds) iresult = [0] icoef = [0] names = ["cellymeans"] for (i, r) in enumerate(rs) view(r.lsweights.r, rinds) == ri || throw(ArgumentError( "Cells for least-square weights comparisons must be identical across the inputs")) cinds = get(dcoefs, i, nothing) cinds = cinds === nothing ? (1:ntreatcoef(r)) : _parse_subset(treatcells(r), cinds) m[i+1] = view(r.lsweights.m, rinds, cinds) ic = view(1:ntreatcoef(r), cinds) push!(iresult, (i for k in 1:length(ic))...) append!(icoef, ic) append!(names, view(treatnames(r), cinds)) end m = hcat(m...) ci = VecColumnTable((iresult=iresult, icoef=icoef, name=names)) return ContrastResult(rs, TableIndexedMatrix(m, ri, ci)) end function Base.:(==)(x::ContrastResult, y::ContrastResult) # Assume no missing x.m == y.m || return false x.r == y.r || return false x.c == y.c || return false return parent(x) == parent(y) end function Base.sort!(cr::ContrastResult; @nospecialize(kwargs...)) p = sortperm(cr.r; kwargs...) @inbounds for col in cr.r col .= col[p] end @inbounds cr.m .= cr.m[p,:] return cr end function Base.view(cr::ContrastResult, subset) inds = _parse_subset(cr.r, subset) r = view(cr.r, inds) m = view(cr.m, inds, :) return ContrastResult(parent(cr), TableIndexedMatrix(m, r, cr.c)) end function _checklengthmatch(v, name::String, N::Int) length(v) == N || throw(ArgumentError( "The length of $name ($(length(v))) does not match the number of rows of cr ($(N))")) end _checklengthmatch(v::Nothing, name::String, N::Int) = nothing """ post!(gl, gr, gd, ::StataPostHDF, cr::ContrastResult, left::Int=2, right::Int=3; kwargs...) Export the least-square weights for coefficients indexed by `left` and `right` from `cr` for Stata module [`posthdf`](https://github.com/junyuan-chen/posthdf). The contribution of each cell to the difference between two coefficients are computed and also exported. The weights and contributions are stored as coefficient estimates in three groups `gl`, `gr` and `gd` respectively. The groups can be `HDF5.Group`s or objects that can be indexed by strings. # Keywords - `lefttag::String=string(left)`: name to be used as `depvar` in Stata after being prefixed by `"l_"` for the coefficient indexed by `left`. - `righttag::String=string(right)`: name to be used as `depvar` in Stata after being prefixed by `"r_"` for the coefficient indexed by `right`. - `model::String="InteractionWeightedDIDs.ContrastResult"`: name of the model. - `eqnames::Union{AbstractVector, Nothing}=nothing`: equation names prefixed to coefficient names in Stata. - `colnames::Union{AbstractVector, Nothing}=nothing`: column names used as coefficient names in Stata. - `at::Union{AbstractVector{<:Real}, Nothing}=nothing`: the `at` vector in Stata. """ function post!(gl, gr, gd, ::StataPostHDF, cr::ContrastResult, left::Int=2, right::Int=3; lefttag::String=string(left), righttag::String=string(right), model::String="InteractionWeightedDIDs.ContrastResult", eqnames::Union{AbstractVector, Nothing}=nothing, colnames::Union{AbstractVector, Nothing}=nothing, at::Union{AbstractVector{<:Real}, Nothing}=nothing) N = size(cr.m, 1) _checklengthmatch(eqnames, "eqnames", N) _checklengthmatch(colnames, "colnames", N) _checklengthmatch(at, "at", N) gl["depvar"] = string("l_", lefttag) wtl = view(cr.m, :, left)[:] gl["b"] = wtl gr["depvar"] = string("r_", righttag) wtr = view(cr.m, :, right)[:] gr["b"] = wtr gd["depvar"] = string("d_", lefttag, "_", righttag) diff = (wtl.-wtr).*view(cr.m,:,1)[:] gd["b"] = diff colnames === nothing && (colnames = 1:N) cnames = eqnames === nothing ? string.(colnames) : string.(eqnames, ":", colnames) for g in (gl, gr, gd) g["model"] = model g["coefnames"] = cnames at === nothing || (g["at"] = at) end end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
22452
""" checkvcov!(args...) Exclude rows that are invalid for variance-covariance estimator. See also [`CheckVcov`](@ref). """ checkvcov!(data, esample::BitVector, aux::BitVector, vce::Union{Vcov.SimpleCovariance, Vcov.RobustCovariance}) = NamedTuple() function checkvcov!(data, esample::BitVector, aux::BitVector, vce::Vcov.ClusterCovariance) for name in Vcov.names(vce) col = getcolumn(data, name) if Missing <: eltype(col) aux .= .!ismissing.(col) esample .&= aux end end return (esample=esample,) end """ CheckVcov <: StatsStep Call [`InteractionWeightedDIDs.checkvcov!`](@ref) to exclude rows that are invalid for variance-covariance estimator. """ const CheckVcov = StatsStep{:CheckVcov, typeof(checkvcov!), true} # Get esample and aux directly from CheckData required(::CheckVcov) = (:data, :esample, :aux) default(::CheckVcov) = (vce=Vcov.robust(),) copyargs(::CheckVcov) = (2,) """ parsefeterms!(xterms) Extract any `FixedEffectTerm` or interaction of `FixedEffectTerm` from `xterms` and determine whether any intercept term should be omitted. See also [`ParseFEterms`](@ref). """ function parsefeterms!(xterms::TermSet) feterms = Set{FETerm}() has_fe_intercept = false for t in xterms result = _parsefeterm(t) if result !== nothing push!(feterms, result) delete!(xterms, t) end end if !isempty(feterms) if any(t->isempty(t[2]), feterms) has_fe_intercept = true for t in xterms t isa Union{ConstantTerm,InterceptTerm} && delete!(xterms, t) end push!(xterms, InterceptTerm{false}()) end end return (xterms=xterms, feterms=feterms, has_fe_intercept=has_fe_intercept) end """ ParseFEterms <: StatsStep Call [`InteractionWeightedDIDs.parsefeterms!`](@ref) to extract any `FixedEffectTerm` or interaction of `FixedEffectTerm` from `xterms`. Whether any intercept term should be omitted is also determined. """ const ParseFEterms = StatsStep{:ParseFEterms, typeof(parsefeterms!), true} required(::ParseFEterms) = (:xterms,) """ groupfeterms(feterms) Return the argument without change for allowing later comparisons based on object-id. See also [`GroupFEterms`](@ref). """ groupfeterms(feterms::Set{FETerm}) = (feterms=feterms,) """ GroupFEterms <: StatsStep Call [`InteractionWeightedDIDs.groupfeterms`](@ref) to obtain one of the instances of `feterms` that have been grouped by equality (`hash`) for allowing later comparisons based on object-id. This step is only useful when working with [`@specset`](@ref) and [`proceed`](@ref). """ const GroupFEterms = StatsStep{:GroupFEterms, typeof(groupfeterms), false} required(::GroupFEterms) = (:feterms,) """ makefes(args...) Construct `FixedEffect`s from `data` (the full sample). See also [`MakeFEs`](@ref). """ function makefes(data, allfeterms::Vector{FETerm}) # Must use Dict instead of IdDict since the same feterm can be in multiple feterms allfes = Dict{FETerm,FixedEffect}() for t in allfeterms haskey(allfes, t) && continue if isempty(t[2]) allfes[t] = FixedEffect((getcolumn(data, n) for n in t[1])...) else allfes[t] = FixedEffect((getcolumn(data, n) for n in t[1])...; interaction=_multiply(data, t[2])) end end return (allfes=allfes,) end """ MakeFEs <: StatsStep Call [`InteractionWeightedDIDs.makefes`](@ref) to construct `FixedEffect`s from `data` (the full sample). """ const MakeFEs = StatsStep{:MakeFEs, typeof(makefes), false} required(::MakeFEs) = (:data,) combinedargs(::MakeFEs, allntargs) = (FETerm[t for nt in allntargs for t in nt.feterms],) """ checkfes!(args...) Drop any singleton observation from fixed effects over the relevant subsample. See also [`CheckFEs`](@ref). """ function checkfes!(feterms::Set{FETerm}, allfes::Dict{FETerm,FixedEffect}, esample::BitVector, drop_singletons::Bool) nsingle = 0 nfe = length(feterms) if nfe > 0 fes = Vector{FixedEffect}(undef, nfe) fenames = Vector{String}(undef, nfe) # Loop together to ensure the orders are the same for (i, t) in enumerate(feterms) fes[i] = allfes[t] fenames[i] = getfename(t) end # Determine the unique order based on names order = sortperm(fenames) fes = fes[order] fenames = fenames[order] if drop_singletons for fe in fes nsingle += drop_singletons!(esample, fe) end end sum(esample) == 0 && error("no nonmissing data") for i in 1:nfe fes[i] = fes[i][esample] end return (esample=esample, fes=fes, fenames=fenames, nsingle=nsingle) else return (esample=esample, fes=FixedEffect[], fenames=String[], nsingle=0) end end """ CheckFEs <: StatsStep Call [`InteractionWeightedDIDs.checkfes!`](@ref) to drop any singleton observation from fixed effects over the relevant subsample. """ const CheckFEs = StatsStep{:CheckFEs, typeof(checkfes!), true} required(::CheckFEs) = (:feterms, :allfes, :esample) default(::CheckFEs) = (drop_singletons=true,) copyargs(::CheckFEs) = (3,) """ makefesolver(args...) Construct `FixedEffects.AbstractFixedEffectSolver`. See also [`MakeFESolver`](@ref). """ function makefesolver(fes::Vector{FixedEffect}, weights::AbstractWeights, nfethreads::Int) if !isempty(fes) feM = AbstractFixedEffectSolver{Float64}(fes, weights, Val{:cpu}, nfethreads) return (feM=feM,) else return (feM=nothing,) end end """ MakeFESolver <: StatsStep Call [`InteractionWeightedDIDs.makefesolver`](@ref) to construct the fixed effect solver. """ const MakeFESolver = StatsStep{:MakeFESolver, typeof(makefesolver), true} required(::MakeFESolver) = (:fes, :weights) default(::MakeFESolver) = (nfethreads=Threads.nthreads(),) function _makeyxcols!(yxterms::Dict, yxcols::Dict, yxschema, data, t::AbstractTerm) ct = apply_schema(t, yxschema, StatisticalModel) yxterms[t] = ct if width(ct) > 0 tcol = convert(Array{Float64}, modelcols(ct, data)) all(isfinite, tcol) || error("data for term $ct contain NaN or Inf") yxcols[ct] = tcol end end function _feresiduals!(M, feM::AbstractFixedEffectSolver, tol::Real, maxiter::Integer) _, iters, convs = _solve_residuals!(M, feM; tol=tol, maxiter=maxiter, progress_bar=false) iter = maximum(iters) conv = all(convs) conv || @warn "no convergence of fixed effect solver in $(iter) iterations" return iter, conv end """ makeyxcols(args...) Construct columns for outcome variables and covariates and residualize them with fixed effects. See also [`MakeYXCols`](@ref). """ function makeyxcols(data, weights::AbstractWeights, esample::BitVector, feM::Union{AbstractFixedEffectSolver, Nothing}, has_fe_intercept::Bool, contrasts::Union{Dict, Nothing}, fetol::Real, femaxiter::Int, allyxterms::TermSet) # Standardize how an intercept or omitsintercept is represented parse_intercept!(allyxterms) yxdata = subcolumns(data, termvars(allyxterms), esample) yxschema = StatsModels.FullRank(schema(allyxterms, yxdata, contrasts)) has_fe_intercept && push!(yxschema.already, InterceptTerm{true}()) yxterms = Dict{AbstractTerm, AbstractTerm}() yxcols = Dict{AbstractTerm, VecOrMat{Float64}}() for t in allyxterms _makeyxcols!(yxterms, yxcols, yxschema, yxdata, t) end if !has_fe_intercept yxcols[InterceptTerm{true}()] = ones(sum(esample)) end iter, conv = nothing, nothing if feM !== nothing YX = values(yxcols) iter, conv = _feresiduals!(YX, feM, fetol, femaxiter) end if !(weights isa UnitWeights) for col in values(yxcols) col .*= sqrt.(weights) end end return (yxterms=yxterms, yxcols=yxcols, nfeiterations=iter, feconverged=conv) end """ MakeYXCols <: StatsStep Call [`InteractionWeightedDIDs.makeyxcols`](@ref) to obtain residualized outcome variables and covariates. """ const MakeYXCols = StatsStep{:MakeYXCols, typeof(makeyxcols), true} required(::MakeYXCols) = (:data, :weights, :esample, :feM, :has_fe_intercept) default(::MakeYXCols) = (contrasts=nothing, fetol=1e-8, femaxiter=10000) function combinedargs(::MakeYXCols, allntargs) yx = TermSet() for nt in allntargs push!(yx, nt.yterm) foreach(x->push!(yx, x), nt.xterms) end return (yx,) end """ maketreatcols(args...) Construct residualized binary columns that capture treatment effects and obtain cell-level weight sums and observation counts. See also [`MakeTreatCols`](@ref). """ function maketreatcols(data, treatname::Symbol, treatintterms::TermSet, feM::Union{AbstractFixedEffectSolver, Nothing}, weights::AbstractWeights, esample::BitVector, cohortinteracted::Bool, fetol::Real, femaxiter::Int, time::Symbol, exc::Dict{Int,Int}, notreat::IdDict{ValidTimeType,Int}) nobs = sum(esample) # Putting treatname before time avoids sorting twice if cohortinteracted cellnames = Symbol[treatname, time, sort!(termvars(treatintterms))...] cols = subcolumns(data, cellnames, esample) cells, rows = cellrows(cols, findcell(cols)) if cells[1] isa RotatingTimeArray rel = refarray(cells[2].time) .- refarray(cells[1].time) else rel = refarray(cells[2]) .- refarray(cells[1]) end kept = .!haskey.(Ref(exc), rel) .& .!haskey.(Ref(notreat), cells[1]) treatrows = rows[kept] # Construct cells needed for treatment indicators if cohortinteracted ntcellcol = length(cellnames) tcellcols = Vector{AbstractVector}(undef, ntcellcol) tcellnames = Vector{Symbol}(undef, ntcellcol) tcellcols[1] = view(cells[1], kept) tcellnames[1] = cellnames[1] tcellcols[2] = view(rel, kept) tcellnames[2] = :rel if ntcellcol > 2 @inbounds for i in 3:ntcellcol tcellcols[i] = view(cells[i], kept) tcellnames[i] = cellnames[i] end end treatcells = VecColumnTable(tcellcols, tcellnames) else ntcellcol = length(cellnames) - 1 tcellcols = Vector{AbstractVector}(undef, ntcellcol) tcellnames = Vector{Symbol}(undef, ntcellcol) tcellcols[1] = view(rel, kept) tcellnames[1] = :rel if ntcellcol > 1 @inbounds for i in 2:ntcellcol tcellcols[i] = view(cells[i+1], kept) tcellnames[i] = cellnames[i+1] end end tcols = VecColumnTable(tcellcols, tcellnames) treatcells, subtrows = cellrows(tcols, findcell(tcols)) trows = Vector{Vector{Int}}(undef, length(subtrows)) @inbounds for (i, rs) in enumerate(subtrows) trows[i] = vcat(view(treatrows, rs)...) end treatrows = trows end # Generate treatment indicators ntcells = length(treatrows) treatcols = Vector{Vector{Float64}}(undef, ntcells) treatweights = Vector{Float64}(undef, ntcells) treatcounts = Vector{Int}(undef, ntcells) @inbounds for i in 1:ntcells rs = treatrows[i] tcol = zeros(nobs) tcol[rs] .= 1.0 treatcols[i] = tcol treatcounts[i] = length(rs) if weights isa UnitWeights treatweights[i] = treatcounts[i] else treatweights[i] = sum(view(weights, rs)) end end if feM !== nothing M = values(treatcols) _feresiduals!(M, feM, fetol, femaxiter) end if !(weights isa UnitWeights) for tcol in values(treatcols) tcol .*= sqrt.(weights) end end return (cells=cells::VecColumnTable, rows=rows::Vector{Vector{Int}}, treatcells=treatcells::VecColumnTable, treatrows=treatrows::Vector{Vector{Int}}, treatcols=treatcols::Vector{Vector{Float64}}, treatweights=treatweights, treatcounts=treatcounts) end """ MakeTreatCols <: StatsStep Call [`InteractionWeightedDIDs.maketreatcols`](@ref) to obtain residualized binary columns that capture treatment effects and obtain cell-level weight sums and observation counts. """ const MakeTreatCols = StatsStep{:MakeTreatCols, typeof(maketreatcols), true} required(::MakeTreatCols) = (:data, :treatname, :treatintterms, :feM, :weights, :esample) default(::MakeTreatCols) = (cohortinteracted=true, fetol=1e-8, femaxiter=10000) # No need to consider typeof(tr) and typeof(pr) given the restrictions by valid_didargs transformed(::MakeTreatCols, @nospecialize(nt::NamedTuple)) = (nt.tr.time,) # Obtain the relative time periods excluded by all tr # and the treatment groups excluded by all pr in allntargs function combinedargs(::MakeTreatCols, allntargs) # exc cannot be IdDict for comparing different types of one exc = Dict{Int,Int}() notreat = IdDict{ValidTimeType,Int}() for nt in allntargs foreach(x->_count!(exc, x), nt.tr.exc) if nt.pr isa TrendParallel foreach(x->_count!(notreat, x), nt.pr.e) end end nnt = length(allntargs) for (k, v) in exc v == nnt || delete!(exc, k) end for (k, v) in notreat v == nnt || delete!(notreat, k) end return (exc, notreat) end """ solveleastsquares!(args...) Solve the least squares problem for regression coefficients and residuals. See also [`SolveLeastSquares`](@ref). """ function solveleastsquares!(tr::DynamicTreatment{SharpDesign}, pr::TrendOrUnspecifiedPR, yterm::AbstractTerm, xterms::TermSet, yxterms::Dict, yxcols::Dict, treatcells::VecColumnTable, treatcols::Vector, treatweights::Vector, treatcounts::Vector, cohortinteracted::Bool, has_fe_intercept::Bool) y = yxcols[yxterms[yterm]] if cohortinteracted if pr isa TrendParallel tinds = .!((treatcells[2] .∈ (tr.exc,)) .| (treatcells[1] .∈ (pr.e,))) else tinds = .!(treatcells[2] .∈ (tr.exc,)) end else tinds = .!(treatcells[1] .∈ (tr.exc,)) end treatcells = VecColumnTable(treatcells, tinds) tcols = view(treatcols, tinds) # Copy the relevant weights and counts tweights = treatweights[tinds] tcounts = treatcounts[tinds] has_intercept, has_omitsintercept = parse_intercept!(xterms) xwidth = 0 # Only terms with positive width should be collected into xs xs = Vector{AbstractTerm}() for x in xterms cx = yxterms[x] w = width(cx) xwidth += w w > 0 && push!(xs, cx) end sort!(xs, by=coefnames) # Add back an intercept to the last position if needed if !has_fe_intercept && !has_omitsintercept push!(xs, InterceptTerm{true}()) xwidth += 1 end X = hcat(tcols..., (yxcols[x] for x in xs)...) # Get linearly independent columns # The approach follows FixedEffectModels.jl crossx = X'X basiscols = basis!(Symmetric(copy(crossx)); has_intercept = has_intercept) if !all(basiscols) X = X[:, basiscols] crossx = crossx[basiscols, basiscols] end crossx = Symmetric(crossx) # Solve the least squares problem N = size(X, 2) Xy = zeros(N+1, N+1) Xy[1:N, 1:N] .= crossx mul!(view(Xy, 1:N, N+1), X', y) Xy = Symmetric(Xy) invsym!(Xy; diagonal = 1:N) invcrossx = Symmetric(-view(Xy, 1:N, 1:N)) coef = Xy[1:end-1,end] # Check collinearity of xterms with treatment vars ntcols = length(tcols) if N > ntcols # Do not drop any treatment indicator sum(basiscols[1:ntcols]) == ntcols || error("covariates are collinear with treatment indicators") end residuals = copy(y) mul!(residuals, X, coef, -1.0, 1.0) return (coef=coef::Vector{Float64}, X=X::Matrix{Float64}, crossx=crossx::Symmetric{Float64, Matrix{Float64}}, invcrossx=invcrossx::Symmetric{Float64, Matrix{Float64}}, residuals=residuals::Vector{Float64}, treatcells=treatcells::VecColumnTable, xterms=xs::Vector{AbstractTerm}, basiscols=basiscols::BitVector, treatweights=tweights::Vector{Float64}, treatcounts=tcounts::Vector{Int}) end """ SolveLeastSquares <: StatsStep Call [`InteractionWeightedDIDs.solveleastsquares!`](@ref) to solve the least squares problem for regression coefficients and residuals. """ const SolveLeastSquares = StatsStep{:SolveLeastSquares, typeof(solveleastsquares!), true} required(::SolveLeastSquares) = (:tr, :pr, :yterm, :xterms, :yxterms, :yxcols, :treatcells, :treatcols, :treatweights, :treatcounts, :cohortinteracted, :has_fe_intercept) copyargs(::SolveLeastSquares) = (4,) function _vce(data, esample::BitVector, vce::Union{Vcov.SimpleCovariance,Vcov.RobustCovariance}, fes::Vector{FixedEffect}) dof_absorb = 0 for fe in fes dof_absorb += nunique(fe) end return vce, dof_absorb end function _vce(data, esample::BitVector, vce::Vcov.ClusterCovariance, fes::Vector{FixedEffect}) cludata = subcolumns(data, Vcov.names(vce), esample) concrete_vce = Vcov.materialize(cludata, vce) dof_absorb = 0 for fe in fes dof_absorb += any(c->isnested(fe, c.groups), concrete_vce.clusters) ? 1 : nunique(fe) end return concrete_vce, dof_absorb end """ estvcov(args...) Estimate variance-covariance matrix and F-statistic. See also [`EstVcov`](@ref). """ function estvcov(data, esample::BitVector, vce::CovarianceEstimator, coef::Vector, X::Matrix, crossx::Symmetric, invcrossx::Symmetric, residuals::Vector, xterms::Vector{AbstractTerm}, fes::Vector{FixedEffect}, has_fe_intercept::Bool) concrete_vce, dof_absorb = _vce(data, esample, vce, fes) dof_resid = max(1, sum(esample) - size(X,2) - dof_absorb) vce_data = Vcov.VcovData(X, crossx, invcrossx, residuals, dof_resid) vcov_mat = vcov(vce_data, concrete_vce) # Fstat assumes the last coef is intercept if having any intercept has_intercept = !isempty(xterms) && isintercept(xterms[end]) F = Fstat(coef, vcov_mat, has_intercept) has_intercept = has_intercept || has_fe_intercept df_F = max(1, Vcov.dof_residual(vce_data, concrete_vce) - has_intercept) p = fdistccdf(max(length(coef) - has_intercept, 1), df_F, F) return (vcov_mat=vcov_mat::Symmetric{Float64,Array{Float64,2}}, vce=concrete_vce, dof_resid=dof_resid::Int, F=F::Float64, p=p::Float64) end """ EstVcov <: StatsStep Call [`InteractionWeightedDIDs.estvcov`](@ref) to estimate variance-covariance matrix and F-statistic. """ const EstVcov = StatsStep{:EstVcov, typeof(estvcov), true} required(::EstVcov) = (:data, :esample, :vce, :coef, :X, :crossx, :invcrossx, :residuals, :xterms, :fes, :has_fe_intercept) """ solveleastsquaresweights(args...) Solve the cell-level weights assigned by least squares. If `lswtnames` is not specified, cells are defined by the partition based on treatment time and calendar time. See also [`SolveLeastSquaresWeights`](@ref). """ function solveleastsquaresweights(::DynamicTreatment{SharpDesign}, solvelsweights::Bool, lswtnames, cells::VecColumnTable, rows::Vector{Vector{Int}}, X::Matrix, crossx::Symmetric, coef::Vector, treatcells::VecColumnTable, yterm::AbstractTerm, xterms::Vector{AbstractTerm}, yxterms::Dict, yxcols::Dict, feM::Union{AbstractFixedEffectSolver, Nothing}, fetol::Real, femaxiter::Int, weights::AbstractWeights) solvelsweights || return (lsweights=nothing, cellymeans=nothing, cellweights=nothing, cellcounts=nothing) cellnames = propertynames(cells) length(lswtnames) == 0 && (lswtnames = cellnames) for n in lswtnames n in cellnames || throw(ArgumentError("$n is invalid for lswtnames")) end # Construct Y residualized by covariates and FEs but not treatment indicators yresid = yxcols[yxterms[yterm]] nx = length(xterms) nt = size(treatcells, 1) if nx > 0 yresid = copy(yresid) for i in 1:nx yresid .-= coef[nt+i] .* yxcols[xterms[i]] end end weights isa UnitWeights || (yresid .*= sqrt.(weights)) if lswtnames == cellnames lswtcells = cells lswtrows = 1:size(cells,1) else cols = subcolumns(cells, lswtnames) lswtcells, lswtrows = cellrows(cols, findcell(cols)) end # Dummy variable on the left-hand-side d = Vector{Float64}(undef, length(yresid)) nlswtrow = length(lswtrows) lswtmat = Matrix{Float64}(undef, nlswtrow, nt) cellymeans = zeros(nlswtrow) cellweights = zeros(nlswtrow) cellcounts = zeros(Int, nlswtrow) Nx = size(X, 2) Xy = Symmetric(Matrix{Float64}(undef, Nx+1, Nx+1)) @inbounds for i in 1:nlswtrow # Reinitialize d for reuse fill!(d, 0.0) for r in lswtrows[i] rs = rows[r] d[rs] .= 1.0 wts = view(weights, rs) cellymeans[i] += sum(view(yresid, rs).*wts) cellweights[i] += sum(wts) cellcounts[i] += length(rs) end feM === nothing || _feresiduals!(d, feM, fetol, femaxiter) weights isa UnitWeights || (d .*= sqrt.(weights)) Xy.data[1:Nx, 1:Nx] .= crossx mul!(view(Xy.data, 1:Nx, Nx+1), X', d) Xy.data[end,:] .= 0.0 invsym!(Xy; diagonal = 1:Nx) lswtmat[i,:] .= view(Xy, 1:nt, Nx+1) end cellymeans ./= cellweights lswt = TableIndexedMatrix(lswtmat, lswtcells, treatcells) return (lsweights=lswt, cellymeans=cellymeans, cellweights=cellweights, cellcounts=cellcounts) end """ SolveLeastSquaresWeights <: StatsStep Call [`InteractionWeightedDIDs.solveleastsquaresweights`](@ref) to solve the cell-level weights assigned by least squares. If `lswtnames` is not specified, cells are defined by the partition based on treatment time and calendar time. """ const SolveLeastSquaresWeights = StatsStep{:SolveLeastSquaresWeights, typeof(solveleastsquaresweights), true} required(::SolveLeastSquaresWeights) = (:tr, :solvelsweights, :lswtnames, :cells, :rows, :X, :crossx, :coef, :treatcells, :yterm, :xterms, :yxterms, :yxcols, :feM, :fetol, :femaxiter, :weights)
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
2095
# A vector of fixed effects paired with a vector of interactions (empty if not interacted) const FETerm = Pair{Vector{Symbol},Vector{Symbol}} # Parse fixed effects from a generic term function _parsefeterm(@nospecialize(t::AbstractTerm)) if has_fe(t) s = fesymbol(t) return [s]=>Symbol[] end end # Parse fixed effects from an InteractionTerm function _parsefeterm(@nospecialize(t::InteractionTerm)) fes = (x for x in t.terms if has_fe(x)) interactions = (x for x in t.terms if !has_fe(x)) if !isempty(fes) fes = sort!([fesymbol(x) for x in fes]) feints = sort!([Symbol(x) for x in interactions]) return fes=>feints end end getfename(feterm::FETerm) = join(vcat("fe_".*string.(feterm[1]), feterm[2]), "&") # Count the number of singletons dropped function drop_singletons!(esample, fe::FixedEffect) cache = zeros(Int, fe.n) n = 0 @inbounds for i in eachindex(esample) if esample[i] cache[fe.refs[i]] += 1 end end @inbounds for i in eachindex(esample) if esample[i] && cache[fe.refs[i]] <= 1 esample[i] = false n += 1 end end return n end # A work around for the type restrictions in FixedEffects.jl function _solve_residuals!(xs::Base.ValueIterator, feM::AbstractFixedEffectSolver; progress_bar=false, kwargs...) iterations = Int[] convergeds = Bool[] for x in xs _, iteration, converged = solve_residuals!(x, feM; kwargs...) push!(iterations, iteration) push!(convergeds, converged) end return xs, iterations, convergeds end # Fallback method _solve_residuals!(xs, feM::AbstractFixedEffectSolver; progress_bar = true, kwargs...) = solve_residuals!(xs, feM; kwargs...) function Fstat(coef::Vector{Float64}, vcov_mat::AbstractMatrix{Float64}, has_intercept::Bool) length(coef) == has_intercept && return NaN if has_intercept coef = coef[1:end-1] vcov_mat = vcov_mat[1:end-1, 1:end-1] end return (coef' * (vcov_mat \ coef)) / length(coef) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
18598
@testset "RegressionBasedDID" begin hrs = exampledata("hrs") r = @did(Reg, data=hrs, dynamic(:wave, -1), notyettreated(11), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=(fe(:wave)+fe(:hhidpn)), solvelsweights=true) # Compare estimates with Stata @test coef(r, "wave_hosp: 8 & rel: 0") ≈ 2825.5659 atol=1e-4 @test coef(r, "wave_hosp: 8 & rel: 1") ≈ 825.14585 atol=1e-5 @test coef(r, "wave_hosp: 8 & rel: 2") ≈ 800.10647 atol=1e-5 @test coef(r, "wave_hosp: 9 & rel: -2") ≈ 298.97735 atol=1e-5 @test coef(r, "wave_hosp: 9 & rel: 0") ≈ 3030.8408 atol=1e-4 @test coef(r, "wave_hosp: 9 & rel: 1") ≈ 106.83785 atol=1e-5 @test coef(r, "wave_hosp: 10 & rel: -3") ≈ 591.04639 atol=1e-5 @test coef(r, "wave_hosp: 10 & rel: -2") ≈ 410.58102 atol=1e-5 @test coef(r, "wave_hosp: 10 & rel: 0") ≈ 3091.5084 atol=1e-4 @test coef(r) === r.coef @test vcov(r) === r.vcov @test vce(r) === r.vce @test treatment(r) == dynamic(:wave, -1) @test nobs(r) == 2624 @test outcomename(r) == "oop_spend" @test coefnames(r) == ["wave_hosp: $w & rel: $r" for (w, r) in zip(repeat(8:10, inner=3), [0, 1, 2, -2, 0, 1, -3, -2, 0])] @test treatcells(r) == r.treatcells @test weights(r) === nothing @test ntreatcoef(r) == 9 @test treatcoef(r) == coef(r) @test treatvcov(r) == vcov(r) @test treatnames(r) == coefnames(r) @test dof_residual(r) == 2610 @test responsename(r) == "oop_spend" @test coefinds(r) == r.coefinds @test ncovariate(r) == 0 @test has_lsweights(r) @test r.cellweights == r.cellcounts @test r.cellcounts == repeat([252, 176, 163, 65], inner=4) @test all(i->r.coef[i] ≈ sum(r.lsweights[:,i].*r.cellymeans), 1:ntreatcoef(r)) @test has_fe(r) @test sprint(show, r) == "Regression-based DID result" pv = VERSION < v"1.6.0" ? " <1e-7" : "<1e-07" @test sprint(show, MIME("text/plain"), r) == """ ────────────────────────────────────────────────────────────────────── Summary of results: Regression-based DID ────────────────────────────────────────────────────────────────────── Number of obs: 2624 Degrees of freedom: 14 F-statistic: 6.42 p-value: $pv ────────────────────────────────────────────────────────────────────── Cohort-interacted sharp dynamic specification ────────────────────────────────────────────────────────────────────── Number of cohorts: 3 Interactions within cohorts: 0 Relative time periods: 5 Excluded periods: -1 ────────────────────────────────────────────────────────────────────── Fixed effects: fe_hhidpn fe_wave ────────────────────────────────────────────────────────────────────── Converged: true Singletons dropped: 0 ──────────────────────────────────────────────────────────────────────""" df = DataFrame(hrs) df.wave = settime(Date.(hrs.wave), Year(1)) df.wave_hosp = settime(Date.(hrs.wave_hosp), Year(1), start=Date(7)) r1 = @did(Reg, data=df, dynamic(:wave, -1), notyettreated(Date(11)), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=(fe(:wave)+fe(:hhidpn)), solvelsweights=true) @test coef(r1) ≈ coef(r) @test r1.coefnames[1] == "wave_hosp: 0008-01-01 & rel: 0" rot = ifelse.(isodd.(hrs.hhidpn), 1, 2) df.wave = settime(Date.(hrs.wave), Year(1), rotation=rot) df.wave_hosp = settime(Date.(hrs.wave_hosp), Year(1), start=Date(7), rotation=rot) e = rotatingtime((1,2), Date(11)) r2 = @did(Reg, data=df, dynamic(:wave, -1), notyettreated(e), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=(fe(:wave)+fe(:hhidpn)), solvelsweights=true) @test length(coef(r2)) == 18 @test coef(r2)[1] ≈ 3790.7218412450593 @test r2.coefnames[1] == "wave_hosp: 1_0008-01-01 & rel: 0" r = @did(Reg, data=hrs, dynamic(:wave, -1), notyettreated([11]), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), cohortinteracted=false, lswtnames=(:wave_hosp, :wave)) @test all(i->r.coef[i] ≈ sum(r.lsweights[:,i].*r.cellymeans), 1:ntreatcoef(r)) @test sprint(show, MIME("text/plain"), r) == """ ────────────────────────────────────────────────────────────────────── Summary of results: Regression-based DID ────────────────────────────────────────────────────────────────────── Number of obs: 2624 Degrees of freedom: 6 F-statistic: 12.50 p-value: <1e-10 ────────────────────────────────────────────────────────────────────── Sharp dynamic specification ────────────────────────────────────────────────────────────────────── Relative time periods: 5 Excluded periods: -1 ────────────────────────────────────────────────────────────────────── Fixed effects: none ──────────────────────────────────────────────────────────────────────""" r0 = @did(Reg, data=hrs, dynamic(:wave, -1), unspecifiedpr(), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=(fe(:wave),), cohortinteracted=false, solvelsweights=true) # Compare estimates with Stata # gen rel = wave - wave_hosp # gen irel?? = rel==?? # reghdfe oop_spend irel*, a(wave) cluster(hhidpn) @test coef(r0) ≈ [-1029.0482, 245.20926, 188.59266, 3063.2707, 1060.5317, 1152.3315, 1986.7811] atol=1e-4 @test diag(vcov(r0)) ≈ [764612.86, 626165.68, 236556.13, 163459.83, 130471.28, 294368.49, 677821.36] atol=1e0 pv = VERSION < v"1.6.0" ? " <1e-8" : "<1e-08" @test sprint(show, MIME("text/plain"), r0) == """ ────────────────────────────────────────────────────────────────────── Summary of results: Regression-based DID ────────────────────────────────────────────────────────────────────── Number of obs: 3280 Degrees of freedom: 12 F-statistic: 9.12 p-value: $pv ────────────────────────────────────────────────────────────────────── Sharp dynamic specification ────────────────────────────────────────────────────────────────────── Relative time periods: 7 Excluded periods: -1 ────────────────────────────────────────────────────────────────────── Fixed effects: fe_wave ────────────────────────────────────────────────────────────────────── Converged: true Singletons dropped: 0 ──────────────────────────────────────────────────────────────────────""" sr = view(r, 1:3) @test coef(sr)[1] == r.coef[1] @test vcov(sr)[1] == r.vcov[1] @test parent(sr) === r tr = rescale(r, fill(2, 5), 1:5) @test coef(tr)[1] ≈ 2 * coef(sr)[1] @test vcov(tr)[1] ≈ 4 * vcov(sr)[1] end @testset "AggregatedRegDIDResult" begin hrs = exampledata("hrs") r = @did(Reg, data=hrs, dynamic(:wave, -1), notyettreated(11), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=(fe(:wave)+fe(:hhidpn))) a = agg(r) @test coef(a) == coef(r) @test vcov(a) == vcov(r) @test vce(a) == vce(r) @test treatment(a) == dynamic(:wave, -1) @test nobs(a) == nobs(r) @test outcomename(a) == outcomename(r) @test coefnames(a) === a.coefnames @test treatcells(a) === a.treatcells @test weights(a) == weights(r) @test ntreatcoef(a) == 9 @test treatcoef(a) == coef(a) @test treatvcov(a) == vcov(a) @test treatnames(a) == a.coefnames @test parent(a) === r @test dof_residual(a) == dof_residual(r) @test responsename(a) == "oop_spend" @test coefinds(a) === a.coefinds @test ncovariate(a) == 0 @test !has_lsweights(a) pv = VERSION < v"1.6.0" ? "<1e-4 " : "<1e-04" @test sprint(show, a) === """ ─────────────────────────────────────────────────────────────────────────────────── Estimate Std. Error t Pr(>|t|) Lower 95% Upper 95% ─────────────────────────────────────────────────────────────────────────────────── wave_hosp: 8 & rel: 0 2825.57 1038.18 2.72 0.0065 789.825 4861.31 wave_hosp: 8 & rel: 1 825.146 912.101 0.90 0.3657 -963.368 2613.66 wave_hosp: 8 & rel: 2 800.106 1010.81 0.79 0.4287 -1181.97 2782.18 wave_hosp: 9 & rel: -2 298.977 967.362 0.31 0.7573 -1597.9 2195.85 wave_hosp: 9 & rel: 0 3030.84 704.631 4.30 $pv 1649.15 4412.53 wave_hosp: 9 & rel: 1 106.838 652.767 0.16 0.8700 -1173.16 1386.83 wave_hosp: 10 & rel: -3 591.046 1273.08 0.46 0.6425 -1905.3 3087.39 wave_hosp: 10 & rel: -2 410.581 1030.4 0.40 0.6903 -1609.9 2431.06 wave_hosp: 10 & rel: 0 3091.51 998.667 3.10 0.0020 1133.25 5049.77 ───────────────────────────────────────────────────────────────────────────────────""" r = @did(Reg, data=hrs, dynamic(:wave, -1), notyettreated(11), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=(fe(:wave)+fe(:hhidpn)), solvelsweights=true) # Compare estimates with Stata results from Sun and Abraham (2020) a = agg(r, :rel) @test coef(a, "rel: -3") ≈ 591.04639 atol=1e-5 @test coef(a, "rel: -2") ≈ 352.63929 atol=1e-5 @test coef(a, "rel: 0") ≈ 2960.0448 atol=1e-4 @test coef(a, "rel: 1") ≈ 529.76686 atol=1e-5 @test coef(a, "rel: 2") ≈ 800.10647 atol=1e-5 @test has_lsweights(a) @test a.treatweights == a.treatcounts @test a.treatcounts == [163, 339, 591, 428, 252] @test all(i->a.coef[i] ≈ sum(a.lsweights[:,i].*r.cellymeans), 1:ntreatcoef(a)) a1 = agg(r, (:rel,), subset=:rel=>isodd) @test length(coef(a1)) == 2 @test coef(a1, "rel: -3") == coef(a, "rel: -3") @test coef(a1, "rel: 1") == coef(a, "rel: 1") @test sprint(show, a1) === """ ─────────────────────────────────────────────────────────────────── Estimate Std. Error t Pr(>|t|) Lower 95% Upper 95% ─────────────────────────────────────────────────────────────────── rel: -3 591.046 1273.08 0.46 0.6425 -1905.3 3087.39 rel: 1 529.767 586.831 0.90 0.3667 -620.935 1680.47 ───────────────────────────────────────────────────────────────────""" a1 = agg(r, [:rel], bys=:rel=>isodd) @test length(coef(a1)) == 2 @test coef(a1, "rel: false") ≈ sum(coef(a, "rel: $r") for r in ["-2", "0", "2"]) @test coef(a1, "rel: true") ≈ sum(coef(a, "rel: $r") for r in ["-3", "1"]) a2 = agg(r, :rel, bys=:rel=>isodd, subset=:rel=>isodd) @test coef(a2) == coef(a1, 2:2) @test_throws ArgumentError agg(r, subset=:rel=>x->x>10) end const TestDID = DiffinDiffsEstimator{:TestDID, Tuple{CheckData, GroupTreatintterms, GroupXterms, GroupContrasts, CheckVcov, CheckVars, GroupSample, ParseFEterms, GroupFEterms, MakeFEs, CheckFEs, MakeWeights}} prerequisites(::TestDID, ::CheckData) = () prerequisites(::TestDID, ::GroupTreatintterms) = () prerequisites(::TestDID, ::GroupXterms) = () prerequisites(::TestDID, ::GroupContrasts) = () prerequisites(::TestDID, ::CheckVcov) = (CheckData(),) prerequisites(::TestDID, ::CheckVars) = (CheckData(), GroupTreatintterms(), GroupXterms()) prerequisites(::TestDID, ::GroupSample) = (CheckVcov(), CheckVars()) prerequisites(::TestDID, ::ParseFEterms) = (GroupXterms(),) prerequisites(::TestDID, ::GroupFEterms) = (ParseFEterms(),) prerequisites(::TestDID, ::MakeFEs) = (GroupFEterms(),) prerequisites(::TestDID, ::CheckFEs) = (MakeFEs(),) prerequisites(::TestDID, ::MakeWeights) = (CheckFEs(),) @testset "@specset" begin hrs = exampledata("hrs") ps = AbstractStatsProcedure[Reg(), TestDID()] p1 = pool(ps) # Order of the steps needs to be checked manually @test length(p1) == length(Reg()) # The first two specs are identical hence no repetition of steps should occur # The third spec should share all the steps until SolveLeastSquares # The fourth and fifth specs should not add tasks for MakeFEs and MakeYXCols # The sixth spec should not add any task for MakeFEs r = @specset [verbose] data=hrs yterm=term(:oop_spend) treatname=:wave_hosp begin @did(Reg, dynamic(:wave, -1), notyettreated(11), xterms=(fe(:wave)+fe(:hhidpn))) @did(Reg, dynamic(:wave, -1), notyettreated(11), xterms=[fe(:hhidpn), fe(:wave)]) @did(Reg, dynamic(:wave, -2:-1), notyettreated(11), xterms=[fe(:hhidpn), fe(:wave)]) @did(Reg, dynamic(:wave, -1), notyettreated(11), xterms=[term(:male), fe(:hhidpn), fe(:wave)]) @did(Reg, dynamic(:wave, -1), notyettreated(11), treatintterms=TermSet(:male), xterms=[fe(:hhidpn), fe(:wave)]) @did(Reg, dynamic(:wave, -1), nevertreated(11), xterms=(fe(:wave)+fe(:hhidpn))) end @test r[2][4] == didspec(Reg, dynamic(:wave, -1), notyettreated(11), data=hrs, yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=TermSet(term(:male), fe(:wave), fe(:hhidpn)))() r = @specset data=hrs yterm=term(:oop_spend) treatname=:wave_hosp begin @did(Reg, dynamic(:wave, -2:-1), nevertreated(11), xterms=(fe(:wave)+fe(:hhidpn))) @did(Reg, dynamic(:wave, -1), nevertreated(11), xterms=[fe(:hhidpn), fe(:wave)]) end @test r[2][1] == @did(Reg, data=hrs, yterm=term(:oop_spend), treatname=:wave_hosp, dynamic(:wave, -2:-1), nevertreated(11), xterms=(fe(:wave)+fe(:hhidpn))) end @testset "contrast" begin hrs = exampledata("hrs") r1 = @did(Reg, data=hrs, dynamic(:wave, -1), notyettreated(11), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=(fe(:wave)+fe(:hhidpn)), solvelsweights=true) r2 = agg(r1, :rel) c1 = contrast(r1) @test size(c1) == (16, 10) @test parent(c1) == [r1] c2 = contrast(r1, r2) @test size(c2) == (16, 15) @test c2[1] == r1.cellymeans[1] @test c2[1,2] == r1.lsweights[1] @test IndexStyle(typeof(c2)) == IndexLinear() @test c2.r == r1.lsweights.r == r2.lsweights.r @test c2.c.name[1] == "cellymeans" @test c2.c.name[2] == r1.coefnames[c2.c.icoef[2]] @test c2.c.iresult == [0, (1 for i in 1:9)..., (2 for i in 1:5)...] @test c2.c.icoef == [0, 1:9..., 1:5...] @test parent(c2)[1] === r1 @test parent(c2)[2] === r2 @test c1.r !== r1.lsweights.r sort!(c1, rev=true) @test c1.r == sort(r1.lsweights.r, rev=true) @test view(c1, :) == c1 v = view(c1, :wave=>x->x==10) @test v.m == c1.m[c1.r.wave.==10,:] v = view(c1, 1:10) @test v.m == c1.m[1:10,:] @test v.r == view(c1.r, 1:10) v = view(c1, [:wave=>x->x==10, :wave_hosp=>x->x==10]) @test v.m == c1.m[(c1.r.wave.==10).&(c1.r.wave_hosp.==10),:] @test v.r == view(c1.r, (c1.r.wave.==10).&(c1.r.wave_hosp.==10)) c3 = contrast(r1, r2, subset=:wave=>7, coefs=1=>(:wave_hosp,2)=>(x,y)->x+y==8) @test size(c3) == (4, 8) @test parent(c3)[1] === r1 @test c3.c.name[2] == "wave_hosp: 8 & rel: 0" @test c3.c.name[3] == "wave_hosp: 10 & rel: -2" @test c3.c.iresult == [0, (1 for i in 1:2)..., (2 for i in 1:5)...] @test c3.c.icoef == [0, 1, 8, 1:5...] @test all(c3.r.wave.==7) ri = r1.lsweights.r.wave.==7 @test c3[:,1] == r1.cellymeans[ri] @test c3[:,2:end] == c2[ri,[2,9,11:15...]] c4 = contrast(r1, r2, subset=1:3, coefs=(1=>1:2, 2=>:)) @test size(c4) == (3, 8) @test c4.c.iresult == [0, (1 for i in 1:2)..., (2 for i in 1:5)...] @test c4.c.icoef == [0:2..., 1:5...] @test c4.r == view(r1.lsweights.r, 1:3) @test c4[:,2:end] == c2[1:3,[2,3,11:15...]] end @testset "post!" begin hrs = exampledata("hrs") r1 = @did(Reg, data=hrs, dynamic(:wave, -1), notyettreated(11), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=(fe(:wave)+fe(:hhidpn)), solvelsweights=true) c1 = contrast(r1) gl = Dict{String,Any}() gr = Dict{String,Any}() gd = Dict{String,Any}() post!(gl, gr, gd, StataPostHDF(), c1, model="m") @test gl["model"] == "m" @test gl["depvar"] == "l_2" @test gl["b"] == r1.lsweights[:,1] @test gr["depvar"] == "r_3" @test gr["b"] == r1.lsweights[:,2] @test gd["depvar"] == "d_2_3" @test gd["b"] == (r1.lsweights[:,1].-r1.lsweights[:,2]).*r1.cellymeans cnames = string.(1:16) @test all(g->g["coefnames"]==cnames, (gl, gr, gd)) @test all(g->!haskey(g, "at"), (gl, gr, gd)) gl = Dict{String,Any}() gr = Dict{String,Any}() gd = Dict{String,Any}() post!(gl, gr, gd, StataPostHDF(), c1, lefttag="x", righttag="y", colnames=16:-1:1, at=1:16) @test gl["depvar"] == "l_x" @test gl["b"] == r1.lsweights[:,1] @test gr["depvar"] == "r_y" @test gr["b"] == r1.lsweights[:,2] cnames = string.(16:-1:1) @test all(g->g["coefnames"]==cnames, (gl, gr, gd)) @test all(g->g["at"]==1:16, (gl, gr, gd)) gl = Dict{String,Any}() gr = Dict{String,Any}() gd = Dict{String,Any}() post!(gl, gr, gd, StataPostHDF(), c1, eqnames=1:16) cnames = [string(i,":",i) for i in 1:16] @test all(g->g["coefnames"]==cnames, (gl, gr, gd)) gl = Dict{String,Any}() gr = Dict{String,Any}() gd = Dict{String,Any}() post!(gl, gr, gd, StataPostHDF(), c1, eqnames=1:16, colnames=16:-1:1) cnames = [string(i,":",17-i) for i in 1:16] @test all(g->g["coefnames"]==cnames, (gl, gr, gd)) gl = Dict{String,Any}() gr = Dict{String,Any}() gd = Dict{String,Any}() @test_throws ArgumentError post!(gl, gr, gd, StataPostHDF(), c1, eqnames=1:2) @test_throws ArgumentError post!(gl, gr, gd, StataPostHDF(), c1, colnames=1:2) @test_throws ArgumentError post!(gl, gr, gd, StataPostHDF(), c1, at=1:2) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
27719
@testset "CheckVcov" begin hrs = exampledata("hrs") nt = (data=hrs, esample=trues(size(hrs,1)), aux=trues(size(hrs,1)), vce=Vcov.robust()) @test checkvcov!(nt...) == NamedTuple() nt = merge(nt, (vce=Vcov.cluster(:hhidpn),)) @test checkvcov!(nt...) == (esample=trues(size(hrs,1)),) df = DataFrame(hrs) allowmissing!(df, :hhidpn) nt = merge(nt, (data=df,)) @test checkvcov!(nt...) == (esample=trues(size(hrs,1)),) @test CheckVcov()((data=hrs, esample=trues(size(hrs,1)), aux=trues(size(hrs,1)))) == (data=hrs, esample=trues(size(hrs,1)), aux=trues(size(hrs,1))) end @testset "ParseFEterms" begin hrs = exampledata(:hrs) ret = parsefeterms!(TermSet()) @test (ret...,) == (TermSet(), Set{FETerm}(), false) ts = TermSet((term(1), term(:male))) ret = parsefeterms!(ts) @test (ret...,) == (ts, Set{FETerm}(), false) ts = TermSet(term(1)+term(:male)+fe(:hhidpn)) ret = parsefeterms!(ts) @test (ret...,) == (TermSet(InterceptTerm{false}(), term(:male)), Set(([:hhidpn]=>Symbol[],)), true) ts = TermSet(fe(:wave)+fe(:hhidpn)) ret = parsefeterms!(ts) @test (ret...,) == (TermSet(InterceptTerm{false}()), Set(([:hhidpn]=>Symbol[], [:wave]=>Symbol[])), true) # Verify that no change is made on intercept ts = TermSet((term(:male), fe(:hhidpn)&term(:wave))) ret = parsefeterms!(ts) @test (ret...,) == (TermSet(term(:male)), Set(([:hhidpn]=>[:wave],)), false) ts = TermSet((term(:male), fe(:hhidpn)&term(:wave))) nt = (xterms=ts,) @test ParseFEterms()(nt) == (xterms=TermSet(term(:male)), feterms=Set(([:hhidpn]=>[:wave],)), has_fe_intercept=false) end @testset "GroupFEterms" begin nt = (feterms=Set(([:hhidpn]=>[:wave],)),) @test groupfeterms(nt...) === nt @test _byid(SharedStatsStep(GroupFEterms(), 1)) == false @test GroupFEterms()(nt) === nt end @testset "MakeFEs" begin hrs = exampledata("hrs") @test makefes(hrs, FETerm[]) == (allfes=Dict{FETerm,FixedEffect}(),) feterms = [[:hhidpn]=>Symbol[], [:hhidpn,:wave]=>[:male]] ret = makefes(hrs, feterms) @test ret == (allfes=Dict{FETerm,FixedEffect}(feterms[1]=>FixedEffect(hrs.hhidpn), feterms[2]=>FixedEffect(hrs.hhidpn, hrs.wave, interaction=_multiply(hrs, [:male]))),) allntargs = NamedTuple[(feterms=Set{FETerm}(),), (feterms=Set(feterms),), (feterms=Set(([:hhidpn]=>Symbol[],)),)] @test Set(combinedargs(MakeFEs(), allntargs)...) == Set(push!(feterms, [:hhidpn]=>Symbol[])) nt = (data=hrs, feterms=feterms) @test MakeFEs()(nt) == merge(nt, ret) end @testset "CheckFEs" begin hrs = exampledata("hrs") N = size(hrs, 1) nt = (feterms=Set{FETerm}(), allfes=Dict{FETerm,FixedEffect}(), esample=trues(N), drop_singletons=true) @test checkfes!(nt...) == (esample=nt.esample, fes=FixedEffect[], fenames=String[], nsingle=0) feterm = [:hhidpn]=>Symbol[] allfes = makefes(hrs, [[:hhidpn]=>Symbol[], [:wave]=>[:male]]).allfes nt = merge(nt, (feterms=Set((feterm,)), allfes=allfes)) @test checkfes!(nt...) == (esample=trues(N), fes=[FixedEffect(hrs.hhidpn)], fenames=["fe_hhidpn"], nsingle=0) # fes are sorted by name feterms = Set(([:wave]=>Symbol[], [:hhidpn]=>Symbol[])) allfes = makefes(hrs, [[:hhidpn]=>Symbol[], [:wave]=>Symbol[]]).allfes nt = merge(nt, (feterms=feterms, allfes=allfes)) @test checkfes!(nt...) == (esample=trues(N), fes=[FixedEffect(hrs.hhidpn), FixedEffect(hrs.wave)], fenames=["fe_hhidpn", "fe_wave"], nsingle=0) df = DataFrame(hrs) df = df[(df.wave.==7).|((df.wave.==8).&(df.wave_hosp.==8)), :] N = size(df, 1) feterm = [:hhidpn]=>Symbol[] allfes = makefes(df, [[:hhidpn]=>Symbol[]]).allfes nt = merge(nt, (feterms=Set((feterm,)), allfes=allfes, esample=trues(N))) kept = df.wave_hosp.==8 @test checkfes!(nt...) == (esample=kept, fes=[FixedEffect(df.hhidpn)[kept]], fenames=["fe_hhidpn"], nsingle=N-sum(kept)) df = df[df.wave.==7, :] N = size(df, 1) allfes = makefes(df, [[:hhidpn]=>Symbol[]]).allfes nt = merge(nt, (allfes=allfes, esample=trues(N))) @test_throws ErrorException checkfes!(nt...) nt = merge(nt, (esample=trues(N),)) @test_throws ErrorException CheckFEs()(nt) nt = merge(nt, (esample=trues(N), drop_singletons=false)) @test CheckFEs()(nt) == merge(nt, (fes=[FixedEffect(df.hhidpn)], fenames=["fe_hhidpn"], nsingle=0)) end @testset "MakeFESolver" begin hrs = exampledata("hrs") N = size(hrs, 1) fes = FixedEffect[FixedEffect(hrs.hhidpn)] fenames = [:fe_hhidpn] nt = (fes=fes, weights=uweights(N), default(MakeFESolver())...) ret = makefesolver(nt...) @test ret.feM isa FixedEffects.FixedEffectSolverCPU{Float64} nt = merge(nt, (fes=FixedEffect[],)) @test makefesolver(nt...) == (feM=nothing,) @test MakeFESolver()(nt) == merge(nt, (feM=nothing,)) end @testset "MakeYXCols" begin hrs = exampledata("hrs") N = size(hrs, 1) t1 = InterceptTerm{true}() nt = (data=hrs, weights=uweights(N), esample=trues(N), feM=nothing, has_fe_intercept=false, default(MakeYXCols())...) ret = makeyxcols(nt..., TermSet(term(:oop_spend), term(1))) @test ret.yxterms[term(:oop_spend)] isa ContinuousTerm @test ret.yxcols == Dict(ret.yxterms[term(:oop_spend)]=>hrs.oop_spend, t1=>ones(N)) @test ret.nfeiterations === nothing @test ret.feconverged === nothing # Verify that an intercept will be added if not having one ret1 = makeyxcols(nt..., TermSet(term(:oop_spend))) @test ret1 == ret ret1 = makeyxcols(nt..., TermSet(term(:oop_spend), term(0))) @test collect(keys(ret1.yxterms)) == [term(:oop_spend)] @test ret1.yxcols == ret.yxcols wt = Weights(hrs.rwthh) nt = merge(nt, (weights=wt,)) ret = makeyxcols(nt..., TermSet(term(:oop_spend), term(:riearnsemp), term(:male))) @test ret.yxcols == Dict(ret.yxterms[term(:oop_spend)]=>hrs.oop_spend.*sqrt.(wt), ret.yxterms[term(:riearnsemp)]=>hrs.riearnsemp.*sqrt.(wt), ret.yxterms[term(:male)]=>reshape(hrs.male.*sqrt.(wt), N), t1=>reshape(sqrt.(wt), N)) df = DataFrame(hrs) df.riearnsemp[1] = NaN nt = merge(nt, (data=df,)) @test_throws ErrorException makeyxcols(nt..., TermSet(term(:riearnsemp), term(1))) df.spouse = convert(Vector{Float64}, df.spouse) df.spouse[1] = Inf @test_throws ErrorException makeyxcols(nt..., TermSet(term(:oop_spend), term(:spouse))) df = DataFrame(hrs) x = randn(N) df.x = x wt = uweights(N) fes = [FixedEffect(df.hhidpn)] feM = AbstractFixedEffectSolver{Float64}(fes, wt, Val{:cpu}, Threads.nthreads()) nt = merge(nt, (data=df, weights=wt, feM=feM, has_fe_intercept=true)) ret = makeyxcols(nt..., TermSet(term(:oop_spend), InterceptTerm{false}(), term(:x))) resids = reshape(copy(df.oop_spend), N, 1) _feresiduals!(resids, feM, 1e-8, 10000) resids .*= sqrt.(wt) @test ret.yxcols[ret.yxterms[term(:oop_spend)]] == reshape(resids, N) # Verify input data are not modified @test df.oop_spend == hrs.oop_spend @test df.x == x df = DataFrame(hrs) esample = df.rwthh.> 0 N = sum(esample) wt = Weights(hrs.rwthh[esample]) fes = [FixedEffect(df.hhidpn[esample])] feM = AbstractFixedEffectSolver{Float64}(fes, wt, Val{:cpu}, Threads.nthreads()) nt = merge(nt, (data=df, esample=esample, weights=wt, feM=feM, has_fe_intercept=true)) ret = makeyxcols(nt..., TermSet(term(:oop_spend), InterceptTerm{false}())) resids = reshape(df.oop_spend[esample], N, 1) _feresiduals!(resids, feM, 1e-8, 10000) resids .*= sqrt.(wt) @test ret.yxcols == Dict(ret.yxterms[term(:oop_spend)]=>reshape(resids, N)) @test ret.nfeiterations isa Int @test ret.feconverged # Verify input data are not modified @test df.oop_spend == hrs.oop_spend allntargs = NamedTuple[(yterm=term(:oop_spend), xterms=TermSet())] @test combinedargs(MakeYXCols(), allntargs) == (TermSet(term(:oop_spend)),) push!(allntargs, allntargs[1]) @test combinedargs(MakeYXCols(), allntargs) == (TermSet(term(:oop_spend)),) push!(allntargs, (yterm=term(:riearnsemp), xterms=TermSet(InterceptTerm{false}()))) @test combinedargs(MakeYXCols(), allntargs) == (TermSet(term(:oop_spend), term(:riearnsemp), InterceptTerm{false}()),) push!(allntargs, (yterm=term(:riearnsemp), xterms=TermSet(term(:male)))) @test combinedargs(MakeYXCols(), allntargs) == (TermSet(term(:oop_spend), term(:riearnsemp), InterceptTerm{false}(), term(:male)),) nt = merge(nt, (data=df, yterm=term(:oop_spend), xterms=TermSet(InterceptTerm{false}()))) @test MakeYXCols()(nt) == merge(nt, ret) end @testset "MakeTreatCols" begin hrs = exampledata("hrs") N = size(hrs, 1) tr = dynamic(:wave, -1) pr = nevertreated(11) nt = (data=hrs, treatname=:wave_hosp, treatintterms=TermSet(), feM=nothing, weights=uweights(N), esample=trues(N), default(MakeTreatCols())...) ret = maketreatcols(nt..., tr.time, Dict(-1=>1), IdDict{ValidTimeType,Int}(11=>1)) @test size(ret.cells) == (20, 2) @test length(ret.rows) == 20 @test size(ret.treatcells) == (12, 2) @test length(ret.treatcols) == length(ret.treatrows) == 12 @test length(ret.treatweights) == length(ret.treatcounts) == length(ret.treatrows) @test ret.cells.wave_hosp == repeat(8:11, inner=5) @test ret.cells.wave == repeat(7:11, 4) @test ret.rows[end] == findall((hrs.wave_hosp.==11).&(hrs.wave.==11)) @test ret.treatcells.wave_hosp == repeat(8:10, inner=4) rel = ret.cells.wave .- ret.cells.wave_hosp @test ret.treatcells.rel == rel[(rel.!=-1).&(ret.cells.wave_hosp.!=11)] @test ret.treatrows[1] == findall((hrs.wave_hosp.==8).&(hrs.wave.==8)) col = convert(Vector{Float64}, (hrs.wave_hosp.==8).&(hrs.wave.==8)) @test ret.treatcols[1] == col @test ret.treatweights == ret.treatcounts w = ret.treatweights @test all(w[ret.treatcells.wave_hosp.==8].==252) @test all(w[ret.treatcells.wave_hosp.==9].==176) @test all(w[ret.treatcells.wave_hosp.==10].==163) nt = merge(nt, (treatintterms=TermSet(term(:male)),)) ret1 = maketreatcols(nt..., tr.time, Dict(-1=>1), IdDict{ValidTimeType,Int}(11=>1)) @test size(ret1.cells) == (40, 3) @test length(ret1.rows) == 40 @test size(ret1.treatcells) == (24, 3) @test length(ret1.treatcols) == length(ret1.treatrows) == 24 @test length(ret1.treatweights) == length(ret1.treatcounts) == length(ret1.treatrows) @test ret1.cells.wave_hosp == repeat(8:11, inner=10) @test ret1.cells.wave == repeat(repeat(7:11, inner=2), 4) @test ret1.cells.male == repeat(0:1, 20) @test ret1.rows[end] == findall((hrs.wave_hosp.==11).&(hrs.wave.==11).&(hrs.male.==1)) @test ret1.treatcells.wave_hosp == repeat(8:10, inner=8) rel = ret1.cells.wave .- ret1.cells.wave_hosp @test ret1.treatcells.rel == rel[(rel.!=-1).&(ret1.cells.wave_hosp.!=11)] @test ret1.treatrows[1] == findall((hrs.wave_hosp.==8).&(hrs.wave.==8).&(hrs.male.==0)) col1 = convert(Vector{Float64}, (hrs.wave_hosp.==8).&(hrs.wave.==8).&(hrs.male.==0)) @test ret1.treatcols[1] == col1 @test ret1.treatweights == ret1.treatcounts nt = merge(nt, (cohortinteracted=false, treatintterms=TermSet())) ret2 = maketreatcols(nt..., tr.time, Dict(-1=>1), IdDict{ValidTimeType,Int}(11=>1)) @test ret2.cells[1] == ret.cells[1] @test ret2.cells[2] == ret.cells[2] @test ret2.rows == ret.rows @test size(ret2.treatcells) == (6, 1) @test length(ret2.treatcols) == length(ret2.treatrows) == 6 @test length(ret2.treatweights) == length(ret2.treatcounts) == length(ret2.treatrows) @test ret2.treatcells.rel == [-3, -2, 0, 1, 2, 3] @test ret2.treatrows[1] == findall((hrs.wave.-hrs.wave_hosp.==-3).&(hrs.wave_hosp.!=11)) col2 = convert(Vector{Float64}, (hrs.wave.-hrs.wave_hosp.==-3).&(hrs.wave_hosp.!=11)) @test ret2.treatcols[1] == col2 @test ret2.treatweights == ret2.treatcounts nt = merge(nt, (treatintterms=TermSet(term(:male)),)) ret3 = maketreatcols(nt..., tr.time, Dict(-1=>1), IdDict{ValidTimeType,Int}(11=>1)) @test ret3.cells[1] == ret1.cells[1] @test ret3.cells[2] == ret1.cells[2] @test ret3.cells[3] == ret1.cells[3] @test ret3.rows == ret1.rows @test size(ret3.treatcells) == (12, 2) @test length(ret3.treatcols) == length(ret3.treatrows) == 12 @test length(ret3.treatweights) == length(ret3.treatcounts) == length(ret3.treatrows) @test ret3.treatcells.rel == repeat([-3, -2, 0, 1, 2, 3], inner=2) @test ret3.treatcells.male == repeat(0:1, 6) @test ret3.treatrows[1] == findall((hrs.wave.-hrs.wave_hosp.==-3).&(hrs.wave_hosp.!=11).&(hrs.male.==0)) df = DataFrame(hrs) esample = df.rwthh.> 0 N = sum(esample) wt = Weights(hrs.rwthh[esample]) fes = [FixedEffect(df.hhidpn[esample])] feM = AbstractFixedEffectSolver{Float64}(fes, wt, Val{:cpu}, Threads.nthreads()) nt = merge(nt, (data=df, feM=feM, weights=wt, esample=esample, treatintterms=TermSet(), cohortinteracted=true)) ret = maketreatcols(nt..., tr.time, Dict(-1=>1), IdDict{ValidTimeType,Int}(11=>1)) col = reshape(col[esample], N, 1) defaults = (default(MakeTreatCols())...,) _feresiduals!(col, feM, defaults[2:3]...) @test ret.treatcols[1] == (col.*sqrt.(wt))[:] @test ret.treatcounts == [252, 252, 252, 251, 176, 176, 176, 175, 162, 160, 163, 162] @test ret.treatweights[1] == 1776173 allntargs = NamedTuple[(tr=tr, pr=pr)] @test combinedargs(MakeTreatCols(), allntargs) == (Dict(-1=>1), IdDict{ValidTimeType,Int}(11=>1)) push!(allntargs, allntargs[1]) @test combinedargs(MakeTreatCols(), allntargs) == (Dict(-1=>2), IdDict{ValidTimeType,Int}(11=>2)) push!(allntargs, (tr=dynamic(:wave, [-1,-2]), pr=nevertreated(10:11))) @test combinedargs(MakeTreatCols(), allntargs) == (Dict(-1=>3), IdDict{ValidTimeType,Int}(11=>3)) push!(allntargs, (tr=dynamic(:wave, [-3]), pr=nevertreated(10))) @test combinedargs(MakeTreatCols(), allntargs) == (Dict{Int,Int}(), IdDict{ValidTimeType,Int}()) allntargs = NamedTuple[(tr=tr, pr=pr), (tr=tr, pr=unspecifiedpr())] @test combinedargs(MakeTreatCols(), allntargs) == (Dict(-1=>2), IdDict{ValidTimeType,Int}()) df.wave = settime(Date.(hrs.wave), Year(1)) df.wave_hosp = settime(Date.(hrs.wave_hosp), Year(1), start=Date(7)) ret1 = maketreatcols(nt..., tr.time, Dict(-1=>1), IdDict{ValidTimeType,Int}(Date(11)=>1)) @test ret1.cells[1] == Date.(ret.cells[1]) @test ret1.cells[2] == Date.(ret.cells[2]) @test ret1.rows == ret.rows @test ret1.treatcells[1] == Date.(ret.treatcells[1]) @test ret1.treatcells[2] == ret.treatcells[2] @test ret1.treatrows == ret.treatrows @test ret1.treatcols == ret.treatcols @test ret1.treatweights == ret.treatweights @test ret1.treatcounts == ret.treatcounts rot = ifelse.(isodd.(hrs.hhidpn), 1, 2) df.wave = RotatingTimeArray(rot, hrs.wave) df.wave_hosp = RotatingTimeArray(rot, hrs.wave_hosp) e = rotatingtime((1,1,2), (10,11,11)) ret2 = maketreatcols(nt..., tr.time, Dict(-1=>1), IdDict{ValidTimeType,Int}(c=>1 for c in e)) @test ret2.cells[1] == sort!(append!((rotatingtime(r, ret.cells[1]) for r in (1,2))...)) rt = append!((rotatingtime(r, 7:11) for r in (1,2))...) @test ret2.cells[2] == repeat(rt, 4) @test size(ret2.treatcells) == (20, 2) @test sort!(unique(ret2.treatcells[1])) == sort!(append!(rotatingtime(1, 8:9), rotatingtime(2, 8:10))) df.wave = settime(Date.(hrs.wave), Year(1), rotation=rot) df.wave_hosp = settime(Date.(hrs.wave_hosp), Year(1), start=Date(7), rotation=rot) e = rotatingtime((1,1,2), Date.((10,11,11))) ret3 = maketreatcols(nt..., tr.time, Dict(-1=>1), IdDict{ValidTimeType,Int}(c=>1 for c in e)) @test ret3.cells[1].time == Date.(ret2.cells[1].time) @test ret3.cells[2].time == Date.(ret2.cells[2].time) @test ret3.rows == ret2.rows @test ret3.treatcells[1].time == Date.(ret2.treatcells[1].time) @test ret3.treatcells[2] == ret2.treatcells[2] @test ret3.treatrows == ret2.treatrows @test ret3.treatcols == ret2.treatcols @test ret3.treatweights == ret2.treatweights @test ret3.treatcounts == ret2.treatcounts nt = merge(nt, (data=hrs, tr=tr, pr=pr)) @test MakeTreatCols()(nt) == merge(nt, (cells=ret.cells, rows=ret.rows, treatcells=ret.treatcells, treatrows=ret.treatrows, treatcols=ret.treatcols, treatweights=ret.treatweights, treatcounts=ret.treatcounts)) end @testset "SolveLeastSquares" begin hrs = exampledata("hrs") N = size(hrs, 1) df = DataFrame(hrs) df.t2 = fill(2.0, N) t1 = InterceptTerm{true}() t0 = InterceptTerm{false}() tr = dynamic(:wave, -1) pr = nevertreated(11) yxterms = Dict([x=>apply_schema(x, schema(x, df), StatisticalModel) for x in (term(:oop_spend), t1, term(:t2), t0, term(:male), term(:spouse))]) yxcols0 = Dict(yxterms[term(:oop_spend)]=>hrs.oop_spend, t1=>ones(N, 1), yxterms[term(:male)]=>hrs.male, yxterms[term(:spouse)]=>hrs.spouse) col0 = convert(Vector{Float64}, (hrs.wave_hosp.==10).&(hrs.wave.==10)) col1 = convert(Vector{Float64}, (hrs.wave_hosp.==10).&(hrs.wave.==11)) col2 = convert(Vector{Float64}, (hrs.wave_hosp.==11).&(hrs.wave.==11)) treatcells0 = VecColumnTable((wave_hosp=[10, 10, 11], rel=[0, 1, 0])) treatcols0 = [col0, col1, col2] treatcounts0 = [sum(c.==1) for c in treatcols0] treatweights0 = convert(Vector{Float64}, treatcounts0) nt = (tr=tr, pr=pr, yterm=term(:oop_spend), xterms=TermSet(term(1)), yxterms=yxterms, yxcols=yxcols0, treatcells=treatcells0, treatcols=treatcols0, treatweights=treatweights0, treatcounts=treatcounts0, cohortinteracted=true, has_fe_intercept=false) ret = solveleastsquares!(nt...) # Compare estimates with Stata # gen col0 = wave_hosp==10 & wave==10 # gen col1 = wave_hosp==10 & wave==11 # reg oop_spend col0 col1 @test ret.coef[1] ≈ 2862.4141 atol=1e-4 @test ret.coef[2] ≈ 490.44869 atol=1e-4 @test ret.coef[3] ≈ 3353.6565 atol=1e-4 @test ret.treatcells.wave_hosp == [10, 10] @test ret.treatcells.rel == [0, 1] @test ret.xterms == AbstractTerm[t1] @test ret.basiscols == trues(3) # Verify that an intercept will only be added when needed nt1 = merge(nt, (xterms=TermSet(),)) ret1 = solveleastsquares!(nt1...) @test ret1 == ret nt1 = merge(nt, (xterms=TermSet(term(0)),)) ret1 = solveleastsquares!(nt1...) @test ret1.xterms == AbstractTerm[] @test size(ret1.X, 2) == 2 nt1 = merge(nt, (xterms=TermSet((term(:spouse), term(:male))),)) ret1 = solveleastsquares!(nt1...) @test ret1.xterms == AbstractTerm[yxterms[term(:male)], yxterms[term(:spouse)], InterceptTerm{true}()] # Test colliner xterms are handled yxcols1 = Dict(yxterms[term(:oop_spend)]=>hrs.oop_spend, t1=>ones(N), yxterms[term(:t2)]=>df.t2) nt1 = merge(nt, (xterms=TermSet(term(1), term(:t2)), yxcols=yxcols1)) ret1 = solveleastsquares!(nt1...) @test ret1.coef[1:2] == ret.coef[1:2] @test sum(ret1.basiscols) == 3 treatcells1 = VecColumnTable((rel=[0, 1, 1, 1], wave_hosp=[10, 10, 0, 1])) treatcols1 = push!(treatcols0[1:2], ones(N), ones(N)) treatweights1 = push!(copy(treatweights0), 10.0) treatcounts1 = push!(copy(treatcounts0), 10) # Need to have at least one term in xterms for the check to work yxcols2 = Dict(yxterms[term(:oop_spend)]=>hrs.oop_spend, yxterms[term(:male)]=>hrs.male) nt1 = merge(nt1, (xterms=TermSet(term(:male), term(0)), treatcells=treatcells1, yxcols=yxcols2, treatcols=treatcols1, treatweights=treatweights1, treatcounts=treatcounts1)) @test SolveLeastSquares()(nt) == merge(nt, ret) end @testset "EstVcov" begin hrs = exampledata("hrs") N = size(hrs, 1) col0 = convert(Vector{Float64}, (hrs.wave_hosp.==10).&(hrs.wave.==10)) col1 = convert(Vector{Float64}, (hrs.wave_hosp.==10).&(hrs.wave.==11)) y = convert(Vector{Float64}, hrs.oop_spend) X = hcat(col0, col1, ones(N, 1)) crossx = Symmetric(X'X) Nx = size(X, 2) Xy = Symmetric(hvcat(2, crossx, X'y, zeros(1, Nx), [0.0])) invsym!(Xy; diagonal = 1:Nx) invcrossx = Symmetric(-view(Xy, 1:Nx, 1:Nx)) cf = Xy[1:end-1,end] residuals = y - X * cf nt = (data=hrs, esample=trues(N), vce=Vcov.simple(), coef=cf, X=X, crossx=crossx, invcrossx=invcrossx, residuals=residuals, xterms=AbstractTerm[term(1)], fes=FixedEffect[], has_fe_intercept=false) ret = estvcov(nt...) # Compare estimates with Stata # reg oop_spend col0 col1 # mat list e(V) @test ret.vcov_mat[1,1] ≈ 388844.2 atol=0.1 @test ret.vcov_mat[2,2] ≈ 388844.2 atol=0.1 @test ret.vcov_mat[3,3] ≈ 20334.169 atol=1e-3 @test ret.vcov_mat[2,1] ≈ 20334.169 atol=1e-3 @test ret.vcov_mat[3,1] ≈ -20334.169 atol=1e-3 @test ret.dof_resid == N - 3 @test ret.F ≈ 10.68532285556941 atol=1e-6 nt = merge(nt, (vce=Vcov.robust(), fes=FixedEffect[])) ret = estvcov(nt...) # Compare estimates with Stata # reg oop_spend col0 col1, r # mat list e(V) @test ret.vcov_mat[1,1] ≈ 815817.44 atol=0.1 @test ret.vcov_mat[2,2] ≈ 254993.93 atol=1e-2 @test ret.vcov_mat[3,3] ≈ 19436.209 atol=1e-3 @test ret.vcov_mat[2,1] ≈ 19436.209 atol=1e-3 @test ret.vcov_mat[3,1] ≈ -19436.209 atol=1e-3 @test ret.dof_resid == N - 3 @test ret.F ≈ 5.371847047691197 atol=1e-6 nt = merge(nt, (vce=Vcov.cluster(:hhidpn),)) ret = estvcov(nt...) # Compare estimates with Stata # reghdfe oop_spend col0 col1, noa clu(hhidpn) # mat list e(V) @test ret.vcov_mat[1,1] ≈ 744005.01 atol=0.1 @test ret.vcov_mat[2,2] ≈ 242011.45 atol=1e-2 @test ret.vcov_mat[3,3] ≈ 28067.783 atol=1e-3 @test ret.vcov_mat[2,1] ≈ 94113.386 atol=1e-2 @test ret.vcov_mat[3,1] ≈ 12640.559 atol=1e-2 @test ret.dof_resid == N - 3 @test ret.F ≈ 5.542094561672688 atol=1e-6 fes = FixedEffect[FixedEffect(hrs.hhidpn)] wt = uweights(N) feM = AbstractFixedEffectSolver{Float64}(fes, wt, Val{:cpu}, Threads.nthreads()) X = hcat(col0, col1) _feresiduals!(y, feM, 1e-8, 10000) _feresiduals!(X, feM, 1e-8, 10000) crossx = Symmetric(X'X) Nx = size(X, 2) Xy = Symmetric(hvcat(2, crossx, X'y, zeros(1, Nx), [0.0])) invsym!(Xy; diagonal = 1:Nx) invcrossx = Symmetric(-view(Xy, 1:Nx, 1:Nx)) cf = Xy[1:end-1,end] residuals = y - X * cf nt = merge(nt, (vce=Vcov.robust(), coef=cf, X=X, crossx=crossx, invcrossx=invcrossx, residuals=residuals, xterms=AbstractTerm[], fes=fes, has_fe_intercept=true)) ret = estvcov(nt...) # Compare estimates with Stata # reghdfe oop_spend col0 col1, a(hhidpn) vce(robust) # mat list e(V) @test ret.vcov_mat[1,1] ≈ 654959.97 atol=0.1 @test ret.vcov_mat[2,2] ≈ 503679.27 atol=0.1 @test ret.vcov_mat[2,1] ≈ 192866.2 atol=0.1 @test ret.dof_resid == N - nunique(fes[1]) - 2 @test ret.F ≈ 7.559815337537517 atol=1e-6 nt = merge(nt, (vce=Vcov.cluster(:hhidpn),)) ret = estvcov(nt...) # Compare estimates with Stata # reghdfe oop_spend col0 col1, a(hhidpn) clu(hhidpn) # mat list e(V) @test ret.vcov_mat[1,1] ≈ 606384.66 atol=0.1 @test ret.vcov_mat[2,2] ≈ 404399.89 atol=0.1 @test ret.vcov_mat[2,1] ≈ 106497.43 atol=0.1 @test ret.dof_resid == N - 3 @test ret.F ≈ 8.197452252592386 atol=1e-6 @test EstVcov()(nt) == merge(nt, ret) end @testset "SolveLeastSquaresWeights" begin hrs = exampledata("hrs") tr = dynamic(:wave, -1) N = size(hrs, 1) col0 = convert(Vector{Float64}, (hrs.wave_hosp.==10).&(hrs.wave.==10)) col1 = convert(Vector{Float64}, (hrs.wave_hosp.==10).&(hrs.wave.==11)) cellnames = [:wave_hosp, :wave] cols = subcolumns(hrs, cellnames) cells, rows = cellrows(cols, findcell(cols)) yterm = term(:oop_spend) yxterms = Dict(x=>apply_schema(x, schema(x, hrs), StatisticalModel) for x in (term(:oop_spend), term(:male))) yxcols = Dict(yxterms[term(:oop_spend)]=>convert(Vector{Float64}, hrs.oop_spend)) wt = uweights(N) fes = [FixedEffect(hrs.hhidpn)] feM = AbstractFixedEffectSolver{Float64}(fes, wt, Val{:cpu}, Threads.nthreads()) y = yxcols[yxterms[term(:oop_spend)]] fetol = 1e-8 _feresiduals!([y, col0, col1], feM, fetol, 10000) X = hcat(col0, col1) crossx = Symmetric(X'X) cf = crossx \ (X'y) tcells = VecColumnTable((rel=[0, 1],)) nt = (tr=tr, solvelsweights=true, lswtnames=(), cells=cells, rows=rows, X=X, crossx=crossx, coef=cf, treatcells=tcells, yterm=yterm, xterms=AbstractTerm[], yxterms=yxterms, yxcols=yxcols, feM=feM, fetol=1e-8, femaxiter=10000, weights=wt) ret = solveleastsquaresweights(nt...) lswt = ret.lsweights @test lswt.r === cells @test lswt.c === tcells @test lswt[lswt.r.wave_hosp.==10, 1] ≈ [-1/3, -1/3, -1/3, 1, 0] atol=fetol @test lswt[lswt.r.wave_hosp.==10, 1] ≈ [-1/3, -1/3, -1/3, 1, 0] atol=fetol @test lswt[lswt.r.wave_hosp.==10, 2] ≈ [-1/3, -1/3, -1/3, 0, 1] atol=fetol @test all(x->isapprox(x, 0, atol=fetol), lswt[lswt.r.wave_hosp.!=10, :]) @test ret.cellweights == ret.cellcounts == length.(rows) @test all(i->ret.cellymeans[i] ≈ sum(y[rows[i]])/length(rows[i]), 1:length(rows)) nt0 = merge(nt, (lswtnames=(:no,),)) @test_throws ArgumentError solveleastsquaresweights(nt0...) nt = merge(nt, (lswtnames=(:wave,),)) ret = solveleastsquaresweights(nt...) lswt = ret.lsweights @test size(lswt.r) == (5, 1) @test lswt.r.wave == 7:11 nt = merge(nt, (lswtnames=(:wave, :wave_hosp),)) ret = solveleastsquaresweights(nt...) lswt = ret.lsweights @test size(lswt.r) == (20, 2) @test lswt.r.wave == repeat(7:11, inner=4) @test lswt.r.wave_hosp == repeat(8:11, outer=5) @test lswt[lswt.r.wave_hosp.==10, 1] ≈ [-1/3, -1/3, -1/3, 1, 0] atol=fetol @test lswt[lswt.r.wave_hosp.==10, 2] ≈ [-1/3, -1/3, -1/3, 0, 1] atol=fetol df = DataFrame(hrs) df.x = zeros(N) df.x[df.wave.==7] .= rand(656) yxterms = Dict(x=>apply_schema(x, schema(x, df), StatisticalModel) for x in (term(:oop_spend), term(:x))) yxcols = Dict(yxterms[term(:oop_spend)]=>convert(Vector{Float64}, hrs.oop_spend), yxterms[term(:x)]=>convert(Vector{Float64}, df.x)) fes = [FixedEffect(hrs.hhidpn), FixedEffect(hrs.wave)] feM = AbstractFixedEffectSolver{Float64}(fes, wt, Val{:cpu}, Threads.nthreads()) y = yxcols[yxterms[term(:oop_spend)]] x = yxcols[yxterms[term(:x)]] _feresiduals!(hcat(y, col0, col1, x), feM, fetol, 10000) X = hcat(col0, col1, x) crossx = Symmetric(X'X) cf = crossx \ (X'y) xterms = AbstractTerm[yxterms[term(:x)]] nt = merge(nt, (lswtnames=(:wave_hosp, :wave), X=X, crossx=crossx, coef=cf, xterms=xterms, yxterms=yxterms, yxcols=yxcols)) ret = solveleastsquaresweights(nt...) lswt = ret.lsweights @test lswt[lswt.r.wave.<=9, 1] ≈ lswt[lswt.r.wave.<=9, 2] @test lswt[lswt.r.wave.==10, 1] ≈ lswt[lswt.r.wave.==11, 2] @test lswt[lswt.r.wave.==11, 1] ≈ lswt[lswt.r.wave.==10, 2] y1 = y .- cf[3].*x @test all(i->ret.cellymeans[i] == sum(y1[rows[i]])/length(rows[i]), 1:length(rows)) @test SolveLeastSquaresWeights()(nt) == merge(nt, ret) end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
1027
using Test using InteractionWeightedDIDs using DataFrames using Dates: Date, Year using DiffinDiffsBase: exampledata, ValidTimeType, @fieldequal, valid_didargs using DiffinDiffsBase.StatsProcedures: required, default, transformed, combinedargs, _byid, pool using FixedEffectModels: nunique, _multiply, invsym! using FixedEffects using InteractionWeightedDIDs: FETerm, _parsefeterm, getfename, checkvcov!, parsefeterms!, groupfeterms, makefes, checkfes!, makefesolver, _feresiduals!, makeyxcols, maketreatcols, solveleastsquares!, estvcov, solveleastsquaresweights using LinearAlgebra using StatsBase: Weights, uweights import Base: == import DiffinDiffsBase.StatsProcedures: prerequisites @fieldequal FixedEffect @fieldequal Vcov.ClusterCovariance @fieldequal RegressionBasedDIDResult const tests = [ "utils", "procedures", "did" ] printstyled("Running tests:\n", color=:blue, bold=true) @time for test in tests include("$test.jl") println("\033[1m\033[32mPASSED\033[0m: $(test)") end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
395
@testset "_parsefeterm" begin @test _parsefeterm(term(:male)) === nothing @test _parsefeterm(fe(:hhidpn)) == ([:hhidpn]=>Symbol[]) @test _parsefeterm(fe(:hhidpn)&fe(:wave)&term(:male)) == ([:hhidpn, :wave]=>[:male]) end @testset "getfename" begin @test getfename([:hhidpn]=>Symbol[]) == "fe_hhidpn" @test getfename([:hhidpn, :wave]=>[:male]) == "fe_hhidpn&fe_wave&male" end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
113
module DiffinDiffs using Reexport @reexport using DiffinDiffsBase @reexport using InteractionWeightedDIDs end
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
code
305
# Redirect test to the library package if TEST_TARGET is set using Pkg tar = get(ENV, "TEST_TARGET", nothing) libpath = joinpath(dirname(@__DIR__), "lib") if tar in readdir(libpath) Pkg.test(tar; coverage=true) exit() end using Test using DiffinDiffs using Documenter @time doctest(DiffinDiffs)
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
3870
<p align="center"> <img src="docs/src/assets/banner.svg" height="200"><br><br> <a href="https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/actions?query=workflow%3ACI-stable"> <img alt="CI-stable" src="https://img.shields.io/github/actions/workflow/status/JuliaDiffinDiffs/DiffinDiffs.jl/.github/workflows/CI-stable.yml?branch=master&label=CI-stable&logo=github&style=flat-square"> </a> <a href="https://codecov.io/gh/JuliaDiffinDiffs/DiffinDiffs.jl"> <img alt="codecov" src="https://img.shields.io/codecov/c/github/JuliaDiffinDiffs/DiffinDiffs.jl?label=codecov&logo=codecov&style=flat-square"> </a> <a href="https://JuliaDiffinDiffs.github.io/DiffinDiffs.jl/stable"> <img alt="docs-stable" src="https://img.shields.io/badge/docs-stable-blue?style=flat-square"> </a> <a href="https://JuliaDiffinDiffs.github.io/DiffinDiffs.jl/dev"> <img alt="docs-dev" src="https://img.shields.io/badge/docs-dev-blue?style=flat-square"> </a> <a href="https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/blob/master/LICENSE.md"> <img alt="license" src="https://img.shields.io/github/license/JuliaDiffinDiffs/DiffinDiffs.jl?color=blue&style=flat-square"> </a> </p> [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) is a suite of Julia packages for difference-in-differences (DID). The goal of its development is to promote applications of the latest advances in econometric methodology related to DID in academic research while leveraging the performance and composability of the Julia language. ## Why DiffinDiffs.jl? - **Fast:** Handle datasets of multiple gigabytes with ease - **Transparent:** Completely open source and natively written in Julia - **Extensible:** Unified interface with modular package organization ## Package Organization [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) reexports types, functions and macros defined in component packages that are separately registered. The package itself does not host any concrete functionality except documentation. This facilitates decentralized code development under a unified framework. | Package | Description | Version | Status | |:--------|:------------|:-------|:---| [DiffinDiffsBase](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/tree/master/lib/DiffinDiffsBase) | Base package for DiffinDiffs.jl | [![version](https://juliahub.com/docs/DiffinDiffsBase/version.svg)](https://juliahub.com/ui/Packages/DiffinDiffsBase/AGMId) | [![pkgeval](https://juliaci.github.io/NanosoldierReports/pkgeval_badges/D/DiffinDiffsBase.svg)](https://juliaci.github.io/NanosoldierReports/pkgeval_badges/D/DiffinDiffsBase.html) | [InteractionWeightedDIDs](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/tree/master/lib/InteractionWeightedDIDs) | Regression-based multi-period DID | [![version](https://juliahub.com/docs/InteractionWeightedDIDs/version.svg)](https://juliahub.com/ui/Packages/InteractionWeightedDIDs/Vf93d) | [![pkgeval](https://juliaci.github.io/NanosoldierReports/pkgeval_badges/I/InteractionWeightedDIDs.svg)](https://juliaci.github.io/NanosoldierReports/pkgeval_badges/I/InteractionWeightedDIDs.html) | More components will be included in the future as development moves forward. ## Installation [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) can be installed with the Julia package manager [Pkg](https://docs.julialang.org/en/v1/stdlib/Pkg/). From the Julia REPL, type `]` to enter the Pkg REPL and run: ``` pkg> add DiffinDiffs ``` This will install all the component packages of [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) as dependencies. There is no need to explicitly add the individual components unless one needs to access internal objects. ## Usage For details on the usage, please see the [documentation](https://JuliaDiffinDiffs.github.io/DiffinDiffs.jl/stable).
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
2521
# DiffinDiffs.jl Welcome to the documentation site for DiffinDiffs.jl! [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) is a suite of Julia packages for difference-in-differences (DID). The goal of its development is to promote applications of the latest advances in econometric methodology related to DID in academic research while leveraging the performance and composability of the Julia language. ## Why DiffinDiffs.jl? - **Fast:** Handle datasets of multiple gigabytes with ease - **Transparent:** Completely open source and natively written in Julia - **Extensible:** Unified interface with modular package organization ## Package Organization [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) reexports types, functions and macros defined in component packages that are separately registered. The package itself does not host any concrete functionality except documentation. This facilitates decentralized code development under a unified framework. | Package | Description | Version | Status | |:--------|:------------|:--------|:-------| [DiffinDiffsBase](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/tree/master/lib/DiffinDiffsBase) | Base package for DiffinDiffs.jl | [![version](https://juliahub.com/docs/DiffinDiffsBase/version.svg)](https://juliahub.com/ui/Packages/DiffinDiffsBase/AGMId) | [![pkgeval](https://juliahub.com/docs/DiffinDiffsBase/pkgeval.svg)](https://juliahub.com/ui/Packages/DiffinDiffsBase/AGMId) | [InteractionWeightedDIDs](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/tree/master/lib/InteractionWeightedDIDs) | Regression-based multi-period DID | [![version](https://juliahub.com/docs/InteractionWeightedDIDs/version.svg)](https://juliahub.com/ui/Packages/InteractionWeightedDIDs/Vf93d) | [![pkgeval](https://juliahub.com/docs/InteractionWeightedDIDs/pkgeval.svg)](https://juliahub.com/ui/Packages/InteractionWeightedDIDs/Vf93d) | More components will be included in the future as development moves forward. ## Installation [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) can be installed with the Julia package manager [Pkg](https://docs.julialang.org/en/v1/stdlib/Pkg/). From the Julia REPL, type `]` to enter the Pkg REPL and run: ``` pkg> add DiffinDiffs ``` This will install all the component packages of [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) as dependencies. There is no need to explicitly add the individual components unless one needs to access internal objects.
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
35
# References ```@bibliography ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
93
# ScaledArrays ```@autodocs Modules = [DiffinDiffsBase] Pages = ["src/ScaledArrays.jl"] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
64
# StatsProcedures ```@autodocs Modules = [StatsProcedures] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
150
# Estimators ```@autodocs Modules = [DiffinDiffsBase, InteractionWeightedDIDs] Filter = t -> typeof(t) === DataType && t <: DiffinDiffsEstimator ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
47
# Inference ```@autodocs Modules = [Vcov] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
110
# Miscellanea ```@autodocs Modules = [DiffinDiffsBase, InteractionWeightedDIDs] Pages = ["src/utils.jl"] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
110
# Panel Operations ```@autodocs Modules = [DiffinDiffsBase] Pages = ["src/operations.jl", "src/time.jl"] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
92
# Parallel Types ```@autodocs Modules = [DiffinDiffsBase] Pages = ["src/parallels.jl"] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
114
# Procedures ```@autodocs Modules = [DiffinDiffsBase, InteractionWeightedDIDs] Pages = ["src/procedures.jl"] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
173
# Results ```@autodocs Modules = [DiffinDiffsBase, InteractionWeightedDIDs] Pages = ["src/did.jl"] Filter = t -> !(typeof(t) === DataType && t <: DiffinDiffsEstimator) ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
81
# Tables ```@autodocs Modules = [DiffinDiffsBase] Pages = ["src/tables.jl"] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
89
# Treatment Terms ```@autodocs Modules = [DiffinDiffsBase] Pages = ["src/terms.jl"] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
94
# Treatment Types ```@autodocs Modules = [DiffinDiffsBase] Pages = ["src/treatments.jl"] ```
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
4947
# Getting Started To demonstrate the basic usage of [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl), we walk through the processes of reproducing empirical results from relevant studies. Please refer to the original papers for details on the context. ## Dynamic Effects in Event Studies As a starting point, we reproduce results from the empirical illustration in [SunA21E](@citet). ### Data Preparation [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) requires that the data used for estimation are stored in a column table compatible with the interface defined in [Tables.jl](https://github.com/JuliaData/Tables.jl). This means that virtually all types of data frames, including [DataFrames.jl](https://github.com/JuliaData/DataFrames.jl), are supported. For the sake of illustration, here we directly load the dataset that is bundled with the package by calling `DiffinDiffsBase.exampledata`: ```@example reprSA using DiffinDiffs hrs = DiffinDiffsBase.exampledata("hrs") ``` In this example, `hhidpn`, `wave`, and `wave_hosp` are columns for the unit IDs, time IDs and treatment time respectively. The rest of the columns contain the outcome variables and covariates. It is important that the time IDs and treatment time refer to each time period in a compatible way so that subtracting a value of treatment time from a value of calendar time (represented by a time ID) with operator `-` yields a meaningful value of relative time, the amount of time elapsed since treatment time. ### Empirical Specifications To produce the estimates reported in panel (a) of Table 3 from [SunA21E](@citet), we specify the estimation via [`@did`](@ref) as follows: ```@example reprSA r = @did(Reg, data=hrs, dynamic(:wave, -1), notyettreated(11), vce=Vcov.cluster(:hhidpn), yterm=term(:oop_spend), treatname=:wave_hosp, treatintterms=(), xterms=(fe(:wave)+fe(:hhidpn))) nothing # hide ``` Before we look at the results, we briefly explain some of the arguments that are relatively more important. [`Reg`](@ref), which is a shorthand for [`RegressionBasedDID`](@ref), is the type of the estimation to be conducted. Here, we need estimation that is conducted by directly solving least-squares regression and hence we use [`Reg`](@ref) to inform [`@did`](@ref) the relevant set of procedures, which also determines the set of arguments that are accepted by [`@did`](@ref). We are interested in the dynamic treatment effects. Hence, we use [`dynamic`](@ref) to specify the data column containing values representing calendar time of the observations and the reference period, which is `-1`. For identification, a crucial assumption underlying DID is the parallel trends assumption. Here, we assume that the average outcome paths of units treated in periods before `11` would be parallel to the observed paths of units treated in period `11`. That is, we are taking units with treatment time `11` as the not-yet-treated control group. We specify `treatname` to be `:wave_hosp`, which indicates the column that contains the treatment time. The interpretation of `treatname` depends on the context that is jointly determined by the type of the estimator, the type of the treatment and possibly the type of parallel trends assumption. The rest of the arguments provide additional information on the regression specifications. The use of them can be found in the documentation for [`RegressionBasedDID`](@ref). We now move on to the result returned by [`@did`](@ref): ```@example reprSA r # hide ``` The object returned is of type [`RegressionBasedDIDResult`](@ref), which contains the estimates for treatment-group-specific average treatment effects among other information. Instead of printing the estimates from the regression, which can be very long if there are many treatment groups, REPL prints a summary table for `r`. Here we verify that the estimate for relative time `0` among the cohort who received treatment in period `8` is about `2826`, the value reported in the third column of Table 3(a) in the paper. ```@example reprSA coef(r, "wave_hosp: 8 & rel: 0") ``` Various accessor methods are defined for retrieving values from a result such as `r`. See [Results](@ref) for a full list of them. ### Aggregation of Estimates The treatment-group-specific estimates in `r` are typically not the ultimate objects of interest. We need to estimate the path of the average dynamic treatment effects across all treatment groups. Such estimates can be easily obtained by aggregating the estimates in `r` via [`agg`](@ref): ```@example reprSA a = agg(r, :rel) ``` Notice that `:rel` is a special value used to indicate that the aggregation is conducted for each value of relative time separately. The aggregation takes into account sample weights of each treatment group and the variance-covariance matrix. The resulting estimates match those reported in the second column of Table 3(a) exactly.
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
1172
# DiffinDiffsBase.jl *Base package for [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl)* [![CI-stable][CI-stable-img]][CI-stable-url] [![codecov][codecov-img]][codecov-url] [![version][version-img]][version-url] [![PkgEval][pkgeval-img]][pkgeval-url] [CI-stable-img]: https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/workflows/CI-stable/badge.svg [CI-stable-url]: https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/actions?query=workflow%3ACI-stable [codecov-img]: https://codecov.io/gh/JuliaDiffinDiffs/DiffinDiffs.jl/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/JuliaDiffinDiffs/DiffinDiffs.jl [version-img]: https://juliahub.com/docs/DiffinDiffsBase/version.svg [version-url]: https://juliahub.com/ui/Packages/DiffinDiffsBase/AGMId [pkgeval-img]: https://juliahub.com/docs/DiffinDiffsBase/pkgeval.svg [pkgeval-url]: https://juliahub.com/ui/Packages/DiffinDiffsBase/AGMId This package provides types, functions, macros and [example data](data) that are shared among other component packages of [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl). It is not intended to be used as a standalone package.
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
2697
# Example Data A collection of data files are provided here for the ease of testing and illustrations. The included data are modified from the original sources and stored in compressed CSV (`.csv.gz`) files. See [`data/src/make.jl`](src/make.jl) for the source code that generates these files from original data. [DiffinDiffsBase.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffsBase.jl) provides methods for looking up and loading these example data. Call `exampledata()` for a name list of the available datasets. To load one of them, call `exampledata(name)` where `name` is the `Symbol` of filename without extension (e.g., `:hrs`). ## Sources and Licenses | Name | Source | File Link | License | Note | | :--- | :----: | :-------: | :-----: | :--- | | hrs | [Dobkin et al. (2018)](https://doi.org/10.1257/aer.20161038) | [HRS_long.dta](https://doi.org/10.3886/E116186V1-73160) | [CC BY 4.0](https://doi.org/10.3886/E116186V1-73120) | Data are processed as in [Sun and Abraham (2020)](https://doi.org/10.1016/j.jeconom.2020.09.006) | | nsw | [Diamond and Sekhon (2013)](https://doi.org/10.1162/REST_a_00318) | [ec675_nsw.tab](https://doi.org/10.7910/DVN/23407/DYEWLO) | [CC0 1.0](https://dataverse.org/best-practices/harvard-dataverse-general-terms-use) | Data are rearranged in a long format as in the R package [DRDID](https://github.com/pedrohcgs/DRDID/blob/master/data-raw/nsw.R) | | mpdta | [Callaway and Sant'Anna (2020)](https://doi.org/10.1016/j.jeconom.2020.12.001) | [mpdta.rda](https://github.com/bcallaway11/did/blob/master/data/mpdta.rda) | [GPL-2](https://cran.r-project.org/web/licenses/GPL-2) | | ## References <a name="CallawayS20">**Callaway, Brantly, and Pedro H. C. Sant'Anna.** 2020. "Difference-in-Differences with Multiple Time Periods." *Journal of Econometrics*, forthcoming.</a> <a name="DiamondS13G">**Diamond, Alexis and Jasjeet S. Sekhon.** 2013. "Replication data for: Genetic Matching for Estimating Causal Effects: A General Multivariate Matching Method for Achieving Balance in Observational Studies." *MIT Press* [publisher], Harvard Dataverse [distributor]. https://doi.org/10.7910/DVN/23407/DYEWLO.</a> <a name="DobkinFK18E">**Dobkin, Carlos, Amy Finkelstein, Raymond Kluender, and Matthew J. Notowidigdo.** 2018. "Replication data for: The Economic Consequences of Hospital Admissions." *American Economic Association* [publisher], Inter-university Consortium for Political and Social Research [distributor]. https://doi.org/10.3886/E116186V1.</a> <a name="SunA20">**Sun, Liyang, and Sarah Abraham.** 2020. "Estimating Dynamic Treatment Effects in Event Studies with Heterogeneous Treatment Effects." *Journal of Econometrics*, forthcoming.</a>
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
0.2.0
9e21bd90ad9f49c460197dc45a340deaf3038bf4
docs
5186
# InteractionWeightedDIDs.jl *Regression-based multi-period difference-in-differences with heterogenous treatment effects* [![CI-stable][CI-stable-img]][CI-stable-url] [![codecov][codecov-img]][codecov-url] [![version][version-img]][version-url] [![PkgEval][pkgeval-img]][pkgeval-url] [CI-stable-img]: https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/workflows/CI-stable/badge.svg [CI-stable-url]: https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl/actions?query=workflow%3ACI-stable [codecov-img]: https://codecov.io/gh/JuliaDiffinDiffs/DiffinDiffs.jl/branch/master/graph/badge.svg [codecov-url]: https://codecov.io/gh/JuliaDiffinDiffs/DiffinDiffs.jl [version-img]: https://juliahub.com/docs/InteractionWeightedDIDs/version.svg [version-url]: https://juliahub.com/ui/Packages/InteractionWeightedDIDs/Vf93d [pkgeval-img]: https://juliahub.com/docs/InteractionWeightedDIDs/pkgeval.svg [pkgeval-url]: https://juliahub.com/ui/Packages/InteractionWeightedDIDs/Vf93d This package provides a collection of regression-based estimators and auxiliary tools for difference-in-differences (DID) across multiple treatment groups over multiple time periods. It is a component of [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl) that can also be used as a standalone package. > **Note:** > > The development of this package is not fully complete. > New features and improvements are being added over time. ## Applicable Environment The baseline empirical environment this package focuses on is the same as the one considered by [Sun and Abraham (2020)](https://doi.org/10.1016/j.jeconom.2020.09.006): * Treatment states are binary, irreversible and sharp. * Units may receive treatment in different periods in a staggered fashion. * Treatment effects may evolve over time following possibly heterogenous paths across treated groups. The parameters of interest include: * A collection of average treatment effects on each group of treated units in different periods. * Interpretable aggregations of these group-time-level parameters. ## Main Features This package is developed with dedication to both the credibility of econometric methodology and high performance for working with relatively large datasets. The main features are the following: * Automatic and efficient generation of indicator variables based on empirical design and data coverage. * Enforcement of an overlap condition based on the parallel trends assumption. * Fast residualization of regressors from fixed effects via [FixedEffects.jl](https://github.com/FixedEffects/FixedEffects.jl). * Interaction-weighted DID estimators proposed by [Sun and Abraham (2020)](https://doi.org/10.1016/j.jeconom.2020.09.006). * Cell-level decomposition of coefficient estimates for analytical reconciliation across specifications. As a component of [DiffinDiffs.jl](https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl), it follows the same programming interface shared by all component packages. In particular, it is benefited from the macros `@did` and `@specset` that largely simplify the construction of groups of related specifications and reduce unnecessary repetitions of identical intermediate steps (e.g., partialling out fixed effects for the same regressors). Tools for easing the export of estimation results are also being developed. ## Econometric Foundations The package does not enforce the use of a specific estimation procedure and allows some flexibility from the users. However, it is mainly designed to ease the adoption of recent advances in the difference-in-differences literature that overcome certain pitfalls that may arise in scenarios where the treated units get treated in different periods (i.e., the staggered adoption design). The development of this package is directly based on the following studies: * [Sun and Abraham (2020)](https://doi.org/10.1016/j.jeconom.2020.09.006) * Unpublished work by the package author Some other studies are also relevant and have provided inspiration: * [de Chaisemartin and D'Haultfœuille (2020)](https://doi.org/10.1257/aer.20181169) * [Borusyak and Jaravel (2018)](#BorusyakJ18) * [Goodman-Bacon (2020)](#Goodman20) * [Callaway and Sant'Anna (2020)](https://doi.org/10.1016/j.jeconom.2020.12.001) ## References <a name="BorusyakJ18">**Borusyak, Kirill, and Xavier Jaravel.** 2018. "Revisiting Event Study Designs with an Application to the Estimation of the Marginal Propensity to Consume." Unpublished.</a> <a name="CallawayS20">**Callaway, Brantly, and Pedro H. C. Sant'Anna.** 2020. "Difference-in-Differences with Multiple Time Periods." *Journal of Econometrics*, forthcoming.</a> <a name="ChaisemartD20T">**de Chaisemartin, Clément, and Xavier D'Haultfœuille.** 2020. "Two-Way Fixed Effects Estimators with Heterogeneous Treatment Effects." *American Economic Review* 110 (9): 2964-96.</a> <a name="Goodman20">**Goodman-Bacon, Andrew.** 2020. "Difference-in-Differences with Variation in Treatment Timing." Unpublished.</a> <a name="SunA20">**Sun, Liyang, and Sarah Abraham.** 2020. "Estimating Dynamic Treatment Effects in Event Studies with Heterogeneous Treatment Effects." *Journal of Econometrics*, forthcoming.</a>
DiffinDiffs
https://github.com/JuliaDiffinDiffs/DiffinDiffs.jl.git
[ "MIT" ]
1.0.0
f5250392b7837dce007760f9becab963b54e1a42
code
2948
module HierarchialPerformanceTest using HypothesisTests using Statistics const PerfMatrix = Array{Float64,2} function hptRankSumTest(x::AbstractVector{S}, y::AbstractVector{T}, num_runs::Int) where {S<:Real,T<:Real} # Custom threshold as specified by the paper if num_runs < 12 ExactMannWhitneyUTest(x, y) else ApproximateMannWhitneyUTest(x, y) end end function hptSignedRankTest(x::AbstractVector{T}, num_tests::Int) where T<:Real # Custom threshold as specified by the paper if num_tests < 25 ExactSignedRankTest(x) else ApproximateSignedRankTest(x) end end function hpt(a::PerfMatrix, b::PerfMatrix; tail=:right) # Enforce identical and sane matrix sizes if size(a) != size(b) error("mismatching number of benchmarks/runs") elseif length(a) == 0 error("no benchmarks given") end num_tests = size(a, 1) # n num_runs = size(a, 2) # m # Max significance for the *null* hypothesis, not the alternative maxNullSignificance = if (num_runs >= 5) 0.05 else 0.10 end # Calculate performance delta per benchmark test_deltas = Array{Float64}(undef, num_tests) # dT for test = 1:num_tests aRuns = a[test,:] bRuns = b[test,:] # Use SHT to determine which side is better shtP = pvalue(hptRankSumTest(aRuns, bRuns, num_runs), tail=tail) # Check is inverted because shtP = probability of null hypothesis (equal) test_deltas[test] = if (shtP < maxNullSignificance) median(aRuns) - median(bRuns) else 0 end end # Evaluate general performance using the selected SHT 1 - pvalue(hptSignedRankTest(test_deltas, num_tests), tail=tail) end function hptSpeedup(a::PerfMatrix, b::PerfMatrix, minConfidence::Float64 = 0.95, digits::Int = 3, increment::Int = 1) # Calculate an extra digit internally to facilitate rounding baseSpeedup = 10 ^ digits # Use int for storing speedup to mitigate floating-point precision loss intSpeedup = baseSpeedup speedup = 1.0 tail = :right # Invert if slower if hpt(a, b) < minConfidence increment *= -1 tail = :left end while true confidence = hpt(a / speedup, b, tail=tail) if confidence >= minConfidence # Increment int and recalculate float to mitigate floating-point precision loss intSpeedup += increment speedup = intSpeedup / baseSpeedup else break end end speedup end function calcScore(results::PerfMatrix, reference::PerfMatrix, refScore::Int = 1000) # 95%-confidence speedup # We swap a and b because HPT considers higher values to be better, but # since our values are times rather than performance, lower is better round(Int, hptSpeedup(reference, results) * refScore) end export PerfMatrix, hpt, hptSpeedup, calcScore end
HierarchialPerformanceTest
https://github.com/kdrag0n/HierarchialPerformanceTest.jl.git
[ "MIT" ]
1.0.0
f5250392b7837dce007760f9becab963b54e1a42
code
125
using HierarchialPerformanceTest using Test @testset "HierarchialPerformanceTest.jl" begin # Write your tests here. end
HierarchialPerformanceTest
https://github.com/kdrag0n/HierarchialPerformanceTest.jl.git
[ "MIT" ]
1.0.0
f5250392b7837dce007760f9becab963b54e1a42
docs
1244
# Hierarchial Performance Test This is a Julia implementation of the Non-parametric Hierarchial Performance Testing statistical technique described in [Statistical Performance Comparisons of Computers](https://parsec.cs.princeton.edu/publications/chen14ieeetc.pdf). It is meant to compare the performance of different computers on a common set of benchmarks with high statistical confidence, rather than . For more information, check the [official website](http://novel.ict.ac.cn/tchen/hpt/) maintained by one of the technique's creators. ## Example usage Each set of benchmark results should be provided as a 2D matrix where each row is comprised of the same benchmark's results. ```julia using HierarchialPerformanceTest # Computer A's benchmark matrix a = [86 86 86; 46 46 46; 2.491 2.3 2.314; 5.629 5.31 5.91; 262.69 262.39 262.632; 17.761 16.882 15.541; 3.264 3.205 3.256; 3678 3612 3642; 4251 4220 4170; 58176 56384 56512] # Computer B's benchmark matrix b = [83 83 83; 46 46 46; 2.263 2.239 2.228; 5.663 6.488 5.383; 260.977 261.075 260.757; 14.816 11.811 15.633; 2.323 2.153 2.315; 3456 3540 3442; 4009 4118 4090; 57664 58432 54848] hptSpeedup(a, b) # => 1.013 ``` This shows that computer B is 1.013x faster than computer A.
HierarchialPerformanceTest
https://github.com/kdrag0n/HierarchialPerformanceTest.jl.git
[ "MIT" ]
0.1.1
a3f7ec76e7632834193e3985728b2c913731424b
code
523
using Ising2D using Documenter makedocs(; modules=[Ising2D], authors="genkuroki <[email protected]> and contributors", repo="https://github.com/genkuroki/Ising2D.jl/blob/{commit}{path}#L{line}", sitename="Ising2D.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://genkuroki.github.io/Ising2D.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/genkuroki/Ising2D.jl", )
Ising2D
https://github.com/genkuroki/Ising2D.jl.git
[ "MIT" ]
0.1.1
a3f7ec76e7632834193e3985728b2c913731424b
code
11662
""" Ising2D is a simple Julia module of 2D Ising model. Benchmark 1: ```julia using Ising2D, BenchmarkTools s = rand_ising2d() print("VERSION = \$VERSION:") @btime ising2d!(\$s; algorithm=IfElse()); ``` Benchmark 2: ```julia using Ising2D, BenchmarkTools s = rand_ising2d() print("VERSION = \$VERSION:") @btime ising2d!(\$s; algorithm=MultiFor()); ``` """ module Ising2D using Plots using Plots.PlotMeasures using Random using Random: default_rng using ProgressMeter export default_rng, β_ising2d, rand_ising2d, ones_ising2d, IfElse, MultiFor, ising2d!, plot_ising2d, gif_ising2d, mcmc_ising2d!, energy_density_ising2d, magnetization_ising2d, plot_mcmc_ising2d, histogram_mcmc_ising2d, gif_mcmc_ising2d """ β_ising2d = log(1 + √2)/2 is the critical inverse temperature of 2D Ising model on the square lattice. """ const β_ising2d = log(1 + √2)/2 """ rand_ising2d(rng::AbstractRNG, m=100, n=m) rand_ising2d(m=100, n=m) generate the random state of 2D Ising model. """ rand_ising2d(rng::AbstractRNG, m=100, n=m) = rand(rng, Int8[-1, 1], m, n) rand_ising2d(m=100, n=m) = rand(Int8[-1, 1], m, n) """ ones_ising2d(m=100, n=m) generates the all-one state of 2D Ising model. """ ones_ising2d(m=100, n=m) = ones(Int8, m, n) """ `IfElse()` = Algorithm using ifelse """ struct IfElse end """ `MultiFor()` = Algorithm using multiple for-loops """ struct MultiFor end """ `default_algorithm() = MultiFor()` """ default_algorithm() = MultiFor() """ ising2d!(s=rand_ising2d(), β=β_ising2d, niters=10^3, rng=default_rng(); algorithm=default_algorithm()) updates the 2-dimensional array `s` with values ±1 randomly by 2D Ising model rule. Example 1: ```julia using Ising2D @time s = ising2d!(rand_ising2d(), β_ising2d, 10^5) plot_ising2d(s) ``` Example 2: ```julia using Ising2D @time s = ising2d!(rand_ising2d(), β_ising2d, 10^5; algorithm=IfElse()) plot_ising2d(s) ``` """ function ising2d!(s=rand_ising2d(), β=β_ising2d, niters=10^3, rng=default_rng(); algorithm=default_algorithm()) ising2d!(algorithm, s, β, niters, rng) end """ ising2d!(::IfElse, s=rand_ising2d(), β=β_ising2d, niters=10^3, rng=default_rng()) uses the algorithm using ifelse in only one for-loop. Example: ```julia s = ones_ising2d() ising2d!(IfElse(), s) plot_ising2d(s) ``` """ function ising2d!(::IfElse, s=rand_ising2d(), β=β_ising2d, niters=10^3, rng=default_rng()) m, n = size(s) prob = [exp(-2*β*k) for k in -4:4] @inbounds for iter in 1:niters, j in 1:n, i in 1:m NN = s[ifelse(i == 1, m, i-1), j] SS = s[ifelse(i == m, 1, i+1), j] WW = s[i, ifelse(j == 1, n, j-1)] EE = s[i, ifelse(j == n, 1, j+1)] CT = s[i, j] k = CT * (NN + SS + WW + EE) s[i,j] = ifelse(rand(rng) < prob[k+5], -CT, CT) end s end """ ising2d!(::MultiFor, s=rand_ising2d(), β=β_ising2d, niters=10^3, rng=default_rng()) uses the algorithm using multiple for-loops. Example: ```julia s = ones_ising2d() ising2d!(MultiFor(), s) plot_ising2d(s) ``` """ function ising2d!(::MultiFor, s=rand_ising2d(), β=β_ising2d, niters=10^3, rng=default_rng()) m, n = size(s) prob = [exp(-2*β*r) for r in -4:4] @inbounds for iter in 1:niters let s₁ = s[1,1], k = s₁ * (s[2,1] + s[m,1] + s[1,2] + s[1,n]) s[1,1] = ifelse(rand(rng) < prob[k+5], -s₁, s₁) end for i in 2:m-1 let s₁ = s[i,1], k = s₁ * (s[i+1,1] + s[i-1,1] + s[i,2] + s[i,n]) s[i,1] = ifelse(rand(rng) < prob[k+5], -s₁, s₁) end end let s₁ = s[m,1], k = s₁ * (s[1,1] + s[m-1,1] + s[m,2] + s[m,n]) s[m,1] = ifelse(rand(rng) < prob[k+5], -s₁, s₁) end for j in 2:n-1 let s₁ = s[1,j], k = s₁ * (s[2,j] + s[m,j] + s[1,j+1] + s[1,j-1]) s[1,j] = ifelse(rand(rng) < prob[k+5], -s₁, s₁) end for i in 2:m-1 let s₁ = s[i,j], k = s₁ * (s[i+1,j] + s[i-1,j] + s[i,j+1] + s[i,j-1]) s[i,j] = ifelse(rand(rng) < prob[k+5], -s₁, s₁) end end let s₁ = s[m,j], k = s₁ * (s[1,j] + s[m-1,j] + s[m,j+1] + s[m,j-1]) s[m,j] = ifelse(rand(rng) < prob[k+5], -s₁, s₁) end end let s₁ = s[1,n], k = s₁ * (s[2,n] + s[m,n] + s[1,1] + s[1,n-1]) s[1,n] = ifelse(rand(rng) < prob[k+5], -s₁, s₁) end for i in 2:m-1 let s₁ = s[i,n], k = s₁ * (s[i+1,n] + s[i-1,n] + s[i,1] + s[i,n-1]) s[i,n] = ifelse(rand(rng) < prob[k+5], -s₁, s₁) end end let s₁ = s[m,n], k = s₁ * (s[1,n] + s[m-1,n] + s[m,1] + s[m,n-1]) s[m,n] = ifelse(rand(rng) < prob[k+5], -s₁, s₁) end end s end """ plot_ising2d(s; size=(201.5, 201.5), color=:gist_earth, clim=(-2, 1.1), kwargs...) plots the state `s` of 2D Ising model. """ function plot_ising2d(s; size=(201.5, 201.5), color=:gist_earth, clim=(-2, 1.1), kwargs...) heatmap(s; size=size, color=color, clim=clim, colorbar = false, axis = false, leftmargin = -20mm, rightmargin = -20mm, top_margin = -2mm, bottom_margin = -20mm, titlefontsize = 8 ) plot!(; kwargs...) end """ gif_ising2d(; s=rand_ising2d(), k=1.0, β=k*β_ising2d, rng=default_rng(), algorithm=default_algorithm(), progress=true, nwarmups=0, nskips=10, niters=100, gifname="ising2d.gif", fps=10, size=(201.5, 217.5), color=:gist_earth, clim=(-2, 1.1), kwargs... ) creates the gif animation of 2D Ising model. Example: To create a 200x200 GIF animation, run ```julia gif_ising2d(s=rand_ising2d(200)) ``` """ function gif_ising2d(; s=rand_ising2d(), k=1.0, β=k*β_ising2d, rng=default_rng(), algorithm=default_algorithm(), progress=true, nwarmups=0, nskips=10, niters=100, gifname="ising2d.gif", fps=10, size=(201.5, 217.5), color=:gist_earth, clim=(-2, 1.1), kwargs... ) ising2d!(algorithm, s, β, nwarmups, rng) progress && (prog = Progress(niters, 0)) anim = @animate for t in 0:niters iszero(t) || ising2d!(algorithm, s, β, nskips, rng) title="β=$(round(β/β_ising2d, digits=4))β_c, t=$t" plot_ising2d(s; size=size, color=color, clim=clim, title=title, kwargs...) progress && next!(prog) end gif(anim, gifname; fps=fps) end """ mcmc_ising2d!(; s=rand_ising2d(), k=1.0, β=k*β_ising2d, rng=default_rng(), algorithm=default_algorithm(), progress=true, nwarmups=1000, nskips=100, niters=5000 ) returns the result of the Markov Chain Monte Carlo simulation with length niters, which is the array of the states of 2D Ising model. """ function mcmc_ising2d!(; s=rand_ising2d(), k=1.0, β=k*β_ising2d, rng=default_rng(), algorithm=default_algorithm(), progress=true, nwarmups=1000, nskips=100, niters=5000 ) S = Array{typeof(s), 1}(undef, niters) ising2d!(algorithm, s, β, nwarmups, rng) progress && (prog = Progress(niters, 1, "mcmc_ising2d!: ")) for i in 1:niters ising2d!(algorithm, s, β, nskips, rng) S[i] = copy(s) progress && next!(prog) end S end """ energy_ising2d(s) returns the energy density (energy per site) of the state `s` of 2D Ising model. """ function energy_density_ising2d(s) m, n = size(s) E = 0.0 @inbounds begin for j in 1:n, i in 1:m-1 E -= s[i,j]*s[i+1,j] end for j in 1:n E -= s[m,j]*s[1,j] end for j in 1:n-1, i in 1:m E -= s[i,j]*s[i,j+1] end for i in 1:m E -= s[i,m]*s[i,1] end end E/(m*n) end """ magnetization_ising2d(s) returns the magnetization of the state `s` of 2D Ising model. """ function magnetization_ising2d(s) m, n = size(s) sum(s)/(m*n) end """ plot_mcmc_ising2d(S, E=nothing, M=nothing; k=1.0, β=k*β_ising2d, niters=length(S), t=niters, ylim_E=(-1.50, -1.35), ylim_M=(-0.75, 0.75), lw=0.5, alpha=0.8, size=(600, 300), color=:gist_earth, clim=(-2, 1.1), kwargs... ) plots the MCMC result S with energy per site and magnetization. """ function plot_mcmc_ising2d(S, E=nothing, M=nothing; k=1.0, β=k*β_ising2d, niters=length(S), t=niters, ylim_E=(-1.55, -1.3), ylim_M=(-0.8, 0.8), lw=0.5, alpha=0.8, size=(600, 300), color=:gist_earth, clim=(-2, 1.1), kwargs... ) if isnothing(E) E = energy_density_ising2d.(S) end if isnothing(M) M = magnetization_ising2d.(S) end title="β=$(round(β/β_ising2d, digits=4))β_c, t=$t" P1 = heatmap(S[t]; color=color, clim=clim, colorbar=false, axis=false, title=title) P2 = plot(@view(E[1:t]); xlim=(1, niters), ylim=ylim_E, lw=lw, alpha=alpha, title="energy per site") P3 = plot(@view(M[1:t]); xlim=(1, niters), ylim=ylim_M, lw=lw, alpha=alpha, title="magnetization") plot(P1, P2, P3; size=size, legend=false, titlefontsize=10, layout=@layout([a [b; c]])) plot!(; kwargs...) end """ histogram_mcmc_ising2d(S, E=nothing, M=nothing; niters=length(S), bin=min(100, max(10, round(Int, 1.2*√niters))), size=(600, 200), kwargs... ) plots the histogram of energy per site and magnetization of the MCMC result S. """ function histogram_mcmc_ising2d(S, E=nothing, M=nothing; niters=length(S), bin=min(100, max(10, round(Int, 1.2*√niters))), size=(600, 200), kwargs... ) if isnothing(E) E = energy_density_ising2d.(S) end if isnothing(M) M = magnetization_ising2d.(S) end P1 = histogram(E; norm=true, bin=bin, alpha=0.3, title="energy per site") P2 = histogram(M; norm=true, bin=bin, alpha=0.3, title="magnetization") plot(P1, P2; size=size, legend=false, titlefontsize=10) plot!(; kwargs...) end """ gif_mcmc_ising2d(S=nothing, E=nothing, M=nothing; s=rand_ising2d(), k=1.0, β=k*β_ising2d, rng=default_rng(), algorithm=default_algorithm(), progress=true, nwarmups=1000, nskips=1000, niters=500, ylim_E=(-1.55, -1.30), ylim_M=(-0.8, 0.8), lw=1.0, alpha=0.8, gifname="ising2d_mcmc.gif", fps=10, size=(600, 300), color=:gist_earth, clim=(-2, 1.1), kwargs... ) creates the gif animation of 2D Ising model with energy per site and magnetization. Example: ``` gif_mcmc_ising2d() ``` """ function gif_mcmc_ising2d(S=nothing, E=nothing, M=nothing; s=rand_ising2d(), k=1.0, β=k*β_ising2d, rng=default_rng(), algorithm=default_algorithm(), progress=true, nwarmups=1000, nskips=1000, niters=500, ylim_E=(-1.55, -1.30), ylim_M=(-0.8, 0.8), lw=1.0, alpha=0.8, gifname="ising2d_mcmc.gif", fps=10, size=(600, 300), color=:gist_earth, clim=(-2, 1.1), kwargs... ) if isnothing(S) S = mcmc_ising2d!(; s=s, k=k, β=β, rng=rng, algorithm=algorithm, progress=progress, nwarmups=nwarmups, nskips=nskips, niters=niters) else niters = length(S) end if isnothing(E) E = energy_density_ising2d.(S) end if isnothing(M) M = magnetization_ising2d.(S) end progress && (prog = Progress(niters, 1, "@animate for: ")) anim = @animate for t in 1:niters plot_mcmc_ising2d(S, E, M; k=k, β=β, t=t, ylim_E=ylim_E, ylim_M=ylim_M, lw=lw, alpha=alpha, size=size, color=color, clim=clim, kwargs... ) progress && next!(prog) end gif(anim, gifname; fps=fps) end end # module
Ising2D
https://github.com/genkuroki/Ising2D.jl.git
[ "MIT" ]
0.1.1
a3f7ec76e7632834193e3985728b2c913731424b
code
628
using Ising2D using Random: seed! using Test @testset "Ising2D.jl" begin N = 100 seed!(4649373) S_ifelse = [ising2d!(IfElse(), rand_ising2d(), β_ising2d, 100) for _ in 1:N] @test abs(sum(energy_density_ising2d.(S_ifelse))/N + 1.37) < 0.015 @test abs(sum(abs.(magnetization_ising2d.(S_ifelse)))/N - 0.184) < 0.07 seed!(4649373) S_multifor = [ising2d!(MultiFor(), rand_ising2d(), β_ising2d, 100) for _ in 1:N] @test abs(sum(energy_density_ising2d.(S_multifor))/N + 1.37) < 0.015 @test abs(sum(abs.(magnetization_ising2d.(S_multifor)))/N - 0.184) < 0.07 @test S_ifelse == S_multifor end
Ising2D
https://github.com/genkuroki/Ising2D.jl.git
[ "MIT" ]
0.1.1
a3f7ec76e7632834193e3985728b2c913731424b
docs
1258
# Ising2D.jl - Julia package of the 2D Ising model <!-- [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://genkuroki.github.io/Ising2D.jl/stable) --> [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://genkuroki.github.io/Ising2D.jl/dev) [![Build Status](https://travis-ci.com/genkuroki/Ising2D.jl.svg?branch=master)](https://travis-ci.com/genkuroki/Ising2D.jl) ## Install ``` julia> ] pkg> add Ising2D#master ``` ``` julia> ] pkg> add https://github.com/genkuroki/Ising2D.jl ``` ## Example Jupyter notebook: [Ising2D.ipynb](https://nbviewer.jupyter.org/github/genkuroki/Ising2D.jl/blob/master/Ising2D.ipynb) ```julia using Ising2D ``` Generate a 100x100 random state of 2D Ising model: ```julia s = rand_ising2d(200) P0 = plot_ising2d(s) ``` <img src="s0.png" /> Update the whole state 500 times: ```julia ising2d!(s, β_ising2d, 500) P1 = plot_ising2d(s) ``` <img src="s1.png" /> Create PNG files: ```julia Ising2D.Plots.png(P0, "s0.png") Ising2D.Plots.png(P1, "s1.png") ``` Create the GIF animation of 2D Ising model: ```julia s = rand_ising2d(200) gif_ising2d(s, 1.0; nwarmups=0, nskips=1, nframes=500, fps=15) ``` <img src="ising2d.gif" /> ```julia gif_mcmc_ising2d() ``` <img src="ising2d_mcmc.gif" />
Ising2D
https://github.com/genkuroki/Ising2D.jl.git
[ "MIT" ]
0.1.1
a3f7ec76e7632834193e3985728b2c913731424b
docs
1152
# Ising2D.jl - Julia package of the 2D Ising model <!-- [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://genkuroki.github.io/Ising2D.jl/stable) --> [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://genkuroki.github.io/Ising2D.jl/dev) [![Build Status](https://travis-ci.com/genkuroki/Ising2D.jl.svg?branch=master)](https://travis-ci.com/genkuroki/Ising2D.jl) ## Install ``` julia> ] pkg> add https://github.com/genkuroki/Ising2D.jl ``` ## Example Jupyter notebook: [Ising2D.ipynb](https://nbviewer.jupyter.org/github/genkuroki/Ising2D.jl/blob/master/Ising2D.ipynb) ```julia using Ising2D ``` Generate a 100x100 random state of 2D Ising model: ```julia s = rand_ising2d(200) P0 = plot_ising2d(s) ``` <img src="s0.png" /> Update the whole state 500 times: ```julia ising2d!(s, β_ising2d, 500) P1 = plot_ising2d(s) ``` <img src="s1.png" /> Create PNG files: ```julia Ising2D.Plots.png(P0, "s0.png") Ising2D.Plots.png(P1, "s1.png") ``` Create the GIF animation of 2D Ising model: ```julia s = rand_ising2d(200) gif_ising2d(s, 1.0; nwarmups=0, nskips=1, nframes=500, fps=15) ``` <img src="ising2d.gif" />
Ising2D
https://github.com/genkuroki/Ising2D.jl.git
[ "MIT" ]
0.1.1
a3f7ec76e7632834193e3985728b2c913731424b
docs
101
```@meta CurrentModule = Ising2D ``` # Ising2D ```@index ``` ```@autodocs Modules = [Ising2D] ```
Ising2D
https://github.com/genkuroki/Ising2D.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
code
744
using Documenter, DocumenterMarkdown using Literate get_example_path(p) = joinpath(@__DIR__, ".", "examples", p) OUTPUT = joinpath(@__DIR__, "src", "examples", "generated") folders = readdir(joinpath(@__DIR__, ".", "examples")) setdiff!(folders, [".DS_Store"]) function getfiles() srcsfiles = [] for f in folders names = readdir(joinpath(@__DIR__, ".", "examples", f)) setdiff!(names, [".DS_Store"]) fpaths = "$(f)/" .* names srcsfiles = vcat(srcsfiles, fpaths...) end return srcsfiles end srcsfiles = getfiles() for (d, paths) in (("tutorial", srcsfiles),) for p in paths Literate.markdown(get_example_path(p), joinpath(OUTPUT, dirname(p)); documenter=true) end end
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
code
2241
using Documenter, DocumenterVitepress using Tidier, DataFrames, RDatasets DocTestMeta = quote using Tidier, DataFrames, Chain, Statistics end DocMeta.setdocmeta!(Tidier, :DocTestSetup, DocTestMeta; recursive=true ) pgs = [ "Home" => "index.md", "Get Started" => [ "Installation" => "installation.md", "A Simple Data Analysis" => "simple-analysis.md", "From Data to Plots" => "simple-plotting.md" ], # "API Reference" => "reference.md", "Changelog" => "news.md", "FAQ" => "faq.md", # "Contributing" => "contributing.md", ] fmt = DocumenterVitepress.MarkdownVitepress( repo = "https://github.com/TidierOrg/Tidier.jl", devurl = "dev", # deploy_url = "yourgithubusername.github.io/Tidier.jl.jl", ) makedocs(; modules = [Tidier], authors = "Karandeep Singh et al.", repo = "https://github.com/TidierOrg/Tidier.jl", sitename = "Tidier.jl", format = fmt, pages= pgs, warnonly = true, ) deploydocs(; repo = "https://github.com/TidierOrg/Tidier.jl", target="build", # this is where Vitepress stores its output branch = "gh-pages", devbranch = "main", push_preview = true, ) # makedocs( # modules=[Tidier], # clean=true, # doctest=true, # #format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true"), # sitename="Tidier.jl", # authors="Karandeep Singh et al.", # strict=[ # :doctest, # :linkcheck, # :parse_error, # :example_block, # # Other available options are # # :autodocs_block, :cross_references, :docs_block, :eval_block, :example_block, # # :footnote, :meta_block, :missing_docs, :setup_block # ], # checkdocs=:all, # format=Markdown(), # draft=false, # build=joinpath(@__DIR__, "docs") # ) # deploydocs(; repo="https://github.com/TidierOrg/Tidier.jl", push_preview=true, # deps=Deps.pip("mkdocs", "pygments", "python-markdown-math", "mkdocs-material", # "pymdown-extensions", "mkdocstrings", "mknotebooks", # "pytkdocs_tweaks", "mkdocs_include_exclude_files", "jinja2", "mkdocs-video"), # make=() -> run(`mkdocs build`), target="site", devbranch="main")
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
code
1431
# ## Contribute to Documentation # Contributing with examples can be done by first creating a new file example # [here](https://tidierorg.github.io/Tidier.jl/tree/main/docs/examples/UserGuide) # !!! info # - `your_new_file.jl` at `docs/examples/UserGuide/` # Once this is done you need to add a new entry [here](https://tidierorg.github.io/Tidier.jl/blob/main/docs/mkdocs.yml) # at the bottom and the appropriate level. # !!! info # Your new entry should look like: # - `"Your title example" : "examples/generated/UserGuide/your_new_file.md"` # ## Build docs locally # If you want to take a look at the docs locally before doing a PR # follow the next steps: # !!! warning "build docs locally" # Install the following dependencies in your system via pip, i.e. # - `pip install mkdocs pygments python-markdown-math` # - `pip install mkdocs-material pymdown-extensions mkdocstrings` # - `pip mknotebooks pytkdocs_tweaks mkdocs_include_exclude_files jinja2 mkdocs-video` # Then simply go to your `docs` env and activate it, i.e. # `docs> julia` # `julia> ]` # `(docs) pkg> activate .` # Next, run the scripts: # !!! info # Generate files and build docs by running: # - `genfiles.jl` # - `make.jl` # Now go to your `terminal` in the same path `docs>` and run: # `mkdocs serve` # This should output `http://127.0.0.1:8000`, copy/paste this into your # browser and you are all set.
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
code
316
module Tidier export DB using Reexport @reexport using TidierData @reexport using TidierPlots @reexport using TidierCats @reexport using TidierDates @reexport import TidierDB const DB = TidierDB @reexport using TidierFiles @reexport using TidierStrings @reexport using TidierText @reexport using TidierVest end
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
code
162
module TestTidier using Tidier using Test using Documenter # DocMeta.setdocmeta!(Tidier, :DocTestSetup, :(using Tidier); recursive=true) # doctest(Tidier) end
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
docs
29047
# Tidier.jl [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/TidierOrg/Tidier.jl/blob/main/LICENSE) [![Docs: Latest](https://img.shields.io/badge/Docs-Latest-blue.svg)](https://tidierorg.github.io/Tidier.jl/dev) [![Build Status](https://github.com/TidierOrg/Tidier.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/TidierOrg/Tidier.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Downloads](https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/Tidier&label=Downloads)](https://pkgs.genieframework.com?packages=Tidier) <a href="https://github.com/TidierOrg/Tidier.jl"><img src="https://raw.githubusercontent.com/TidierOrg/Tidier.jl/main/docs/src/assets/Tidier_jl_logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://github.com/TidierOrg/Tidier.jl">Tidier.jl</a> Tidier.jl is a data analysis package inspired by R's tidyverse and crafted specifically for Julia. Tidier.jl is a meta-package in that its functionality comes from a series of smaller packages. Installing and using Tidier.jl brings the combined functionality of each of these packages to your fingertips. [[GitHub]](https://github.com/TidierOrg/Tidier.jl) | [[Documentation]](https://tidierorg.github.io/Tidier.jl/dev/) ## Installing Tidier.jl There are 2 ways to install Tidier.jl: using the package console, or using Julia code when you're using the Julia console. You might also see the console referred to as the "REPL," which stands for Read-Evaluate-Print Loop. The REPL is where you can interactively run code and view the output. Julia's REPL is particularly cool because it provides a built-in package REPL and shell REPL, which allow you to take actions on managing packages (in the case of the package REPL) or run shell commands (in the shell REPL) without ever leaving the Julia REPL. To install the stable version of Tidier.jl, you can type the following into the Julia REPL: ``` ]add Tidier ``` The `]` character starts the Julia [package manager](https://docs.julialang.org/en/v1/stdlib/Pkg/). The `add Tidier` command tells the package manager to install the Tidier package from the Julia registry. You can exit the package REPL by pressing the backspace key to return to the Julia prompt. If you already have the Tidier package installed, the `add Tidier` command *will not* update the package. Instead, you can update the package using the the `update Tidier` (or `up Tidier` for short) commnds. As with the `add Tidier` command, make sure you are in the package REPL before you run these package manager commands. If you need to (or prefer to) install packages using Julia code, you can achieve the same outcome using the following code to install Tidier: ```julia import Pkg Pkg.add("Tidier") ``` You can update Tidier.jl using the `Pkg.update()` function, as follows: ```julia import Pkg; Pkg.update("Tidier") ``` Note that while Julia allows you to separate statements by using multiple lines of code, you can also use a semi-colon (`;`) to separate multiple statements. This is convenient for short snippets of code. There's another practical reason to use semi-colons in coding, which is to silence the output of a function call. We will come back to this in the "Getting Started" section below. In general, installing the latest version of the package from the Julia registry should be sufficient because we follow a continuous-release cycle. After every update to the code, we update the version based on the magnitude of the change and then release the latest version to the registry. That's why it's so important to know how to update the package! However, if for some reason you do want to install the package directly from GitHub, you can get the newest version using either the package REPL... ``` ]add Tidier#main ``` ...or using Julia code. ```julia import Pkg; Pkg.add(url="https://github.com/TidierOrg/Tidier.jl") ``` ## Loading Tidier.jl Once you've installed Tidier.jl, you can load it by typing: ```julia using Tidier ``` When you type this command, multiple things happen behind the scenes. First, the following packages are loaded and re-exported, which is to say that all of the exported macros and functions from these packages become available: - TidierData - TidierPlots - TidierCats - TidierDates - TidierStrings - TidierText - TidierVest Don't worry if you don't know what each of these packages does yet. We will cover them in package-specific documentation pages, which can be accessed below. For now, all you need to know is that these smaller packages are actually the ones doing all the work when you use Tidier. There are also a few other packages whose exported functions also become available. We will discuss these in the individual package documentation, but the most important ones for you to know about are: - The `DataFrame()` function from the DataFrames package is re-exported so that you can create a data frame without loading the DataFrames package. - The `@chain()` macro from the Chain package is re-exported, so you chain together functions and macros - The entire Statistics package is re-exported so you can access summary statistics like `mean()` and `median()` - The CategoricalArrays package is re-exported so you can access the `categorical()` function to define categorical variables - The Dates package is re-exported to enable support for variables containing dates ## What can Tidier.jl do? Before we dive into an introduction of Julia and a look into how Tidier.jl works, it's useful to show you what Tidier.jl can do. First, we will read in some data, and then we will use Tidier.jl to chain together some data analysis operations. ### First, let's read in the "Visits to Physician Office" dataset. This dataset comes with the Ecdat R package and and is titled OFP. [You can read more about the dataset here](https://rdrr.io/cran/Ecdat/man/OFP.html). To read in datasets packaged with commonly used R packages, we can use the RDatasets Julia package. ```julia julia> using Tidier, RDatasets julia> ofp = dataset("Ecdat", "OFP") 4406×19 DataFrame Row │ OFP OFNP OPP OPNP EMR Hosp NumChro ⋯ │ Int32 Int32 Int32 Int32 Int32 Int32 Int32 ⋯ ──────┼──────────────────────────────────────────────────── 1 │ 5 0 0 0 0 1 ⋯ 2 │ 1 0 2 0 2 0 3 │ 13 0 0 0 3 3 4 │ 16 0 5 0 1 1 5 │ 3 0 0 0 0 0 ⋯ 6 │ 17 0 0 0 0 0 7 │ 9 0 0 0 0 0 ⋮ │ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋱ 4401 │ 12 4 1 0 0 0 4402 │ 11 0 0 0 0 0 ⋯ 4403 │ 12 0 0 0 0 0 4404 │ 10 0 20 0 1 1 4405 │ 16 1 0 0 0 0 4406 │ 0 0 0 0 0 0 ⋯ 13 columns and 4393 rows omitted ``` Note that a preview of the data frame is automatically printed to the console. The reason this happens is that when you run this code line by line, the output of each line is printed to the console. This is convenient because it saves you from having to directly print the newly created `ofp` to the console in order to get a preview for what it contains. If this code were bundled in a code chunk (such as in a Jupyter notebook), then only the final line of the code chunk would be printed. The exact number of rows and columns that print will depend on the physical size of the REPL window. If you resize the console (e.g., in VS Code), Julia will adjust the number of rows/columns accordingly. If you want to suppress the output, you can add a `;` at the end of this statement, like this: ```julia julia> ofp = dataset("Ecdat", "OFP"); # Nothing prints ``` ### With the OFP dataset loaded, let's ask some basic questions. #### What does the dataset consist of? We can use `@glimpse()` to find out the columns, data types, and peek at the first few values contained within the dataset. ```julia julia> @glimpse(ofp) Rows: 4406 Columns: 19 .OFP Int32 5, 1, 13, 16, 3, 17, 9, 3, 1, 0, 0, 44, 2, 1, 19, .OFNP Int32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, .OPP Int32 0, 2, 0, 5, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, .OPNP Int32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, .EMR Int32 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .Hosp Int32 1, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, .NumChron Int32 2, 2, 4, 2, 2, 5, 0, 0, 0, 0, 1, 5, 1, 1, 1, 0, 1, .AdlDiff Int32 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, .Age Float64 6.9, 7.4, 6.6, 7.6, 7.9, 6.6, 7.5, 8.7, 7.3, 7.8, .Black CategoricalValue{String, UInt8}yes, no, yes, no, no, no, no, no, .Sex CategoricalValue{String, UInt8}male, female, female, male, female .Married CategoricalValue{String, UInt8}yes, yes, no, yes, yes, no, no, no .School Int32 6, 10, 10, 3, 6, 7, 8, 8, 8, 8, 8, 15, 8, 8, 12, 8 .FamInc Float64 2.881, 2.7478, 0.6532, 0.6588, 0.6588, 0.3301, 0.8 .Employed CategoricalValue{String, UInt8}yes, no, no, no, no, no, no, no, n .Privins CategoricalValue{String, UInt8}yes, yes, no, yes, yes, no, yes, y .Medicaid CategoricalValue{String, UInt8}no, no, yes, no, no, yes, no, no, .Region CategoricalValue{String, UInt8}other, other, other, other, other, .Hlth CategoricalValue{String, UInt8}other, other, poor, poor, other, p ``` If you're wondering why we need to place a `@` at the beginning of the word so that it reads `@glimpse()` rather than `glimpse()`, that's because including a `@` at the beginning denotes that this is a special type of function known as a macro. Macros have special capabilities in Julia, and many Tidier.jl functions that operate on data frames are implemented as macros. In this specific instance, we could have implemented `@glimpse()` without making use of any of the macro capabilities. However, for the sake of consistency, we have kept `@glimpse()` as a macro so that you can remember a basic rule of thumb: if Tidier.jl operates on a dataframe, then we will use macros rather than functions. The TidierPlots.jl package is a slight exception to this rule in that it is nearly entirely implemented as functions (rather than macros), and this will be described more in the TidierPlots documentation. #### Can we clean up the names of the columns? To avoid having to keep track of capitalization, data analysts often prefer column names to be in snake_case rather than TitleCase. Let's quickly apply this transformation to the `ofp` dataset. ```julia julia> ofp = @clean_names(ofp) julia> @glimpse(ofp) Rows: 4406 Columns: 19 .ofp Int32 5, 1, 13, 16, 3, 17, 9, 3, 1, 0, 0, 44, 2, 1, 19, .ofnp Int32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, .opp Int32 0, 2, 0, 5, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, .opnp Int32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, .emr Int32 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .hosp Int32 1, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, .num_chron Int32 2, 2, 4, 2, 2, 5, 0, 0, 0, 0, 1, 5, 1, 1, 1, 0, 1, .adl_diff Int32 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, .age Float64 6.9, 7.4, 6.6, 7.6, 7.9, 6.6, 7.5, 8.7, 7.3, 7.8, .black CategoricalValue{String, UInt8}yes, no, yes, no, no, no, no, no, .sex CategoricalValue{String, UInt8}male, female, female, male, female .married CategoricalValue{String, UInt8}yes, yes, no, yes, yes, no, no, no .school Int32 6, 10, 10, 3, 6, 7, 8, 8, 8, 8, 8, 15, 8, 8, 12, 8 .fam_inc Float64 2.881, 2.7478, 0.6532, 0.6588, 0.6588, 0.3301, 0.8 .employed CategoricalValue{String, UInt8}yes, no, no, no, no, no, no, no, n .privins CategoricalValue{String, UInt8}yes, yes, no, yes, yes, no, yes, y .medicaid CategoricalValue{String, UInt8}no, no, yes, no, no, yes, no, no, .region CategoricalValue{String, UInt8}other, other, other, other, other, .hlth CategoricalValue{String, UInt8}other, other, poor, poor, other, p ``` Now that our column names are cleaned up, we can ask some basic analysis questions. #### What is the mean age for people in each of the regions Because age is measured in decades according to the [dataset documentation](https://rdrr.io/cran/Ecdat/man/OFP.html)), we will multiply everyone's age by 10 before we calculate the median. ```julia julia> @chain ofp @group_by(region) @summarize(mean_age = mean(age * 10)) 4×2 DataFrame Row │ region mean_age │ Cat… Float64 ─────┼─────────────────── 1 │ other 73.987 2 │ midwest 74.0769 3 │ noreast 73.9343 4 │ west 74.1165 ``` Overall, the mean age looks pretty similar across regions. The fact that we were able to calculate each region's age also reveals that there are no missing values. Any region containing a missing value would have returned `missing` instead of a number. The `@chain` macro, which is defined in the Chain package and re-exported by Tidier, allows us to pipe together multiple operations sequentially from left to right. In the example above, the `ofp` dataset is being piped into the first argument of the `@group_by()` macro, the result of which is then being piped into the `@summarize()` macro, which is then automatically removing the grouping and returning the result. For grouped data frames, `@summarize()` behaves differently than other Tidier.jl macros: `@summarize()` removes one layer of grouping. Because the data frame was only grouped by one column, the result is no longer grouped. Had we grouped by multiple columns, the result would still be grouped by all but the last column. The other Tidier.jl macros keep the data grouped. Grouped data frames can be ungrouped using `@ungroup()`. If you apply a new `@group_by()` macro to an already-grouped data frame, then the newly specified groups override the old ones. When we use the `@chain` macro, we are taking advantage of the fact that Julia macros can either be called using parentheses syntax, where each argument is separated by a comma, or they can be called with a spaced syntax where no parentheses are used. In the case of Tidier.jl macros, we always use the parentheses syntax, which makes is very easy to use the spaced syntax when working with `@chain`. An alternate way of calling `@chain` using the parentheses syntax is as follows. From a purely stylistic perspective, I don't recommend this because it adds a number of extra characters. However, if you're new to Julia, it's worth knowing about this form so that you realize that there is no magic involved when working with macros. ```julia julia> @chain(ofp, @group_by(region), @summarize(mean_age = mean(age * 10))) 4×2 DataFrame Row │ region mean_age │ Cat… Float64 ─────┼─────────────────── 1 │ other 73.987 2 │ midwest 74.0769 3 │ noreast 73.9343 4 │ west 74.1165 ``` On the other hand, either of these single-line expressions can get quite hard-to-read as more and more expressions are chained together. To make this easier to handle, `@chain` supports multi-line expressions using `begin-end` blocks like this: ```julia julia> @chain ofp begin @group_by(region) @summarize(mean_age = mean(age * 10)) end 4×2 DataFrame Row │ region mean_age │ Cat… Float64 ─────┼─────────────────── 1 │ other 73.987 2 │ midwest 74.0769 3 │ noreast 73.9343 4 │ west 74.1165 ``` This format is convenient for interactive data analysis because you can easily comment out individual operations and view the result. For example, if we wanted to know the mean age for the overall dataset, we could simply comment out the `@group_by()` operation. ```julia julia> @chain ofp begin # @group_by(region) @summarize(mean_age = mean(age * 10)) end 1×1 DataFrame Row │ mean_age │ Float64 ─────┼────────── 1 │ 74.0241 ``` ## Frequently asked questions ### I'm a Julia user. Why should I use Tidier.jl rather than other data analysis packages? While Julia has a number of great data analysis packages, the most mature and idiomatic Julia package for data analysis is DataFrames.jl. Most other data analysis packages in Julia build on top of DataFrames.jl, and Tidier.jl is no exception. DataFrames.jl emphasizes idiomatic Julia code without macros. While it is elegant, it can be verbose because of the need to write out anonymous functions. DataFrames.jl also emphasizes correctness, which means that errors are favored over warnings. For example, grouping by one variable and then subsequently grouping the already-grouped data frame by another variable results in an error in DataFrames.jl. These restrictions, while justified in some instances, can make interactive data analysis feel clunky and slow. A number of macro-based data analysis packages have emerged as extensions of DataFrames.jl to make data analysis syntax less verbose, including DataFramesMeta.jl, Query.jl, and DataFrameMacros.jl. All of these packages have their strengths, and each of these served as an inspiration towards the creation of Tidier.jl. What sets Tidier.jl apart is that it borrows the design of the tried-and-widely-adopted tidyverse and brings it to Julia. Our goal is to make data analysis code as easy and readable as possible. In our view, the reason you should use Tidier.jl is because of the richness, consistency, and thoroughness of the design made possible by bringing together two powerful tools: DataFrames.jl and the tidyverse. In Tidier.jl, nearly every possible transformation on data frames (e.g., aggregating, pivoting, nesting, and joining) can be accomplished using a consistent syntax. While you always have the option to intermix Tidier.jl code with DataFrames.jl code, Tidier.jl strives for completeness -- there should never be a requirement to fall back to DataFrames.jl for any kind of data analysis task. Tidier.jl also focuses on conciseness. This shows up most readily in two ways: the use of bare column names, and an approach to auto-vectorizing code. 1. **Bare column names:** If you are referring to a column named `a`, you can simply refer to it as `a` in Tidier.jl. You are essentially referring to `a` as if it was within an anonymous function, where the variable `a` was mapped to the column `a` in the data frame. If you want to refer to an object `a` that is defined outside of the data frame, then you can write `!!a`, which we refer to as "bang-bang interpolation." This syntax is motivated by the tidyverse, where [the `!!` operator was selected because it is the least-bad "polite fiction" way of representing lazy interpolation](https://adv-r.hadley.nz/quasiquotation.html#the-polite-fiction-of). 2. **Auto-vectorized code:** Most data transformation functions and operators are intended to be used on scalars. However, transformations are usually performed on columns of data (represented as 1-dimensional arrays, or vectors), which means that most functions need to be vectorized, which can get unwieldy and verbose. However, there are functions which operate directly on vectors and thus should not be vectorized when applied to columns (e.g., `mean()` and `median()`). Tidier.jl uses a customizable look-up table to know which functions to vectorize and which ones not to vectorize. This means that you can largely leave code as un-vectorized (i.e., `mean(a + 1)` rather than `mean(a .+ 1)`), and Tidier.jl will correctly infer convert the first code into the second before running it. There are several ways to manually override the defaults. Lastly, the reason you should consider using Tidier.jl is that it brings a consistent syntax not only to data manipulation but also to plotting (by wrapping Makie.jl and AlgebraOfGraphics.jl) and to the handling of categorical variables, strings, and dates. Wherever possible, Tidier.jl uses existing classes rather than defining new ones. As a result, using Tidier.jl should never preclude you from using other Base Julia functions with which you may already be familiar. ### I'm an R user and I'm perfectly happy with the tidyverse. Why should I consider using Tidier.jl? If you're happy with the R tidyverse, then there's no imminent reason to switch to using Tidier.jl. While DataFrames.jl (the package on which TidierData.jl depends) [is faster than R's dplyr and tidyr on benchmarks](https://duckdblabs.github.io/db-benchmark/), there are other faster backends in R that allow for the use of tidyverse syntax with better speed (e.g., dtplyr, tidytable, tidypolars). The primary reason to consider using Tidier.jl is the value proposition of using Julia itself. Julia has many similarities to R (e.g., interactive coding in a console, functional style, multiple dispatch, dynamic data types), but unlike R, Julia is automatically compiled (to LLVM) before it runs. This means that certain compiler optimations, which are normally only possible in more verbose languages like C/C++ become available to Julia. There are a number of situations in R where the end-user is able to write fast R code as a direct result of C++ being used on the backend (e.g., through the use of the Rcpp package). This is why R is sometimes referred to as a glue language -- because it provides a very nice way of glueing together faster C++ code. The main value proposition of Julia is that you can use it as *both* a glue language *and* as a backend language. Tidier.jl embraces the glue language aspect of Julia while relying on packages like DataFrames.jl and Makie.jl on the backend. While Julia has very mature backends, we hope that Tidier.jl demonstrates the value of, and need for, more glue-oriented data analysis packages in Julia. ### Why does Tidier.jl re-export so many packages? Tidier comes with batteries included. If you are using Tidier, you generally won't have to load in other packages for basic data analysis. Tidier is meant for interactive use. You can start your code with `using Tidier` and expect to have what you need at your fingertips. If you are a package developer, then you definitely should consider depending on one of the smaller packages that make up Tidier.jl rather than Tidier itself. For example, if you want to use the categorical variable functions from Tidier, then you should use rely on only TidierCats.jl as a dependency. ### Should I update Tidier.jl or the underlying packages (e.g., TidierPlots.jl) individually? Either approach is okay. For most users, we recommend updating Tidier.jl directly, as this will update the underlying packages up to their latest minor versions (but not necessarily up to their latest patch release). However, if you need access to the latest functionality in the underlying packages, you should feel free to update them directly. We will keep Tidier.jl future-proof to underlying package updates, so this shouldn't cause any problems with Tidier.jl. ### Where can I learn more about the underlying packages that make up Tidier.jl? <a href="https://tidierorg.github.io/TidierData.jl/latest/"><img src="https://raw.githubusercontent.com/TidierOrg/TidierData.jl/main/docs/src/assets/Tidier_jl_logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://tidierorg.github.io/TidierData.jl/latest/">TidierData.jl</a> TidierData.jl is a package dedicated to data transformation and reshaping, powered by DataFrames.jl, ShiftedArrays.jl, and Cleaner.jl. It focuses on functionality within the dplyr, tidyr, and janitor R packages. [[GitHub]](https://github.com/TidierOrg/TidierData.jl) | [[Documentation]](https://tidierorg.github.io/TidierData.jl/latest/) <br><br> <a href="https://tidierorg.github.io/TidierPlots.jl/latest/"><img src="https://raw.githubusercontent.com/TidierOrg/TidierPlots.jl/main/assets/logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://tidierorg.github.io/TidierPlots.jl/latest/">TidierPlots.jl</a> TidierPlots.jl is a package dedicated to plotting, powered by Makie.jl. It focuses on functionality within the ggplot2 R package. [[GitHub]](https://github.com/TidierOrg/TidierPlots.jl) | [[Documentation]](https://tidierorg.github.io/TidierPlots.jl/latest/) <br><br> <a href="https://tidierorg.github.io/TidierDB.jl/latest/"><img src="https://github.com/TidierOrg/TidierDB.jl/raw/main/assets/logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://tidierorg.github.io/TidierDB.jl/latest/">TidierDB.jl</a> TidierDB.jl is a package dedicated to data transformation on databases using syntax similar to TidierData. It focuses on functionality within the dbplyr R package. [[GitHub]](https://github.com/TidierOrg/TidierDB.jl) | [[Documentation]](https://tidierorg.github.io/TidierDB.jl/latest/) <br><br> <a href="https://tidierorg.github.io/TidierFiles.jl/latest/"><img src="https://github.com/TidierOrg/TidierFiles.jl/raw/main/assets/logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://tidierorg.github.io/TidierFiles.jl/latest/">TidierFiles.jl</a> TidierFiles.jl is a package dedicated to reading and writing tabular data. It focuses on functionality within the readr, haven, readxl, and writexl R packages. [[GitHub]](https://github.com/TidierOrg/TidierFiles.jl) | [[Documentation]](https://tidierorg.github.io/TidierFiles.jl/latest/) <br><br> <a href="https://tidierorg.github.io/TidierCats.jl/dev/"><img src="https://raw.githubusercontent.com/TidierOrg/TidierCats.jl/main/docs/src/assets/TidierCats_logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://tidierorg.github.io/TidierCats.jl/dev/">TidierCats.jl</a> TidierCats.jl is a package dedicated to handling categorical variables, powered by CategoricalArrays.jl. It focuses on functionality within the forcats R package. [[GitHub]](https://github.com/TidierOrg/TidierCats.jl) | [[Documentation]](https://tidierorg.github.io/TidierCats.jl/dev/) <br><br> <a href="https://github.com/TidierOrg/TidierDates.jl"><img src="https://raw.githubusercontent.com/TidierOrg/TidierDates.jl/main/docs/src/assets/TidierDates_logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://github.com/TidierOrg/TidierDates.jl">TidierDates.jl</a> TidierDates.jl is a package dedicated to handling dates and times. It focuses on functionality within the lubridate R package. [[GitHub]](https://github.com/TidierOrg/TidierDates.jl) | [[Documentation]](https://tidierorg.github.io/TidierDates.jl/dev/) <br><br> <a href="https://tidierorg.github.io/TidierStrings.jl/dev/"><img src="https://raw.githubusercontent.com/TidierOrg/TidierStrings.jl/main/docs/src/assets/TidierStrings_logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://tidierorg.github.io/TidierStrings.jl/dev/">TidierStrings.jl</a> TidierStrings.jl is a package dedicated to handling strings. It focuses on functionality within the stringr R package. [[GitHub]](https://github.com/TidierOrg/TidierStrings.jl) | [[Documentation]](https://tidierorg.github.io/TidierStrings.jl/dev/) <br><br> <a href="https://github.com/TidierOrg/TidierText.jl"><img src="https://raw.githubusercontent.com/TidierOrg/TidierText.jl/main/docs/src/assets/TidierText_logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://github.com/TidierOrg/TidierText.jl">TidierText.jl</a> TidierText.jl is a package dedicated to handling and tidying text data. It focuses on functionality within the tidytext R package. [[GitHub]](https://github.com/TidierOrg/TidierText.jl) <br><br> <a href="https://github.com/TidierOrg/TidierVest.jl"><img src="https://raw.githubusercontent.com/TidierOrg/TidierVest.jl/main/docs/src/assets/TidierVest_logo.png" align="left" style="padding-right:10px;" width="150"></img></a> ## <a href="https://github.com/TidierOrg/TidierVest.jl">TidierVest.jl</a> TidierVest.jl is a package dedicated to scraping and tidying website data. It focuses on functionality within the rvest R package. [[GitHub]](https://github.com/TidierOrg/TidierVest.jl) <br><br> ## What’s new in the Tidier.jl meta-package? See [NEWS.md](https://github.com/TidierOrg/Tidier.jl/blob/main/NEWS.md) for the latest updates. ## What's missing Is there a tidyverse feature missing that you would like to see in Tidier.jl? Please file a GitHub issue to start a discussion.
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
docs
6987
## Frequently asked questions ### I'm a Julia user. Why should I use Tidier.jl rather than other data analysis packages? While Julia has a number of great data analysis packages, the most mature and idiomatic Julia package for data analysis is DataFrames.jl. Most other data analysis packages in Julia build on top of DataFrames.jl, and Tidier.jl is no exception. DataFrames.jl emphasizes idiomatic Julia code without macros. While it is elegant, it can be verbose because of the need to write out anonymous functions. DataFrames.jl also emphasizes correctness, which means that errors are favored over warnings. For example, grouping by one variable and then subsequently grouping the already-grouped data frame by another variable results in an error in DataFrames.jl. These restrictions, while justified in some instances, can make interactive data analysis feel clunky and slow. A number of macro-based data analysis packages have emerged as extensions of DataFrames.jl to make data analysis syntax less verbose, including DataFramesMeta.jl, Query.jl, and DataFrameMacros.jl. All of these packages have their strengths, and each of these served as an inspiration towards the creation of Tidier.jl. What sets Tidier.jl apart is that it borrows the design of the tried-and-widely-adopted tidyverse and brings it to Julia. Our goal is to make data analysis code as easy and readable as possible. In our view, the reason you should use Tidier.jl is because of the richness, consistency, and thoroughness of the design made possible by bringing together two powerful tools: DataFrames.jl and the tidyverse. In Tidier.jl, nearly every possible transformation on data frames (e.g., aggregating, pivoting, nesting, and joining) can be accomplished using a consistent syntax. While you always have the option to intermix Tidier.jl code with DataFrames.jl code, Tidier.jl strives for completeness -- there should never be a requirement to fall back to DataFrames.jl for any kind of data analysis task. Tidier.jl also focuses on conciseness. This shows up most readily in two ways: the use of bare column names, and an approach to auto-vectorizing code. 1. **Bare column names:** If you are referring to a column named `a`, you can simply refer to it as `a` in Tidier.jl. You are essentially referring to `a` as if it was within an anonymous function, where the variable `a` was mapped to the column `a` in the data frame. If you want to refer to an object `a` that is defined outside of the data frame, then you can write `!!a`, which we refer to as "bang-bang interpolation." This syntax is motivated by the tidyverse, where [the `!!` operator was selected because it is the least-bad "polite fiction" way of representing lazy interpolation](https://adv-r.hadley.nz/quasiquotation.html#the-polite-fiction-of). 2. **Auto-vectorized code:** Most data transformation functions and operators are intended to be used on scalars. However, transformations are usually performed on columns of data (represented as 1-dimensional arrays, or vectors), which means that most functions need to be vectorized, which can get unwieldy and verbose. However, there are functions which operate directly on vectors and thus should not be vectorized when applied to columns (e.g., `mean()` and `median()`). Tidier.jl uses a customizable look-up table to know which functions to vectorize and which ones not to vectorize. This means that you can largely leave code as un-vectorized (i.e., `mean(a + 1)` rather than `mean(a .+ 1)`), and Tidier.jl will correctly infer convert the first code into the second before running it. There are several ways to manually override the defaults. Lastly, the reason you should consider using Tidier.jl is that it brings a consistent syntax not only to data manipulation but also to plotting (by wrapping Makie.jl and AlgebraOfGraphics.jl) and to the handling of categorical variables, strings, and dates. Wherever possible, Tidier.jl uses existing classes rather than defining new ones. As a result, using Tidier.jl should never preclude you from using other Base Julia functions with which you may already be familiar. ### I'm an R user and I'm perfectly happy with the tidyverse. Why should I consider using Tidier.jl? If you're happy with the R tidyverse, then there's no imminent reason to switch to using Tidier.jl. While DataFrames.jl (the package on which TidierData.jl depends) [is faster than R's dplyr and tidyr on benchmarks](https://duckdblabs.github.io/db-benchmark/), there are other faster backends in R that allow for the use of tidyverse syntax with better speed (e.g., dtplyr, tidytable, tidypolars). The primary reason to consider using Tidier.jl is the value proposition of using Julia itself. Julia has many similarities to R (e.g., interactive coding in a console, functional style, multiple dispatch, dynamic data types), but unlike R, Julia is automatically compiled (to LLVM) before it runs. This means that certain compiler optimations, which are normally only possible in more verbose languages like C/C++ become available to Julia. There are a number of situations in R where the end-user is able to write fast R code as a direct result of C++ being used on the backend (e.g., through the use of the Rcpp package). This is why R is sometimes referred to as a glue language -- because it provides a very nice way of glueing together faster C++ code. The main value proposition of Julia is that you can use it as *both* a glue language *and* as a backend language. Tidier.jl embraces the glue language aspect of Julia while relying on packages like DataFrames.jl and Makie.jl on the backend. While Julia has very mature backends, we hope that Tidier.jl demonstrates the value of, and need for, more glue-oriented data analysis packages in Julia. ### Why does Tidier.jl re-export so many packages? Tidier comes with batteries included. If you are using Tidier, you generally won't have to load in other packages for basic data analysis. Tidier is meant for interactive use. You can start your code with `using Tidier` and expect to have what you need at your fingertips. If you are a package developer, then you definitely should consider depending on one of the smaller packages that make up Tidier.jl rather than Tidier itself. For example, if you want to use the categorical variable functions from Tidier, then you should use rely on only TidierCats.jl as a dependency. ### Should I update Tidier.jl or the underlying packages (e.g., TidierPlots.jl) individually? Either approach is okay. For most users, we recommend updating Tidier.jl directly, as this will update the underlying packages up to their latest minor versions (but not necessarily up to their latest patch release). However, if you need access to the latest functionality in the underlying packages, you should feel free to update them directly. We will keep Tidier.jl future-proof to underlying package updates, so this shouldn't cause any problems with Tidier.jl.
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
docs
4478
```@raw html --- # https://vitepress.dev/reference/default-theme-home-page layout: home hero: name: "Tidier.jl" tagline: Tidier.jl is a data analysis package inspired by R's tidyverse and crafted specifically for Julia. image: src: /Tidier_jl_logo.png actions: - theme: brand text: Get Started link: installation.md - theme: alt text: View on GitHub link: https://github.com/TidierOrg/Tidier.jl features: - icon: <img width="200" height="200" src="https://github.com/TidierOrg/TidierData.jl/raw/main/docs/src/assets/Tidier_jl_logo.png" alt="tidierdata"/> title: TidierData.jl details: "TidierData.jl is a 100% Julia implementation of the dplyr and tidyr R packages. Powered by the DataFrames.jl package and Julia’s extensive meta-programming capabilities, TidierData.jl is an R user’s love letter to data analysis in Julia." link: https://tidierorg.github.io/TidierData.jl/latest/ - icon: <img width="200" height="200" src="https://github.com/TidierOrg/TidierPlots.jl/raw/main/assets/logo.png" alt="tidierplots"/> title: TidierPlots.jl details: "TidierPlots.jl is a 100% Julia implementation of the R package ggplot in Julia. Powered by Makie.jl, and Julia’s extensive meta-programming capabilities, TidierPlots.jl is an R user’s love letter to data visualization in Julia." link: https://tidierorg.github.io/TidierPlots.jl/latest/ - icon: <img width="200" height="200" src="https://github.com/TidierOrg/TidierDB.jl/raw/main/assets/logo.png" alt="tidierdb"/> title: TidierDB.jl details: "TidierDB.jl is a 100% Julia implementation of the R package dbplyr in Julia and similar to Python's ibis package. Its main goal is to bring the syntax of Tidier.jl to multiple SQL backends, making it possible to analyze data directly on databases without needing to copy the entire database into memory." link: https://tidierorg.github.io/TidierDB.jl/latest/ - icon: <img width="200" height="200" src="https://github.com/TidierOrg/TidierFiles.jl/raw/main/assets/logo.png" alt="tidierfiles"/> title: TidierFiles.jl details: "TidierFiles.jl leverages the CSV.jl, XLSX.jl, and ReadStatTables.jl packages to reimplement the R haven and readr packages." link: https://tidierorg.github.io/TidierFiles.jl/latest/ - icon: <img width="200" height="200" src="https://github.com/TidierOrg/TidierCats.jl/raw/main/docs/src/assets/TidierCats_logo.png" alt="tidiercats"/> title: TidierCats.jl details: "TidierCats.jl is a 100% Julia implementation of the R package forcats in Julia. It has one main goal: to implement forcats's straightforward syntax and of ease of use while working with categorical variables for Julia users." link: https://tidierorg.github.io/TidierCats.jl/dev/ - icon: <img width="200" height="200" src="https://github.com/TidierOrg/TidierDates.jl/raw/main/docs/src/assets/TidierDates_logo.png" alt="tidierdates"/> title: TidierDates.jl details: "TidierDates.jl is a 100% Julia implementation of the R package lubridate in Julia. It has one main goal: to implement lubridate's straightforward syntax and of ease of use while working with dates for Julia users." link: https://tidierorg.github.io/TidierDates.jl/dev/ - icon: <img width="200" height="200" src="https://github.com/TidierOrg/TidierStrings.jl/raw/main/docs/src/assets/TidierStrings_logo.png" alt="tidierstrings"/> title: TidierStrings.jl details: "TidierStrings.jl is a 100% Julia implementation of the R package stringr in Julia. It has one main goal: to implement stringr's straightforward syntax and of ease of use while working with strings for Julia users." link: https://tidierorg.github.io/TidierStrings.jl/dev/ - icon: <img width="200" height="200" src="https://raw.githubusercontent.com/TidierOrg/TidierText.jl/main/docs/src/assets/TidierText_logo.png" alt="tidiertext"/> title: TidierText.jl details: "TidierText.jl is a 100% Julia implementation of the R tidytext package. The purpose of the package is to make it easy analyze text data using DataFrames." link: https://github.com/TidierOrg/TidierText.jl - icon: <img width="200" height="200" src="https://github.com/TidierOrg/TidierVest.jl/raw/main/docs/src/assets/TidierVest_logo.png" alt="tidierstrings"/> title: TidierVest.jl details: "This library combines HTTP, Gumbo and Cascadia for a more simple way to scrape data" link: https://github.com/TidierOrg/TidierVest.jl --- ```
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
docs
2677
# Installation ## Installing Tidier.jl There are 2 ways to install Tidier.jl: using the package console, or using Julia code when you're using the Julia console. You might also see the console referred to as the "REPL," which stands for Read-Evaluate-Print Loop. The REPL is where you can interactively run code and view the output. Julia's REPL is particularly cool because it provides a built-in package REPL and shell REPL, which allow you to take actions on managing packages (in the case of the package REPL) or run shell commands (in the shell REPL) without ever leaving the Julia REPL. To install the stable version of Tidier.jl, you can type the following into the Julia REPL: ```julia ]add Tidier ``` The `]` character starts the Julia [package manager](https://docs.julialang.org/en/v1/stdlib/Pkg/). The `add Tidier` command tells the package manager to install the Tidier package from the Julia registry. You can exit the package REPL by pressing the backspace key to return to the Julia prompt. If you already have the Tidier package installed, the `add Tidier` command *will not* update the package. Instead, you can update the package using the the `update Tidier` (or `up Tidier` for short) commnds. As with the `add Tidier` command, make sure you are in the package REPL before you run these package manager commands. If you need to (or prefer to) install packages using Julia code, you can achieve the same outcome using the following code to install Tidier: ```julia import Pkg Pkg.add("Tidier") ``` You can update Tidier.jl using the `Pkg.update()` function, as follows: ```julia import Pkg; Pkg.update("Tidier") ``` Note that while Julia allows you to separate statements by using multiple lines of code, you can also use a semi-colon (`;`) to separate multiple statements. This is convenient for short snippets of code. There's another practical reason to use semi-colons in coding, which is to silence the output of a function call. We will come back to this in the "Getting Started" section below. In general, installing the latest version of the package from the Julia registry should be sufficient because we follow a continuous-release cycle. After every update to the code, we update the version based on the magnitude of the change and then release the latest version to the registry. That's why it's so important to know how to update the package! However, if for some reason you do want to install the package directly from GitHub, you can get the newest version using either the package REPL... ```julia ]add Tidier#main ``` ...or using Julia code. ```julia import Pkg; Pkg.add(url="https://github.com/TidierOrg/Tidier.jl") ```
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
docs
8166
# Tidier.jl updates ## v1.4.0 - 2024-04-19 - Add and re-export TidierDB.jl as DB - Add and re-export TidierFiles.jl ## v1.3.0 - 2024-04-09 - Update minimum Julia required version to 1.9 - Base package version updates - New documentation ## v1.2.1 - 2024-01-02 - Base package version updates ## v1.2.0 - 2023-11-28 - Add and re-export TidierText.jl - Bugfix: Re-export TidierVest.jl (forgot to do this in 1.1.0) ## v1.1.0 - 2023-11-18 - Update versions of base packages - Add TidierVest.jl ## v1.0.0 - 2023-08-07 - Convert Tidier.jl to a meta-package that only re-exports other Tidier packages ## v0.7.7 - 2023-07-15 - Added documentation on how to interpolate variables inside of `for` loops. Note: `!!` interpolation doesn't work inside of `for` loops because macros are expanded during parsing and not at runtime. - Fixed bug in `parse_pivot_arg()` to enable interpolation inside of pivoting functions when used inside a `for` loop. - Added `cumsum()`, `cumprod()`, and `accumulate()` to the do-not-vectorize list. ## v0.7.6 - 2023-05-04 - Fixed bug to allow multiple columns in `@distinct()` separated by commas or using selection helpers. ## v0.7.5 - 2023-04-30 - Fixed bug to ensure that `&&` and `||` are auto-vectorized - Added docstrings and examples to show different ways of filtering by multiple "and" conditions, including `&&`, `&`, and separating multiple expressions with commas. ## v0.7.4 - 2023-04-11 - Added `as_float()`, `as_integer()`, and `as_string()` ## v0.7.3 - 2023-04-10 - Added `@glimpse()` ## v0.7.2 - 2023-04-05 - Moved repo to TidierOrg ## v0.7.1 - 2023-04-01 - Added `@drop_na()` with optional column selection parameter - Re-exported `lead()` and `lag()` from ShiftedArrays.jl and added both to the do-not-vectorize list - Bug fix: Fixed `ntile()` condition for when all elements are missing ## v0.7.0 - 2023-03-27 - Added `@count()` and `@tally()` - Added `@bind_rows()` and `@bind_cols()` - Added `@clean_names()` to mimic R's `janitor::clean_names()` by wrapping the Cleaner.jl package - Added support for backticks to select columns containing spaces. - Added support for `ntile()`, which is on the do-not-vectorize list because it takes in a vector and returns a vector. - Bug fix: removed selection helpers (`startswith`, `contains`, and `endswith` from the do-not-vectorize list). ## v0.6.0 - 2023-03-18 - Added `@distinct()`. It behaves slightly differently from dplyr when provided arguments in that it returns all columns, not just the selected ones. - Added support for `n()` and `row_number()`. - Added support for negative selection helper functions (e.g., `-contains("a")`). - Added support for negative selection using `!` (e.g., `!a`, `!(a:b)`, `!contains("a")`). - In `@pivot_longer()`, the `names_to` and `values_to` arguments now also support strings (in addition to bare unquoted names). - In `@pivot_wider()`, the `names_from` and `values_from` arguments now also support strings (in addition to bare unquoted names). - Bug fix: `@mutate(a = 1)` or any scalar previously errored because the `1` was being wrapped inside a `QuoteNode`. Now, 1 is correctly broadcasted. - Bug fix: `@slice(df, 1,2,1)` previously only returned rows 1 and 2 only (and not 1 again). `@slice(df, 1,2,1)` now returns rows 1, 2, and 1 again. - Bug fix: added `repeat()` to the do-not-vectorize list. ## v0.5.0 - 2023-03-10 - Added `@pivot_wider()` and `@pivot_wider()`. - Added `if_else()` and `case_when()`. - Updated documentation to include `Main.variable` example as an alternative syntax for interpolation. - Simplified internal use of `subset()` by using keyword argument of `skipmissing = true` instead of using `coalesce(..., false)`. - For developers: doctests can now be run locally using `runtests.jl`. ## v0.4.1 - 2023-03-05 - In addition to `in` being auto-vectorized as before, the second argument is automatically wrapped inside of `Ref(Set(arg2))` if not already done to ensure that it is evaluated correctly and fast. See: https://bkamins.github.io/julialang/2023/02/10/in.html for details. This same behavior is also implemented for `∈` and `∉`. - Added documentation and docstrings for new `in` behavior with `@filter()` and `@mutate()`. - Improved interpolation to support values and not just column names. Note: there is a change of behavior now for strings, which are treated as values and not as column names. Updated examples in the documentation webpage for interpolation. - Bug fix: Re-exported `Cols()` because this is required for interpolated columns inside of `across()`. Previously, this was passing tests because `using RDatasets` was exporting `Cols()`. ## v0.4.0 - 2023-02-29 - Rewrote the parsing engine to remove all regular expression and string parsing - Selection helpers now work within both `@select()` and `across()`. - `@group_by()` now sorts the groups (similar to `dplyr`) and supports tidy expressions, for example `@group_by(df, d = b + c)`. - `@slice()` now supports grouped data frames. For example, `@slice(gdf, 1:2)` will slice the first 2 rows from each group if `gdf` is a grouped data frame. - All functions now work correctly with both grouped and ungrouped data frames following `dplyr` behavior. In other words, all functions retain grouping for grouped data frames (e.g., `ungroup = false`), other than `@summarize()`, which "peels off" one layer of grouping in a similar fashion to `dplyr`. - Added `@ungroup` to explicitly remove grouping - Added `@pull` macro to extract vectors - Added joins: `@left_join()`, `@right_join()`, `@inner_join()`, and `@full_join()`, which support natural joins (i.e., where no `by` argument is given) or explicit joins by providing keys. All join functions ungroup both data frames before joining. - Added `starts_with()` as an alias for Julia's `startswith()`, `ends_with()` as an alias for Julia's `endswith()`, and `matches()` as an alias for Julia's `Regex()`. - Enabled interpolation of global user variables using `!!` similar to R's `rlang`. - Enabled a `~` tilde operator to mark functions (or operators) as unvectorized so that Tidier.jl does not "auto-vectorize" them. - Disabled `@info` logging of generated `DataFrames.jl` code. This code can be shown by setting an option using the new `Tidier_set()` function. - Fixed a bug where functions were evaluated inside the module, which meant that user-provided functions would not work. - `@filter()` now skips rows that evaluate to missing values. - Re-export a handful of functions from the `DataFrames.jl` package. - Added doctests to all examples in the docstrings. ## v0.3.0 - 2023-02-11 - Updated auto-vectorization so that operators are vectorized differently from other types of functions. This leads to nicer printing of the generated DataFrames.jl code. For example, 1 .+ 1 instead of (+).(1,1) - The generated DataFrames.jl code now prints to the screen - Updated the ordering of columns when using `across()` so that each column is summarized in consecutive columns (e.g., `Rating_mean`, `Rating_median`, `Budget_mean`, `Budget_median`) instead of being organized by function (e.g. of prior ordering: `Rating_mean`, `Budget_mean`, `Rating_median`, `Budget_median`) - Added exported functions for `across()` and `desc()` as a placeholder for documentation, though these functions will throw an error if called because they should only be called inside of Tidier macros - Corrected GitHub actions and added tests (contributed by @rdboyes) - Bumped version to 0.3.0 ## v0.2.0 - 2023-02-09 - Fixed bug with `@rename()` so that it supports multiple arguments - Added support for numerical selection (both positive and negative) to `@select()` - Added support for `@slice()`, including positive and negative indexing - Added support for `@arrange()`, including the use of `desc()` to specify descending order - Added support for `across()`, which has been confirmed to work with both `@mutate()`, `@summarize()`, and `@summarise()`. - Updated auto-vectorization so that `@summarize` and `@summarise` do not vectorize any functions - Re-export `Statistics` and `Chain.jl` - Bumped version to 0.2.0 ## v0.1.0 - 2023-02-07 - Initial release, version 0.1.0
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
docs
223
```@meta DocTestSetup= quote using Tidier end ``` ## Reference - Exported functions ```@autodocs Modules = [Tidier] Private = false ``` ## Reference - Internal functions ```@autodocs Modules = [Tidier] Public = false ```
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
docs
12562
# A Simple Data Analysis ## Loading Tidier.jl Once you've installed Tidier.jl, you can load it by typing: ```julia using Tidier ``` When you type this command, multiple things happen behind the scenes. First, the following packages are loaded and re-exported, which is to say that all of the exported macros and functions from these packages become available, TidierData, TidierPlots, TidierCats, TidierDates, TidierStrings, TidierText, TidierVest Don't worry if you don't know what each of these packages does yet. We will cover them in package-specific documentation pages, which can be accessed below. For now, all you need to know is that these smaller packages are actually the ones doing all the work when you use Tidier. There are also a few other packages whose exported functions also become available. We will discuss these in the individual package documentation, but the most important ones for you to know about are: - The `DataFrame()` function from the DataFrames package is re-exported so that you can create a data frame without loading the DataFrames package. - The `@chain()` macro from the Chain package is re-exported, so you chain together functions and macros - The entire Statistics package is re-exported so you can access summary statistics like `mean()` and `median()` - The CategoricalArrays package is re-exported so you can access the `categorical()` function to define categorical variables - The Dates package is re-exported to enable support for variables containing dates ## What can Tidier.jl do? Before we dive into an introduction of Julia and a look into how Tidier.jl works, it's useful to show you what Tidier.jl can do. First, we will read in some data, and then we will use Tidier.jl to chain together some data analysis operations. ### First, let's read in the "Visits to Physician Office" dataset. This dataset comes with the Ecdat R package and and is titled OFP. [You can read more about the dataset here](https://rdrr.io/cran/Ecdat/man/OFP.html). To read in datasets packaged with commonly used R packages, we can use the RDatasets Julia package. ```julia julia> using Tidier, RDatasets julia> ofp = dataset("Ecdat", "OFP") 4406×19 DataFrame Row │ OFP OFNP OPP OPNP EMR Hosp NumChro ⋯ │ Int32 Int32 Int32 Int32 Int32 Int32 Int32 ⋯ ──────┼──────────────────────────────────────────────────── 1 │ 5 0 0 0 0 1 ⋯ 2 │ 1 0 2 0 2 0 3 │ 13 0 0 0 3 3 4 │ 16 0 5 0 1 1 5 │ 3 0 0 0 0 0 ⋯ 6 │ 17 0 0 0 0 0 7 │ 9 0 0 0 0 0 ⋮ │ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋮ ⋱ 4401 │ 12 4 1 0 0 0 4402 │ 11 0 0 0 0 0 ⋯ 4403 │ 12 0 0 0 0 0 4404 │ 10 0 20 0 1 1 4405 │ 16 1 0 0 0 0 4406 │ 0 0 0 0 0 0 ⋯ 13 columns and 4393 rows omitted ``` Note that a preview of the data frame is automatically printed to the console. The reason this happens is that when you run this code line by line, the output of each line is printed to the console. This is convenient because it saves you from having to directly print the newly created `ofp` to the console in order to get a preview for what it contains. If this code were bundled in a code chunk (such as in a Jupyter notebook), then only the final line of the code chunk would be printed. The exact number of rows and columns that print will depend on the physical size of the REPL window. If you resize the console (e.g., in VS Code), Julia will adjust the number of rows/columns accordingly. If you want to suppress the output, you can add a `;` at the end of this statement, like this: ```julia julia> ofp = dataset("Ecdat", "OFP"); # Nothing prints ``` ### With the OFP dataset loaded, let's ask some basic questions. #### What does the dataset consist of? We can use `@glimpse()` to find out the columns, data types, and peek at the first few values contained within the dataset. ```julia julia> @glimpse(ofp) Rows: 4406 Columns: 19 .OFP Int32 5, 1, 13, 16, 3, 17, 9, 3, 1, 0, 0, 44, 2, 1, 19, .OFNP Int32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, .OPP Int32 0, 2, 0, 5, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, .OPNP Int32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, .EMR Int32 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .Hosp Int32 1, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, .NumChron Int32 2, 2, 4, 2, 2, 5, 0, 0, 0, 0, 1, 5, 1, 1, 1, 0, 1, .AdlDiff Int32 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, .Age Float64 6.9, 7.4, 6.6, 7.6, 7.9, 6.6, 7.5, 8.7, 7.3, 7.8, .Black CategoricalValue{String, UInt8}yes, no, yes, no, no, no, no, no, .Sex CategoricalValue{String, UInt8}male, female, female, male, female .Married CategoricalValue{String, UInt8}yes, yes, no, yes, yes, no, no, no .School Int32 6, 10, 10, 3, 6, 7, 8, 8, 8, 8, 8, 15, 8, 8, 12, 8 .FamInc Float64 2.881, 2.7478, 0.6532, 0.6588, 0.6588, 0.3301, 0.8 .Employed CategoricalValue{String, UInt8}yes, no, no, no, no, no, no, no, n .Privins CategoricalValue{String, UInt8}yes, yes, no, yes, yes, no, yes, y .Medicaid CategoricalValue{String, UInt8}no, no, yes, no, no, yes, no, no, .Region CategoricalValue{String, UInt8}other, other, other, other, other, .Hlth CategoricalValue{String, UInt8}other, other, poor, poor, other, p ``` If you're wondering why we need to place a `@` at the beginning of the word so that it reads `@glimpse()` rather than `glimpse()`, that's because including a `@` at the beginning denotes that this is a special type of function known as a macro. Macros have special capabilities in Julia, and many Tidier.jl functions that operate on data frames are implemented as macros. In this specific instance, we could have implemented `@glimpse()` without making use of any of the macro capabilities. However, for the sake of consistency, we have kept `@glimpse()` as a macro so that you can remember a basic rule of thumb: if Tidier.jl operates on a dataframe, then we will use macros rather than functions. The TidierPlots.jl package is a slight exception to this rule in that it is nearly entirely implemented as functions (rather than macros), and this will be described more in the TidierPlots documentation. #### Can we clean up the names of the columns? To avoid having to keep track of capitalization, data analysts often prefer column names to be in snake_case rather than TitleCase. Let's quickly apply this transformation to the `ofp` dataset. ```julia julia> ofp = @clean_names(ofp) julia> @glimpse(ofp) Rows: 4406 Columns: 19 .ofp Int32 5, 1, 13, 16, 3, 17, 9, 3, 1, 0, 0, 44, 2, 1, 19, .ofnp Int32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, .opp Int32 0, 2, 0, 5, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 1, 0, 0, .opnp Int32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, .emr Int32 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, .hosp Int32 1, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, .num_chron Int32 2, 2, 4, 2, 2, 5, 0, 0, 0, 0, 1, 5, 1, 1, 1, 0, 1, .adl_diff Int32 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, .age Float64 6.9, 7.4, 6.6, 7.6, 7.9, 6.6, 7.5, 8.7, 7.3, 7.8, .black CategoricalValue{String, UInt8}yes, no, yes, no, no, no, no, no, .sex CategoricalValue{String, UInt8}male, female, female, male, female .married CategoricalValue{String, UInt8}yes, yes, no, yes, yes, no, no, no .school Int32 6, 10, 10, 3, 6, 7, 8, 8, 8, 8, 8, 15, 8, 8, 12, 8 .fam_inc Float64 2.881, 2.7478, 0.6532, 0.6588, 0.6588, 0.3301, 0.8 .employed CategoricalValue{String, UInt8}yes, no, no, no, no, no, no, no, n .privins CategoricalValue{String, UInt8}yes, yes, no, yes, yes, no, yes, y .medicaid CategoricalValue{String, UInt8}no, no, yes, no, no, yes, no, no, .region CategoricalValue{String, UInt8}other, other, other, other, other, .hlth CategoricalValue{String, UInt8}other, other, poor, poor, other, p ``` Now that our column names are cleaned up, we can ask some basic analysis questions. #### What is the mean age for people in each of the regions Because age is measured in decades according to the [dataset documentation](https://rdrr.io/cran/Ecdat/man/OFP.html)), we will multiply everyone's age by 10 before we calculate the median. ```julia julia> @chain ofp @group_by(region) @summarize(mean_age = mean(age * 10)) 4×2 DataFrame Row │ region mean_age │ Cat… Float64 ─────┼─────────────────── 1 │ other 73.987 2 │ midwest 74.0769 3 │ noreast 73.9343 4 │ west 74.1165 ``` Overall, the mean age looks pretty similar across regions. The fact that we were able to calculate each region's age also reveals that there are no missing values. Any region containing a missing value would have returned `missing` instead of a number. The `@chain` macro, which is defined in the Chain package and re-exported by Tidier, allows us to pipe together multiple operations sequentially from left to right. In the example above, the `ofp` dataset is being piped into the first argument of the `@group_by()` macro, the result of which is then being piped into the `@summarize()` macro, which is then automatically removing the grouping and returning the result. For grouped data frames, `@summarize()` behaves differently than other Tidier.jl macros: `@summarize()` removes one layer of grouping. Because the data frame was only grouped by one column, the result is no longer grouped. Had we grouped by multiple columns, the result would still be grouped by all but the last column. The other Tidier.jl macros keep the data grouped. Grouped data frames can be ungrouped using `@ungroup()`. If you apply a new `@group_by()` macro to an already-grouped data frame, then the newly specified groups override the old ones. When we use the `@chain` macro, we are taking advantage of the fact that Julia macros can either be called using parentheses syntax, where each argument is separated by a comma, or they can be called with a spaced syntax where no parentheses are used. In the case of Tidier.jl macros, we always use the parentheses syntax, which makes is very easy to use the spaced syntax when working with `@chain`. An alternate way of calling `@chain` using the parentheses syntax is as follows. From a purely stylistic perspective, I don't recommend this because it adds a number of extra characters. However, if you're new to Julia, it's worth knowing about this form so that you realize that there is no magic involved when working with macros. ```julia julia> @chain(ofp, @group_by(region), @summarize(mean_age = mean(age * 10))) 4×2 DataFrame Row │ region mean_age │ Cat… Float64 ─────┼─────────────────── 1 │ other 73.987 2 │ midwest 74.0769 3 │ noreast 73.9343 4 │ west 74.1165 ``` On the other hand, either of these single-line expressions can get quite hard-to-read as more and more expressions are chained together. To make this easier to handle, `@chain` supports multi-line expressions using `begin-end` blocks like this: ```julia julia> @chain ofp begin @group_by(region) @summarize(mean_age = mean(age * 10)) end 4×2 DataFrame Row │ region mean_age │ Cat… Float64 ─────┼─────────────────── 1 │ other 73.987 2 │ midwest 74.0769 3 │ noreast 73.9343 4 │ west 74.1165 ``` This format is convenient for interactive data analysis because you can easily comment out individual operations and view the result. For example, if we wanted to know the mean age for the overall dataset, we could simply comment out the `@group_by()` operation. ```julia julia> @chain ofp begin # @group_by(region) @summarize(mean_age = mean(age * 10)) end 1×1 DataFrame Row │ mean_age │ Float64 ─────┼────────── 1 │ 74.0241 ```
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "MIT" ]
1.4.0
23b118d06bb897dec5c972af0c39458799e8cb52
docs
4214
# From data to plots ## Exploring the penguins data A very well known dataset in the R community is the `palmerpenguins` dataset. It contains data about penguins, including their species and some ecological measurements. Let's load the data and take a look at it. ```julia using Tidier #exports TidierPlots.jl and others using DataFrames using PalmerPenguins penguins = dropmissing(DataFrame(PalmerPenguins.load())); ``` The `penguins` DataFrame contains the following columns (from `TiderData.jl` let us take a glimpse): ```julia @glimpse penguins ``` ``` Rows: 333 Columns: 7 .species InlineStrings.String15Adelie, Adelie, Adelie, Adelie, Adelie, Ade .island InlineStrings.String15Torgersen, Torgersen, Torgersen, Torgersen, .bill_length_mm Float64 39.1, 39.5, 40.3, 36.7, 39.3, 38.9, 39.2, 41.1, 38 .bill_depth_mm Float64 18.7, 17.4, 18.0, 19.3, 20.6, 17.8, 19.6, 17.6, 21 .flipper_length _mmInt64 181, 186, 195, 193, 190, 181, 195, 182, 191, 19 .body_mass_g Int64 3750, 3800, 3250, 3450, 3650, 3625, 4675, 3200, 38 .sex InlineStrings.String7male, female, female, female, male, female, ``` ## A simple `TiderPlots.jl` scatterplot Now the experience to plot using `TidierPlots.jl` will be as seamless as in R. Let's start by plotting the `bill_length_mm` and `bill_depth_mm` columns. ```julia ggplot(penguins, @aes(x=bill_length_mm, y=bill_depth_mm, color = species))+ geom_point() ``` ![A simple scatter plot](figs/scatter.png) This is *not* R code, its pure Julia. And if you are familiar with R, you will find it very similar. The `ggplot` function creates a plot object, and the `geom_point` function adds a scatter layer on top of it. The `@aes` macro is used to map the variables of the `penguins` DataFrame to the aesthetics of the plot. In this case, we are mapping the `bill_length_mm` column to the x-axis, the `bill_depth_mm` column to the y-axis, and the `species` column to the color of the points. The output is a scatter plot of the `bill_length_mm` and `bill_depth_mm` columns, colored by the `species` column. Now, `@aes()` is used to map variables in your data to visual properties (aesthetics) of the plot. These aesthetics can include things like position (x and y coordinates), color, shape, size, etc. Each aesthetic is a way of visualizing a variable or a statistical transformation of a variable. Aesthetics are specified in the form aes(aesthetic = variable), where aesthetic is the name of the aesthetic, and variable is the column name in your data that you want to map to the aesthetic. The variable names do not need to be preceded by a colon. This is the first difference you might encounter when using `TidierPlots.jl`, and the best part is that it also accepts multiple forms for `aes` specification, none of which is exactly the same as ggplot2. Option 1: `@aes` macro, aes as in ggplot2: ```julia @aes(x = x, y = y) ``` Option 2: `@es`: ```julia @es(x = x, y = y) ``` Option 3: `aes` function, julia-style columns: ```julia aes(x = :x, y = :y) ``` Option 4: `aes` function, strings for columns: ```julia aes(x = "x", y = "y") ``` ## Customizing the plot Moving from general rules, to specific plots, let us first explore `geom_point()` `geom_point()` is used to create a scatter plot. It is typically used with aesthetics mapping variables to x and y positions, and optionally to other aesthetics like color, shape, and size. `geom_point()` can be used to visualize the relationship between two continuous variables, or a continuous and a discrete variable. The following visuals features can be changed within geom_point(), shape, size, stroke, strokecolour, and alpha. ```julia ggplot(penguins, @aes(x = bill_length_mm, y = bill_depth_mm, color = species)) + geom_point( size = 20, stroke = 1, strokecolor = "black", alpha = 0.2) + labs(x = "Bill Length (mm)", y = "Bill Width (mm)") + lims(x = c(40, 60), y = c(15, 20)) + theme_minimal() ``` ![Customized scatter plot](figs/customized-scatter.png) To see more about the `TidierPlots.jl` package, you can visit the [documentation](https://tidierorg.github.io/TidierPlots.jl/latest/).
Tidier
https://github.com/TidierOrg/Tidier.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
1865
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. using Behavior: parseonly using Behavior.Gherkin: ParseOptions argslength = length(ARGS) if argslength !== 1 && argslength !== 2 println("Usage: julia parseonly.jl <root-directory> [--experimental]") exit(1) end use_experimental = argslength == 2 && ARGS[2] == "--experimental" parseoptions = ParseOptions(allow_any_step_order=true, use_experimental=use_experimental) results = parseonly(ARGS[1], parseoptions=parseoptions) num_files = length(results) num_success = count(x -> x.success === true, results) if num_success === num_files println("All good!") else num_failed = num_files - num_success println("Files failed parsing:") for rs in results print(rs.filename) if rs.success println(": OK") else if use_experimental println(": NOT OK") println(rs.result) else println() println(" reason: ", rs.result.reason) println(" expected: ", rs.result.expected) println(" actual: ", rs.result.actual) println(" line $(rs.result.linenumber): $(rs.result.line)") end end end println("Parsing failed: ", num_failed) println("Total number of files: ", num_files) end
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
1073
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. using Behavior using Behavior.Gherkin # In case you want a more lenient parser, you can do something like this. # For instance, the below options allows the Given/When/Then steps to be in any order # exitcode = runspec(; parseoptions=ParseOptions(allow_any_step_order=true)) ? 0 : - 1 const use_experimental = length(ARGS) == 1 && ARGS[1] == "--experimental" const options = Gherkin.ParseOptions(use_experimental=use_experimental) exitcode = runspec(parseoptions=options) ? 0 : - 1 exit(exitcode)
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
1067
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. using Behavior: suggestmissingsteps, ParseOptions if length(ARGS) !== 2 && length(ARGS) !== 3 println("Usage: julia suggeststeps.jl <feature file> <steps root path> [--experimental]") exit(1) end featurefile = ARGS[1] stepsrootpath = ARGS[2] const use_experimental = length(ARGS) == 3 && ARGS[3] == "--experimental" parseoptions = ParseOptions(allow_any_step_order=true, use_experimental=use_experimental) suggestmissingsteps(featurefile, stepsrootpath, parseoptions=parseoptions)
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
280
using Documenter, Behavior makedocs( sitename="Behavior", pages = [ "Home" => "index.md", "Usage" => "usage.md", "Tutorial" => "tutorial.md", "Functions" => "functions.md", "Gherkin Experimental" => "gherkin_experimental.md" ])
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
1685
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. using Behavior: @given, @when, @then, @expect @given("that the context variable :x has value 1") do context context[:x] = 1 end @when("the context variable :x is compared with 1") do context v = context[:x] == 1 context[:result] = v end @then("the comparison is true") do context @expect context[:result] end @when("this step fails") do context @expect 1 == 2 end @then("this step is skipped") do context @assert false "This code is never executed, because the previous step failed." end @when("this step throws an exception, the result is \"Unknown exception\"") do context throw(ErrorException("This is an unknown exception")) end # This step is commented to show what happens when a step definition is not found. #@given("a step that has no corresponding step definition in steps/spec.jl") do context # #end @when("it is executed") do context @assert false "This step should be skipped, because the previous failed." end @then("it fails with error \"No matching step\"") do context @assert false "This step should be skipped, because a previous step failed." end
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
1832
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. using Behavior: @given, @when, @then, @expect @given("some precondition which does nothing") do context end @when("we perform a no-op step") do context end @then("the scenario as a whole succeeds") do context end @when("a step has more than one matching step definition") do context end @when("a step has more than one matching step definition") do context end # This demonstrates the use of a String parameter, which will match # more than one step. # NOTE: At the time of writing, only String parameters are supported. # In the near future, one will be able to write {Int} directly, # and the argument `vstr` will be of type `Int` instead. @when("foo is set to value {String}") do context, vstr v = parse(Int, vstr) context[:foo] = v end @then("foo is greater than zero") do context @expect context[:foo] > 0 end @then("foo is less than zero") do context @expect context[:foo] < 0 end @when("we need multiple lines of text") do context docstring = context[:block_text] @expect docstring == """ This is line 1. This is line 2.""" end @then("we can use doc strings like this") do context docstring = context[:block_text] @expect docstring == """ And like this.""" end
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
1299
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Behavior include("Gherkin.jl") include("Selection.jl") "Abstraction for presenting results from scenario steps." abstract type Presenter end "Presenting results from scenario steps as they occur." abstract type RealTimePresenter <: Presenter end include("stepdefinitions.jl") include("exec_env.jl") include("executor.jl") include("asserts.jl") include("presenter.jl") include("terse_presenter.jl") include("result_accumulator.jl") include("engine.jl") include("runner.jl") export @given, @when, @then, @expect, @fail, @beforescenario, @afterscenario, runspec export @beforefeature, @afterfeature, @beforeall, @afterall export suggestmissingsteps export TerseRealTimePresenter, ColorConsolePresenter end # module
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
25891
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Gherkin import Base: ==, hash export Scenario, ScenarioOutline, Feature, FeatureHeader, Given, When, Then, ScenarioStep export parsefeature, hastag, ParseOptions "A step in a Gherkin Scenario." abstract type ScenarioStep end "Equality for scenario steps is their text and their block text." function ==(a::T, b::T) where {T <: ScenarioStep} a.text == b.text && a.block_text == b.block_text end "Hash scenario steps by their text and block text." hash(a::T, h::UInt) where {T <: ScenarioStep} = hash((a.text, a.block_text), h) const DataTableRow = Vector{String} const DataTable = Array{DataTableRow, 1} "A Given scenario step." struct Given <: ScenarioStep text::String block_text::String datatable::DataTable Given(text::AbstractString; block_text = "", datatable=DataTable()) = new(text, block_text, datatable) end "A When scenario step." struct When <: ScenarioStep text::String block_text::String datatable::DataTable When(text::AbstractString; block_text="", datatable=DataTable()) = new(text, block_text, datatable) end "A Then scenario step." struct Then <: ScenarioStep text::String block_text::String datatable::DataTable Then(text::AbstractString; block_text="", datatable=DataTable()) = new(text, block_text, datatable) end "An AbstractScenario is a Scenario or a Scenario Outline in Gherkin." abstract type AbstractScenario end """ A Gherkin Scenario. # Example ``` @tag1 @tag2 Scenario: Some description Given some precondition When some action is taken Then some postcondition holds ``` becomes a `Scenario` struct with description "Some description", tags `["@tag1", "@tag2"]`, and steps ```[ Given("some precondition"), When("some action is taken"), Then("some postcondition holds") ]```. """ struct Scenario <: AbstractScenario description::String tags::Vector{String} steps::Vector{ScenarioStep} long_description::String function Scenario(description::AbstractString, tags::Vector{String}, steps::Vector{ScenarioStep}; long_description::AbstractString = "") new(description, tags, steps, long_description) end end """ A `ScenarioOutline` is a scenario with multiple examples. # Example ``` @tag1 @tag2 Scenario: Some description Given some precondition When some action is taken Then some postcondition holds ``` """ struct ScenarioOutline <: AbstractScenario description::String tags::Vector{String} steps::Vector{ScenarioStep} placeholders::Vector{String} examples::AbstractArray long_description::String function ScenarioOutline( description::AbstractString, tags::Vector{String}, steps::Vector{ScenarioStep}, placeholders::AbstractVector{String}, examples::AbstractArray; long_description::AbstractString = "") new(description, tags, steps, placeholders, examples, long_description) end end struct Background description::String steps::Vector{ScenarioStep} long_description::String Background(description::AbstractString, steps::Vector{ScenarioStep}; long_description::String = "") = new(description, steps, long_description) end Background() = Background("", ScenarioStep[]) """ A FeatureHeader has a (short) description, a longer description, and a list of applicable tags. # Example ``` @tag1 @tag2 Feature: This is a description This is a longer description. ``` """ struct FeatureHeader description::String long_description::Vector{String} tags::Vector{String} end """ A Feature has a feature header and a list of Scenarios and Scenario Outlines. """ struct Feature header::FeatureHeader background::Background scenarios::Vector{AbstractScenario} Feature(header::FeatureHeader, background::Background, scenarios::Vector{<:AbstractScenario}) = new(header, background, scenarios) Feature(header::FeatureHeader, scenarios::Vector{<:AbstractScenario}) = new(header, Background(), scenarios) Feature(feature::Feature, newscenarios::Vector{<:AbstractScenario}) = new(feature.header, feature.background, newscenarios) end """ ParseOptions lets the user control certain behavior of the parser, making it more lenient towards errors. """ struct ParseOptions allow_any_step_order::Bool use_experimental::Bool function ParseOptions(; allow_any_step_order::Bool = false, use_experimental::Bool = false) new(allow_any_step_order, use_experimental) end end """ ByLineParser takes a long text and lets the Gherkin parser work line by line. """ mutable struct ByLineParser current::String rest::Vector{String} isempty::Bool linenumber::Union{Nothing, Int} options::ParseOptions function ByLineParser(text::String, options::ParseOptions = ParseOptions()) lines = split(text, "\n") current = lines[1] rest = lines[2:end] new(current, rest, false, 1, options) end end """ consume!(p::ByLineParser) The current line has been consumed by the Gherkin parser. """ function consume!(p::ByLineParser) if isempty(p.rest) p.current = "" p.isempty = true p.linenumber = nothing else p.current = p.rest[1] p.rest = p.rest[2:end] p.linenumber += 1 end end "A good or bad result when parsing Gherkin." abstract type ParseResult{T} end "A successful parse that results in the expected value." struct OKParseResult{T} <: ParseResult{T} value::T end "An unsuccessful parse that results in an error." struct BadParseResult{T} <: ParseResult{T} reason::Symbol expected::Symbol actual::Symbol linenumber::Union{Nothing, Int} line::String function BadParseResult{T}(reason::Symbol, expected::Symbol, actual::Symbol, parser::ByLineParser) where {T} new(reason, expected, actual, parser.linenumber, parser.current) end function BadParseResult{T}(reason::Symbol, expected::Symbol, actual::Symbol, linenumber::Int, line::String) where {T} new(reason, expected, actual, linenumber, line) end end function BadParseResult{T}(inner::BadParseResult{K}) where {T, K} BadParseResult{T}(inner.reason, inner.expected, inner.actual, inner.linenumber, inner.line) end "Was the parsing successful?" issuccessful(::OKParseResult{T}) where {T} = true issuccessful(::BadParseResult{T}) where {T} = false """ lookaheadfor(byline::ByLineParser, istarget::Function, isallowedprefix::Function) Look ahead to see if all lines match isallowedprefix until we reach a line matching istarget. Example: Here the tags mark the start of the scenario @tag1 @tag2 @tag3 Scenario: Some scenario `lookaheadfor(byline, iscurrentlineasection, istagline) -> true` Example: Here the tags _do_ not mark the start of the scenario @tag1 @tag2 @tag3 This is some free text. Scenario: Some scenario `lookaheadfor(byline, iscurrentlineasection, istagline) -> false` """ function lookaheadfor(byline::ByLineParser, istarget::Function, isallowedprefix::Function) :: Bool for nextline in byline.rest if istarget(nextline) return true end if isallowedprefix(nextline) continue end # The line matched neither istarget or isallowedprefix. # Therefore the current line did not mark the beginning of an # istarget line. break end false end """ @untilemptyline(byline::Symbol,) Execute the function for each line, until an empty line is encountered, or no further lines are available. """ macro untilemptyline(ex::Expr) esc(quote while !isempty(byline) if iscurrentlineempty(byline) consume!(byline) break end $ex consume!(byline) end end) end function iscurrentlineasection(s::String) m = match(r"(Background|Scenario|Scenario Outline|Examples):.*", s) m !== nothing end iscomment(s::AbstractString) = startswith(strip(s), "#") """ @untilnextsection(byline::Symbol,) Execute the function for each line, until another section is encountered, or no further lines are available. A section is another Scenario, Scenario Outline. Also skips empty lines and comment lines. """ macro untilnextsection(ex::Expr) esc(quote while !isempty(byline) if iscurrentlineasection(byline.current) break end if istagsline(byline.current) && lookaheadfor(byline, iscurrentlineasection, x -> istagsline(x) || iscomment(x)) break end if iscurrentlineempty(byline) consume!(byline) continue end $ex consume!(byline) end end) end isstoppingline(pattern::Regex, s::AbstractString) = match(pattern, s) !== nothing """ @untilnextstep(byline::Symbol[, steps]) Execute the function for each line, until a step is encountered, or no further lines are available. Also skips empty lines and comment lines. The optional parameter steps can specify exactly which keywords to stop at. """ macro untilnextstep(ex::Expr, steps = ["Given", "When", "Then", "And", "But", "Scenario"]) esc(quote stepsregex = join($steps, "|") regex = "^($(stepsregex))" r = Regex(regex) while !isempty(byline) if isstoppingline(r, strip(byline.current)) break end $ex consume!(byline) end end) end """ ignoringemptylines!(f::Function, byline::ByLineParser) Execute function `f` for all non-empty lines, until the end of the file. """ macro ignoringemptylines(ex::Expr) esc(quote while !isempty(byline) if iscurrentlineempty(byline) consume!(byline) continue end $ex end end) end """ Override the normal `isempty` method for `ByLineParser`. """ Base.isempty(p::ByLineParser) = p.isempty """ iscurrentlineempty(p::ByLineParser) Check if the current line in the parser is empty. """ iscurrentlineempty(p::ByLineParser) = strip(p.current) == "" || startswith(strip(p.current), "#") function consumeemptylines!(p::ByLineParser) while !isempty(p) && iscurrentlineempty(p) consume!(p) end end """ istagsline(current::String) True if this is a line containing only tags, false otherwise. """ function istagsline(current::String) tagsandwhitespace = split(current, r"\s+") thesetags = filter(x -> !isempty(x), tagsandwhitespace) # the all function will match an empty list, which would happen on blank lines, # so we have to manually check for an empty list. !isempty(thesetags) && all(startswith("@"), thesetags) end """ parsetags!(byline::ByLineParser) Parse all tags on form @tagname until a non-tag is encountered. Return a possibly empty list of tags. """ function parsetags!(byline::ByLineParser) :: Vector{String} tags = String[] while !isempty(byline) if iscomment(byline.current) consume!(byline) continue end tagsandwhitespace = split(byline.current, r"\s+") thesetags = filter(x -> !isempty(x), tagsandwhitespace) istags = all(startswith("@"), thesetags) # Break if something that isn't a list of tags is encountered. if !istags break end consume!(byline) append!(tags, thesetags) end tags end """ parsefeatureheader!(byline::ByLineParser) :: ParseResult{FeatureHeader} Parse a feature header and return the feature header on success, or a bad parse result on failure. # Example of a feature header ``` @tag1 @tag2 Feature: Some description A longer description on multiple lines. ``` """ function parsefeatureheader!(byline::ByLineParser) :: ParseResult{FeatureHeader} feature_tags = parsetags!(byline) description_match = match(r"Feature: (?<description>.+)", byline.current) if description_match == nothing return BadParseResult{FeatureHeader}(:unexpected_construct, :feature, :scenario, byline) end consume!(byline) # Consume all lines after the `Feature:` row as a long description, until a keyword is # encountered. long_description_lines = [] @untilnextsection begin push!(long_description_lines, strip(byline.current)) end feature_header = FeatureHeader(description_match[:description], long_description_lines, feature_tags) return OKParseResult{FeatureHeader}(feature_header) end """ parseblocktext!(byline::ByLineParser) Parse a block of text that may occur as part of a scenario step. A block of text is multiple lines of text surrounded by three double quotes. For example, this comment is a valid block text. Precondition: This function assumes that the current line is the starting line of three double quotes. """ function parseblocktext!(byline::ByLineParser) # Consume the current line with three double quotes """ consume!(byline) block_text_lines = [] # Consume and save all lines, until we reach one that is the ending line of three double quotes. @untilnextstep begin line = byline.current push!(block_text_lines, strip(line)) end ["\"\"\""] consume!(byline) return OKParseResult{String}(join(block_text_lines, "\n")) end """ parsetable!(byline::ByLineParser) Parse a table delimited by |. # Example ```Gherkin Scenario: Table Given a data table | header 1 | header 2 | | foo | bar | | baz | quux | ``` If `parsetable!` is called on the line containing the headers, then all lines of the table will be returned. """ function parsetable!(byline::ByLineParser) :: ParseResult{DataTable} table = DataTable() while !isempty(byline) # Skip comments and empty lines if iscurrentlineempty(byline) || iscomment(byline.current) consume!(byline) continue end # If the line does not contain a | otherwise, then the last # line was the last table line. Break out. line = strip(byline.current) if !startswith(line, "|") break end # Each variable is in a column, separated by | row = split(line, "|") # The split will have two empty elements at either end, which are before and # after the | separators. We need to strip them away. row = row[2:length(row) - 1] # Remove surrounding whitespace around each value. row = map(strip, row) push!(table, row) consume!(byline) end OKParseResult{DataTable}(table) end """ parsescenariosteps!(byline::ByLineParser) Parse all scenario steps following a Scenario or Scenario Outline. """ function parsescenariosteps!(byline::ByLineParser; valid_step_types::String = "Given|When|Then") steps = [] allowed_step_types = Set([Given, When, Then]) @untilnextsection begin # Match Given, When, or Then on the line, or match a block text. # Note: This is a place where English Gherkin is hard coded. step_match = match(Regex("(?<step_type>$(valid_step_types)|And|But|\\*) (?<step_definition>.+)"), byline.current) block_text_start_match = match(r"\"\"\"", byline.current) data_table_start_match = match(r"^\|", strip(byline.current)) # A line must either be a new scenario step, data table, or a block text following the previous scenario # step. if step_match === nothing && block_text_start_match === nothing && data_table_start_match === nothing return BadParseResult{Vector{ScenarioStep}}(:invalid_step, :step_definition, :invalid_step_definition, byline) end if data_table_start_match !== nothing table_result = parsetable!(byline) prev_step_type = typeof(steps[end]) steps[end] = prev_step_type(steps[end].text; datatable=table_result.value) continue end # The current line starts a block text. Parse the rest of the block text and continue with # the following line. # Note: The method parseblocktext!(byline) consumes the current line, so it doesn't need to # be done here. if block_text_start_match !== nothing block_text_result = parseblocktext!(byline) prev_step_type = typeof(steps[end]) steps[end] = prev_step_type(steps[end].text; block_text=block_text_result.value) continue end # The current line is a scenario step. # Check that the scenario step is allowed, and create a Given/When/Then object. # Note that scenario steps must occur in the order Given, When, Then. A Given may not follow # once a When has been seen, and a When must not follow when a Then has been seen. # This is what `allowed_step_types` keeps track of. # Options: allow_any_step_order disables this check. step_type = step_match[:step_type] step_definition = strip(step_match[:step_definition]) if step_type == "Given" if !byline.options.allow_any_step_order && !(Given in allowed_step_types) return BadParseResult{Vector{ScenarioStep}}(:bad_step_order, :NotGiven, :Given, byline) end step = Given(step_definition) elseif step_type == "When" if !byline.options.allow_any_step_order && !(When in allowed_step_types) return BadParseResult{Vector{ScenarioStep}}(:bad_step_order, :NotWhen, :When, byline) end step = When(step_definition) delete!(allowed_step_types, Given) elseif step_type == "Then" step = Then(step_definition) delete!(allowed_step_types, Given) delete!(allowed_step_types, When) elseif step_type == "And" || step_type == "But" || step_type == "*" # A scenario step may be And, in which case it's the same type as the previous step. # This means that an And may not be the first scenario step. if isempty(steps) return BadParseResult{Vector{ScenarioStep}}(:leading_and, :specific_step, :and_step, byline) end last_specific_type = typeof(steps[end]) step = last_specific_type(step_definition) end push!(steps, step) end return OKParseResult{Vector{ScenarioStep}}(steps) end """ parsescenario!(byline::ByLineParser) Parse a Scenario or a Scenario Outline. # Example of a scenario ``` @tag1 @tag2 Scenario: Some description Given some precondition When some action is taken Then some postcondition holds ``` """ function parsescenario!(byline::ByLineParser) tags = parsetags!(byline) # The scenario is either a Scenario or a Scenario Outline. Check for Scenario Outline first. scenario_outline_match = match(r"Scenario Outline: (?<description>.+)", byline.current) if scenario_outline_match != nothing description = scenario_outline_match[:description] consume!(byline) # Parse longer descriptions long_description_lines = [] @untilnextstep begin push!(long_description_lines, strip(byline.current)) end long_description = strip(join(long_description_lines, "\n")) # Parse scenario outline steps. steps_result = parsescenariosteps!(byline) if !issuccessful(steps_result) return steps_result end steps = steps_result.value # Consume the Example: line. consume!(byline) # Get the name of each placeholder variable. placeholders = split(strip(byline.current), "|") placeholders = placeholders[2:length(placeholders) - 1] placeholders = map(strip, placeholders) placeholders = map(String, placeholders) consume!(byline) # Parse the examples, until we hit an empty line. # TODO: This needs to be updated to allow for multiple Examples sections. examples = Array{String,2}(undef, length(placeholders), 0) @untilnextsection begin # Each variable is in a column, separated by | example = split(strip(byline.current), "|") # The split will have two empty elements at either end, which are before and # after the | separators. We need to strip them away. example = example[2:length(example) - 1] # Remove surrounding whitespace around each value. example = map(strip, example) examples = [examples example] end return OKParseResult{ScenarioOutline}( ScenarioOutline(description, tags, steps, placeholders, examples; long_description=long_description)) end # Here we parse a normal Scenario instead. scenario_match = match(r"Scenario: (?<description>.+)", byline.current) if scenario_match === nothing return BadParseResult{Scenario}(:invalid_scenario_header, :scenario_or_outline, :invalid_header, byline) end description = scenario_match[:description] consume!(byline) # Parse longer descriptions long_description_lines = [] @untilnextstep begin push!(long_description_lines, strip(byline.current)) end long_description = strip(join(long_description_lines, "\n")) steps_result = parsescenariosteps!(byline) if !issuccessful(steps_result) return steps_result end steps = steps_result.value OKParseResult{Scenario}(Scenario(description, tags, steps, long_description=long_description)) end function parsebackground!(byline::ByLineParser) :: ParseResult{Background} consumeemptylines!(byline) background_match = match(r"Background:(?<description>.*)", byline.current) if background_match !== nothing consume!(byline) steps_result = parsescenariosteps!(byline; valid_step_types = "Given") if !issuccessful(steps_result) return BadParseResult{Background}(steps_result.reason, steps_result.expected, steps_result.actual, byline) end steps = steps_result.value description = strip(background_match[:description]) return OKParseResult{Background}(Background(description, steps)) end OKParseResult{Background}(Background()) end """ parsefeature(::String) Parse an entire feature file. # Example of a feature file ``` @tag1 @tag2 Feature: Some feature description This is some block text, and it may be multiple lines. Scenario: Some scenario description Given some precondition When some action is taken Then some postcondition holds ``` """ function parsefeature(text::String; options :: ParseOptions = ParseOptions()) :: ParseResult{Feature} byline = ByLineParser(text, options) try # Skip any leading blank lines or comments consumeemptylines!(byline) # The feature header includes all feature level tags, the description, and the long multiline # description. feature_header_result = parsefeatureheader!(byline) if !issuccessful(feature_header_result) return BadParseResult{Feature}(feature_header_result.reason, feature_header_result.expected, feature_header_result.actual, byline) end # Optionally read a Background section background_result = parsebackground!(byline) if !issuccessful(background_result) return BadParseResult{Feature}(background_result.reason, background_result.expected, background_result.actual, byline) end background = background_result.value # Each `parsescenario!` scenarios = AbstractScenario[] @ignoringemptylines begin scenario_parse_result = parsescenario!(byline) if issuccessful(scenario_parse_result) push!(scenarios, scenario_parse_result.value) else return BadParseResult{Feature}(scenario_parse_result) end end OKParseResult{Feature}( Feature(feature_header_result.value, background, scenarios)) catch ex println(ex) BadParseResult{Feature}(:exception, :nothing, Symbol(ex), byline) end end """ hastag(feature::Feature, tag::String) Check if a feature has a given tag. # Example ``` feature = parsefeature(featuretext) hassometag = hastag(feature, "@sometag") ``` """ hastag(feature::Feature, tag::String) = tag in feature.header.tags hastag(scenario::Scenario, tag::String) = tag in scenario.tags include("GherkinExperimental.jl") end
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
20225
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Experimental import Base: (|), show using Behavior.Gherkin: Given, When, Then, Scenario, ScenarioStep, AbstractScenario using Behavior.Gherkin: Feature, FeatureHeader, Background, DataTableRow, DataTable using Behavior.Gherkin: ScenarioOutline struct GherkinSource lines::Vector{String} GherkinSource(source::String) = new(split(source, "\n")) end notempty(s) = !isempty(strip(s)) notcomment(s) = !startswith(strip(s), "#") defaultlinecondition(s) = notempty(s) && notcomment(s) anyline(s) = true """ ParserInput ParserInput encapsulates - the Gherkin source - the parser state (current line) - the parser line operation (not implemented yet) """ struct ParserInput source::GherkinSource index::Int condition::Function ParserInput(source::String) = new(GherkinSource(source), 1, defaultlinecondition) ParserInput(input::ParserInput, index::Int) = new(input.source, index, defaultlinecondition) ParserInput(input::ParserInput, index::Int, condition::Function) = new(input.source, index, condition) end consume(input::ParserInput, n::Int) :: ParserInput = ParserInput(input, input.index + n) function line(input::ParserInput) :: Tuple{Union{Nothing, String}, ParserInput} nextline = findfirst(input.condition, input.source.lines[input.index:end]) if nextline === nothing return nothing, input end strip(input.source.lines[input.index + nextline - 1]), consume(input, nextline) end """ Parser{T} A Parser{T} is a callable that takes a ParserInput and produces a ParseResult{T}. The parameter T is the type of what it parses. """ abstract type Parser{T} end """ ParseResult{T} A ParseResult{T} is the either successful or failed result of trying to parse a value of T from the input. """ abstract type ParseResult{T} end """ OKParseResult{T}(value::T) OKParseResult{T} is a successful parse result. """ struct OKParseResult{T} <: ParseResult{T} value::T newinput::ParserInput end """ BadParseResult{T} BadParseResult{T} is an abstract supertype for all failed parse results. """ abstract type BadParseResult{T} <: ParseResult{T} end """ isparseok(::ParseResult{T}) isparseok returns true for successful parse results, and false for unsuccessful ones. """ isparseok(::OKParseResult{T}) where {T} = true isparseok(::BadParseResult{T}) where {T} = false struct BadExpectationParseResult{T} <: BadParseResult{T} expected::String actual::String newinput::ParserInput end struct BadUnexpectedParseResult{T} <: BadParseResult{T} unexpected::String newinput::ParserInput end struct BadInnerParseResult{S, T} <: BadParseResult{T} inner::ParseResult{<:S} newinput::ParserInput end function Base.show(io::IO, result::BadInnerParseResult{S, T}) where {S, T} show(io, result.inner) end function Base.show(io::IO, mime::MIME"text/plain", result::BadInnerParseResult{S, T}) where {S, T} show(io, mime, result.inner) end struct BadCardinalityParseResult{S, T} <: BadParseResult{T} inner::BadParseResult{S} atleast::Int actual::Int newinput::ParserInput end struct BadUnexpectedEOFParseResult{T} <: BadParseResult{T} newinput::ParserInput end struct BadExpectedEOFParseResult{T} <: BadParseResult{T} newinput::ParserInput end function Base.show(io::IO, result::BadExpectedEOFParseResult{T}) where {T} s, _newinput = line(result.newinput) println(io, "Expected EOF but found at line $(result.newinput.index):") println(io) println(io, " $s") end struct BadExceptionParseResult{T} <: BadParseResult{T} ex end function Base.show(io::IO, result::BadExceptionParseResult{T}) where {T} show(io, "Exception: $(result.ex)") end """ Line(expected::String) Line is a parser that recognizes when a line is exactly an expected value. It returns the expected value if it is found, or a bad parse result if not. """ struct Line <: Parser{String} expected::String end function (parser::Line)(input::ParserInput) :: ParseResult{String} s, newinput = line(input) if s === nothing BadUnexpectedEOFParseResult{String}(input) elseif s == parser.expected OKParseResult{String}(parser.expected, newinput) else BadExpectationParseResult{String}(parser.expected, s, input) end end """ Optionally{T} Optionally{T} parses a value of type T if the inner parser succeeds, or nothing if the inner parser fails. It always succeeds. """ struct Optionally{T} <: Parser{Union{Nothing, T}} inner::Parser{T} end function (parser::Optionally{T})(input::ParserInput) :: ParseResult{Union{Nothing, T}} where {T} result = parser.inner(input) if isparseok(result) OKParseResult{Union{Nothing, T}}(result.value, result.newinput) else OKParseResult{Union{Nothing, T}}(nothing, input) end end """ optionalordefault(value, default) Return `value` if it is not nothing, default otherwise. """ function optionalordefault(value, default) if value === nothing default else value end end """ Or{T}(::Parser{T}, ::Parser{T}) Or matches either of the provided parsers. It short-circuits. """ struct Or{T} <: Parser{T} a::Parser{<:T} b::Parser{<:T} end function (parser::Or{T})(input::ParserInput) :: ParseResult{<:T} where {T} result = parser.a(input) if isparseok(result) result else parser.b(input) end end (|)(a::Parser{T}, b::Parser{T}) where {T} = Or{T}(a, b) """ Transformer{S, T} Transforms a parser of type S to a parser of type T, using a transform function. """ struct Transformer{S, T} <: Parser{T} inner::Parser{S} transform::Function end function (parser::Transformer{S, T})(input::ParserInput) where {S, T} result = parser.inner(input) if isparseok(result) newvalue = parser.transform(result.value) OKParseResult{T}(newvalue, result.newinput) else BadInnerParseResult{S, T}(result, input) end end """ Sequence{T} Combine parsers into a sequence, that matches all of them in order. """ struct Sequence{T} <: Parser{Vector{T}} inner::Vector{Parser{<:T}} Sequence{T}(parsers...) where {T} = new(collect(parsers)) end function (parser::Sequence{T})(input::ParserInput) :: ParseResult{Vector{T}} where {T} values = Vector{T}() currentinput = input for p in parser.inner result = p(currentinput) if isparseok(result) push!(values, result.value) currentinput = result.newinput else return BadInnerParseResult{T, Vector{T}}(result, input) end end OKParseResult{Vector{T}}(values, currentinput) end """ Joined Joins a sequence of strings together into one string. """ Joined(inner::Parser{Vector{String}}) = Transformer{Vector{String}, String}(inner, x -> join(x, "\n")) """ Repeating{T} Repeats the provided parser until it no longer recognizes the input. """ struct Repeating{T} <: Parser{Vector{T}} inner::Parser{T} atleast::Int Repeating{T}(inner::Parser{T}; atleast::Int = 0) where {T} = new(inner, atleast) end function (parser::Repeating{T})(input::ParserInput) :: ParseResult{Vector{T}} where {T} values = Vector{T}() currentinput = input while true result = parser.inner(currentinput) if !isparseok(result) cardinality = length(values) if cardinality < parser.atleast return BadCardinalityParseResult{T, Vector{T}}(result, parser.atleast, cardinality, input) end break end push!(values, result.value) currentinput = result.newinput end OKParseResult{Vector{T}}(values, currentinput) end """ LineIfNot Consumes a line if it does not match a given parser. """ struct LineIfNot <: Parser{String} inner::Parser{<:Any} linecondition::Function LineIfNot(inner::Parser{<:Any}) = new(inner, defaultlinecondition) LineIfNot(inner::Parser{<:Any}, condition::Function) = new(inner, condition) end function (parser::LineIfNot)(realinput::ParserInput) :: ParseResult{String} # This parser has support for providing the inner parser with a # non-default line condition. input = ParserInput(realinput, realinput.index, parser.linecondition) result = parser.inner(input) if isparseok(result) badline, _badinput = line(input) BadUnexpectedParseResult{String}(badline, input) else s, newinput = line(input) if s === nothing BadUnexpectedEOFParseResult{String}(input) else OKParseResult{String}(s, newinput) end end end """ StartsWith Consumes a line if it starts with a given string. """ struct StartsWith <: Parser{String} prefix::String end function (parser::StartsWith)(input::ParserInput) :: ParseResult{String} s, newinput = line(input) if s === nothing BadUnexpectedEOFParseResult{String}(input) elseif startswith(s, parser.prefix) OKParseResult{String}(s, newinput) else BadExpectationParseResult{String}(parser.prefix, s, input) end end struct EOFParser <: Parser{Nothing} end function (parser::EOFParser)(input::ParserInput) :: ParseResult{Nothing} s, newinput = line(input) if s === nothing OKParseResult{Nothing}(nothing, newinput) else BadExpectedEOFParseResult{Nothing}(input) end end ## ## Gherkin-specific parser ## takeelement(i::Int) = xs -> xs[i] """ BlockText Parses a Gherkin block text. """ BlockText() = Transformer{Vector{String}, String}( Sequence{String}( Line("\"\"\""), Joined(Repeating{String}(LineIfNot(Line("\"\"\""), anyline))), Line("\"\"\""), ), takeelement(2) ) struct Keyword keyword::String rest::String end """ DataTableParser() Consumes a data table in a scenario step. ## Example | Header 1 | Header 2 | | Foo | Bar | | Baz | Quux | """ struct DataTableRowParser <: Parser{DataTableRow} end function (parser::DataTableRowParser)(input::ParserInput) :: ParseResult{DataTableRow} s, newinput = line(input) if s === nothing return BadUnexpectedEOFParseResult{DataTableRow}(input) end parts = split(s, "|") if length(parts) >= 3 columns = collect([strip(p) for p in parts if strip(p) != ""]) OKParseResult{DataTableRow}(columns, newinput) else BadExpectationParseResult{DataTableRow}("| column 1 | column 2 | ... | column n |", s, input) end end DataTableParser() = Transformer{Vector{DataTableRow}, DataTable}( Repeating{DataTableRow}(DataTableRowParser(), atleast=1), rows -> rows ) struct AnyLine <: Parser{String} end function (parser::AnyLine)(input::ParserInput) :: ParseResult{String} s, newinput = line(input) if s === nothing BadUnexpectedEOFParseResult{String}(input) else OKParseResult{String}(s, newinput) end end Splitter(inner::Parser{String}, delimiter) :: Parser{Vector{String}} = Transformer{String, Vector{String}}( inner, s -> split(s, delimiter, keepempty=false) ) struct Validator{T} <: Parser{Vector{T}} inner::Parser{Vector{T}} f::Function end function (parser::Validator{T})(input::ParserInput) :: ParseResult{Vector{T}} where {T} result = parser.inner(input) if isparseok(result) && all(parser.f, result.value) OKParseResult{Vector{T}}(result.value, result.newinput) else BadInnerParseResult{Vector{T}, Vector{T}}(result, input) end end const TagList = Vector{String} """ TagParser() Consumes a single tag in the form `@tagname`. """ TagParser() :: Parser{TagList} = Validator{String}(Splitter(AnyLine(), isspace), x -> startswith(x, "@")) """ TagLinesParser() Read tags until they stop. """ TagLinesParser() :: Parser{TagList} = Transformer{Vector{TagList}, TagList}( Repeating{TagList}(TagParser()), taglines -> vcat(taglines...) ) """ KeywordParser Recognizes a keyword, and any following text on the same line. """ KeywordParser(word::String) = Transformer{String, Keyword}( StartsWith(word), s -> begin Keyword(word, strip(replace(s, word => "", count=1))) end ) const TableOrBlockTextTypes = Union{String, DataTable} const DataTableOrBlockText = ( Sequence{TableOrBlockTextTypes}(DataTableParser(), BlockText()) | Sequence{TableOrBlockTextTypes}(BlockText(), DataTableParser()) | Sequence{TableOrBlockTextTypes}(BlockText()) | Sequence{TableOrBlockTextTypes}(DataTableParser()) ) const StepPieces = Union{Keyword, Union{Nothing, Vector{TableOrBlockTextTypes}}} mutable struct StepBuilder{T} steptype::Type{T} keyword::Keyword blocktext::String datatable::DataTable StepBuilder{T}(steptype::Type{T}, keyword::Keyword) where {T} = new(steptype, keyword, "", DataTable()) end accumulate!(sb::StepBuilder{T}, table::DataTable) where {T} = sb.datatable = table accumulate!(sb::StepBuilder{T}, blocktext::String) where {T} = sb.blocktext = blocktext accumulate!(sb::StepBuilder{T}, vs::Vector{TableOrBlockTextTypes}) where {T} = foreach(v -> accumulate!(sb, v), vs) accumulate!(::StepBuilder{T}, ::Nothing) where {T} = nothing buildstep(sb::StepBuilder{T}) where {T} = sb.steptype(sb.keyword.rest, block_text=sb.blocktext, datatable=sb.datatable) function StepParser(steptype::Type{T}, keyword::String) :: Parser{T} where {T} Transformer{Vector{StepPieces}, T}( Sequence{StepPieces}(KeywordParser(keyword), Optionally(DataTableOrBlockText)), sequence -> begin keyword = sequence[1] stepbuilder = StepBuilder{T}(steptype, keyword) accumulate!(stepbuilder, sequence[2]) buildstep(stepbuilder) end ) end """ And An `And` type scenario step """ struct And <: ScenarioStep text::String block_text::String datatable::DataTable And(text::AbstractString; block_text = "", datatable=DataTable()) = new(text, block_text, datatable) end """ GivenParser Consumes a Given step. """ GivenParser() = StepParser(Given, "Given ") WhenParser() = StepParser(When, "When ") ThenParser() = StepParser(Then, "Then ") AndParser() = StepParser(And, "And ") # TODO Find a way to express this as # GivenParser() | WhenParser() | ThenParser() const AnyStepParser = Or{ScenarioStep}( Or{ScenarioStep}(GivenParser(), WhenParser()), Or{ScenarioStep}(ThenParser(), AndParser()) ) """ StepsParser Parses zero or more steps. """ StepsParser() = Repeating{ScenarioStep}(AnyStepParser) const AnyKeyword = ( KeywordParser("Given ") | KeywordParser("When ") | KeywordParser("Then ") | KeywordParser("Feature:") | KeywordParser("Scenario:") | KeywordParser("Scenario Outline:") | KeywordParser("Background:") | KeywordParser("Rule:") ) const MaybeTags = Union{Nothing, Vector{String}} const ScenarioBits = Union{Keyword, String, Vector{ScenarioStep}, MaybeTags} const LongDescription = Joined(Repeating{String}(LineIfNot(AnyKeyword))) """ ScenarioParser() Consumes a Scenario. """ ScenarioParser() = Transformer{Vector{ScenarioBits}, Scenario}( Sequence{ScenarioBits}( Optionally(TagLinesParser()), KeywordParser("Scenario:"), Optionally(LongDescription), StepsParser()), sequence -> begin tags = optionalordefault(sequence[1], []) keyword = sequence[2] longdescription = optionalordefault(sequence[3], "") Scenario(keyword.rest, tags, Vector{ScenarioStep}(sequence[4]), long_description=longdescription) end ) const ScenarioOutlineBits = Union{Keyword, String, Vector{ScenarioStep}, MaybeTags, DataTable} """ ScenarioOutlineParser() Consumes a Scenario Outline. """ ScenarioOutlineParser() = Transformer{Vector{ScenarioOutlineBits}, ScenarioOutline}( Sequence{ScenarioOutlineBits}( Optionally(TagLinesParser()), KeywordParser("Scenario Outline:"), Optionally(LongDescription), StepsParser(), Line("Examples:"), DataTableParser() ), sequence -> begin tags = optionalordefault(sequence[1], []) keyword = sequence[2] longdescription = optionalordefault(sequence[3], "") steps = sequence[4] examples = sequence[6] # The DataTableParser guarantees at least 1 row. placeholders = examples[1] ScenarioOutline( keyword.rest, tags, steps, placeholders, examples[2:end], long_description=longdescription ) end ) const BackgroundBits = ScenarioBits """ BackgroundParser() Consume a Background. """ BackgroundParser() = Transformer{Vector{BackgroundBits}, Background}( Sequence{BackgroundBits}( KeywordParser("Background:"), Optionally(LongDescription), StepsParser() ), sequence -> begin keyword = sequence[1] longdescription = optionalordefault(sequence[2], "") Background(keyword.rest, sequence[3], long_description=longdescription) end ) struct Rule <: AbstractScenario description::String longdescription::String scenarios::Vector{AbstractScenario} tags::Vector{String} end const ScenarioList = Vector{Scenario} const RuleBits = Union{Keyword, MaybeTags, Nothing, String, ScenarioList} """ RuleParser Consumes a Rule and its child scenarios. """ RuleParser() = Transformer{Vector{RuleBits}, Rule}( Sequence{RuleBits}( Optionally(TagLinesParser()), KeywordParser("Rule:"), Optionally(LongDescription), Repeating{Scenario}(ScenarioParser())), sequence -> begin tags = optionalordefault(sequence[1], String[]) keyword = sequence[2] longdescription = optionalordefault(sequence[3], "") scenarios = sequence[4] Rule(keyword.rest, longdescription, scenarios, tags) end ) const FeatureBits = Union{Keyword, String, Background, Nothing, Vector{AbstractScenario}, MaybeTags} """ FeatureParser Consumes a full feature file. """ const ScenarioOrRule = Or{AbstractScenario}( Or{AbstractScenario}(ScenarioParser(), ScenarioOutlineParser()), RuleParser() ) FeatureParser() = Transformer{Vector{FeatureBits}, Feature}( Sequence{FeatureBits}( Optionally(TagLinesParser()), KeywordParser("Feature:"), Optionally(LongDescription), Optionally(BackgroundParser()), Repeating{AbstractScenario}(ScenarioOrRule)), sequence -> begin keyword = sequence[2] tags = optionalordefault(sequence[1], String[]) longdescription = optionalordefault(sequence[3], "") background = optionalordefault(sequence[4], Background()) Feature(FeatureHeader(keyword.rest, [longdescription], tags), background, sequence[5]) end ) const FeatureFileBits = Union{Feature, Nothing} FeatureFileParser() = Transformer{Vector{FeatureFileBits}, Feature}( Sequence{FeatureFileBits}(FeatureParser(), EOFParser()), takeelement(1) ) ## ## Exports ## export ParserInput, OKParseResult, BadParseResult, isparseok # Basic combinators export Line, Optionally, Or, Transformer, Sequence export Joined, Repeating, LineIfNot, StartsWith, EOFParser # Gherkin combinators export BlockText, KeywordParser export StepsParser, GivenParser, WhenParser, ThenParser export ScenarioParser, RuleParser, FeatureParser, FeatureFileParser, BackgroundParser export DataTableParser, TagParser, TagLinesParser, ScenarioOutlineParser # Data carrier types export Keyword, Rule end
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
12131
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Selecting which features and scenarios to run, based on tags. # Exports TagSelector select(::TagSelector, tags::AbstractVector{String}) :: Bool parsetagselector(::String) :: TagSelector """ module Selection using Behavior.Gherkin export select, parsetagselector, TagSelector """ Abstract type for a tag expression. Each tag expression can be matched against a set of tags. """ abstract type TagExpression end """ matches(ex::TagExpression, tags::AbstractVector{String}) :: Bool Returns true if `tags` matches the tag expression `ex`, false otherwise. This must be implemented for each `TagExpression` subtype. """ matches(::TagExpression, tags::AbstractVector{String}) :: Bool = error("Implement this in TagExpression types") """ Tag is an expression that matches against a single tag. It will match if the tag in the `value` is in the `tags` set. """ struct Tag <: TagExpression value::String end matches(ex::Tag, tags::AbstractVector{String}) = ex.value in tags """ Not matches a tag set if and only if the `inner` tag expression _does not_ match. """ struct Not <: TagExpression inner::TagExpression end matches(ex::Not, tags::AbstractVector{String}) = !matches(ex.inner, tags) """ All is a tag expression that matches any tags or no tags. """ struct All <: TagExpression end matches(::All, ::AbstractVector{String}) = true """ Any matches any tags in a list. """ struct Any <: TagExpression exs::Vector{TagExpression} end matches(anyex::Any, tags::AbstractVector{String}) = any(ex -> matches(ex, tags), anyex.exs) """ Or(::TagExpression, ::TagExpression) Match either expression. """ struct Or <: TagExpression a::TagExpression b::TagExpression end struct OrResult <: TagExpression b::TagExpression end """ Parentheses(::TagExpression) An expression in parentheses. """ struct Parentheses <: TagExpression ex::TagExpression end """ NothingExpression Represents an empty parse result. """ struct NothingExpression <: TagExpression end """ parsetagexpression(s::String) :: TagExpression Parse the string `s` into a `TagExpression`. """ function parsetagexpression(s::String) :: TagExpression if isempty(strip(s)) All() elseif startswith(s, "not ") tag = replace(s, "not " => "") Not(parsetagexpression(tag)) else tags = split(s, ",") Any([Tag(t) for t in tags]) end end """ TagSelector is used to select a feature or scenario based on its tags. The `TagSelector` is created by parsing a tag expression in string form. Then the `select` method can be used to query if a given feature or scenario should be selected for execution. """ struct TagSelector expression::TagExpression end """ selectscenario(::TagSelector, feature::Feature, scenario::Scenario) :: Boolean Check if a given scenario ought to be included in the execution. Returns true if that is the case, false otherwise. """ function select(ts::TagSelector, feature::Feature, scenario::Gherkin.AbstractScenario) :: Bool tags = vcat(feature.header.tags, scenario.tags) matches(ts.expression, tags) end """ select(::TagSelector, feature::Feature) :: Union{Feature,Nothing} Filter a feature and its scenarios based on the selected tags. Returns a feature with zero or more scenarios, or nothing if the feature and none of the scenarios matched the tag selector. """ function select(ts::TagSelector, feature::Feature) :: Feature newscenarios = [scenario for scenario in feature.scenarios if select(ts, feature, scenario)] Feature(feature, newscenarios) end """ parsetagselector(s::String) :: TagSelector Parse a string into a `TagSelector` struct. This can then be used with the `select` query to determine if a given feature or scenario should be selected for execution. # Examples ```julia-repl julia> # Will match any feature/scenario with the tag @foo julia> parsetagselector("@foo") julia> # Will match any feature/scenario without the tag @bar julia> parsetagselector("not @bar") ``` """ function parsetagselector(s::String) :: TagSelector TagSelector(parsetagexpression(s)) end const AllScenarios = TagSelector(All()) ## ## Parser combinators for tag expressions ## ## This will soonish replace most of the code above. ## struct TagExpressionInput source::String position::Int function TagExpressionInput(source::String, position::Int = 1) nextnonwhitespace = findnext(c -> c != ' ', source, position) newposition = if nextnonwhitespace !== nothing nextnonwhitespace else length(source) + 1 end new(source, newposition) end end currentchar(input::TagExpressionInput) = (input.source[input.position], TagExpressionInput(input.source, input.position + 1)) iseof(input::TagExpressionInput) = input.position > length(input.source) abstract type ParseResult{T} end struct OKParseResult{T} <: ParseResult{T} value::T newinput::TagExpressionInput end struct BadParseResult{T} <: ParseResult{T} newinput::TagExpressionInput end abstract type TagExpressionParser{T} end """ AnyTagExpression() Consumes any type of tag expression. The actual parser constructor is defined further down below, after all expression types have been defined. """ struct AnyTagExpression <: TagExpressionParser{TagExpression} end """ Repeating(::TagExpressionParser) Repeat a given parser while it succeeds. """ struct Repeating{T} <: TagExpressionParser{Vector{T}} inner::TagExpressionParser{T} end function (parser::Repeating{T})(input::TagExpressionInput) :: ParseResult{Vector{T}} where {T} result = Vector{T}() currentinput = input while true innerresult = parser.inner(currentinput) if innerresult isa BadParseResult{T} break end push!(result, innerresult.value) currentinput = innerresult.newinput end OKParseResult{Vector{T}}(result, currentinput) end """ Transforming(::TagExpressionParser, f::Function) Transforms an OK parse result using a provided function """ struct Transforming{S, T} <: TagExpressionParser{T} inner::TagExpressionParser{S} f::Function end function (parser::Transforming{S, T})(input::TagExpressionInput) :: ParseResult{T} where {S, T} result = parser.inner(input) if result isa OKParseResult{S} OKParseResult{T}(parser.f(result.value), result.newinput) else BadParseResult{T}(input) end end struct TakeUntil <: TagExpressionParser{String} anyof::String end function (parser::TakeUntil)(input::TagExpressionInput) :: ParseResult{String} delimiterindex = findnext(c -> contains(parser.anyof, c), input.source, input.position) lastindex = if delimiterindex !== nothing delimiterindex - 1 else length(input.source) end s = input.source[input.position:lastindex] OKParseResult{String}(s, TagExpressionInput(input.source, lastindex + 1)) end SingleTagParser() = Transforming{Vector{String}, Tag}( SequenceParser{String}( Literal("@"), TakeUntil("() "), ), s -> Tag(join(s))) """ SequenceParser{T}(parsers...) Consumes a sequence of other parsers. """ struct SequenceParser{T} <: TagExpressionParser{Vector{T}} inner::Vector{TagExpressionParser{<:T}} SequenceParser{T}(parsers...) where {T} = new(collect(parsers)) end function (parser::SequenceParser{T})(input::TagExpressionInput) :: ParseResult{Vector{T}} where {T} values = Vector{T}() currentinput = input for p in parser.inner result = p(currentinput) if result isa BadParseResult return BadParseResult{Vector{T}}(input) end push!(values, result.value) currentinput = result.newinput end OKParseResult{Vector{T}}(values, currentinput) end """ Literal(::String) Consumes an exact literal string. """ struct Literal <: TagExpressionParser{String} value::String end function (parser::Literal)(input::TagExpressionInput) :: ParseResult{String} n = length(parser.value) endposition = min(input.position + n - 1, length(input.source)) actual = input.source[input.position:endposition] if parser.value == actual OKParseResult{String}(actual, TagExpressionInput(input.source, endposition + 1)) else BadParseResult{String}(input) end end const NotBits = Union{String, TagExpression} """ NotTagParser() Consumes a logical not of some tag expression. """ NotTagParser() = Transforming{Vector{NotBits}, Not}( SequenceParser{NotBits}( Literal("not"), AnyTagExpression() ), xs -> Not(xs[2]) ) const OrBits = Union{String, TagExpression} """ OrParser() Consumes a logical or expression. """ OrParser() = Transforming{Vector{OrBits}, OrResult}( SequenceParser{OrBits}( Literal("or"), SingleTagParser() ), xs -> OrResult(xs[2]) ) # TODO Create And expression parser const ParenthesesBits = Union{String, TagExpression} """ ParenthesesParser() Consumes a tag expression in parentheses. """ ParenthesesParser() = Transforming{Vector{ParenthesesBits}, Parentheses}( SequenceParser{ParenthesesBits}( Literal("("), AnyTagExpression(), Literal(")") ), xs -> Parentheses(xs[2]) ) """ AnyOfParser(parsers...) Consume any of the supplied parsers. """ struct AnyOfParser <: TagExpressionParser{TagExpression} parsers::Vector{TagExpressionParser{<:TagExpression}} AnyOfParser(parsers...) = new(collect(parsers)) end function (parser::AnyOfParser)(input::TagExpressionInput) :: ParseResult{TagExpression} results = Vector{OKParseResult{<:TagExpression}}() for p in parser.parsers result = p(input) if result isa OKParseResult push!(results, result) end end if isempty(results) BadParseResult{TagExpression}(input) else # Return the longest successful parse resultlength = result -> result.newinput.position - input.position maxresultlength = maximum(resultlength, results) maxresultindex = findfirst(result -> resultlength(result) == maxresultlength, results) maxresult = results[maxresultindex] OKParseResult{TagExpression}(maxresult.value, maxresult.newinput) end end """ NothingParser() Consumes nothing and always succeeds. """ struct NothingParser <: TagExpressionParser{TagExpression} end function (parser::NothingParser)(input::TagExpressionInput) :: ParseResult{TagExpression} OKParseResult{TagExpression}(NothingExpression(), input) end # # The AnyTagExpression constructor is defined here at the bottom, where it # can find all expression types. # const StartExprParser = AnyOfParser( ParenthesesParser(), NotTagParser(), SingleTagParser() ) const EndExprParser = AnyOfParser( OrParser(), SingleTagParser(), NothingParser(), ) function combineResult(a::TagExpression, other::OrResult) :: TagExpression Or(a, other.b) end function combineResult(a::TagExpression, ::NothingExpression) :: TagExpression a end function (::AnyTagExpression)(input::TagExpressionInput) :: ParseResult{TagExpression} combineStartAndEnd = (vs) -> combineResult(vs...) inner = Transforming{Vector{TagExpression}, TagExpression}( SequenceParser{TagExpression}( StartExprParser, EndExprParser, ), combineStartAndEnd ) inner(input) end end
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
2547
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. "Thrown at @expect failures in step definitions." struct StepAssertFailure <: Exception assertion::String evaluated::String StepAssertFailure(assertion::String) = new(assertion, "") StepAssertFailure(assertion::String, evaluated::String) = new(assertion, evaluated) end """ expect(ex) Assert that a condition `ex` is true. Throws a StepAssertFailure if false. Warning: The expressions in the `ex` condition may be evaluated more than once, so only use expression without side effects in the condition. # Examples ``` @then "this condition should hold" begin @expect 1 == 1 end ``` This will fail and throw a `StepAssertFailure` ``` @then "this condition should not hold" begin @expect 1 == 2 end ``` """ macro expect(ex) comparisonops = [:(==), :(===), :(!=), :(!==)] if hasproperty(ex, :head) iscomparison = ex.head === :call && length(ex.args) == 3 && ex.args[1] in comparisonops else iscomparison = false end if iscomparison comparisonop = QuoteNode(ex.args[1]) quote # Evaluate each argument separately local value1 = $(esc(ex.args[2])) local value2 = $(esc(ex.args[3])) # Create a en expression to show local showexpr = Expr(:call, $comparisonop, value1, value2) local msg = $(string(ex)) local evaluated = string(showexpr) # Check the expectation by evaluating the original expression if !($(esc(ex))) throw(StepAssertFailure(msg, evaluated)) end end else quote local msg = $(string(ex)) # Check the expectation. if !(Bool($(esc(ex)))) throw(StepAssertFailure(msg)) end end end end """ @fail(message) Fail a step with a descriptive message. """ macro fail(message) quote throw(StepAssertFailure($message)) end end
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
5156
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. abstract type Engine end abstract type OSAbstraction end findfileswithextension(::OSAbstraction, ::String, ::String) = error("override this method") readfile(::OSAbstraction, ::String) = error("override this method") fileexists(::OSAbstraction, ::String) = error("override this method") struct ExecutorEngine <: Engine accumulator::ResultAccumulator executor::Executor matcher::StepDefinitionMatcher selector::Selection.TagSelector function ExecutorEngine(realtimepresenter::RealTimePresenter; executionenv=NoExecutionEnvironment(), selector::Selection.TagSelector = Selection.AllScenarios) matcher = CompositeStepDefinitionMatcher() executor = Executor(matcher, realtimepresenter; executionenv=executionenv) new(ResultAccumulator(), executor, matcher, selector) end end addmatcher!(engine::ExecutorEngine, matcher::StepDefinitionMatcher) = addmatcher!(engine.matcher, matcher) executionenvironment(engine::ExecutorEngine) = engine.executor.executionenv """ runfeature!(::ExecutorEngine, ::Feature; [keepgoing=true]) Run the scenarios in a feature and record the result. The keyword argument `keepgoing` (default: true) controls whether the execution stops after a failing scenario (`keepgoing=false`), or continues (`keepgoing=true`). """ function runfeature!(engine::ExecutorEngine, feature::Feature; keepgoing=true) result = executefeature(engine.executor, feature; keepgoing=keepgoing) accumulateresult!(engine.accumulator, result) end """ runfeature!(::ExecutorEngine, ::Gherkin.OKParseResult{Feature}) Wrapper method for the above runfeature!. """ const GoodParseResultType = Union{Gherkin.OKParseResult{Feature}, Gherkin.Experimental.OKParseResult{Feature}} function runfeature!(engine::ExecutorEngine, parseresult::GoodParseResultType, _featurefile::String, keepgoing::Bool) # Filter all features to run only the scenarios chosen by the tag selector, if any. # Any features or scenarios that do not match the tag selector will be removed here. filteredfeature = Selection.select(engine.selector, parseresult.value) # If there are no scenarios in this feature, then do not run it at all. # This matters because we don't want it listed in the results view having 0 successes # and 0 failures. if !isempty(filteredfeature.scenarios) runfeature!(engine, filteredfeature; keepgoing=keepgoing) end end """ runfeature!(::ExecutorEngine, ::Gherkin.BadParseResult{Feature}) A feature could not be parsed. Record the result. """ function runfeature!(engine::ExecutorEngine, parsefailure::Gherkin.BadParseResult{Feature}, featurefile::String, _keepgoing::Bool) accumulateresult!(engine.accumulator, parsefailure, featurefile) end function runfeature!(engine::ExecutorEngine, parsefailure::Gherkin.Experimental.BadParseResult{Feature}, featurefile::String, _keepgoing::Bool) accumulateresult!(engine.accumulator, parsefailure, featurefile) end finish(engine::ExecutorEngine) = engine.accumulator struct Driver os::OSAbstraction engine::Engine Driver(os::OSAbstraction, engine::Engine) = new(os, engine) end function readstepdefinitions!(driver::Driver, path::String) stepdefinitionfiles = findfileswithextension(driver.os, path, ".jl") for f in stepdefinitionfiles addmatcher!(driver.engine, FromMacroStepDefinitionMatcher(readfile(driver.os, f), filename = f)) end end function readfeature(driver::Driver, featurefile::String, parseoptions::ParseOptions) if parseoptions.use_experimental input = Gherkin.Experimental.ParserInput(read(featurefile, String)) parser = Gherkin.Experimental.FeatureFileParser() parser(input) else parsefeature(readfile(driver.os, featurefile), options=parseoptions) end end function runfeatures!(driver::Driver, path::String; parseoptions::ParseOptions = ParseOptions(), keepgoing::Bool=true) featurefiles = findfileswithextension(driver.os, path, ".feature") # Call the hook that runs before any feature beforeall(executionenvironment(driver.engine)) for featurefile in featurefiles featureparseresult = readfeature(driver, featurefile, parseoptions) runfeature!(driver.engine, featureparseresult, featurefile, keepgoing) if !issuccess(driver.engine.accumulator) && !keepgoing break end end # Call the hook that runs after all features afterall(executionenvironment(driver.engine)) finish(driver.engine) end
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
3714
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. abstract type ExecutionEnvironment end struct NoExecutionEnvironment <: ExecutionEnvironment end beforescenario(::NoExecutionEnvironment, ::StepDefinitionContext, ::Gherkin.Scenario) = nothing afterscenario(::NoExecutionEnvironment, ::StepDefinitionContext, ::Gherkin.Scenario) = nothing beforefeature(::NoExecutionEnvironment, ::Gherkin.Feature) = nothing afterfeature(::NoExecutionEnvironment, ::Gherkin.Feature) = nothing beforeall(::NoExecutionEnvironment) = nothing afterall(::NoExecutionEnvironment) = nothing module GlobalExecEnv envs = Dict{Symbol, Function}() function clear() global envs envs = Dict{Symbol, Function}() end end macro beforescenario(ex::Expr) envdefinition = :( $ex ) quote GlobalExecEnv.envs[:beforescenario] = $(esc(envdefinition)) end end macro afterscenario(ex::Expr) envdefinition = :( $ex ) quote GlobalExecEnv.envs[:afterscenario] = $(esc(envdefinition)) end end macro beforefeature(ex::Expr) envdefinition = :( $ex ) quote GlobalExecEnv.envs[:beforefeature] = $(esc(envdefinition)) end end macro afterfeature(ex::Expr) envdefinition = :( $ex ) quote GlobalExecEnv.envs[:afterfeature] = $(esc(envdefinition)) end end macro beforeall(ex::Expr) envdefinition = :( $ex ) quote GlobalExecEnv.envs[:beforeall] = $(esc(envdefinition)) end end macro afterall(ex::Expr) envdefinition = :( $ex ) quote GlobalExecEnv.envs[:afterall] = $(esc(envdefinition)) end end struct FromSourceExecutionEnvironment <: ExecutionEnvironment envdefinitions::Dict{Symbol, Function} function FromSourceExecutionEnvironment(source::String) include_string(Main, source) this = new(GlobalExecEnv.envs) GlobalExecEnv.clear() this end end function invokeenvironmentmethod( executionenv::FromSourceExecutionEnvironment, methodsym::Symbol, args...) if haskey(executionenv.envdefinitions, methodsym) method = executionenv.envdefinitions[methodsym] Base.invokelatest(method, args...) end end beforescenario(executionenv::FromSourceExecutionEnvironment, context::StepDefinitionContext, scenario::Gherkin.Scenario) = invokeenvironmentmethod(executionenv, :beforescenario, context, scenario) afterscenario(executionenv::FromSourceExecutionEnvironment, context::StepDefinitionContext, scenario::Gherkin.Scenario) = invokeenvironmentmethod(executionenv, :afterscenario, context, scenario) beforefeature(executionenv::FromSourceExecutionEnvironment, feature::Gherkin.Feature) = invokeenvironmentmethod(executionenv, :beforefeature, feature) afterfeature(executionenv::FromSourceExecutionEnvironment, feature::Gherkin.Feature) = invokeenvironmentmethod(executionenv, :afterfeature, feature) beforeall(executionenv::FromSourceExecutionEnvironment) = invokeenvironmentmethod(executionenv, :beforeall) afterall(executionenv::FromSourceExecutionEnvironment) = invokeenvironmentmethod(executionenv, :afterall)
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
13474
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. using Base.StackTraces "Executes a feature or scenario, and presents the results in real time." struct Executor stepdefmatcher::StepDefinitionMatcher presenter::RealTimePresenter executionenv::ExecutionEnvironment Executor(matcher::StepDefinitionMatcher, presenter::RealTimePresenter = QuietRealTimePresenter(); executionenv::ExecutionEnvironment = NoExecutionEnvironment()) = new(matcher, presenter, executionenv) end "Abstract type for a result when executing a scenario step." abstract type StepExecutionResult end "No matching step definition was found." struct NoStepDefinitionFound <: StepExecutionResult step::Gherkin.ScenarioStep end "More than one matching step definition was found." struct NonUniqueMatch <: StepExecutionResult locations::Vector{StepDefinitionLocation} end "Successfully executed a step." struct SuccessfulStepExecution <: StepExecutionResult end "An assert failed in the step." struct StepFailed <: StepExecutionResult assertion::String evaluated::String StepFailed(assertion::AbstractString) = new(assertion, "") StepFailed(assertion::AbstractString, evaluated::AbstractString) = new(assertion, evaluated) end "An unexpected error or exception occurred during the step execution." struct UnexpectedStepError <: StepExecutionResult ex::Exception stack::StackTrace end "The step was not executed." struct SkippedStep <: StepExecutionResult end """ issuccess(::StepExecutionResult) True for successful step executions, and false otherwise. """ issuccess(::SuccessfulStepExecution) = true issuccess(::StepExecutionResult) = false "A result for a complete scenario." struct ScenarioResult steps::Vector{StepExecutionResult} scenario::Scenario background::Gherkin.Background backgroundresult::Vector{StepExecutionResult} end issuccess(sr::ScenarioResult) = all(x -> issuccess(x), sr.steps) issuccess(srs::AbstractVector{ScenarioResult}) = all(x -> issuccess(x), srs) function executesteps(executor::Executor, context::StepDefinitionContext, steps::Vector{ScenarioStep}, isfailedyet::Bool) # The `steps` vector contains the results for all steps. At initialization, # they are all `Skipped`, because if one step fails then we stop the execution of the following # steps. results = Vector{StepExecutionResult}(undef, length(steps)) fill!(results, SkippedStep()) # Find a unique step definition for each step and execute it. # Present each step, first as it is about to be executed, and then once more with the result. for i = 1:length(steps) # If any previous step has failed, then skip all the steps that follow. if isfailedyet present(executor.presenter, steps[i]) present(executor.presenter, steps[i], results[i]) continue end step = steps[i] # Tell the presenter that this step is about to be executed. present(executor.presenter, step) results[i] = try # Find a step definition matching the step text. stepdefinitionmatch = findstepdefinition(executor.stepdefmatcher, step) # The block text is provided to the step definition via the context. context[:block_text] = step.block_text context.datatable = step.datatable try # Execute the step definition. Note that it's important to use `Base.invokelatest` here, # because otherwise it might not find that function defined yet. Base.invokelatest(stepdefinitionmatch.stepdefinition.definition, context, stepdefinitionmatch.variables) catch ex UnexpectedStepError(ex, stacktrace(catch_backtrace())) end catch ex if ex isa NoMatchingStepDefinition NoStepDefinitionFound(step) elseif ex isa NonUniqueStepDefinition NonUniqueMatch(ex.locations) else rethrow(ex) end end # Present the result after execution. present(executor.presenter, step, results[i]) # If this step failed, then we skip any remaining steps. if !issuccess(results[i]) isfailedyet = true end end results, isfailedyet end """ executescenario(::Executor, ::Gherkin.Scenario) Execute each step in a `Scenario`. Present the results in real time. Returns a `ScenarioResult`. """ function executescenario(executor::Executor, background::Gherkin.Background, scenario::Gherkin.Scenario) # Tell the presenter of the start of a scenario execution. present(executor.presenter, scenario) # The `context` object for a scenario execution is provided to each step, # so they may store intermediate values. context = StepDefinitionContext() beforescenario(executor.executionenv, context, scenario) # Execute the Background section isfailedyet = false backgroundresults, isfailedyet = executesteps(executor, context, background.steps, isfailedyet) # Execute the Scenario results, _isfailedyet = executesteps(executor, context, scenario.steps, isfailedyet) afterscenario(executor.executionenv, context, scenario) scenarioresult = ScenarioResult(results, scenario, background, backgroundresults) present(executor.presenter, scenario, scenarioresult) scenarioresult end """ executescenario(::Executor, ::Gherkin.ScenarioOutline) Execute a `Scenario Outline`, which contains one or more examples. Each example is transformed into a regular `Scenario`, and it's executed. Reeturns a list of `ScenarioResult`s. """ function executescenario(executor::Executor, background::Gherkin.Background, outline::Gherkin.ScenarioOutline) scenarios = transformoutline(outline) [executescenario(executor, background, scenario) for scenario in scenarios] end "The execution result for a feature, containing one or more scenarios." struct FeatureResult feature::Feature scenarioresults::Vector{ScenarioResult} end """ extendresults!(scenarioresults, result::ScenarioResult) extendresults!(scenarioresults, result::AbstractVector{ScenarioResult}) Push or append results from a feature to a list of scenario results. """ extendresult!(scenarioresults::AbstractVector{ScenarioResult}, result::ScenarioResult) = push!(scenarioresults, result) extendresult!(scenarioresults::AbstractVector{ScenarioResult}, result::AbstractVector{ScenarioResult}) = append!(scenarioresults, result) """ executefeature(::Executor, ::Gherkin.Feature) Execute all scenarios and scenario outlines in a feature. """ function executefeature(executor::Executor, feature::Gherkin.Feature; keepgoing::Bool=true) # A hook that runs before each feature. beforefeature(executor.executionenv, feature) # Present that a new feature is about to be executed. present(executor.presenter, feature) # Execute each scenario and scenario outline in the feature. scenarioresults = ScenarioResult[] for scenario in feature.scenarios scenarioresult = executescenario(executor, feature.background, scenario) extendresult!(scenarioresults, scenarioresult) if !issuccess(scenarioresult) && !keepgoing break end end # A hook that runs after each feature afterfeature(executor.executionenv, feature) # Return a list of `ScenarioResults`. # Since regular scenarios return a `ScenarioResult` directly, and scenario outlines return lists # of `ScenarioResult`s, we have to flatten that list. FeatureResult(feature, reduce(vcat, scenarioresults, init=[])) end # # Finding missing step implementations # function findmissingsteps(executor::Executor, steps::Vector{ScenarioStep}) :: Vector{ScenarioStep} findstep = step -> begin try findstepdefinition(executor.stepdefmatcher, step) catch ex if ex isa NoMatchingStepDefinition NoStepDefinitionFound(step) else rethrow(ex) end end end filter(step -> findstep(step) isa NoStepDefinitionFound, steps) end function findmissingsteps(executor::Executor, feature::Feature) :: Vector{ScenarioStep} backgroundmissingsteps = findmissingsteps(executor, feature.background.steps) # findmissingstep(executor, scenario.steps) returns a list of missing steps, # so we're creating a list of lists here. We flatten it into one list of missing steps. missingsteps = Iterators.flatten([ findmissingsteps(executor, scenario.steps) for scenario in feature.scenarios ]) # We call unique to remove duplicate steps. # We check uniqueness using only the step text, ignoring block text # and data tables. unique(step -> step.text, vcat(collect(missingsteps), backgroundmissingsteps)) end function stepimplementationsuggestion(steptype::String, text::String) :: String # Escaping the string here ensures that the step text is a valid Julia string. # If the text is # some precondition with $x and a quote " # then the $x will be interpreted as string interpolation by Julia, which is # not what we intend. Also, the " needs to be escaped so we don't have mismatched # double quotes. escaped_text = escape_string(text, "\$\"") """$steptype(\"$(escaped_text)\") do context @fail "Implement me" end """ end stepimplementationsuggestion(given::Given) :: String = stepimplementationsuggestion("@given", given.text) stepimplementationsuggestion(when::When) :: String = stepimplementationsuggestion("@when", when.text) stepimplementationsuggestion(then::Then) :: String = stepimplementationsuggestion("@then", then.text) function suggestmissingsteps(executor::Executor, feature::Feature) :: String missingsteps = findmissingsteps(executor, feature) missingstepimpls = [ stepimplementationsuggestion(step) for step in missingsteps ] missingstepcode = join(missingstepimpls, "\n\n") """ using Behavior $(missingstepcode) """ end # # Interpolation of Scenario Outlines # function transformoutline(outline::ScenarioOutline) # The examples are in a multidimensional array. # The size of dimension 1 is the number of placeholders. # The size of dimension 2 is the number of examples. [interpolatexample(outline, outline.examples[:,exampleindex]) for exampleindex in 1:size(outline.examples, 2)] end function interpolatexample(outline::ScenarioOutline, example::Vector{T}) where {T <: AbstractString} # Create placeholders on the form `<foo>` for each placeholder `foo`, and map it against the # value for this particular example. # # An example Scenario Outline could have two placeholders `foo` and `bar`: # Scenario Outline: An example # When some action <foo> # Then some postcondition <bar> # # Examples: # | foo | bar | # | 1 | 2 | # | 17 | 42 | # # The parsed Scenario Outline object already has a list of the placeholders `foo` and `bar`. # This method is called twice, once with example vector `[1, 2]` and once with `[17, 42]`. # placeholders_kv = ["<$(outline.placeholders[i])>" => example[i] for i in 1:length(example)] placeholders = Dict{String, T}(placeholders_kv...) # `interpolatestep` just creates a new scenario step of the same type, but with all occurrences # of placeholders replace with the example value. fromplaceholders = x -> placeholders[x] steps = ScenarioStep[interpolatestep(step, fromplaceholders) for step in outline.steps] Scenario(outline.description, outline.tags, steps) end interpolatestep(step::Given, fromplaceholders::Function) = Given(interpolatesteptext(step.text, fromplaceholders); block_text=interpolatesteptext(step.block_text, fromplaceholders), datatable=step.datatable) interpolatestep(step::When, fromplaceholders::Function) = When(interpolatesteptext(step.text, fromplaceholders); block_text=interpolatesteptext(step.block_text, fromplaceholders), datatable=step.datatable) interpolatestep(step::Then, fromplaceholders::Function) = Then(interpolatesteptext(step.text, fromplaceholders); block_text=interpolatesteptext(step.block_text, fromplaceholders), datatable=step.datatable) interpolatesteptext(text::String, fromplaceholders::Function) = replace(text, r"<[^>]*>" => fromplaceholders)
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
4269
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ A `QuietRealTimePresenter` prints nothing as scenarios are being executed. This is useful if you're only after a final report, after all features have been executed. """ struct QuietRealTimePresenter <: RealTimePresenter end present(::QuietRealTimePresenter, ::Scenario) = nothing present(::QuietRealTimePresenter, ::Scenario, ::ScenarioResult) = nothing present(::QuietRealTimePresenter, ::Gherkin.ScenarioStep) = nothing present(::QuietRealTimePresenter, ::Gherkin.ScenarioStep, ::StepExecutionResult) = nothing present(::QuietRealTimePresenter, ::Gherkin.Feature) = nothing """ This presenter prints a line to the console before, during, and after a scenario. Results are color coded. """ struct ColorConsolePresenter <: RealTimePresenter io::IO colors::Dict{Type, Symbol} function ColorConsolePresenter(io::IO = stdout) colors = Dict{Type, Symbol}( NoStepDefinitionFound => :yellow, NonUniqueMatch => :magenta, SuccessfulStepExecution => :green, StepFailed => :red, UnexpectedStepError => :light_magenta, SkippedStep => :light_black ) new(io, colors) end end """ stepformat(step::ScenarioStep) Format a step according to Gherkin syntax. """ stepformat(step::Given) = "Given $(step.text)" stepformat(step::When) = " When $(step.text)" stepformat(step::Then) = " Then $(step.text)" stepformat(step::Gherkin.Experimental.And) = " And $(step.text)" """ stepcolor(::Presenter, ::StepExecutionResult) Get a console color for a given result when executing a scenario step. """ stepcolor(presenter::Presenter, step::StepExecutionResult) = presenter.colors[typeof(step)] """ stepresultmessage(::StepExecutionResult) A human readable message for a given result. """ function stepresultmessage(step::StepFailed) if isempty(step.evaluated) || step.assertion == step.evaluated ["FAILED: " * step.assertion] else ["FAILED", " Expression: " * step.assertion, " Evaluated: " * step.evaluated] end end stepresultmessage(nomatch::NoStepDefinitionFound) = ["No match for '$(stepformat(nomatch.step))'"] stepresultmessage(nonunique::NonUniqueMatch) = vcat(["Multiple matches found:"], [" In " * location.filename for location in nonunique.locations]) stepresultmessage(::SuccessfulStepExecution) = [] stepresultmessage(::SkippedStep) = [] stepresultmessage(unexpected::UnexpectedStepError) = vcat(["Exception: $(string(unexpected.ex))"], [" " * string(x) for x in unexpected.stack]) stepresultmessage(::StepExecutionResult) = [] function present(presenter::ColorConsolePresenter, feature::Feature) println() printstyled(presenter.io, "Feature: $(feature.header.description)\n"; color=:white) end function present(presenter::ColorConsolePresenter, scenario::Scenario) printstyled(presenter.io, " Scenario: $(scenario.description)\n"; color=:blue) end function present(presenter::ColorConsolePresenter, scenario::Scenario, ::ScenarioResult) printstyled(presenter.io, "\n") end function present(presenter::ColorConsolePresenter, step::Gherkin.ScenarioStep) printstyled(presenter.io, " $(stepformat(step))"; color=:light_cyan) end function present(presenter::ColorConsolePresenter, step::Gherkin.ScenarioStep, result::StepExecutionResult) color = stepcolor(presenter, result) printstyled(presenter.io, "\r $(stepformat(step))\n"; color=color) resultmessage = stepresultmessage(result) if !isempty(resultmessage) # The result message may be one or more lines. Indent them all. s = [" " ^ 8 * x * "\n" for x in resultmessage] println() println(join(s)) end end
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
3131
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Combine a feature along with the number of scenario successes and failures. """ struct FeatureSuccessAndFailure feature::Feature n_success::UInt n_failure::UInt end """ Accumulate results from executed features as they are being executed. Keep track of whether the total run is a success of a failure. """ mutable struct ResultAccumulator isaccumsuccess::Bool features::Vector{FeatureSuccessAndFailure} errors::Vector{Tuple{String, Gherkin.BadParseResult{Feature}}} ResultAccumulator() = new(true, [], []) end """ accumulateresult!(acc::ResultAccumulator, result::FeatureResult) Check for success or failure in this feature result and update the accumulator accordingly. """ function accumulateresult!(acc::ResultAccumulator, result::FeatureResult) n_success::UInt = 0 n_failure::UInt = 0 # Count the number of successes and failures for each step in each scenario. A scenario is # successful if all its steps are successful. for scenarioresult in result.scenarioresults arestepssuccessful = [issuccess(step) for step in scenarioresult.steps] arebackgroundstepsgood = [issuccess(result) for result in scenarioresult.backgroundresult] isscenariosuccessful = all(arestepssuccessful) && all(arebackgroundstepsgood) if isscenariosuccessful n_success += 1 else n_failure += 1 end acc.isaccumsuccess &= isscenariosuccessful end push!(acc.features, FeatureSuccessAndFailure(result.feature, n_success, n_failure)) end """ accumulateresult!(acc::ResultAccumulator, parsefailure::Gherkin.BadParseResult{Feature}) A feature file could not be parsed properly. Record the error. """ const BadParseType = Union{Gherkin.BadParseResult{Feature}, Gherkin.Experimental.BadParseResult{Feature}} function accumulateresult!(acc::ResultAccumulator, parsefailure::BadParseType, featurefile::String) push!(acc.errors, (featurefile, parsefailure)) acc.isaccumsuccess = false end """ issuccess(acc::ResultAccumulator) True if all scenarios in all accumulated features are successful. """ issuccess(acc::ResultAccumulator) = acc.isaccumsuccess """ featureresults(accumulator::ResultAccumulator) A public getter for the results of all features. """ function featureresults(accumulator::ResultAccumulator) accumulator.features end """ isempty(r::ResultAccumulator) :: Bool True if no results have been accumulated, false otherwise. """ Base.isempty(r::ResultAccumulator) :: Bool = isempty(r.features)
Behavior
https://github.com/erikedin/Behavior.jl.git
[ "Apache-2.0" ]
0.4.0
6836146e6131a4cdc48722eb9700e19603278875
code
8469
# Copyright 2018 Erik Edin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. using Behavior: ExecutorEngine, ColorConsolePresenter, Driver, readstepdefinitions!, runfeatures!, issuccess, FromSourceExecutionEnvironment, NoExecutionEnvironment import Behavior: findfileswithextension, readfile, fileexists using Behavior.Gherkin using Behavior.Gherkin.Experimental using Glob struct OSAL <: Behavior.OSAbstraction end function findfileswithextension(::OSAL, path::String, extension::String) return rglob("*$extension", path) end readfile(::OSAL, path::String) = read(path, String) fileexists(::OSAL, path::String) = isfile(path) """ rglob(pattern, path) Find files recursively. """ rglob(pattern, path) = Base.Iterators.flatten(map(d -> glob(pattern, d[1]), walkdir(path))) function parseonly(featurepath::String; parseoptions::ParseOptions=ParseOptions()) # ----------------------------------------------------------------------------- # borrowed code from runspec; should be refactored later os = OSAL() engine = ExecutorEngine(ColorConsolePresenter(); executionenv=NoExecutionEnvironment()) driver = Driver(os, engine) # ----------------------------------------------------------------------------- featurefiles = rglob("*.feature", featurepath) # Parse all feature files and collect results to an array of named tuples results = [] for featurefile in featurefiles if parseoptions.use_experimental try input = Experimental.ParserInput(read(featurefile, String)) featureparser = Experimental.FeatureFileParser() result = featureparser(input) if Experimental.isparseok(result) push!(results, (filename = featurefile, success = true, result = result.value)) else push!(results, (filename = featurefile, success = false, result = result)) end catch ex push!(results, (filename = featurefile, success = false, result = Experimental.BadExceptionParseResult{Feature}(ex))) end else try parseddata = parsefeature(readfile(driver.os, featurefile), options=parseoptions) isbad = parseddata isa BadParseResult push!(results, (filename = featurefile, success = !isbad, result = parseddata)) catch ex push!(results, (filename = featurefile, success = false, result = Gherkin.BadParseResult{Feature}(:exception, :nothing, Symbol("$ex"), 0, ""))) end end end return results end """ printbadparseresult(error::BadParseResult{T}) Print parse errors. """ function printbadparseresult(featurefile::String, err::Gherkin.BadParseResult{T}) where {T} println("ERROR: $(featurefile):$(err.linenumber)") println(" Line: $(err.line)") println(" Reason: $(err.reason)") println(" Expected: $(err.expected)") println(" Actual: $(err.actual)") end """ runspec(rootpath; featurepath, stepspath, execenvpath, parseoptions, presenter, tags) Execute all features found from the `rootpath`. By default, it looks for feature files in `<rootpath>/features` and step files `<rootpath>/features/steps`. An `environment.jl` file may be added to `<rootpath>/features` directory for running certain before/after code. You may override the default locations by specifying `featurepath`, `stepspath`, or `execenvpath`. The `tagselector` option is an expression you can use to select which scenarios to run based on tags. For instance, the tag selector `@foo` will run only those scenarios that have the tag `@foo`, while `not @ignore` will run only that scenarios that _do not_ have the `@ignore` tag. See also: [Gherkin.ParseOptions](@ref). """ function runspec( rootpath::String = "."; featurepath = joinpath(rootpath, "features"), stepspath = joinpath(featurepath, "steps"), execenvpath = joinpath(featurepath, "environment.jl"), parseoptions::ParseOptions=ParseOptions(), presenter::RealTimePresenter=ColorConsolePresenter(), tags::String = "", keepgoing::Bool=true ) os = OSAL() executionenv = if fileexists(os, execenvpath) FromSourceExecutionEnvironment(readfile(os, execenvpath)) else NoExecutionEnvironment() end if parseoptions.use_experimental println("WARNING: Experimental parser used for feature files!") println() end # TODO: Handle tag selector errors once the syntax is more complex. selector = Selection.parsetagselector(tags) engine = ExecutorEngine(presenter; executionenv=executionenv, selector=selector) driver = Driver(os, engine) readstepdefinitions!(driver, stepspath) resultaccumulator = runfeatures!(driver, featurepath, parseoptions=parseoptions, keepgoing=keepgoing) if isempty(resultaccumulator) println("No features found.") return true end # # Present number of scenarios that succeeded and failed for each feature # results = featureresults(resultaccumulator) # Find the longest feature name, so we can align the result table. maxfeature = maximum(length(r.feature.header.description) for r in results) featureprefix = " Feature: " printstyled(" " ^ (length(featureprefix) + maxfeature + 1), "| Success | Failure\n"; color=:white) for r in results linecolor = r.n_failure == 0 ? :green : :red printstyled(featureprefix, rpad(r.feature.header.description, maxfeature); color=linecolor) printstyled(" | "; color=:white) printstyled(rpad("$(r.n_success)", 7); color=:green) printstyled(" | "; color=:white) printstyled(rpad("$(r.n_failure)", 7), "\n"; color=linecolor) end println() # # Present any syntax errors # for (featurefile, err) in resultaccumulator.errors println() printbadparseresult(featurefile, err) end println() istotalsuccess = issuccess(resultaccumulator) if istotalsuccess println("SUCCESS") else println("FAILURE") end istotalsuccess end """ suggestmissingsteps(featurepath::String, stepspath::String; parseoptions::ParseOptions=ParseOptions(), tagselector::String = "") Find missing steps from the feature and print suggestions on step implementations to match those missing steps. """ function suggestmissingsteps( featurepath::String, stepspath = joinpath(dirname(featurepath), "steps"); parseoptions::ParseOptions=ParseOptions()) # All of the below is quite hacky, which I'm motivating by the fact that # I just want something working. It most definitely indicates that I need to rework the whole # Driver/ExecutorEngine design. # ----------------------------------------------------------------------------- # borrowed code from runspec; should be refactored later os = OSAL() engine = ExecutorEngine(QuietRealTimePresenter(); executionenv=NoExecutionEnvironment()) driver = Driver(os, engine) readstepdefinitions!(driver, stepspath) # Parse the feature file and suggest missing steps. BadParseResultTypes = Union{Gherkin.BadParseResult{Feature}, Experimental.BadParseResult{Feature}} parseresult = if parseoptions.use_experimental println("WARNING: suggestmissingsteps is using the experimental Gherkin parser") input = ParserInput(read(featurepath, String)) parser = Experimental.FeatureFileParser() parser(input) else parsefeature(read(featurepath, String), options=parseoptions) end if parseresult isa BadParseResultTypes println("Failed to parse feature file $featurepath") println(parseresult) return end feature = parseresult.value suggestedcode = suggestmissingsteps(driver.engine.executor, feature) println(suggestedcode) end
Behavior
https://github.com/erikedin/Behavior.jl.git