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.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
code
3297
""" grad(fdm, f, x::AbstractVector) Approximate the gradient of `f` at `x` using `fdm`. Assumes that `f(x)` is scalar. """ function grad(fdm, f, x::Vector{T}) where T<:Real v, dx, tmp = fill(zero(T), size(x)), similar(x), similar(x) for n in eachindex(x) v[n] = one(T) dx[n] = fdm(function(ϵ) tmp .= x .+ ϵ .* v return f(tmp) end, zero(T), ) v[n] = zero(T) end return dx end """ jacobian(fdm, f, x::AbstractVector{<:Real}, D::Int) jacobian(fdm, f, x::AbstractVector{<:Real}) Approximate the Jacobian of `f` at `x` using `fdm`. `f(x)` must be a length `D` vector. If `D` is not provided, then `f(x)` is computed once to determine the output size. """ function jacobian(fdm, f, x::Vector{T}, D::Int) where {T<:Real} J = Matrix{T}(undef, D, length(x)) for d in 1:D J[d, :] = grad(fdm, x->f(x)[d], x) end return J end jacobian(fdm, f, x::Vector{<:Real}) = jacobian(fdm, f, x, length(f(x))) """ _jvp(fdm, f, x::Vector{<:Real}, ẋ::AbstractVector{<:Real}) Convenience function to compute `jacobian(f, x) * ẋ`. """ _jvp(fdm, f, x::Vector{<:Real}, ẋ::AV{<:Real}) = jacobian(fdm, f, x) * ẋ """ _j′vp(fdm, f, ȳ::AbstractVector{<:Real}, x::Vector{<:Real}) Convenience function to compute `jacobian(f, x)' * ȳ`. """ _j′vp(fdm, f, ȳ::AV{<:Real}, x::Vector{<:Real}) = jacobian(fdm, f, x, length(ȳ))' * ȳ """ jvp(fdm, f, x, ẋ) Compute a Jacobian-vector product with any types of arguments for which `to_vec` is defined. """ function jvp(fdm, f, (x, ẋ)::Tuple{Any, Any}) x_vec, vec_to_x = to_vec(x) _, vec_to_y = to_vec(f(x)) return vec_to_y(_jvp(fdm, x_vec->to_vec(f(vec_to_x(x_vec)))[1], x_vec, to_vec(ẋ)[1])) end function jvp(fdm, f, xẋs::Tuple{Any, Any}...) x, ẋ = collect(zip(xẋs...)) return jvp(fdm, xs->f(xs...), (x, ẋ)) end """ j′vp(fdm, f, ȳ, x...) Compute an adjoint with any types of arguments for which `to_vec` is defined. """ function j′vp(fdm, f, ȳ, x) x_vec, vec_to_x = to_vec(x) ȳ_vec, _ = to_vec(ȳ) return vec_to_x(_j′vp(fdm, x_vec->to_vec(f(vec_to_x(x_vec)))[1], ȳ_vec, x_vec)) end j′vp(fdm, f, ȳ, xs...) = j′vp(fdm, xs->f(xs...), ȳ, xs) """ to_vec(x) Transform `x` into a `Vector`, and return a closure which inverts the transformation. """ to_vec(x::Real) = ([x], first) # Arrays. to_vec(x::Vector{<:Real}) = (x, identity) to_vec(x::Array) = vec(x), x_vec->reshape(x_vec, size(x)) # AbstractArrays. function to_vec(x::T) where {T<:LinearAlgebra.AbstractTriangular} x_vec, back = to_vec(Matrix(x)) return x_vec, x_vec->T(reshape(back(x_vec), size(x))) end to_vec(x::Symmetric) = vec(Matrix(x)), x_vec->Symmetric(reshape(x_vec, size(x))) to_vec(X::Diagonal) = vec(Matrix(X)), x_vec->Diagonal(reshape(x_vec, size(X)...)) function to_vec(X::T) where T<:Union{Adjoint,Transpose} U = T.name.wrapper return vec(Matrix(X)), x_vec->U(permutedims(reshape(x_vec, size(X)))) end # Non-array data structures. function to_vec(x::Tuple) x_vecs, x_backs = zip(map(to_vec, x)...) sz = cumsum([map(length, x_vecs)...]) return vcat(x_vecs...), function(v) return ntuple(n->x_backs[n](v[sz[n]-length(x_vecs[n])+1:sz[n]]), length(x)) end end
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
code
9416
export fdm, backward_fdm, forward_fdm, central_fdm """ FDM.DEFAULT_CONDITION The default [condition number](https://en.wikipedia.org/wiki/Condition_number) used when computing bounds. It provides amplification of the ∞-norm when passed to the function's derivatives. """ const DEFAULT_CONDITION = 100 """ FDM.TINY A tiny number added to some quantities to ensure that division by 0 does not occur. """ const TINY = 1e-20 forward_grid(p::Int) = 0:(p - 1) backward_grid(p::Int) = (1 - p):0 function central_grid(p::Int) if isodd(p) return div(1 - p, 2):div(p - 1, 2) else return vcat(div(-p, 2):-1, 1:div(p, 2)) end end """ History A mutable type that tracks several values during adaptive bound computation. """ mutable struct History adapt::Int eps::Real bound::Real step::Real accuracy::Real function History(; kwargs...) h = new() for (k, v) in kwargs setfield!(h, k, v) end return h end end """ FDMethod Abstract type for all finite differencing method types. Subtypes of `FDMethod` are callable with the signature ``` method(f, x; kwargs...) ``` where the keyword arguments can be any of * `adapt`: The number of adaptive steps to use improve the estimate of `bound`. * `bound`: Bound on the value of the function and its derivatives at `x`. * `condition`: The condition number. See [`DEFAULT_CONDITION`](@ref). * `eps`: The assumed roundoff error. Defaults to `eps()` plus [`TINY`](@ref). """ abstract type FDMethod end function Base.show(io::IO, x::FDMethod) @printf io "FDMethod:\n" @printf io " order of method: %d\n" x.p @printf io " order of derivative: %d\n" x.q @printf io " grid: %s\n" x.grid @printf io " coefficients: %s\n" x.coefs h = x.history if all(p->isdefined(h, p), propertynames(h)) @printf io " roundoff error: %.2e\n" h.eps @printf io " bounds on derivatives: %.2e\n" h.bound @printf io " step size: %.2e\n" h.step @printf io " accuracy: %.2e\n" h.accuracy end end for D in (:Forward, :Backward, :Central, :Nonstandard) @eval begin struct $D{G<:AbstractVector, C<:AbstractVector} <: FDMethod p::Int q::Int grid::G coefs::C history::History end (d::$D)(f, x=0.0; kwargs...) = fdm(d, f, x; kwargs...) end end # The below does not apply to Nonstandard, as it has its own constructor for D in (:Forward, :Backward, :Central) lcname = lowercase(String(D)) gridf = Symbol(lcname, "_grid") fdmf = Symbol(lcname, "_fdm") @eval begin # Compatibility layer over the "old" API function $fdmf(p::Integer, q::Integer; adapt=1, kwargs...) _dep_kwarg(kwargs) return $D(p, q; adapt=adapt, kwargs...) end function $D(p::Integer, q::Integer; adapt=1, kwargs...) _check_p_q(p, q) grid = $gridf(p) coefs = _coefs(grid, p, q) hist = History(; adapt=adapt, kwargs...) return $D{typeof(grid), typeof(coefs)}(Int(p), Int(q), grid, coefs, hist) end @doc """ FDM.$($(Meta.quot(D)))(p, q; kwargs...) $($(Meta.quot(fdmf)))(p, q; kwargs...) Construct a $($lcname) finite difference method of order `p` to compute the `q`th derivative. See [`FDMethod`](@ref) for more details. """ ($D, $fdmf) end end """ FDM.Nonstandard(grid, q; kwargs...) An finite differencing method which is constructed based on a user-defined grid. It is nonstandard in the sense that it represents neither forward, backward, nor central differencing. See [`FDMethod`](@ref) for further details. """ function Nonstandard(grid::AbstractVector{<:Real}, q::Integer; adapt=0, kwargs...) p = length(grid) _check_p_q(p, q) coefs = _coefs(grid, p, q) hist = History(; adapt=adapt, kwargs...) return Nonstandard{typeof(grid), typeof(coefs)}(Int(p), Int(q), grid, coefs, hist) end # Check the method and derivative orders for consistency function _check_p_q(p::Integer, q::Integer) q < p || throw(ArgumentError("order of the method must be strictly greater than that " * "of the derivative")) # Check whether the method can be computed. We require the factorial of the # method order to be computable with regular `Int`s, but `factorial` will overflow # after 20, so 20 is the largest we can allow. p > 20 && throw(ArgumentError("order of the method is too large to be computed")) return end # Compute coefficients for the method function _coefs(grid::AbstractVector{<:Real}, p::Integer, q::Integer) C = [g^i for i in 0:(p - 1), g in grid] x = zeros(Int, p) x[q + 1] = factorial(q) return C \ x end # Estimate the bound on the function value and its derivatives at a point _estimate_bound(x, cond) = cond * maximum(abs, x) + TINY """ fdm(m::FDMethod, f, x[, Val(false)]; kwargs...) -> Real fdm(m::FDMethod, f, x, Val(true); kwargs...) -> Tuple{FDMethod, Real} Compute the derivative of `f` at `x` using the finite differencing method `m`. The optional `Val` argument dictates whether the method should be returned alongside the derivative value, which can be useful for examining the step size used and other such parameters. The recognized keywords are: * `adapt`: The number of adaptive steps to use improve the estimate of `bound`. * `bound`: Bound on the value of the function and its derivatives at `x`. * `condition`: The condition number. See [`DEFAULT_CONDITION`](@ref). * `eps`: The assumed roundoff error. Defaults to `eps()` plus [`TINY`](@ref). !!! warning Bounds can't be adaptively computed over nonstandard grids; passing a value for `adapt` greater than 0 when `m::Nonstandard` results in an error. !!! note Calling [`FDMethod`](@ref) objects is equivalent to passing them to `fdm`. # Examples ```julia-repl julia> fdm(central_fdm(5, 1), sin, 1; adapt=2) 0.5403023058681039 julia> fdm(central_fdm(2, 1), exp, 0, Val(true)) (FDMethod: order of method: 2 order of derivative: 1 grid: [-1, 1] coefficients: [-0.5, 0.5] roundoff error: 1.42e-14 bounds on derivatives: 1.00e+02 step size: 1.69e-08 accuracy: 1.69e-06 , 1.0000000031817473) ``` """ function fdm( m::M, f, x, ::Val{true}; condition=DEFAULT_CONDITION, bound=_estimate_bound(f(x), condition), eps=(Base.eps(float(bound)) + TINY), adapt=m.history.adapt, max_step=0.1, ) where M<:FDMethod if M <: Nonstandard && adapt > 0 throw(ArgumentError("can't adaptively compute bounds over Nonstandard grids")) end eps > 0 || throw(ArgumentError("eps must be positive, got $eps")) bound > 0 || throw(ArgumentError("bound must be positive, got $bound")) 0 <= adapt < 20 - m.p || throw(ArgumentError("can't perform $adapt adaptation steps")) p = m.p q = m.q grid = m.grid coefs = m.coefs # Adaptively compute the bound on the function and derivative values, if applicable. if adapt > 0 newm = (M.name.wrapper)(p + 1, p) dfdx = fdm( newm, f, x; condition=condition, eps=eps, bound=bound, max_step=max_step, adapt=(adapt - 1), ) bound = _estimate_bound(dfdx, condition) end # Set the step size by minimising an upper bound on the error of the estimate. C₁ = eps * sum(abs, coefs) C₂ = bound * sum(n->abs(coefs[n] * grid[n]^p), eachindex(coefs)) / factorial(p) ĥ = min((q / (p - q) * C₁ / C₂)^(1 / p), max_step) # Estimate the accuracy of the method. accuracy = ĥ^(-q) * C₁ + ĥ^(p - q) * C₂ # Estimate the value of the derivative. dfdx = sum(i->coefs[i] * f(x + ĥ * grid[i]), eachindex(grid)) / ĥ^q m.history.eps = eps m.history.bound = bound m.history.step = ĥ m.history.accuracy = accuracy return m, dfdx end function fdm(m::FDMethod, f, x, ::Val{false}=Val(false); kwargs...) _, dfdx = fdm(m, f, x, Val(true); kwargs...) return dfdx end ## Deprecations # Used for keyword argument name deprecations function _dep_kwarg(kwargs) for (old, new) in [(:ε, :eps), (:M, :bound)] haskey(kwargs, old) || continue val = kwargs[old] error( "keyword argument `", old, "` should now be passed as `", new, "` upon ", "application of the method. For example:\n ", "central_fdm(5, 1)(f, x; $new=$val)\n", "not\n ", "central_fdm(5, 1; $old=$val)(f, x)" ) end end function fdm( grid::AbstractVector{<:Real}, q::Int, ::Union{Val{true}, Val{false}}=Val(false); kwargs..., ) error("to use a custom grid, use `Nonstandard(grid, q)` and pass the result to `fdm`") end for fdmf in (:central_fdm, :backward_fdm, :forward_fdm) @eval function $fdmf(p::Int, q::Int, ::Union{Val{true}, Val{false}}; kwargs...) error( "the `Val` argument should now be passed directly to `fdm` after ", "constructing the method, not to the method constructor itself" ) end end
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
code
1327
export assert_approx_equal """ assert_approx_equal(x, y, ε_abs, ε_rel[, desc]) Assert that `x` is approximately equal to `y`. Let `eps_z = eps_abs / eps_rel`. Call `x` and `y` small if `abs(x) < eps_z` and `abs(y) < eps_z`, and call `x` and `y` large otherwise. If this function returns `True`, then it is guaranteed that `abs(x - y) < 2 eps_rel max(abs(x), abs(y))` if `x` and `y` are large, and `abs(x - y) < 2 eps_abs` if `x` and `y` are small. # Arguments - `x`: First object to compare. - `y`: Second object to compare. - `ε_abs`: Absolute tolerance. - `ε_rel`: Relative tolerance. - `desc`: Description of the comparison. Omit or set to `false` to have no description. """ function assert_approx_equal(x, y, ε_abs, ε_rel, desc) if abs(x - y) >= ε_abs + ε_rel * max(abs(x), abs(y)) msg = "$(desc != false ? "\"$desc\": " : "")large deviation from reference:\n" * " relative error: $(@sprintf "%.3e" abs(x - y) / max(abs(x), abs(y)))\n" * " tolerance: $(@sprintf "%.3e" ε_rel)\n" * " absolute error: $(@sprintf "%.3e" abs(x - y))\n" * " tolerance: $(@sprintf "%.3e" ε_abs)\n" throw(ErrorException(msg)) end return true end assert_approx_equal(x, y, ε_abs, ε_rel) = assert_approx_equal(x, y, ε_abs, ε_rel, false)
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
code
3648
using FDM: grad, jacobian, _jvp, _j′vp, jvp, j′vp, to_vec # Dummy type where length(x::DummyType) ≠ length(first(to_vec(x))) struct DummyType{TX<:Matrix} X::TX end function FDM.to_vec(x::DummyType) x_vec, back = to_vec(x.X) return x_vec, x_vec -> DummyType(back(x_vec)) end Base.:(==)(x::DummyType, y::DummyType) = x.X == y.X Base.length(x::DummyType) = size(x.X, 1) @testset "grad" begin @testset "grad" begin rng, fdm = MersenneTwister(123456), central_fdm(5, 1) x = randn(rng, 2) xc = copy(x) @test grad(fdm, x->sin(x[1]) + cos(x[2]), x) ≈ [cos(x[1]), -sin(x[2])] @test xc == x end function check_jac_and_jvp_and_j′vp(fdm, f, ȳ, x, ẋ, J_exact) xc = copy(x) @test jacobian(fdm, f, x, length(ȳ)) ≈ J_exact @test jacobian(fdm, f, x) == jacobian(fdm, f, x, length(ȳ)) @test _jvp(fdm, f, x, ẋ) ≈ J_exact * ẋ @test _j′vp(fdm, f, ȳ, x) ≈ J_exact' * ȳ @test xc == x end @testset "jacobian / _jvp / _j′vp" begin rng, P, Q, fdm = MersenneTwister(123456), 3, 2, central_fdm(5, 1) ȳ, A, x, ẋ = randn(rng, P), randn(rng, P, Q), randn(rng, Q), randn(rng, Q) Ac = copy(A) check_jac_and_jvp_and_j′vp(fdm, x->A * x, ȳ, x, ẋ, A) @test Ac == A check_jac_and_jvp_and_j′vp(fdm, x->sin.(A * x), ȳ, x, ẋ, cos.(A * x) .* A) @test Ac == A end function test_to_vec(x) x_vec, back = to_vec(x) @test x_vec isa Vector @test x == back(x_vec) return nothing end @testset "to_vec" begin test_to_vec(1.0) test_to_vec(1) test_to_vec(randn(3)) test_to_vec(randn(5, 11)) test_to_vec(randn(13, 17, 19)) test_to_vec(randn(13, 0, 19)) test_to_vec(UpperTriangular(randn(13, 13))) test_to_vec(Symmetric(randn(11, 11))) test_to_vec(Diagonal(randn(7))) test_to_vec(DummyType(randn(2, 9))) @testset "$T" for T in (Adjoint, Transpose) test_to_vec(T(randn(4, 4))) test_to_vec(T(randn(6))) test_to_vec(T(randn(2, 5))) end @testset "Tuples" begin test_to_vec((5, 4)) test_to_vec((5, randn(5))) test_to_vec((randn(4), randn(4, 3, 2), 1)) test_to_vec((5, randn(4, 3, 2), UpperTriangular(randn(4, 4)), 2.5)) test_to_vec(((6, 5), 3, randn(3, 2, 0, 1))) test_to_vec((DummyType(randn(2, 7)), DummyType(randn(3, 9)))) test_to_vec((DummyType(randn(3, 2)), randn(11, 8))) end end @testset "jvp" begin rng, N, M, fdm = MersenneTwister(123456), 2, 3, central_fdm(5, 1) x, y = randn(rng, N), randn(rng, M) ẋ, ẏ = randn(rng, N), randn(rng, M) xy, ẋẏ = vcat(x, y), vcat(ẋ, ẏ) ż_manual = _jvp(fdm, (xy)->sum(sin, xy), xy, ẋẏ)[1] ż_auto = jvp(fdm, x->sum(sin, x[1]) + sum(sin, x[2]), ((x, y), (ẋ, ẏ))) ż_multi = jvp(fdm, (x, y)->sum(sin, x) + sum(sin, y), (x, ẋ), (y, ẏ)) @test ż_manual ≈ ż_auto @test ż_manual ≈ ż_multi end @testset "j′vp" begin rng, N, M, fdm = MersenneTwister(123456), 2, 3, central_fdm(5, 1) x, y = randn(rng, N), randn(rng, M) z̄ = randn(rng, N + M) xy = vcat(x, y) x̄ȳ_manual = j′vp(fdm, xy->sin.(xy), z̄, xy) x̄ȳ_auto = j′vp(fdm, x->sin.(vcat(x[1], x[2])), z̄, (x, y)) x̄ȳ_multi = j′vp(fdm, (x, y)->sin.(vcat(x, y)), z̄, x, y) @test x̄ȳ_manual ≈ vcat(x̄ȳ_auto...) @test x̄ȳ_manual ≈ vcat(x̄ȳ_multi...) end end
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
code
2990
using FDM: Forward, Backward, Central, Nonstandard @testset "Methods" begin for f in [:forward_fdm, :backward_fdm, :central_fdm] @eval @test $f(10, 1; bound=1)(sin, 1) ≈ cos(1) @eval @test $f(10, 2; bound=1)(sin, 1) ≈ -sin(1) @eval @test $f(10, 1; bound=1)(exp, 1) ≈ exp(1) @eval @test $f(10, 2; bound=1)(exp, 1) ≈ exp(1) @eval @test $f(10, 1; bound=1)(abs2, 1) ≈ 2 @eval @test $f(10, 2; bound=1)(abs2, 1) ≈ 2 @eval @test $f(10, 1; bound=1)(sqrt, 1) ≈ .5 @eval @test $f(10, 2; bound=1)(sqrt, 1) ≈ -.25 end @testset "Adaptation improves estimate" begin @test forward_fdm(5, 1)(log, 0.001; adapt=0) ≈ 969.2571703 @test forward_fdm(5, 1)(log, 0.001; adapt=1) ≈ 1000 end @testset "Limiting step size" begin @test !isfinite(central_fdm(5, 1)(abs, 0.001; max_step=0)) @test central_fdm(5, 1)(abs, 0.001) ≈ 1.0 end @testset "Printing FDMethods" begin @test sprint(show, central_fdm(2, 1)) == """ FDMethod: order of method: 2 order of derivative: 1 grid: [-1, 1] coefficients: [-0.5, 0.5] """ m, _ = fdm(central_fdm(2, 1), sin, 1, Val(true)) report = sprint(show, m) regex_float = r"[\d\.\+-e]+" regex_array = r"\[([\d.+-e]+(, )?)+\]" @test occursin(Regex(join(map(x -> x.pattern, [ r"FDMethod:", r"order of method:", r"\d+", r"order of derivative:", r"\d+", r"grid:", regex_array, r"coefficients:", regex_array, r"roundoff error:", regex_float, r"bounds on derivatives:", regex_float, r"step size:", regex_float, r"accuracy:", regex_float, r"" ] ), r"\s*".pattern)), report) end @testset "Breaking deprecations" begin @test_throws ErrorException fdm([1,2,3], 4) # Custom grids need Nonstandard for f in (forward_fdm, backward_fdm, central_fdm) @test_throws ErrorException f(2, 1; M=1) # Old kwarg, now misplaced @test_throws ErrorException f(2, 1, Val(true)) # Ask fdm for reports instead end end @testset "Types" begin @testset "$T" for T in (Forward, Backward, Central) @test T(5, 1)(sin, 1; adapt=4) ≈ cos(1) @test_throws ArgumentError T(3, 4) @test_throws ArgumentError T(40, 5) @test_throws ArgumentError T(5, 1)(sin, 1; adapt=200) @test_throws ArgumentError T(5, 1)(sin, 1; eps=0.0) @test_throws ArgumentError T(5, 1)(sin, 1; bound=0.0) end @testset "Nonstandard" begin @test Nonstandard([-2, -1, 1], 1)(sin, 1) ≈ cos(1) @test_throws ArgumentError Nonstandard([-2, -1, 1], 1)(sin, 1; adapt=2) end end end
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
code
604
@testset "Numerics" begin @test_throws ErrorException assert_approx_equal(1, 1 + 1e-5, 1e-10, 1e-6, "assertion") @test_throws ErrorException assert_approx_equal(1, 1 + 1e-5, 1e-10, 1e-6) @test assert_approx_equal(1, 1 + 1e-7, 1e-10, 1e-6, "assertion") @test assert_approx_equal(1, 1 + 1e-7, 1e-10, 1e-6) @test_throws ErrorException assert_approx_equal(0, 1e-9, 1e-10, 1e-6, "assertion") @test_throws ErrorException assert_approx_equal(0, 1e-9, 1e-10, 1e-6) @test assert_approx_equal(0, 1e-11, 1e-10, 1e-6, "assertion") @test assert_approx_equal(0, 1e-11, 1e-10, 1e-6) end
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
code
149
using FDM, Test, Random, Printf, LinearAlgebra @testset "FDM" begin include("methods.jl") include("numerics.jl") include("grad.jl") end
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
docs
1649
# FDM.jl: Finite Difference Methods [![Build Status](https://travis-ci.org/invenia/FDM.jl.svg?branch=master)](https://travis-ci.org/invenia/FDM.jl) [![Windows Build status](https://ci.appveyor.com/api/projects/status/g0gun5dxbkt631am/branch/master?svg=true)](https://ci.appveyor.com/project/invenia/fdm-jl/branch/master) [![codecov.io](http://codecov.io/github/invenia/FDM.jl/coverage.svg?branch=master)](http://codecov.io/github/invenia/FDM.jl?branch=master) [![Latest Docs](https://img.shields.io/badge/docs-latest-blue.svg)](https://invenia.github.io/FDM.jl/latest/) FDM.jl estimates derivatives with finite differences. See also [FDM](https://github.com/wesselb/fdm). ## Examples Compute the first derivative of `sin` with a 5th order central method: ```julia julia> central_fdm(5, 1)(sin, 1) - cos(1) -1.247890679678676e-13 ``` Compute the second derivative of `sin` with a 5th order central method: ```julia julia> central_fdm(5, 2)(sin, 1) + sin(1) 9.747314066999024e-12 ``` Construct a FDM on a custom grid: ```julia julia> method, report = fdm([-2, 0, 5], 1, report=true) (FDM.method, FDMReport: order of method: 3 order of derivative: 1 grid: [-2, 0, 5] coefficients: [-0.357143, 0.3, 0.0571429] roundoff error: 2.22e-16 bounds on derivatives: 1.00e+00 step size: 3.62e-06 accuracy: 6.57e-11 ) julia> method(sin, 1) - cos(1) -2.05648831297367e-11 ``` Compute a directional derivative: ```julia julia> f(x) = sum(x) f (generic function with 1 method) julia> central_fdm(5, 1)(ε -> f([1, 1, 1] + ε * [1, 2, 3]), 0) - 6 -2.922107000813412e-13 ```
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
docs
1451
# FDM.jl: Finite Difference Methods [![Build Status](https://travis-ci.org/invenia/FDM.jl.svg?branch=master)](https://travis-ci.org/invenia/FDM.jl) [![codecov.io](http://codecov.io/github/invenia/FDM.jl/coverage.svg?branch=master)](http://codecov.io/github/invenia/FDM.jl?branch=master) [![Latest Docs](https://img.shields.io/badge/docs-latest-blue.svg)](https://invenia.github.io/FDM.jl/latest/) FDM.jl approximates derivatives of functions using finite difference methods. ## Examples Compute the first derivative of `sin` with a 5th order central method: ```julia julia> central_fdm(5, 1)(sin, 1) - cos(1) -1.247890679678676e-13 ``` Compute the second derivative of `sin` with a 5th order central method: ```julia julia> central_fdm(5, 2)(sin, 1) + sin(1) 9.747314066999024e-12 ``` Construct a FDM on a custom grid: ```julia julia> method, report = fdm([-2, 0, 5], 1, report=true) (FDM.method, FDMReport: order of method: 3 order of derivative: 1 grid: [-2, 0, 5] coefficients: [-0.357143, 0.3, 0.0571429] roundoff error: 2.22e-16 bounds on derivatives: 1.00e+00 step size: 3.62e-06 accuracy: 6.57e-11 ) julia> method(sin, 1) - cos(1) -2.05648831297367e-11 ``` Compute a directional derivative: ```julia julia> f(x) = sum(x) f (generic function with 1 method) julia> central_fdm(5, 1)(ε -> f([1, 1, 1] + ε * [1, 2, 3]), 0) - 6 -2.922107000813412e-13 ```
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.1
51f56372090c3af1ce784610c5cf3c4c224563e4
docs
49
```@autodocs Modules = [FDM] Private = false ```
FDM
https://github.com/invenia/FDM.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
177
using Documenter, Espresso makedocs() deploydocs( deps = Deps.pip("mkdocs", "python-markdown-math"), repo = "github.com/dfdx/Espresso.jl.git", julia = "0.6" )
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
1967
__precompile__() module Espresso export # utils ExH, to_block, parse_call_args, parse_call_expr, make_call_expr, with_keywords, without_keywords, # rewrite matchex, matchingex, findex, subs, rewrite, tryrewrite, rewrite_all, without, set_default_placeholders, # simplification simplify, @simple_rule, # funexpr funexpr, func_expr, func_name, get_or_generate_argnames, # indexing split_indexed, make_indexed, with_indices, get_vars, get_var_names, get_indices, find_vars, find_var_names, find_indices, forall_sum_indices, forall_indices, sum_indices, # ExNode ExNode, getcategory, getvar, setvar!, varname, varidxs, getexpr, getexpr_kw, setexpr!, getguards, setguards!, getvalue, setvalue!, indexof, dependencies, to_expr, to_expr_kw, isindexed, # ExGraph core AbstractExGraph, ExGraph, parse!, reparse, evaluate!, cat, fuse_assigned, # ExGraph utils dependents, external_vars, topsort, collect_deps, expand_deps, expand_const, remove_unused, eliminate_common, inline_nodes, graph_hash, # expr utils mergeex, sanitize, # tracking TrackedArray, TrackedReal, tracked_val, tracked_exgraph, swap_default_graph!, reset_default_graph!, # conversions to_buffered, to_inplace, @inplacerule, # destruct make_func_expr, isstruct, field_values, named_field_values, destruct, destruct_inputs, # codegens generate_code, VectorCodeGen, BufCodeGen, CuCodeGen, GPUCodeGen, autoselect_codegen, # helpers sum_1, sum_2, squeeze_sum, squeeze_sum_1, squeeze_sum_2, __construct, # re-export mul! include("core.jl") end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
816
# codegen.jl - utils to generate code in different formats from ExGraph and EinGraph include("codegens/vec.jl") include("codegens/buf.jl") include("codegens/cuda.jl") include("codegens/cudavec.jl") include("codegens/gpu.jl") function autoselect_codegen(inputs) # assuming inputs is Base.Iterators.Pairs or Vector{Any} with pairs first_array_idx = findfirst(a -> isa(a, AbstractArray) && eltype(a) != Any, [v for (k,v) in inputs]) first_array_idx != nothing || return VectorCodeGen() eltyp = eltype(inputs[first_array_idx][2]) # we don't want to include CuArrays as dependency, so working on strings if any(startswith(string(typeof(v)), "CuArray") for (k, v) in inputs) return CuCodeGen(eltyp) else return BufCodeGen(eltyp) end end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
829
# core.jl - single place to load all package definitions. # # If you want to learn the package structure, just go through # included files one by one, read header notes and other comments # using Sugar using LinearAlgebra using Statistics import Base: CodeInfo if VERSION <= v"1.10" import Base: Slot else import Core.Compiler.SlotNumber const Slot = SlotNumber end include("types.jl") include("utils.jl") include("rewrite.jl") include("simplify.jl") include("sugar.jl") include("funexpr.jl") include("indexing.jl") include("preprocess.jl") include("exnode.jl") include("exgraph.jl") include("tracked.jl") include("evaluate.jl") include("graph_utils.jl") include("expand_deps.jl") include("optimize.jl") include("merge.jl") include("inplace.jl") include("codegen.jl") include("destruct.jl") include("helpers.jl")
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
1680
## destruct.jl - deconstruction of structs ## ## TODO: now Espresso supports structures natively, remove this? "Check if an object is of a struct type, i.e. not a number or array" isstruct(::Type{T}) where T = !isbits(T) && !(T <: AbstractArray) isstruct(obj) = !isbits(obj) && !isa(obj, AbstractArray) field_values(m) = [getfield(m, f) for f in fieldnames(typeof(m))] named_field_values(m) = [f => getfield(m, f) for f in fieldnames(typeof(m))] """ Replace all struct arguments by a list of their plain analogues. Example: args = [:m, :x, :y] types = (Linear, Matrix{Float64}, Matrix{Float64}) ex = :(sum((m.W * x .+ m.b) - y)) destruct(args, types, ex) # ==> # ([:m_W, :m_b, :x, :y], # :(sum((m_W * x .+ m_b) - y)), # Dict(:(m.W) => :m_W, :(m.b) => :m_b)) """ function destruct(args::Vector{Symbol}, types, ex) st = Dict() new_args = Symbol[] for (arg, T) in zip(args, types) if isstruct(T) for f in fieldnames(T) new_arg = Symbol("$(arg)_$(f)") push!(new_args, new_arg) f_ex = Expr(:., arg, QuoteNode(f)) st[f_ex] = new_arg end else push!(new_args, arg) end end return new_args, subs(ex, st), st end function destruct_inputs(inputs) new_inputs = [] for (k, v) in inputs if isstruct(v) for f in fieldnames(v) new_arg = Symbol("$(k)_$(f)") new_val = getfield(v, f) push!(new_inputs, new_arg => new_val) end else push!(new_inputs, k => v) end end return new_inputs end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
4614
## evaluate.jl - evaluation of graph function remember_size!(g::AbstractExGraph, nd::ExNode) rsizes = @get_or_create(g.ctx, :rsizes, Dict{Symbol,Any}()) buff_exprs = @get_or_create(g.ctx, :buff_exprs, Dict{Symbol, Any}()) val = getvalue(nd) if isa(val, AbstractArray) || isa(val, Number) sz = size(val) rsizes[varname(nd)] = sz if isa(val, Array) T = eltype(val) buff_expr = :(zeros($T, $sz)) else T = typeof(val) buff_expr = :(zero($T)) end buff_exprs[varname(nd)] = buff_expr end end function remember_size!(g::AbstractExGraph, nd::ExNode{:tuple}) end function isconv(nd::ExNode) depwarn_eingraph(:isconv) idxs = nd |> getexpr |> get_indices |> flatten return any(i -> isa(i, Expr), idxs) end function mk_eval_expr(g::ExGraph, nd::ExNode) dep_nodes = [g[dep] for dep in dependencies(nd) if haskey(g, dep)] deps_vals = Dict((varname(nd), getvalue(nd)) for nd in dep_nodes) evex = Expr(:block) for dep in unique(keys(deps_vals)) val = deps_vals[dep] push!(evex.args, :(local $dep = $val)) end codegen = eval_codegen(@get(g.ctx, :codegen, VectorCodeGen())) push!(evex.args, generate_code(codegen, g, nd)) push!(evex.args, varname(nd)) return evex end function mk_eval_expr(g::ExGraph, nd::ExNode{:ctor}) dep_nodes = [g[dep] for dep in dependencies(nd) if haskey(g, dep)] deps_vals = Dict((varname(nd), getvalue(nd)) for nd in dep_nodes) evex = Expr(:block) for dep in unique(keys(deps_vals)) val = deps_vals[dep] push!(evex.args, :(local $dep = $val)) end push!(evex.args, to_expr_kw(nd)) push!(evex.args, varname(nd)) return evex end # function mk_eval_expr(g::ExGraph, nd::ExNode{:ctor}) # dep_nodes = [g[dep] for dep in dependencies(nd) if haskey(g, dep)] # deps_vals = [(varname(nd), getvalue(nd)) for nd in dep_nodes] # eval_ex = Expr(:block, Expr(:let, Expr(:block))) # block = eval_ex.args[1].args[1] # for (dep, val) in unique(deps_vals) # push!(block.args, :(local $dep = $val)) # end # push!(block.args, to_expr_kw(nd)) # push!(block.args, varname(nd)) # return eval_ex # end """ Evaluate node, i.e. fill its `val` by evaluating node's expression using values of its dependencies. """ function evaluate!(g::ExGraph, nd::ExNode{:constant}; force=false) ex = getexpr(nd) if getvalue(nd) == nothing && (isa(ex, Symbol) || isa(ex, Expr)) # constant expression - need to evaluate it evex = mk_eval_expr(g, nd) val = Core.eval(g.ctx[:mod], evex) setvalue!(nd, val) end remember_size!(g, nd) return getvalue(nd) end function evaluate!(g::AbstractExGraph, nd::ExNode{:input}; force=false) remember_size!(g, nd) return getvalue(nd) end function evaluate!(g::AbstractExGraph, nd::ExNode{:(=)}; force=false) if (!force && getvalue(nd) != nothing) return getvalue(nd) end dep = dependencies(nd)[1] evaluate!(g, g[dep]; force=false) evex = mk_eval_expr(g, nd) setvalue!(nd, Core.eval(g.ctx[:mod], evex)) remember_size!(g, nd) return getvalue(nd) end # nd::Union{ExNode{:call}, ExNode{:bcast}, ExNode{:ctor}, # ExNode{:tuple}, ExNode{:opaque}} function evaluate!(g::AbstractExGraph, nd::ExNode; force=false) if (!force && getvalue(nd) != nothing) return getvalue(nd) end deps = dependencies(nd) for dep in deps # if dep is not in graph, consider it a global constant (like π) if haskey(g.idx, dep) evaluate!(g, g[dep]; force=false) # force affects only current node end end evex = mk_eval_expr(g, nd) setvalue!(nd, Core.eval(g.ctx[:mod], evex)) remember_size!(g, nd) return getvalue(nd) end function evaluate!(g::AbstractExGraph, nd::ExNode{:field}; force=false) if (!force && getvalue(nd) != nothing) return getvalue(nd) end depnd = g[dependencies(nd)[1]] obj = getvalue(depnd) fld = getexpr(nd).args[2].value val = getfield(obj, fld) setvalue!(nd, val) remember_size!(g, nd) return getvalue(nd) end evaluate!(g::AbstractExGraph, name::Symbol; force=false) = evaluate!(g, g[name]; force=force) function evaluate!(g::AbstractExGraph; force=false) for i=1:length(g) try evaluate!(g, g[i]; force=force) catch e mod = @get(g.ctx, :mod, nothing) @info("Failed to evaluate node (in module $mod): $(g[i])") throw(e) end end return getvalue(g[end]) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
13791
# exgraph.jl - expression graph as a list of primitive expression nodes abstract type AbstractExGraph end mutable struct ExGraph <: AbstractExGraph tape::Vector{ExNode} # list of ExNode-s idx::Dict{Symbol, ExNode} # map from var name to its node in the graph ctx::Dict{Any,Any} # settings and caches end function ExGraph(; ctx=Dict(), inputs...) ctx = to_context(ctx) # @get_or_create(ctx, :mod, @__MODULE__) @get_or_create(ctx, :mod, get_caller_module()) g = ExGraph(ExNode[], Dict(), ctx) for (var, val) in inputs push!(g, :input, var, var; val=val) end return g end function ExGraph(ex::Expr; fuse=true, ctx=Dict(), inputs...) ex = preprocess(ex) ctx = to_context(ctx) g = ExGraph(;ctx=ctx, inputs...) g.ctx[:expr] = ex method = @get(g.ctx, :method, :parse) if method == :parse parse!(g, ex) elseif method == :track eval_tracked!(g, ex, inputs...) else error("Method $method is not supported") end if fuse g = fuse_assigned(g) end return g end function Base.deepcopy(g::AbstractExGraph) ctx_copy = to_context(Dict()) for (k, v) in g.ctx if isa(v, Module) ctx_copy[k] = v else ctx_copy[k] = deepcopy(v) end end return typeof(g)(deepcopy(g.tape), deepcopy(g.idx), ctx_copy) end function Base.show(io::IO, g::ExGraph) print(io, "ExGraph\n") for node in g.tape print(io, " $node\n") end end Base.haskey(g::AbstractExGraph, var::Symbol) = haskey(g.idx, var) Base.in(var::Symbol, g::AbstractExGraph) = haskey(g, var) Base.lastindex(g::AbstractExGraph) = lastindex(g.tape) Base.length(g::AbstractExGraph) = length(g.tape) Base.get(g::AbstractExGraph, var::Symbol) = g.idx[var] Base.getindex(g::AbstractExGraph, var::Symbol) = g.idx[var] Base.getindex(g::AbstractExGraph, var::String) = g.idx[Symbol(var)] Base.getindex(g::AbstractExGraph, i::Integer) = g.tape[i] Base.setindex!(g::AbstractExGraph, nd::ExNode, i::Integer) = (g.tape[i] = nd; g.idx[varname(nd)] = nd) # indexof(g::AbstractExGraph, vname::Symbol) = findfirst(map(varname, g.tape), vname) indexof(g::AbstractExGraph, vname::Symbol) = findfirst(isequal(vname), map(varname, g.tape)) getsize(g::AbstractExGraph, vname::Symbol) = g.ctx[:rsizes][vname] getsize(g::AbstractExGraph, nd::ExNode) = getsize(g, varname(nd)) Base.iterate(g::ExGraph) = length(g) >= 1 ? (g[1], 2) : nothing Base.iterate(g::ExGraph, state) = length(g) >= state ? (g[state], state + 1) : nothing function Base.cat(g1::T, g2::T) where T<:AbstractExGraph return T(vcat(g1.tape, g2.tape), merge(g1.idx, g2.idx), merge(g1.ctx, g2.ctx)) end function to_expr(g::AbstractExGraph) res = quote end for nd in g.tape if !isa(nd, ExNode{:input}) push!(res.args, to_expr(nd)) end end return res end function to_expr_kw(g::AbstractExGraph) res = quote end for nd in g.tape if !isa(nd, ExNode{:input}) push!(res.args, to_expr_kw(nd)) end end return res end function eval_tracked!(g::ExGraph, ex::Expr, inputs...) og = swap_default_graph!(g) evex = ex.head == :block ? deepcopy(ex) : Expr(:block, deepcopy(ex)) for (var, val) in inputs tv = isa(val, AbstractArray) ? TrackedArray(g, var, val) : TrackedReal(g, var, val) pushfirst!(evex.args, :($var = $tv)) end Core.eval(@get(g.ctx, :mod, Main), evex) new_g = reparse(swap_default_graph!(og); all=true) # copy nodes, but keep old context; maybe we will introduce special copyto! for this later g.tape = new_g.tape g.idx = new_g.idx return g end """Generate a new unique name for intermediate variable in graph""" function genname() s = String(gensym()) return Symbol(replace(s, "##" => "tmp")) end function genname(prefix::String) s = String(gensym()) return Symbol(replace(s, "##" => prefix)) end function genname(prefix::Symbol) s = String(gensym()) return Symbol(replace(s, "##" => prefix)) end function gennames(count::Int) return [genname() for _=1:count] end function rename_repeated(g::AbstractExGraph, ex) st = @get_or_create(g.ctx, :renamings, Dict()) st = prop_subs(st) return subs(ex, st) end rename_repeated(g::AbstractExGraph, ex::ExH) = rename_repeated(g, Expr(ex)) function add_renaming!(g::AbstractExGraph, var::Symbol) old = var while var in g var = inc_var_name(var) end st = @get_or_create(g.ctx, :renamings, Dict()) st[old] = var return var end ## push!, insert!, delete! """ Add a new node to a graph. Expression should be simple, e.g. nested calls or blocks are not allowed (use parse!() for it). """ function Base.push!(g::AbstractExGraph, nd::ExNode) @assert(!haskey(g, varname(nd)), "Graph already contains a node with name $(varname(nd))!") push!(g.tape, nd) g.idx[varname(nd)] = nd return varname(nd) end function Base.push!(g::AbstractExGraph, C::Symbol, var::Union{Symbol,Expr}, ex::Any; val=nothing, meta=Dict()) @assert(!haskey(g, split_indexed(var)[1]), "Graph already contains a node with name $(var)!") nd = ExNode{C}(var, ex; val=val, meta=meta) push!(g, nd) return var end function Base.insert!(g::AbstractExGraph, i::Integer, nd::ExNode) g.idx[varname(nd)] = nd insert!(g.tape, i, nd) end function Base.insert!(g::AbstractExGraph, i::Integer, nds::Vector{ExNode}) for (j, nd) in enumerate(nds) insert!(g, i + j - 1, nd) end end function Base.delete!(g::AbstractExGraph, i::Integer) delete!(g.idx, varname(g[i])) deleteat!(g.tape, i) end function Base.delete!(g::AbstractExGraph, vname::Symbol) delete!(g.idx, vname) i = findall(nd -> varname(nd) == vname, g.tape) deleteat!(g.tape, i) end ## parse! """ Parse Julia expression and build ExGraph in-place. Return the the output variable. """ parse!(g::AbstractExGraph, ex::Expr) = parse!(g, ExH(ex)) parse!(g::AbstractExGraph, ::LineNumberNode) = :nil parse!(g::AbstractExGraph, ::ExH{:line}) = :nil parse!(g::AbstractExGraph, s::Symbol) = rename_repeated(g, s) function parse!(g::AbstractExGraph, x::Number) if haskey(g.ctx, :bitness) x = force_bitness(x, Val(g.ctx[:bitness])) end var = push!(g, :constant, genname(), x; val=x) return var end function parse!(g::AbstractExGraph, x::AbstractArray) if haskey(g.ctx, :bitness) x = force_bitness(x, Val(g.ctx[:bitness])) end var = push!(g, :constant, genname(), x; val=x) return var end function parse!(g::AbstractExGraph, x::ExH{:vect}) @assert all(e -> e isa Number, x.args) "Can only create vector literal node with numbers" nums = convert(Vector{Float64}, x.args) if haskey(g.ctx, :bitness) nums = force_bitness(nums, Val(g.ctx[:bitness])) end var = push!(g, :constant, genname(), nums; val=nums) return var end function parse!(g::ExGraph, ex::ExH{:(=)}) lhs, rhs = ex.args rhs = rename_repeated(g, rhs) dep = parse!(g, rhs) if isa(lhs, Symbol) if haskey(g, lhs) lhs = add_renaming!(g, lhs) end push!(g, :(=), lhs, dep) return lhs elseif isa(lhs, Expr) && lhs.head == :tuple last_vname = nothing for (i, vname) in enumerate(lhs.args) parse!(g, :($vname = $dep[$i])) end return last_vname else error("LHS of $(Expr(ex)) is neither variable, nor tuple") end end function parse!(g::ExGraph, ex::ExH{:ref}) ex = rename_repeated(g, ex) # @assert isa(ex.args[2], Number) "Currently only constant indices are supported" idx_vars = [parse!(g, v) for v in ex.args[2:end]] base = isa(ex.args[1], Symbol) ? ex.args[1] : parse!(g, ex.args[1]) vname = push!(g, :ref, genname(), Expr(:ref, base, idx_vars...)) return vname end # operations that are guaranted to never change their value const CONST_OPS = Set([:length]) function parse!(g::ExGraph, ex::ExH{:call}) ex = rename_repeated(g, ex) op = canonical(g.ctx[:mod], ex.args[1]) args, kw_args = parse_call_args(ex) meta = isempty(kw_args) ? Dict() : Dict(:kw => kw_args) deps = [parse!(g, arg) for arg in args] pex = Expr(:call, op, deps...) if op in CONST_OPS && isempty(meta) var = push!(g, :constant, genname(), pex) else var = push!(g, :call, genname(), pex; meta=meta) end return var end function parse!(g::ExGraph, ex::ExH{:.}) ex = rename_repeated(g, ex) if isa(ex.args[2], Expr) && ex.args[2].head == :tuple # broadcasting op = canonical(g.ctx[:mod], ex.args[1]) deps = [parse!(g, arg) for arg in ex.args[2].args] # pex = Expr(:call, op, deps...) pex = Expr(:., op, Expr(:tuple, deps...)) var = push!(g, :bcast, genname(), pex) return var elseif isa(ex.args[2], QuoteNode) # field var = push!(g, :field, genname(), ex) return var end end function parse!(g::ExGraph, ex::ExH{Symbol("'")}) ex = rename_repeated(g, ex) dep = parse!(g, ex.args[1]) pex = :(transpose($dep)) var = push!(g, :call, genname(), pex) return var end function parse!(g::AbstractExGraph, ex::Union{ExH{:block}, ExH{:body}}) deps = [parse!(g, arg) for arg in ex.args] return deps[end] end function parse!(g::ExGraph, ex::ExH{:tuple}) ex = rename_repeated(g, ex) deps = [parse!(g, arg) for arg in ex.args] pex = Expr(:tuple, deps...) vname = push!(g, :tuple, genname(), pex) end ## reparsing of opaque nodes function reparse(g::AbstractExGraph; all=false) new_g = reset_tape(g) for nd in g.tape if isa(nd, ExNode{:input}) || isa(nd, ExNode{:constant}) push!(new_g, nd) elseif all || isa(nd, ExNode{:opaque}) parse!(new_g, to_expr(nd)) else push!(new_g, nd) end end return fuse_assigned(new_g) end ## graph simlification istemp(var::Symbol) = startswith(string(var), "tmp") function external_vars(g::AbstractExGraph) ext_vnames = Set{Symbol}() for nd in g.tape for dep in dependencies(nd) if !haskey(g, dep) push!(ext_vnames, dep) end end end return ext_vnames end function assign_chain!(g::AbstractExGraph, nd::ExNode{:(=)}, guards::Vector{Expr}, chain::Vector{Symbol}) if getguards(nd) == guards # && !is_special_expr(getexpr(nd)) push!(chain, varname(nd)) dep = dependencies(nd)[1] if haskey(g, dep) && !isa(g[dep], ExNode{:input}) && !isa(g[dep], ExNode{:constant}) dep_nd = g[dep] assign_chain!(g, dep_nd, guards, chain) end end return chain end function assign_chain!(g::AbstractExGraph, nd::ExNode{C}, guards::Vector{Expr}, chain::Vector{Symbol}) where C if getguards(nd) == guards push!(chain, varname(nd)) end end """ Collect all replacable variables from a chain of assignments in a graph. Variables `y` and `x` are considered replacable if there's a node `y = x` and both variables have the same set of guards. Note that this allows nodes to have different sets of indices. """ assign_chain(g::AbstractExGraph, nd::ExNode{C}) where {C} = assign_chain!(g, nd, getguards(nd), Vector{Symbol}()) function assign_chain_index_replacements(g::AbstractExGraph, chain::Vector{Symbol}) nd = g[chain[1]] root_nd = g[chain[end]] st = Dict(zip(varidxs(nd), varidxs(nd))) for i=2:length(chain) prev_idxs = get_indices(getexpr(g[chain[i-1]]))[1] cur_idxs = varidxs(g[chain[i]]) pair_st = Dict(zip(prev_idxs, cur_idxs)) new_st = Dict() for (k, v) in st if haskey(pair_st, v) # propagate replacements new_st[k] = pair_st[v] end end st = new_st end # indices that occur in RHS of the root assignment node, but not on its LHS root_free_idxs_ = find_indices(to_expr(root_nd)) |> flatten |> Set root_free_idxs = Any[idx for idx in root_free_idxs_ if !in(idx, values(st))] free_st = index_replacements(Set(keys(st)), root_free_idxs) rev_st = Dict(zip(values(st), keys(st))) return merge(rev_st, free_st) end """ Collapse unnecessary assignment nodes, rewriting all affected nodes. Example: tmp1 = x * y z = tmp1 will be rewritten to z = x * y """ function fuse_assigned(g::AbstractExGraph; outvars=nothing) new_g = reset_tape(g) for nd in g.tape if isa(nd, ExNode{:(=)}) chain = assign_chain(g, nd) root_assign_nd = g[chain[end]] new_ex = getexpr(root_assign_nd) # st = assign_chain_index_replacements(g, chain) # new_ex = subs(new_ex_, st) new_nd = copy(root_assign_nd; var=getvar(nd), ex=new_ex) push!(new_g, new_nd) else push!(new_g, copy(nd)) end end new_g = remove_unused(new_g, outvars == nothing ? [varname(new_g[end])] : outvars) return new_g end function fuse_assigned(g::ExGraph; outvars=nothing) new_g = reset_tape(g) for nd in g.tape if isa(nd, ExNode{:(=)}) chain = assign_chain(g, nd) root_assign_nd = g[chain[end]] new_ex = getexpr(root_assign_nd) new_nd = copy(root_assign_nd; var=getvar(nd), ex=new_ex) push!(new_g, new_nd) else push!(new_g, copy(nd)) end end new_g = remove_unused(new_g, outvars == nothing ? [varname(new_g[end])] : outvars) return new_g end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
5631
# exnode.jl - ExNode, the building block of ExGraph # # There are several categories of ExNodes: # # * :call - single function call, e.g. ExNode{:call}(z = x + y) # * :bcast - broadcasting, e.g. ExNode{:bcast}(y = exp.(x)) # * :(=) - assignment, e.g. ExNode{:(=)}(y = x) # * :input - input variable # * :constant - constant, e.g. ExNode{:constant}(x = 42) # * :opaque - unparsed expression that can contain any subexpression; # a graph with opaque nodes isn't valid for most tasks, # but it may be converted to normalized graph using `reparse(g)` # exnode mutable struct ExNode{C} # C - category of node, e.g. :call, :=, etc. var::Union{Symbol, Expr} # variable name, possibly with indices ex::Any # primitive expression that produces the var guards::Vector{Expr} # guards, turning ex to 0 when false val::Any # example value meta::Dict # node metadata & optional parameters end function ExNode{C}(var::Union{Symbol,Expr}, ex::Any; guards=[], val=nothing, meta=Dict()) where C return ExNode{C}(var, ex, guards, val, meta) end function ExNode{C}(full_ex::Expr; val=nothing) where C @assert full_ex.head == :(=) var = full_ex.args[1] ex = without_guards(full_ex.args[2]) guards = find_guards(full_ex.args[2]) return ExNode{C}(var, ex; guards=guards, val=val) end ## accessors getcategory(nd::ExNode{C}) where {C} = C getvar(nd::ExNode) = nd.var setvar!(nd::ExNode, var::Union{Symbol,Expr}) = (nd.var = var) varname(nd::ExNode)::Symbol = isa(nd.var, Symbol) ? nd.var : nd.var.args[1] varidxs(nd::ExNode)::Vector = isa(nd.var, Symbol) ? [] : nd.var.args[2:end] varidxs(nd::ExNode{:input})::Vector = IDX_NAMES[1:ndims(getvalue(nd))] getexpr(nd::ExNode) = nd.ex setexpr!(nd::ExNode, ex::Any) = (nd.ex = ex) getguards(nd::ExNode) = nd.guards setguards!(nd::ExNode, guards::Vector{Expr}) = (nd.guards = guards) getvalue(nd::ExNode) = nd.val setvalue!(nd::ExNode, val) = (nd.val = val) Base.copy(nd::ExNode{C}; category=C, var=nd.var, ex=nd.ex, guards=nd.guards, val=nd.val, meta=nd.meta) where {C} = ExNode{category}(var, ex, guards, val, meta) ## pseudo-accessors function getexpr_kw(nd::ExNode) if haskey(nd.meta, :kw) && !isempty(nd.meta[:kw]) ex = copy(getexpr(nd)) insert!(ex.args, 2, make_kw_params(nd.meta[:kw])) return ex else return getexpr(nd) end end function setexpr_kw!(nd::Union{ExNode{:call}, ExNode{:ctor}}, ex) f = ex.args[1] args, kw = parse_call_args(ex) nd.ex = :($f($(args...))) nd.meta[:kw] = kw end setexpr_kw!(nd::ExNode, ex) = setexpr!(nd, ex) ## to_expr and friends """ Convert ExNode to a full expression, e.g. for vectorized notation: z = x + y or for indexed notation: z[i] = x[i] + y[i] """ function to_expr(nd::ExNode) var = getvar(nd) ex = with_guards(getexpr(nd), getguards(nd)) return :($var = $ex) end """ Same as to_expr(ExNode), but includes keyword arguments if any """ function to_expr_kw(nd::ExNode) var = getvar(nd) ex = with_guards(getexpr_kw(nd), getguards(nd)) return :($var = $ex) end """ Convert ExNode to a fortmat compatible with Einsum.jl """ function to_einsum_expr(nd::ExNode) depwarn_eingraph(:to_einsum_expr) ex = getexpr(nd) v = varname(nd) assign_ex = Expr(:(:=), getvar(nd), ex) macrocall_ex = Expr(:macrocall, Symbol("@einsum"), assign_ex) return Expr(:block, macrocall_ex) end function to_einsum_expr(nd::ExNode, var_size) depwarn_eingraph(:to_einsum_expr) ex = getexpr(nd) v = varname(nd) init_ex = :($v = zeros($(var_size))) # TODO: handle data types other than Float64 assign_ex = Expr(:(=), getvar(nd), ex) macrocall_ex = Expr(:macrocall, Symbol("@einsum"), assign_ex) return Expr(:block, init_ex, macrocall_ex) end ## dependencies """Get names of dependenices of this node""" dependencies(nd::ExNode{:input}) = Symbol[] dependencies(nd::ExNode{:constant}) = get_var_names(getexpr(nd)) dependencies(nd::ExNode{:(=)}) = get_var_names(getexpr(nd)) dependencies(nd::ExNode{:call}) = get_var_names(getexpr(nd)) dependencies(nd::ExNode{:bcast}) = get_var_names(getexpr(nd)) dependencies(nd::ExNode{:tuple}) = [split_indexed(dep)[1] for dep in getexpr(nd).args] dependencies(nd::ExNode{:ref}) = getexpr(nd).args dependencies(nd::ExNode{:opaque}) = get_var_names(getexpr(nd); rec=true) dependencies(nd::ExNode{:field}) = [getexpr(nd).args[1]] dependencies(nd::ExNode{:ctor}) = [getexpr(nd).args[2], values(get(nd.meta, :kw, Dict()))...] ## node utils # varsize(nd::ExNode{:tuple}) = map(size, getvalue(nd)) # varsize(nd::ExNode) = size(getvalue(nd)) # buffer_expr(nd::ExNode{:tuple}) function Base.show(io::IO, nd::ExNode{C}) where C val = getvalue(nd) if val == nothing val = "nothing" elseif isa(val, AbstractArray) val = "<$(typeof(val))>" elseif isa(val, Tuple) val = ([isa(v, AbstractArray) ? "<$(typeof(v))>" : v for v in val]...,) elseif isstruct(val) val = "$(typeof(getvalue(nd)))" end ex_str = "ExNode{$C}($(to_expr_kw(nd)) | $val)" print(io, ex_str) end isindexed(nd::ExNode) = any(isref, get_vars(to_expr(nd))) function rewrite(nd::ExNode{C}, pat, rpat; rw_opts...) where C full_ex = to_expr(nd) new_full_ex = rewrite(full_ex, pat, rpat; rw_opts...) @assert new_full_ex.head == :(=) var, ex = new_full_ex.args[1:2] return copy(nd; category=:opaque, var=var, ex=ex, val=nothing) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
2752
# expand_deps.jl - collect & expand all dependencies of a variable in AbstractExGraph ## collect_deps function collect_deps!(g::AbstractExGraph, nd::ExNode, depth::Int, result::Set{Symbol}) if depth > 0 for dep in dependencies(nd) if haskey(g, dep) collect_deps!(g, g[dep], depth - 1, result) end end end push!(result, varname(nd)) end function collect_deps!(g::AbstractExGraph, ex::Expr, depth::Int, result::Set{Symbol}) vnames = get_var_names(ex, rec=true) for vname in vnames collect_deps!(g, vname, depth, result) end end function collect_deps!(g::AbstractExGraph, x::Symbol, depth::Int, result::Set{Symbol}) if haskey(g, x) collect_deps!(g, g[x], depth, result) end end function collect_deps!(g::AbstractExGraph, x, depth::Int, result::Set{Symbol}) # do nothing end function collect_deps(g::AbstractExGraph, nd::ExNode, depth::Int=typemax(Int)) result = Set{Symbol}() collect_deps!(g, nd, depth, result) return result end function collect_deps(g::AbstractExGraph, ex::Expr, depth::Int=typemax(Int)) result = Set{Symbol}() collect_deps!(g, ex, depth, result) return result end function collect_deps(g::AbstractExGraph, x::Symbol, depth::Int=typemax(Int)) result = Set{Symbol}() collect_deps!(g, x, depth, result) return result end function collect_deps(g::AbstractExGraph, xs::Vector{Symbol}, depth::Int=typemax(Int)) result = Set{Symbol}() for x in xs collect_deps!(g, x, depth, result) end return result end collect_deps(g::AbstractExGraph, x, depth::Int=typemax(Int)) = Set{Symbol}() ## expand_deps function expand_deps!(g::AbstractExGraph, nd::ExNode{:input}, depth::Int, result::Vector{Expr}) # do nothing end function expand_deps!(g::AbstractExGraph, nd::ExNode{:constat}, depth::Int, result::Vector{Expr}) push!(result, to_expr(nd)) end function expand_deps!(g::AbstractExGraph, nd::ExNode{:(=)}, depth::Int, result::Vector{Expr}) if depth > 0 expand_deps!(g, [g[var] for var in dependencies(nd)], depth - 1, result) push!(result, to_expr(nd)) end end function expand_deps!(g::AbstractExGraph, nd::ExNode{:call}, depth::Int, result::Vector{Expr}) if depth > 0 for dep in dependencies(nd) expand_deps!(g, g[end], depth - 1, result) end push!(result, to_expr(nd)) end end function expand_deps(g::AbstractExGraph, nd::ExNode, depth::Int=typemax(Int)) deps = collect_deps(g, nd, depth) ex = Expr(:block) for nd in g.tape if !isa(nd, ExNode{:input}) && in(varname(nd), deps) push!(ex.args, to_expr(nd)) end end return ex end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
6354
# funexpr.jl - extract arguments and (sanitized) expression of a function body. # # Here sanitization means removing things like LineNumberNode and replacing # hard-to-consume nodes (e.g. `GloabalRef` and `return`) with their simple # counterparts (e.g. expression with `.` and variable node). sanitize(x) = x sanitize(ex::Expr) = sanitize(ExH(ex)) sanitize(ex::LineNumberNode) = nothing sanitize(m::Module) = Symbol(string(m)) sanitize(ex::ExH{:line}) = nothing sanitize(ex::ExH{:return}) = sanitize(ex.args[1]) sanitize(x::Core.SSAValue) = Symbol("SSAValue_$(x.id)") # sanitize(ex::ExH{:macrocall}) = nothing # note: ignoring macros, experimental function sanitize(ex::ExH{:block}) sanitized_args = [sanitize(arg) for arg in ex.args] new_args = filter(arg -> arg != nothing, sanitized_args) return length(new_args) == 1 ? new_args[1] : Expr(ex.head, new_args...) end function sanitize(ex::ExH{:quote}) return length(ex.args) == 1 ? QuoteNode(ex.args[1]) : ex end function sanitize(ex::ExH{H}) where H sanitized_args = [sanitize(arg) for arg in ex.args] new_args = filter(arg -> arg != nothing, sanitized_args) return Expr(H, new_args...) end function sanitize(ref::GlobalRef) return Expr(:., Symbol(string(ref.mod)), QuoteNode(ref.name)) end ## recover lowered const RECOVER_LOWERED_RULES = [ :(Base.broadcast(_f, _xs...)) => :(_f.(_xs...)), :(Base.broadcast(_m._f, _xs...)) => :(_m._f.(_xs...)), :(A_mul_B(_x, _y)) => :(_x * _y), :(A_mul_Bt(_x, _y)) => :(_x * _y'), :(At_mul_B(_x, _y)) => :(_x' * _y), :(A_mul_Bc(_x, _y)) => :(_x * _y'), :(Ac_mul_B(_x, _y)) => :(_x' * _y), :(Base.literal_pow(Main.:^, _x, _v)) => :(_x ^ _v), :(Core.apply_type(Base.Val, _x)) => :_x, # :(Core.getfield(_x, _y)) => :(_x._y), :(Core.getfield(_x, $(QuoteNode(:_y)))) => :(_x._y), ] """ Try to recover an expression from a lowered form. Example: ex = (Main.sum)((Base.literal_pow)(Main.^, (Base.broadcast)(Main.-, (Main.predict)(W, b, x), y), (Core.apply_type)(Base.Val, 2))) """ recover_lowered(x) = x recover_lowered(ex::Expr) = recover_lowered(ExH(ex)) function recover_lowered(ex::ExH{:block}) recovered_args = [recover_lowered(arg) for arg in ex.args] new_args = filter(arg -> arg != nothing, recovered_args) return length(new_args) == 1 ? new_args[1] : Expr(ex.head, new_args...) end function recover_lowered(ex::ExH{:call}) # recover arguments recovered_args = [recover_lowered(arg) for arg in ex.args[2:end]] new_args = filter(arg -> arg != nothing, recovered_args) ex = Expr(:call, ex.args[1], new_args...) # check patterns for (pat, rpat) in RECOVER_LOWERED_RULES rex = tryrewrite(ex, pat, rpat) if rex != nothing ex = get(rex) break end end ex = canonical_calls(@__MODULE__, ex) |> subs_bcast_with_dot return ex end function recover_lowered(ex::ExH{H}) where H recovered_args = [recover_lowered(arg) for arg in ex.args] new_args = filter(arg -> arg != nothing, recovered_args) return Expr(H, new_args...) end function recover_lowered_rec(ex) ex_old = ex ex = recover_lowered(ex) # TODO: create a function for this while string(ex) != string(ex_old) # no more changes ex_old = ex ex = recover_lowered(ex) end return ex end ## funexpr function replace_slots(ex::Expr, slotnames::Vector) new_args = Array{Any}(undef, length(ex.args)) for (i, arg) in enumerate(ex.args) if isa(arg, Slot) new_args[i] = slotnames[arg.id] elseif isa(arg, Expr) new_args[i] = replace_slots(arg, slotnames) else new_args[i] = arg end end new_ex = Expr(ex.head, new_args...) return new_ex end function arg_names(sig::Expr) # note: ignoring type parameters, may not always be the right thing while sig.head == :where sig = sig.args[1] end return [isa(arg, Symbol) ? arg : arg.args[1] for arg in sig.args[2:end]] end function arg_types(sig::Expr) # note: ignoring type parameters, may not always be the right thing while sig.head == :where sig = sig.args[1] end return [isa(arg, Symbol) ? Any : arg.args[2] for arg in sig.args[2:end]] end function to_expr(src::CodeInfo) if isa(src.code, Array{Any,1}) slotnames = [Symbol(name) for name in Base.sourceinfo_slotnames(src)] body = Expr(:body, src.code...) result = replace_slots(body, slotnames) return result else error("Can't convert CodeInfo to expression: CodeInfo is compressed: $src") end end function concretise_types(code::Expr, types::NTuple{N, DataType}) where N sig_types = arg_types(code.args[1]) st = Dict(zip(sig_types, types)) return subs(code, st) end """ Replace all calls to an inner constructor with the corresponding outer constructor """ function replace_inner_constr(f, ex::Expr) f_name = Meta.parse(string(f)) constr = :($f_name(_xs...)) ex = rewrite_all(ex, :(new{_T1, _T2, _T3}(_xs...)), constr) ex = rewrite_all(ex, :(new{_T1, _T2}(_xs...)), constr) ex = rewrite_all(ex, :(new{_T}(_xs...)), constr) ex = rewrite_all(ex, :(new(_xs...)), constr) return ex end function funexpr(f::Union{Function, DataType, UnionAll}, types::NTuple{N,DataType}) where N method = get_method(f, types) file = string(method.file) linestart = method.line try ex, _ = get_source_at(file, linestart) ex.head == :toplevel && throw(LoadError(file, Int(linestart), "Bad code found")) ex = concretise_types(ex, types) ex = replace_inner_constr(f, ex) return arg_names(ex.args[1]), sanitize(ex.args[2]) catch err if isa(err, LoadError) code = code_lowered(f, types)[1] args = convert(Vector{Symbol}, code.slotnames[2:end]) ex = to_expr(code) |> sanitize |> recover_lowered_rec # ex = subs(ex, Dict(:new => parse(string(f)))) return args, ex else rethrow(err) end end end func_expr = funexpr function get_or_generate_argnames(f, types) try args, _ = funexpr(f, types) return args catch return [Symbol("arg$i") for i=1:length(types)] end end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
5433
## topological sort """ For each variable in graph, calculate all variables that depend on it. This is essentially the opposite of `dependencies(nd::ExNode)`, but operates on variable names rather than nodes. """ function dependents(g::AbstractExGraph) dpts = Dict{Symbol, Vector{Symbol}}() # prepare all dependent lists for nd in g.tape dpts[varname(nd)] = Symbol[] end for nd in g.tape vname = varname(nd) for dep in dependencies(nd) if haskey(dpts, dep) # don't include global constants push!(dpts[dep], vname) end end end return dpts end function topsort_visit!(g::AbstractExGraph, dpts::Dict{Symbol, Vector{Symbol}}, temp_marked::Set{Symbol}, perm_marked::Set{Symbol}, sorted::Vector{Symbol}, vname::Symbol) if vname in temp_marked error("Expression graph isn't a DAG!") end if !in(vname, temp_marked) && !in(vname, perm_marked) push!(temp_marked, vname) for dpt in dpts[vname] topsort_visit!(g, dpts, temp_marked, perm_marked, sorted, dpt) end push!(perm_marked, vname) delete!(temp_marked, vname) push!(sorted, vname) end end """Sort graph topologically""" function topsort(g::AbstractExGraph) dpts = dependents(g) sorted = Symbol[] temp_marked = Set{Symbol}() perm_marked = Set{Symbol}() for vname in keys(dpts) topsort_visit!(g, dpts, temp_marked, perm_marked, sorted, vname) end sg = Espresso.reset_tape(g) for vname in reverse(sorted) push!(sg, g[vname]) end return sg end ## expand const """Expand all constant vars in a given expression""" function expand_const(g::AbstractExGraph, ex) st = Dict{Symbol, Any}() vnames = get_var_names(ex) for vname in vnames if haskey(g, vname) && isa(g[vname], ExNode{:constant}) # st[vname] = g[vname].val st[vname] = getvalue(g[vname]) end end return subs(ex, st) end reindex_from_beginning(g::ExGraph) = g ## inline / inline unknown function subgraph_interm_subs_table(sub_g::ExGraph, dont_subs; prefix="") interm_vars = [varname(sub_nd) for sub_nd in sub_g.tape if !in(varname(sub_nd), dont_subs)] new_names = [genname("$(prefix)_$(v)_") for v in interm_vars] return Dict(zip(interm_vars, new_names)) end """ Find definition of a called function and build its subgraph ready for inlining """ function make_subgraph(g::ExGraph, nd::ExNode{:call}) mod = @get(g.ctx, :mod, Main) # TODO: Main or current_graph()? fname = getexpr(nd).args[1] f = fname isa Symbol ? getproperty(mod, fname) : fname args = dependencies(nd) arg_types = ([typeof(getvalue(g[arg])) for arg in args]...,) params, sub_ex = funexpr(f, arg_types) sub_g = ExGraph(sub_ex; ctx=g.ctx) st = Dict(zip(params, args)) # rename internal params to actual arguments st[varname(sub_g[end])] = varname(nd) # rename output var to this node's dont_subs = Set(keys(st)) st = merge(st, subgraph_interm_subs_table(sub_g, dont_subs; prefix=fname)) rename!(sub_g, st) return sub_g end function inline_subgraphs(g::ExGraph, inline_subs::Dict{Symbol, ExGraph}) new_g = reset_tape(g) for nd in g vname = varname(nd) if haskey(inline_subs, vname) for sub_nd in inline_subs[vname] push!(new_g, sub_nd) end else push!(new_g, nd) end end return new_g end function inline_nodes(g::ExGraph, vnames::Set{Symbol}) inline_subs = Dict(vname => make_subgraph(g, g[vname]) for vname in vnames) return inline_subgraphs(g, inline_subs) end iscall(x) = isa(x, Expr) && x.head == :call function convert_call(g::AbstractExGraph, nd::Union{ExNode{:call}, ExNode{:bcast}}) new_ex = expand_const(g, getexpr(nd)) |> simplify if isa(new_ex, Symbol) || (isa(new_ex, Expr) && new_ex.head == :ref) # convert to assignment return copy(nd; category=:(=), ex=new_ex) elseif isa(new_ex, Number) || isa(new_ex, AbstractArray) # convert to constant if haskey(g.ctx, :bitness) new_ex = force_bitness(new_ex, Val(g.ctx[:bitness])) end return copy(nd; category=:constant, ex=new_ex) elseif isa(new_ex, Tuple) return copy(nd; category=:tuple, ex=new_ex) else error("Call node $nd is simplified to an unknown non-call $new_ex") end end """ Given a symbolic name, either adds `2` to the end or increment existing number. Example: inc_var_name(:x) # ==> x2 inc_var_name(:x2) # ==> x3 """ function inc_var_name(var::Symbol) svar = string(var) r = match(r"(.*)(\d+)", svar) if r != nothing base = r.captures[1] num = parse(Int, r.captures[2]) + 1 return Symbol("$base$num") else return Symbol("$(svar)2") end end function rename_from_beginning(g::ExGraph) new_g = deepcopy(g) vars = [getvar(nd) for nd in g] new_vars = [Symbol("var$i") for i=1:length(vars)] st = Dict(zip(vars, new_vars)) rename!(new_g, st) return new_g end """ A single number to represent a graph. Insensitive to variable names. """ function graph_hash(g::ExGraph) return rename_from_beginning(g) |> to_expr |> hash end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
1434
flip(X::Matrix{T}) where {T} = flipdim(flipdim(X, 1), 2) sum_1(X) = sum(X, dims=1) sum_2(X) = sum(X, dims=2) squeeze_sum(A::Array{T,N}, dim::Integer) where {T,N} = squeeze(sum(A, dims=dim), dims=dim) squeeze_sum_1(A) = squeeze_sum(A, 1) squeeze_sum_2(A) = squeeze_sum(A, 2) ## constructor function struct_like(m) try return typeof(m)() catch e if e isa MethodError println("ERROR: Trying to instantiate mutable type $(typeof(m)), " * "but it doesn't have a default constructor") end throw(e) end end function __construct(mem::Dict, dzdm_v::Symbol, m::T; fields...) where T if isimmutable(m) return __construct_immutable(T; fields...) else dz!dm = @get_or_create(mem, dzdm_v, struct_like(m)) for (f, val) in fields setfield!(dz!dm, f, val) end return dz!dm end end function __construct(m::T; fields...) where T if isimmutable(m) return __construct_immutable(T; fields...) else dz!dm = struct_like(m) for (f, val) in fields setfield!(dz!dm, f, val) end return dz!dm end end function __construct_immutable(::Type{T}; fields...) where T f2i = Dict((f, i) for (i, f) in enumerate(fieldnames(T))) vals = Array{Any}(length(f2i)) for (f, val) in fields vals[f2i[f]] = val end return T(vals...) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
3958
# indexing.jl - low-level utils for working with indexed expressions # TODO: rename since indexing isn't in focus of this package anymore # const IDX_NAMES = [:i, :j, :k, :m, :n, :p, :q, :r, :s, :l] ## utils isref(ex::Expr) = ex.head == :ref isref(x) = false isindexed(ex::Expr) = isref(ex) || any(isindexed, ex.args) isindexed(x) = false """ Split possibly indexed variable into a name and indices. Examples: split_indexed(:x) ==> (:x, []) split_indexed(:(x[i,j])) ==> (:x, [:i,:j]) See also: make_indexed """ split_indexed(var) = (var, []) function split_indexed(ex::Expr) @assert ex.head == :ref return convert(Symbol, ex.args[1]), ex.args[2:end] end """ Make indexed variable. Examples: make_indexed(:x, []) ==> :x make_indexed(:x, [:i,:j]) ==> :(x[i,j]) See also: split_indexed """ function make_indexed(vname::Symbol, vidxs::Vector) return isempty(vidxs) ? vname : Expr(:ref, vname, vidxs...) end """Generate index names and make an indexed variable using them""" function with_indices(x::Symbol, start_idx::Int, num_idxs::Int) return make_indexed(x, IDX_NAMES[start_idx:start_idx+num_idxs-1]) end with_indices(x::Symbol, num_idxs::Int) = with_indices(x, 1, num_idxs) ## get_vars, get_var_names, get_indices function get_vars!(x, rec::Bool, result::Vector{Union{Symbol, Expr}}) # do nothing end function get_vars!(x::Symbol, rec::Bool, result::Vector{Union{Symbol, Expr}}) push!(result, x) end function get_vars!(ex::Expr, rec::Bool, result::Vector{Union{Symbol, Expr}}) get_vars!(ExH(ex), rec, result) end function get_vars!(ex::ExH{:ref}, rec::Bool, result::Vector{Union{Symbol, Expr}}) push!(result, Expr(ex)) end function get_vars!(ex::ExH{:call}, rec::Bool, result::Vector{Union{Symbol, Expr}}) for arg in ex.args[2:end] if isa(arg, Symbol) || isref(arg) push!(result, arg) elseif rec get_vars!(arg, rec, result) end end end function get_vars!(ex::ExH{:.}, rec::Bool, result::Vector{Union{Symbol, Expr}}) @assert ex.args[2].head == :tuple "Dot is only allowed in broadcasting: $ex" for arg in ex.args[2].args if isa(arg, Symbol) || isref(arg) push!(result, arg) elseif rec get_vars!(arg, rec, result) end end end function get_vars!(ex::ExH{Symbol("'")}, rec::Bool, result::Vector{Union{Symbol, Expr}}) arg = ex.args[1] if isa(arg, Symbol) || isref(arg) push!(result, arg) elseif rec get_vars!(arg, rec, result) end end function get_vars!(ex::ExH{:(=)}, rec::Bool, result::Vector{Union{Symbol, Expr}}) get_vars!(ex.args[1], rec, result) get_vars!(ex.args[2], rec, result) end function get_vars!(ex::ExH{:tuple}, rec::Bool, result::Vector{Union{Symbol, Expr}}) for arg in ex.args get_vars!(arg, rec, result) end end function get_vars!(ex::ExH{:block}, rec::Bool, result::Vector{Union{Symbol, Expr}}) for subex in ex.args get_vars!(subex, rec, result) end end """Get variables (`Symbol` or `Expr(:ref)`) involved in exprssion""" function get_vars(ex::Expr; rec::Bool=false) result = Vector{Union{Symbol, Expr}}() get_vars!(ex, rec, result) return result end function get_vars(x::Symbol; rec::Bool=false) return Union{Symbol, Expr}[x] end function get_vars(x; rec::Bool=false) return Union{Symbol, Expr}[] end function get_var_names(ex; rec::Bool=false) vars = get_vars(ex; rec=rec) return [split_indexed(var)[1] for var in vars] end function get_indices(ex; rec::Bool=false) vars = get_vars(ex; rec=rec) return [split_indexed(var)[2] for var in vars] end """ find_vars(ex; rec=true) Same as `get_vars()`, but recursive by default """ find_vars(ex; rec::Bool=true) = get_vars(ex; rec=rec) find_var_names(ex; rec::Bool=true) = get_var_names(ex; rec=rec) find_indices(ex; rec::Bool=true) = get_indices(ex; rec=rec)
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
3394
# to_inplace.jl - transform ExGraph to buffered/in-place operations const Num = Number const Vec = AbstractVector const Mat = AbstractMatrix const INPLACE_PHS = Set([:u, :v, :w, :x, :y, :z, :X, :Y, :Z]) const INPLACE_RULES = [ Type[Mat, Mat] => :(Z = X' * Y) => :(mul!(Z, transpose(X), Y)), Type[Mat, Mat] => :(Z = X * Y') => :(mul!(Z, X, transpose(Y))), Type[Mat, Mat] => :(Z = X * Y) => :(mul!(Z, X, Y)), ] function to_inplace(g::ExGraph) evaluate!(g) g = expand_fixed_sequences(g) g = fuse_broadcasting(g) res = :(begin end) for nd in g.tape if getcategory(nd) != :input vex = to_inplace(g, nd) # push!(res.args, simplify(subs_size(vex, sizes))) push!(res.args, vex) end end res = subs_bcast_with_dot(sanitize(res)) return res end function to_inplace(g::ExGraph, nd::Union{ExNode{:call}, ExNode{:bcast}, ExNode{:opaque}}) ex = expand_const(g, to_expr_kw(nd)) |> simplify if isa(nd, ExNode{:call}) && !iscall(ex.args[2]) return to_inplace(g, convert_call(g, nd)) end # try patterns dep_vals = [getvalue(g[dep]) for dep in dependencies(nd)] for (types, (pat, rpat)) in INPLACE_RULES if all(isa(val, T) for (val, T) in zip(dep_vals, types)) pat = sanitize(pat) rex = tryrewrite(ex, pat, rpat; phs=INPLACE_PHS) if rex != nothing return rex end end end # try broadcasting if is_bcast_vec(nd) lhs_is_scalar = isa(getvalue(nd), Number) return make_elementwise(to_expr_kw(nd); lhs_is_scalar=lhs_is_scalar) end # if LHS is an array, use .= instead of = if isa(getvalue(nd), AbstractArray) rex = to_expr_kw(nd) rex.head = :.= return rex end return to_expr_kw(nd) end function to_inplace(g::ExGraph, nd::ExNode{:ctor}) ex = to_expr_kw(nd) insert!(ex.args[2].args, 3, :mem) insert!(ex.args[2].args, 4, QuoteNode(varname(nd))) return ex end function to_inplace(g::ExGraph, nd::ExNode) return to_expr_kw(nd) end to_buffered = to_inplace ## @inplacerule # TODO: copied from XGrad, fix isparameters(a) = isa(a, Expr) && a.head == :parameters function without_types(pat) rpat = copy(pat) for i=2:length(rpat.args) a = rpat.args[i] if !isparameters(a) # parameters aren't modified rpat.args[i] = isa(a, Expr) ? a.args[1] : a end end return rpat end function get_arg_names(pat) return [isa(a, Expr) ? a.args[1] : a for a in pat.args[2:end] if !isparameters(a)] end function get_arg_types(pat) return [isa(a, Expr) ? eval(Base, a.args[2]) : Any for a in pat.args[2:end] if !isparameters(a)] end function add_inplace_rule(mod::Module, tpat, rpat) @assert tpat.head == :(=) @assert rpat.head == :call op = canonical(mod, tpat.args[2].args[1]) rop = canonical(mod, rpat.args[1]) types = get_arg_types(tpat.args[2]) pat = :($(tpat.args[1]) = $(without_types(tpat.args[2]))) # replace function names with canonical names pat = subs(pat, Dict(tpat.args[2].args[1] => op)) rpat = subs(rpat, Dict(rpat.args[1] => rop)) rule = types => pat => rpat push!(INPLACE_RULES, rule) end macro inplacerule(tpat, rpat) mod = @__MODULE__ add_inplace_rule(mod, tpat, rpat) nothing end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
1902
function rename!(g::AbstractExGraph, name::Symbol, new_name::Symbol) return rename!(g, Dict(name => new_name)) end function rename!(g::AbstractExGraph, st::Dict{Symbol,Symbol}) for nd in g.tape var = getvar(nd) new_var = subs(var, st) setvar!(nd, subs(var, st)) setexpr!(nd, subs(getexpr(nd), st)) delete!(g.idx, var) g.idx[new_var] = nd end return g end function rename(g::AbstractExGraph, st::Dict{Symbol,Symbol}) new_g = reset_tape(g) for nd in g.tape push!(new_g, copy(nd; var=subs(getvar(nd), st), ex=subs(getexpr(nd), st))) end return new_g end function mergeex(g1::AbstractExGraph, g2::AbstractExGraph) g2 = deepcopy(g2) @assert typeof(g1) == typeof(g2) gm = typeof(g1)() # find out what vars in g2 need to be renamed g1_vars = Set(varname(nd) for nd in g1.tape) g2_vars = Set(varname(nd) for nd in g2.tape) need_renaming = Symbol[] for nd in g2.tape vname = varname(nd) if haskey(g1, vname) && getexpr(g1[vname]) != getexpr(nd) push!(need_renaming, vname) end end # rename variables in g2 new_names = gennames(length(need_renaming)) for (name, new_name) in zip(need_renaming, new_names) rename!(g2, name, new_name) end # concat graphs for nd in g1.tape push!(gm, nd) end for nd in g2.tape if !haskey(gm, varname(nd)) push!(gm, nd) end end return gm end function mergeex(gs::Vararg{AbstractExGraph}) return reduce(mergeex, gs) end function mergeex(exs::Vararg{Expr}) indexed = any(isindexed, exs) gs = indexed ? [EinGraph(ex) for ex in exs] : [ExGraph(ex) for ex in exs] gm = mergeex(gs...) block = to_expr(gm) res_vars = [g[end].var for g in gs] push!(block.args, Expr(:tuple, res_vars...)) return block end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
1869
# ops.jl - overloaded operators for constucting symbolic expressions. # # A couple of examples: # # :x ⊕ :y ==> :(x + y) # 2 ⊗ :(x ⊕ y) ==> :(2 * (x + y)) # import Base: +, -, *, /, .+, .-, .*, ./ # ⊕(ex::Symbolic, v::Numeric) = :($ex + $v) # ⊕(v::Numeric, ex::Symbolic) = :($v + $ex) # ⊕(ex1::Symbolic, ex2::Symbolic) = :($ex1 + $ex2) # ⊕(x, y) = x + y # (-)(ex::Symbolic, v::Numeric) = :($ex - $v) # (-)(v::Numeric, ex::Symbolic) = :($v - $ex) # (-)(ex1::Symbolic, ex2::Symbolic) = :($ex1 - $ex2) # ⊗(ex::Symbolic, v::Numeric) = :($ex * $v) # ⊗(v::Numeric, ex::Symbolic) = :($v * $ex) # ⊗(ex1::Symbolic, ex2::Symbolic) = :($ex1 * $ex2) # ⊗(x, y) = x * y # (/)(ex::Symbolic, v::Numeric) = :($ex / $v) # (/)(v::Numeric, ex::Symbolic) = :($v / $ex) # (/)(ex1::Symbolic, ex2::Symbolic) = :($ex1 / $ex2) # elementwise operations ⊕(ex::Symbolic, v::Numeric) = :($ex .+ $v) ⊕(v::Numeric, ex::Symbolic) = :($v .+ $ex) ⊕(ex1::Symbolic, ex2::Symbolic) = :($ex1 .+ $ex2) ⊕(x, y) = x .+ y # (.-)(ex::Symbolic, v::Numeric) = :($ex .- $v) # (.-)(v::Numeric, ex::Symbolic) = :($v .- $ex) # (.-)(ex1::Symbolic, ex2::Symbolic) = :($ex1 .- $ex2) ⊗(ex::Symbolic, v::Numeric) = :($ex .* $v) ⊗(v::Numeric, ex::Symbolic) = :($v .* $ex) ⊗(ex1::Symbolic, ex2::Symbolic) = :($ex1 .* $ex2) ⊗(x, y) = x .* y # (./)(ex::Symbolic, v::Numeric) = :($ex ./ $v) # (./)(v::Numeric, ex::Symbolic) = :($v ./ $ex) # (./)(ex1::Symbolic, ex2::Symbolic) = :($ex1 ./ $ex2) ## Note: this is also correct, but generates more ugly expressions ## ## for op in [:(+), :(-), :(*), :(/)] ## for T in [Number, Array] ## @eval begin ## Base.$(op)(ex::Symbolic, v::$T) = :(($$op)($ex,$v)) ## Base.$(op)(v::$T, ex::Symbolic) = :(($$op)($v,$ex)) ## Base.$(op)(ex1::Symbolic, ex2::Symbolic) = :(($$op($ex1,$ex2))) ## end ## end ## end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
5856
# optmizie.jl - optimize ExGraph const OPT_PHS = [:X, :Y, :Z, :V, :W, :i, :j, :k, :l, :m, :n, :p, :q, :r, :s, :t] const OPT_VEC_RULES = [ :(Z = X * transpose(Y)) => :(Z = X * Y'), :(Z = X * Y') => :(Z = X * Y'), :(Z = transpose(X) * Y) => :(Z = X' * Y), :(Z = X' * Y) => :(Z = X' * Y), ] function remove_unused(g::AbstractExGraph, outvars::Vector{Symbol}) deps = collect_deps(g, outvars) push!(deps, outvars...) gr = reset_tape(g) for nd in g.tape if in(varname(nd), deps) push!(gr, nd) end end return gr end remove_unused(g::AbstractExGraph, outvar::Symbol) = remove_unused(g, [outvar]) remove_unused(g::AbstractExGraph) = remove_unused(g, [varname(g[end])]) """ Removes unused variables from multiline expressions, e.g. in: x = u * v y = x + 1 z = 2x `y` isn't used to compute output variable `z`, so it's removed: x = u * v z = 2x """ function remove_unused(ex::Expr; output_vars=nothing) ex.head == :block || return ex # nothing to remove g = ExGraph(ex; fuse=false) output_vars = output_vars != nothing ? output_vars : [varname(g[end])] deps = collect_deps(g, output_vars) for vname in output_vars push!(deps, vname) end res = quote end for subex in ex.args if subex.head == :(=) vname = split_indexed(subex.args[1])[1] if in(vname, deps) push!(res.args, subex) end else push!(res.args, subex) end end return res end function reset_tape(g::G) where {G <: AbstractExGraph} # new_g = deepcopy(g) new_g = G() new_g.tape = [] new_g.idx = Dict() new_g.ctx = g.ctx return new_g end function tryoptimize(ex::Expr) for (pat, subs_ex) in OPT_VEC_RULES new_ex = tryrewrite(ex, pat, subs_ex; phs=OPT_PHS, allow_ex=false) if new_ex != nothing genname_patterns = unique(findex(:(genname__(_n)), new_ex)) if !isempty(genname_patterns) new_names = gennames(length(genname_patterns)) st = Dict(zip(genname_patterns, new_names)) return subs(new_ex, st) else return new_ex end end end return nothing end function expand_fixed_sequences(g::ExGraph, nd::ExNode) ex = to_expr(nd) changed = false for dep in dependencies(nd) expanded = subs(ex, Dict(dep => getexpr(g[dep]))) new_ex = tryoptimize(expanded) if new_ex != nothing ex = new_ex changed = true end end return changed ? copy(nd; category=:opaque, var=ex.args[1], ex=ex.args[2]) : nd end """ Look at each node's dependencies and, if there are known pattern sequences, rewrite them in a more optimal way. """ function expand_fixed_sequences(g::ExGraph) new_g = reset_tape(g) for nd in g.tape if isa(nd, ExNode{:input}) push!(new_g, nd) else new_nd = expand_fixed_sequences(g, nd) push!(new_g, new_nd) end end new_g = remove_unused(new_g, varname(new_g[end])) # new_g = fuse_assigned(new_g) return new_g end # common subexpression elimination safe_size(a::AbstractArray) = size(a) safe_size(a) = nothing function eliminate_common(g::AbstractExGraph) g = reindex_from_beginning(g) new_g = reset_tape(g) existing = Dict() # index of existing expressions st = Dict{Symbol,Symbol}() # later var -> previous var with the same expression for nd in g.tape new_full_ex = subs(to_expr_kw(nd), st) vname, vidxs = split_indexed(new_full_ex.args[1]) key = string((vidxs, new_full_ex.args[2])) if haskey(existing, key) && (g[vname] |> getvalue |> safe_size) == (g[existing[key]] |> getvalue |> safe_size) st[vname] = existing[key] else # C = getcategory(nd) new_nd = copy(nd) setexpr_kw!(new_nd, new_full_ex.args[2]) push!(new_g, new_nd) existing[key] = vname end end rename!(new_g, st) return new_g end # fuse broadcasting function is_bcast_vec(nd::ExNode{:opaque}) # convert to expression, re-parse and check every node return all(is_bcast_vec(nd) for nd in ExGraph(to_expr(nd)).tape) end const OLD_BCAST_OPS = Set([:.+, :.-, :.*, :./, :.^]) is_bcast_vec(nd::ExNode{:call}) = getexpr(nd).args[1] in OLD_BCAST_OPS is_bcast_vec(nd::ExNode{:bcast}) = true is_bcast_vec(nd::ExNode) = false function fuse_broadcasting_node(g::ExGraph, new_g::ExGraph, nd::ExNode) dep_nds = [new_g[dep] for dep in dependencies(nd)] if any(is_bcast_vec(dep_nd) for dep_nd in dep_nds) # at least one dependency is broadcasting # transform node to :opaque and expand dep expression st = Dict{Any, Any}() for dep_nd in dep_nds if is_bcast_vec(dep_nd) # if dependency is broadcasting, replace its name with its expression dep_ex = getexpr(dep_nd) # idx_st = Dict(zip(varidxs(dep_nd), # get_indices_in_expr(getexpr(nd), varname(dep_nd)))) # new_dep_ex = subs(dep_ex, idx_st) new_dep_ex = dep_ex st[getvar(dep_nd)] = new_dep_ex end end new_ex = subs(getexpr(nd), st) return copy(nd; ex=new_ex, category=:opaque) else return nd end end function fuse_broadcasting(g::ExGraph) new_g = reset_tape(g) for nd in g.tape if is_bcast_vec(nd) push!(new_g, fuse_broadcasting_node(g, new_g, nd)) else push!(new_g, nd) end end return remove_unused(new_g, varname(g[end])) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
210
## preprocess.jl - preprocess an expression for better parsing const PREPROCESS_RULES = [ :(mean(abs2, _)) => :(mean(abs2.(_))), ] function preprocess(ex) return rewrite_all(ex, PREPROCESS_RULES) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
9850
# rewrite.jl - expression pattern matching and rewriting. # # The general idea behind functions in this file is to provide easy means # of finding specific pieces of expressions and using them elsewhere. # At the time of writing it is used in 2 parts of this package: # # * for applyging derivatives, e.g. `x^n` ==> `n*x^(n-1)` # * for expression simplification, e.g. `1 * x` ==> `x` # # Pieces of expression are matched to so-called placeholders - symbols that either # start with `_` (e.g. `_x`) or are passed via `phs` paraneter, or set globally # using `set_default_placeholders(::Set{Symbol})`. Using list of placeholders # instead of _-prefixed names is convenient when writing a lot of transformation # rules where using underscores creates unnecessary noise. const Symbolic = Union{Expr, Symbol} const Numeric = Union{Number, Array} ## pattern matching const DEFAULT_PHS = [Set{Symbol}()] set_default_placeholders(set::Set{Symbol}) = (DEFAULT_PHS[1] = set) isplaceholder(x, phs) = false isplaceholder(x::Symbol, phs) = (startswith(string(x), "_") || in(x, phs)) # isplaceholder(ex::Expr, phs) = ex.head == :... && isplaceholder(ex.args[1], phs) function find_key(d::Dict{K, V}, val) where {K,V} r = nothing for (k,v) in d if v == val r = k break end end return r end function matchex!(m::Dict{Symbol,Any}, p::QuoteNode, x::QuoteNode; opts...) return matchex!(m, p.value, x.value) end function matchex!(m::Dict{Symbol,Any}, ps::Vector, xs::Vector; opts...) opts = to_dict(opts) phs = get(opts, :phs, Set([])) length(ps) <= length(xs) || return false for i in eachindex(ps) if isa(ps[i], Expr) && ps[i].head == :... && isplaceholder(ps[i].args[1], phs) p = ps[i].args[1] haskey(m, p) && m[p] != xs[i] && m[p] != xs[i:end] && return false # TODO: add something here? m[p] = xs[i:end] return true else matchex!(m, ps[i], xs[i]; opts...) || return false end end # matched everything, didn't encounter dots expression return length(ps) == length(xs) end function matchex!(m::Dict{Symbol,Any}, p, x; phs=DEFAULT_PHS[1], allow_ex=true, exact=false) allow_ex = exact ? false : allow_ex # override allow_ex=false if exact==true if isplaceholder(p, phs) if haskey(m, p) && m[p] != x # different bindings to the same pattern, treat as no match return false elseif !allow_ex && isa(x, Expr) # x is expression, but matching to expression is not allowed, treat as no match return false elseif exact k = find_key(m, x) if k != p return false else m[p] = x return true end else m[p] = x return true end elseif isa(p, Expr) && isa(x, Expr) return (matchex!(m, p.head, x.head) && matchex!(m, p.args, x.args; phs=phs, allow_ex=allow_ex, exact=exact)) else return p == x end end """ Match expression `ex` to a pattern `pat`, return nullable dictionary of matched symbols or rpatpressions. Example: ``` ex = :(u ^ v) pat = :(_x ^ _n) matchex(pat, ex) # ==> Union{ Dict{Symbol,Any}(:_n=>:v,:_x=>:u), Void } ``` NOTE: two symbols match if they are equal or symbol in pattern is a placeholder. Placeholder is any symbol that starts with '_'. It's also possible to pass list of placeholder names (not necessarily starting wiht '_') via `phs` parameter: ``` ex = :(u ^ v) pat = :(x ^ n) matchex(pat, ex; phs=Set([:x, :n])) # ==> Union{ Dict{Symbol,Any}(:n=>:v,:x=>:u), Void } ``` Several elements may be matched using `...` expression, e.g.: ``` ex = :(A[i, j, k]) pat = :(x[I...]) matchex(pat, ex; phs=Set([:x, :I])) # ==> Union{ Dict(:x=>:A, :I=>[:i,:j,:k]), Void } ``` Optional parameters: * phs::Set{Symbol} = DEFAULT_PHS[1] A set of placeholder symbols * allow_ex::Boolean = true Allow matchinng of symbol pattern to an expression. Example: matchex(:(_x + 1), :(a*b + 1); allow_ex=true) # ==> matches matchex(:(_x + 1), :(a*b + 1); allow_ex=false) # ==> doesn't match * exact::Boolean = false Allow matching of the same expression to different keys matchex(:(_x + _y), :(a + a); exact=false) # ==> matches matchex(:(_x = _y), :(a + a); exact=true) # ==> doesn't match """ function matchex(pat, ex; opts...) m = Dict{Symbol,Any}() res = matchex!(m, pat, ex; opts...) if res return m else return nothing end end """ Check if expression matches pattern. See `matchex()` for details. """ function matchingex(pat, ex; opts...) return matchex(pat, ex; opts...) != nothing end ## find rpatpression function findex!(res::Vector, pat, ex; phs=DEFAULT_PHS[1]) if matchingex(pat, ex; phs=phs) push!(res, ex) elseif expr_like(ex) for arg in ex.args findex!(res, pat, arg; phs=phs) end end end """ Find sub-expressions matching a pattern. Example: ex = :(a * f(x) + b * f(y)) pat = :(f(_)) findex(pat, ex) # ==> [:(f(x)), :(f(y))] """ function findex(pat, ex; phs=DEFAULT_PHS[1]) res = Any[] findex!(res, pat, ex; phs=phs) return res end ## substitution """ Given a list of expression arguments, flatten the dotted ones. Example: args = [:foo, :([a, b, c]...)] flatten_dots(args) # ==> [:foo, :a, :b, :c] """ function flatten_dots(args::Vector) new_args = Vector{Any}() for arg in args if isa(arg, Expr) && arg.head == :... && isa(arg.args[1], AbstractArray) for x in arg.args[1] push!(new_args, x) end else push!(new_args, arg) end end return new_args end """ Substitute symbols in `ex` according to substitute table `st`. Example: ex = :(x ^ n) subs(ex, x=2) # ==> :(2 ^ n) alternatively: subs(ex, Dict(:x => 2)) # ==> :(2 ^ n) If `ex` contains a :(xs...) argument and `st` contains an array-valued sabstitute for it, the substitute will be flattened: ex = :(foo(xs...)) subs(ex, Dict(:xs => [:a, :b, :c])) # ==> :(foo(a, b, c)) """ function subs(ex::Expr, st::Dict) if haskey(st, ex) return st[ex] # elseif ex.head == :... && haskey(st, ex.args[1]) else new_args = [subs(arg, st) for arg in ex.args] new_args = flatten_dots(new_args) return Expr(ex.head, new_args...) end end function subs(s::Symbol, st::Dict) return haskey(st, s) ? st[s] : s end subs(q::QuoteNode, st::Dict) = QuoteNode(subs(q.value, st)) subs(x::Any, st::Dict) = x subs(ex; st...) = subs(ex, to_dict(st)) ## remove rpatpression """ Remove rpatpression conforming to a pattern. Example: ex = :(x * (m == n)) pat = :(_i == _j) ex = without(ex, pat) # ==> :x """ function without(ex::Expr, pat; phs=DEFAULT_PHS[1]) new_args_without = [without(arg, pat; phs=phs) for arg in ex.args] new_args = filter(arg -> !matchingex(pat, arg; phs=phs), new_args_without) if ex.head == :call && length(new_args) == 2 && (ex.args[1] == :+ || ex.args[1] == :*) # pop argument of now-single-valued operation # TODO: make more general, e.g. handle (x - y) with x removed return new_args[2] elseif ex.head == :call && length(new_args) == 1 && ex.args[1] == :* return 1.0 elseif ex.head == :call && length(new_args) == 1 && ex.args[1] == :+ return 0.0 else return Expr(ex.head, new_args...) |> simplify end end without(x, pat; phs=DEFAULT_PHS[1]) = x ## rewriting """ rewrite(ex, pat, rpat) Rewrite expression `ex` according to a transform from pattern `pat` to a substituting expression `rpat`. Example (derivative of x^n): ex = :(u ^ v) pat = :(_x ^ _n) rpat = :(_n * _x ^ (_n - 1)) rewrite(ex, pat, rpat) # ==> :(v * u ^ (v - 1)) """ function rewrite(ex::Symbolic, pat::Symbolic, rpat::Any; opts...) st = matchex(pat, ex; opts...) if st == nothing error("Expression $ex doesn't match pattern $pat") else return subs(rpat, st) end end """ Same as rewrite, but returns Union{Expr, Void} and doesn't throw an error when expression doesn't match pattern """ function tryrewrite(ex::Symbolic, pat::Symbolic, rpat::Any; opts...) st = matchex(pat, ex; opts...) if st == nothing return nothing else return subs(rpat, st) end end """ rewrite_all(ex, rules) Recursively rewrite an expression according to a list of rules like [pat => rpat] Example: ex = :(foo(bar(foo(A)))) rules = [:(foo(x)) => :(quux(x)), :(bar(x)) => :(baz(x))] rewrite_all(ex, rules; phs=[:x]) # ==> :(quux(baz(quux(A)))) """ function rewrite_all(ex::Symbolic, rules; opts...) new_ex = ex if isa(ex, Expr) new_args = [rewrite_all(arg, rules; opts...) for arg in ex.args] new_ex = Expr(ex.head, new_args...) end for (pat, rpat) in rules if matchingex(pat, new_ex; opts...) new_ex = rewrite(new_ex, pat, rpat; opts...) end end return new_ex end """ rewrite_all(ex, pat, rpat) Recursively rewrite all occurrences of a pattern in an expression. Example: ex = :(foo(bar(foo(A)))) pat = :(foo(x)) rpat = :(quux(x)) rewrite_all(ex, pat, rpat; phs=[:x]) # ==> :(quux(bar(quux(A)))) """ function rewrite_all(ex::Symbolic, pat::Symbolic, rpat; opts...) return rewrite_all(ex, [pat => rpat]; opts...) end rewrite_all(x, pat, rpat; opts...) = x rewrite_all(x, rules; opts...) = x
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
3185
# simplify.jl - simplify numeric expressions in Julia. # # Common examples of expressions that may be simplified are multiplication # by 1 or fully numeric expressions that may be just calculated out. # # Simplification is performed by rewriting original expression according to # a list of simplification rules defined using macro `@simple_rule`. # This macro as well as function `simplify` are exposed to the outer world. # TODO: check if it's possible to add new simplification rules from # outside the module const SIMPLE_RULES = Dict{Symbolic, Any}() const SIMPLE_PHS = Set([:x, :y, :a, :b]) """ Macro to add simplification rules. Example: @simple_rule (-x * -y) (x * y) where `(-x * -y)` is a pattern to match expression and `(x * y)` is what it should be transformed to (see `rewrite()` to understand expression rewriting). Symbols $SIMPLE_PHS may be used as placeholders when defining new rules, all other symbols will be taken literally. """ macro simple_rule(pat, subex) SIMPLE_RULES[pat] = subex nothing end is_calculable(x::Numeric) = true is_calculable(x::Symbol) = false is_calculable(ex::Expr) = (ex.head == :call && reduce(&, [is_calculable(arg) for arg in ex.args[2:end]])) is_calculable(c::Colon) = false tryeval(ex) = is_calculable(ex) ? eval(ex) : nothing function _simplify(ex::Expr) evaled = tryeval(ex) if evaled != nothing return evaled else simplified_args = [_simplify(arg) for arg in ex.args] ex_new_args = Expr(ex.head, simplified_args...) for (pat, subex) in SIMPLE_RULES if matchingex(pat, ex_new_args; phs=SIMPLE_PHS) return rewrite(ex_new_args, pat, subex; phs=SIMPLE_PHS) end end return ex_new_args end end # fallback for non-expressions _simplify(x) = x """ Simplify expression `x` by applying a set of rules. Common examples of simplification include calculation of fully numeric subexpressions, removing needless multiplication by 1, etc. Use macro `@simple_rule` to add new simplification rules. """ function simplify(x) # several rounds of simplification may be needed, so we simplify # until there are no more changes to `x`, but no more than 5 times old_x = nothing rounds = 1 while x != old_x && rounds <= 5 old_x = x x = _simplify(x) rounds += 1 end return x end # simplification rules @simple_rule (x * 1) x @simple_rule (1 * x) x @simple_rule (x ^ 1) x @simple_rule (x ^ 0) 1 @simple_rule (x .* 1) x @simple_rule (1 .* x) x @simple_rule (x .^ 1) x @simple_rule (a * (b * x)) ((a * b) * x) @simple_rule (-1 * x) -x @simple_rule (x * -1) -x @simple_rule (-x * -y) (x * y) @simple_rule (-1 .* x) -x @simple_rule (x .* -1) -x @simple_rule (-x .* -y) (x .* y) @simple_rule size(x)[1] size(x, 1) @simple_rule size(x)[2] size(x, 2) @simple_rule (x, y)[1] x @simple_rule (x, y)[[1]] x @simple_rule (x, y)[2] y @simple_rule (x, y)[[2]] y @simple_rule (x, y)[[1,2]] (x, y) @simple_rule (x, y)[[2,1]] (y, x) @simple_rule (x, y)[[]] () @simple_rule (size(x)...,) size(x) # @simple_rule (x,) x
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
2431
## sugar.jl - (hopefully) temporary copy of needed parts of Sugar.jl package # jlhome() = ccall(:jl_get_julia_home, Any, ()) jlhome() = Sys.BINDIR function juliabasepath(file) srcdir = joinpath(jlhome(),"..","..","base") releasedir = joinpath(jlhome(),"..","share","julia","base") normpath(joinpath(isdir(srcdir) ? srcdir : releasedir, file)) end function get_source_file(path::AbstractString, ln) isfile(path) && return path # if not a file, it might be in julia base file = juliabasepath(path) if !isfile(file) throw(LoadError(path, Int(ln), ErrorException("file $path not found"))) end file end function get_method(f, types::Type) get_method(f, (types.parameters...,)) end function get_method(ftype::DataType, types::Tuple) world = typemax(UInt) if !isclosure(ftype) ftype = Type{ftype} end tt = Tuple{ftype, to_tuple(types)...} (ti, env, meth) = Base._methods_by_ftype(tt, 1, world)[1] Base.func_for_method_checked(meth, tt) end function get_method(f, types::Tuple) if !all(isconcretetype, types) error("Not all types are concrete: $types") end # make sure there is a specialization with precompile # TODO, figure out a better way, since this method is not very reliable. # (I think, e.g. anonymous functions don't work) precompile(f, (types...,)) x = methods(f, types) if isempty(x) throw(NoMethodError(f, types)) elseif length(x) != 1 error(" More than one method found for signature $f $types. Please use more specific types! ") end first(x) end """ Looks up the source of `method` in the file path found in `method`. Returns the AST and source string, might throw an LoadError if file not found. """ function get_source_at(file, linestart) file = get_source_file(file, linestart) code, str = open(file) do io line = "" for i=1:linestart-1 line = readline(io) end try # lines can be one off, which will result in a parse error Meta.parse(line) catch e line = readline(io) end while !eof(io) line = line * "\n" * readline(io) e = Base.parse_input_line(line; filename=file) if !(isa(e,Expr) && e.head === :incomplete) return e, line end end end code, str end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
10165
## tracked.jl - build ExGraph using tracked data types import Base: +, -, *, /, log, exp, min, max, reshape, transpose, sum, abs, abs2, >, >=, <, <=, minimum, maximum, getindex import Statistics: mean # import Broadcast: broadcasted const DEFAULT_GRAPH = Ref(ExGraph()) get_default_graph() = DEFAULT_GRAPH[] set_default_graph(g::ExGraph) = (DEFAULT_GRAPH[] = g) reset_default_graph!() = (DEFAULT_GRAPH[] = ExGraph()) swap_default_graph!(g::ExGraph) = (og = DEFAULT_GRAPH[]; DEFAULT_GRAPH[] = g; og) ## TRACKED REAL struct TrackedReal <: Real graph::ExGraph var::Symbol val::Real end TrackedReal(var::Symbol, val::Real) = TrackedReal(get_default_graph(), var, val) Base.show(io::IO, x::TrackedReal) = print(io, "Tracked($(x.var) = $(x.val))") tracked_val(g::ExGraph, var::Symbol, val::Real) = TrackedReal(g, var, val) struct TrackedArray{T,N} <: AbstractArray{T,N} graph::ExGraph var::Symbol val::AbstractArray{T,N} end TrackedArray(var::Symbol, val::AbstractArray) = TrackedArray(get_default_graph(), var, val) Base.show(io::IO, x::TrackedArray{T,N}) where {T,N} = print(io, "Tracked{$T,$N}($(x.var) = $(x.val))") Base.show(io::IO, ::MIME{Symbol("text/plain")}, x::TrackedArray{T,N}) where {T,N} = print(io, "Tracked{$T,$N}($(x.var) = $(x.val))") tracked_val(g::ExGraph, var::Symbol, val::AbstractArray) = TrackedArray(g, var, val) ## conversion and promotion tracked(g::ExGraph, x::TrackedReal) = x tracked(g::ExGraph, x::TrackedArray) = x function tracked(g::ExGraph, x::T) where {T <: Real} var = genname() push!(g, ExNode{:constant}(var, x; val=x)) return TrackedReal(g, var, x) end function tracked(g::ExGraph, x::T) where {T <: AbstractArray} var = genname() push!(g, ExNode{:constant}(var, x; val=x)) return TrackedArray(g, var, x) end value(x::TrackedArray) = x.val value(x::TrackedReal) = x.val value(x) = x istracked(x::TrackedReal) = true istracked(x::TrackedArray) = true istracked(::Type{T}) where T = (T <: TrackedReal || T <: TrackedArray) istracked(x) = false Base.promote_rule(::Type{TrackedReal}, ::Type{<:Real}) = TrackedReal function Base.convert(::Type{TrackedReal}, x::R) where {R <: Real} var = genname() g = get_default_graph() push!(g, ExNode{:constant}(var, x; val=x)) return TrackedReal(g, var, x) end Base.convert(::Type{TrackedReal}, x::TrackedReal) = x Base.convert(::Type{R}, x::TrackedReal) where {R <: Real} = x.val ## TRACKED ARRAY # TODO: should write this to graph? presumably no Base.size(x::TrackedArray) = size(x.val) # TODO: and these? presumably yes, but be carefull about printing # Base.getindex(x::TrackedArray, I...) = getindex(x.val, I...) # Base.setindex!(x::TrackedArray, val, I...) = setindex!(x.val, val, I...) ## conversion and promotion Base.promote_rule(::Type{TrackedArray}, ::Type{<:AbstractArray}) = TrackedArray function Base.convert(::Type{TrackedArray}, x::A) where {A <: AbstractArray} var = genname() g = get_default_graph() push!(g, ExNode{:constant}(var, x; val=x)) return TrackedArray(g, var, x) end Base.convert(::Type{TrackedArray}, x::TrackedArray) = x # Base.convert(::Type{<:AbstractArray}, x::TrackedArray) = x.val ## @tracked macro function track_call(sig) @assert sig.head == :call op = sig.args[1] vars_types, kw = split_params(sig) call_ex = nothing; ex_in_ex = nothing if isempty(kw) call_ex = Expr(:call, op, [istracked(Core.eval(@__MODULE__, t)) ? :($(v).val) : v for (v, t) in vars_types]...) ex_in_ex = Expr(:call, :Expr, QuoteNode(:call), QuoteNode(op), [(istracked(Core.eval(@__MODULE__, t)) ? Expr(:., sig_var, QuoteNode(:var)) : sig_var) for (sig_var, t) in vars_types]...) else call_ex = Expr(:call, op, make_kw_params(kw), [istracked(Core.eval(@__MODULE__, t)) ? :($(v).val) : v for (v, t) in vars_types]...) keys = [k for (k, v) in kw] # we need to get this: # :( Expr(:call, :mult, Expr(:parameters, Expr(:kw, :pow, pow)), :(x.var)) ) ex_in_ex = Expr(:call, :Expr, QuoteNode(:call), QuoteNode(op), Expr(:call, :Expr, QuoteNode(:parameters), [Expr(:call, :Expr, QuoteNode(:kw), QuoteNode(k), k) for k in keys]...), [(istracked(Core.eval(@__MODULE__, t)) ? Expr(:., sig_var, QuoteNode(:var)) : sig_var) for (sig_var, t) in vars_types]...) end defquot = quote function $op($(sig.args[2:end]...)) val = $call_ex tv = tracked_val(x.graph, genname(), val) # TODO: x may be undefined ex = $ex_in_ex nd = ExNode{:call}(tv.var, ex; val=val) push!(x.graph, nd) return tv end end return defquot.args[2] end function track_bcast(sig) @assert sig.head == :. op = sig.args[1] sig_vars, types = unzip([(arg.args[1], Core.eval(@__MODULE__, arg.args[2])) for arg in sig.args[2].args]) bcast_ex = Expr(:., op, Expr(:tuple, [istracked(t) ? :($(v).val) : v for (v, t) in zip(sig_vars, types)]...)) # we want to get this after code generation: # ex = :(Expr(:., :sin, Expr(:tuple, x.var, y.var))) ex_in_ex = Expr(:call, :Expr, QuoteNode(:.), QuoteNode(op), Expr(:call, :Expr, QuoteNode(:tuple), [istracked(t) ? Expr(:., sv, QuoteNode(:var)) : QuoteNode(:var) for (sv, t) in zip(sig_vars, types)]...)) defquot = quote function Broadcast.broadcasted(::typeof($op), $(sig.args[2].args...)) val = $bcast_ex tv = tracked_val(x.graph, genname(), val) # TODO: x may be undefined ex = $ex_in_ex # println(ex) nd = ExNode{:bcast}(tv.var, ex; val=val) push!(x.graph, nd) return tv end end return defquot.args[2] end """ Define a function or broadcasting rule for the specified signature which computes the result as for ordinary (not tracked) data and writes it to the graph. Note: this function expects at least 1 parameter of TrackedReal or TrackedArray type with name `x`. """ macro tracked(sig) if sig.head == :call return track_call(sig) elseif sig.head == :. # TODO: we also need to add the op to broadcast list in `unfuse.jl` return track_bcast(sig) else error("Can only track calls or broadcasting") end end @tracked +(x::TrackedReal, y::TrackedReal) @tracked -(x::TrackedReal, y::TrackedReal) @tracked *(x::TrackedReal, y::TrackedReal) @tracked /(x::TrackedReal, y::TrackedReal) @tracked -(x::TrackedReal) # @tracked (Base.:<=)(x::TrackedReal, y::TrackedReal) # @tracked (Base.:>)(x::TrackedReal, y::TrackedReal) # @tracked (Base.:>=)(x::TrackedReal, y::TrackedReal) # @tracked (Base.:<)(x::TrackedReal, y::TrackedReal) @tracked sin(x::TrackedReal) @tracked cos(x::TrackedReal) @tracked exp(x::TrackedReal) @tracked log(x::TrackedReal) @tracked abs(x::TrackedReal) @tracked abs2(x::TrackedReal) @tracked *(x::TrackedArray, y::TrackedArray) @tracked maximum(x::TrackedArray) @tracked getindex(x::TrackedArray, i::Integer) @tracked getindex(x::TrackedArray, i::Integer, j::Integer) @tracked getindex(x::TrackedArray, i::Integer, j::Integer, k::Integer) @tracked getindex(x::TrackedArray, i::Integer, j::Integer, k::Integer, l::Integer) @tracked reshape(x::TrackedArray, dims::Tuple{Int}) @tracked reshape(x::TrackedArray, dims::Tuple{Int, Int}) @tracked reshape(x::TrackedArray, dims::Tuple{Int, Int, Int}) @tracked reshape(x::TrackedArray, dims::Tuple{Int, Int, Int, Int}) @tracked reshape(x::TrackedArray, dims::Tuple{Int, Int, Int, Int, Int}) @tracked reshape(x::TrackedArray, dims::Tuple{Int, Int, Int, Int, Int, Int}) @tracked sum(x::TrackedArray) @tracked mean(x::TrackedArray) @tracked sin.(x::TrackedArray) @tracked cos.(x::TrackedArray) @tracked exp.(x::TrackedArray) @tracked log.(x::TrackedArray) @tracked log.(b::Integer, x::TrackedArray) # TODO: make @nontracked macro? # boolean operators aren't tracked for op in [:<, :<=, :>, :>=, :(==)] @eval (Base.$op)(x::TrackedReal, y::TrackedReal) = $op(x.val, y.val) end # I couldn't find a way to overload .+ and friends as either call or broadcasting # fortunately, the list of such unusual operations is small and fixed function Broadcast.broadcasted(::typeof(+), x::TrackedArray, y::TrackedArray) val = x.val .+ y.val var = genname() nd = ExNode{:call}(var, :($(x.var) .+ $(y.var)); val=val) push!(x.graph, nd) return TrackedArray(var, val) end function Broadcast.broadcasted(::typeof(-), x::TrackedArray, y::TrackedArray) val = x.val .- y.val var = genname() nd = ExNode{:call}(var, :($(x.var) .- $(y.var)); val=val) push!(x.graph, nd) return TrackedArray(var, val) end function Broadcast.broadcasted(::typeof(*), x::TrackedArray, y::TrackedArray) val = x.val .* y.val var = genname() nd = ExNode{:call}(var, :($(x.var) .* $(y.var)); val=val) push!(x.graph, nd) return TrackedArray(var, val) end function Broadcast.broadcasted(::typeof(/), x::TrackedArray, y::TrackedArray) val = x.val ./ y.val var = genname() nd = ExNode{:call}(var, :($(x.var) ./ $(y.var)); val=val) push!(x.graph, nd) return TrackedArray(var, val) end # TODO: also track dot ops with scalars, e.g. x .+ 1 ## utils function tracked_exgraph(f::Function, args...) ctx = Dict{Any,Any}(:method => :track) input_vars = [genname() for i=1:length(args)] inputs = [iv => a for (iv, a) in zip(input_vars, args)] g = ExGraph(; ctx=ctx, inputs...) # replace default graph to capture constants to `g` as well og = swap_default_graph!(g) tr_args = [tracked_val(g, var, val) for (var, val) in inputs] # evaluate function with tracked args f(tr_args...) # put original graph back swap_default_graph!(og) return g end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
562
# types.jl - common types and aliases used throught the code # name of operation in a :call node - either symbol or Module.symbol const OpName = Union{Symbol, Expr} # Wrapper around Expr adding `ex.head` to type parameters thus adding convenient # type dispatching mutable struct ExH{H} head::Symbol args::Vector end Base.show(io::IO, ex::ExH) = print(io, "ExH{:$(ex.head)}($(Expr(ex)))") Base.convert(::Type{ExH}, ex::Expr) = ExH{ex.head}(ex.head, ex.args) ExH(ex::Expr) = ExH{ex.head}(ex.head, ex.args) Expr(ex::ExH) = Expr(ex.head, ex.args...)
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
12673
# utils.jl - utility functions """Same as `get` function, but evaluates default_expr only if needed""" macro get(dict, key, default_expr) return esc(quote if haskey($dict, $key) $dict[$key] else $default_expr end end) end """ Same as `@get`, but creates new object from `default_expr` if it didn't exist before """ macro get_or_create(dict, key, default_expr) return esc(quote if !haskey($dict, $key) $dict[$key] = $default_expr end $dict[$key] end) end """ Same as `@get`, but immediately exits function and return `default_expr` if key doesn't exist. """ macro get_or_return(dict, key, default_expr) return esc(quote if haskey($dict, $key) $dict[$key] else return $default_expr nothing # not reachable, but without it code won't compile end end) end """ Get array of size `sz` from a `dict` by `key`. If element doesn't exist or its size is not equal to `sz`, create and return new array using `default_expr`. If element exists, but is not an error, throw ArgumentError. """ macro get_array(dict, key, sz, default_expr) return esc(quote if (haskey($dict, $key) && !isa($dict[$key], Array)) local k = $key throw(ArgumentError("Key `$k` exists, but is not an array")) end if (!haskey($dict, $key) || size($dict[$key]) != $sz) # ensure $default_expr results in an ordinary array $dict[$key] = convert(Array, $default_expr) end $dict[$key] end) end """Flatten vector of vectors in-place""" function flatten!(b::Vector, a::Vector) for x in a if isa(x, AbstractArray) flatten!(b, x) else push!(b, x) end end return b end """Flattenx vector of vectors""" flatten(a::Vector) = flatten!([], a) flatten(::Type{T}, a::Vector) where {T} = convert(Vector{T}, flatten(a)) """Flatten one level of nested vectors""" function flatten1(a::Vector{Vector{T}}) where T result = Array(T, 0) for xs in a for x in xs push!(result, x) end end return result end # function countdict(a::AbstractArray{T}) where T # counts = OrderedDict{T, Int}() # for x in a # if haskey(counts, x) # counts[x] += 1 # else # counts[x] = 1 # end # end # return counts # end unzip(coll) = map(collect, zip(coll...)) ## package-specific stuff # func_name(f) = Base.function_name(f) func_name(f) = nameof(f) # func_mod(f) = Base.function_module(f) func_mod(f) = Base.parentmodule(typeof(f)) """ Given a list of symbols such as `[:x, :y, :z]` constructs expression `x.y.z`. This is useful for building expressions of qualified names such as `Base.LinAlg.exp`. """ function dot_expr(args::Vector{Symbol}) @assert length(args) >= 1 if length(args) == 1 return args[1] else ex = Expr(:., args[1], QuoteNode(args[2])) for i=3:length(args) ex = Expr(:., ex, QuoteNode(args[i])) end return ex end end """ Return canonical representation of a function name, e.g.: Base.+ ==> + Main.+ ==> + (resolved to Base.+) Base.LinAlg.exp ==> exp Mod.foo ==> Mod.foo """ function canonical(cur_mod::Module, qname) try f = getproperty(cur_mod, qname) if f isa Function mod = func_mod(f) name = func_name(f) # TODO: review operators and module names for Julia 0.7/1.0 if qname in [:.*, :./, :.+, :.-, :.^, :.>, :.<, :.>=, :.<=, :.==] return qname # for Julia 0.6 only elseif (mod == cur_mod || mod == Main || mod == Base || mod == Base.Math || mod == Base.DSP) return Symbol(name) else # there should be a smarter way to do it... parts = map(Symbol, split(string(mod), ".")) mod_ex = dot_expr(parts) return Expr(:., mod_ex, QuoteNode(name)) end elseif f isa DataType || f isa UnionAll # parts = split(string(f), ".") # mod = eval(cur_mod, parse(join(parts[1:end-1], "."))) # name = parse(parts[end]) return parse(string(f)) # use it for functions as well? else error("Can't understand module of $f") end catch e # if qname isn't defined in module `cur_mod`, return it as is if isa(e, UndefVarError) return qname else throw(e) end end end function canonical_calls(mod::Module, ex::Expr) if ex.head == :call new_args = [canonical_calls(mod, arg) for arg in ex.args[2:end]] return Expr(:call, canonical(mod, ex.args[1]), new_args...) elseif ex.head == :. new_args = [canonical_calls(mod, arg) for arg in ex.args[2:end]] return Expr(:., canonical(mod, ex.args[1]), new_args...) else new_args = [canonical_calls(mod, arg) for arg in ex.args] return Expr(ex.head, new_args...) end end canonical_calls(mod::Module, x) = x # context function to_context(d::Union{Dict{K,V},Vector{Pair{K,V}}}) where {K,V} ctx = Dict{Any,Any}() for (k, v) in d ctx[k] = to_context(v) end return ctx end to_context(d::Dict{Any,Any}) = d to_context(x) = x function expr_like(x) flds = Set(fieldnames(typeof(x))) return in(:head, flds) && in(:args, flds) end function to_block(exs...) new_exs = flatten([expr_like(ex) && ex.head == :block ? ex.args : [ex] for ex in exs]) return sanitize(Expr(:block, new_exs...)) end """ Propagate substitution rules. Example: Dict( :x => y, :y => z ) is transformed into: Dict( :x => z, :y => z ) """ function prop_subs(st::Dict) new_st = empty(st) for (k, v) in st while haskey(st, v) v = st[v] end new_st[k] = v end return new_st end function with_guards(ex, guards::Vector{Expr}) if isempty(guards) return ex elseif length(guards) == 1 return :($ex * $(guards[1])) else return Expr(:call, :*, ex, guards...) end end # dot-operators & broadcasting const DOT_OPS = Set([:.*, :.+, :./, :.-, :.^]) const SIMPLE_TO_DOT = Dict(:* => :.*, :+ => :.+, :/ => :./, :- => :.-, :^ => :.^) function subs_bcast_with_dot(ex::Expr) if ex.head == :. && ex.args[1] in DOT_OPS new_args = [subs_bcast_with_dot(arg) for arg in ex.args[2].args] return Expr(:call, ex.args[1], new_args...) elseif ex.head == :. && ex.args[1] in keys(SIMPLE_TO_DOT) new_args = [subs_bcast_with_dot(arg) for arg in ex.args[2].args] return Expr(:call, SIMPLE_TO_DOT[ex.args[1]], new_args...) else new_args = [subs_bcast_with_dot(arg) for arg in ex.args] return Expr(ex.head, new_args...) end end subs_bcast_with_dot(x) = x ## is broadcastable """ Check if all operations in this expression are broadcasting """ is_bcast(ex::Expr) = is_bcast(ExH(ex)) function is_bcast(ex::ExH{:.}) bcast = isa(ex.args[2], Expr) && ex.args[2].head == :tuple return bcast && all(map(is_bcast, ex.args)) end function is_bcast(ex::ExH{:call}) bcast_old = ex.args[1] in DOT_OPS return bcast_old && all(map(is_bcast, ex.args)) end is_bcast(ex::Symbol) = true is_bcast(ex::Number) = false is_bcast(x) = error("Don't know if $x is a broadcast expression") # also see broadcasting for EinGraph nodes in optimize.jl ## function parsing """ Given a call expression, parse regular and keyword arguments See also: split_params """ function parse_call_args(ex::ExH{:call}) ordinary_args = [] kw_args = Dict() for arg in ex.args[2:end] if arg isa Expr && arg.head == :kw kw_args[arg.args[1]] = arg.args[2] elseif arg isa Expr && arg.head == :parameters for kw in arg.args kw_args[kw.args[1]] = kw.args[2] end else push!(ordinary_args, arg) end end return ordinary_args, kw_args end function parse_call_args(ex::Expr) @assert ex.head == :call return parse_call_args(ExH(ex)) end """ Parse call expression into function name, ordinary and keyword arguments. :kw and :parameters arguments are treated the same way. The reverse of this operation is make_call_expr() """ function parse_call_expr(ex::Expr) @assert ex.head == :call op = ex.args[1] ordinary_args, kw_args = parse_call_args(ex) return op, ordinary_args, kw_args end """ Make call expression from function name, ordinary and keyword arguments. The reverse of this operation is parse_call_expr() """ function make_call_expr(op::Symbol, args::Vector, kw_args::Dict=Dict{Any,Any}()) if isempty(kw_args) return Expr(:call, op, args...) else return Expr(:call, op, make_kw_params(kw_args), args...) end end """ Split parameters of a function signature, returning a list of (param name, param type) tuples and a list of keyword parameters. See also: parse_call_args """ function split_params(sig::Expr) if length(sig.args) == 1 return Tuple{Symbol,Symbol}[], Any[] elseif isa(sig.args[2], Expr) && sig.args[2].head == :parameters kw_params = Any[a.args[1] => a.args[2] for a in sig.args[2].args] params = [(arg.args[1], arg.args[2]) for arg in sig.args[3:end]] return params, kw_params else return [(arg.args[1], arg.args[2]) for arg in sig.args[2:end]], [] end end """ Remove all :kw and :parameters nodes from a call expression """ function without_keywords(ex::Expr) @assert ex.head == :call ex = without(ex, Expr(:parameters, Expr(:..., :_x))) ex = without(ex, Expr(:kw, Expr(:..., :_x))) return ex end function with_keywords(ex::Expr, kw_args::Dict) @assert ex.head == :call if isempty(kw_args) return ex else return Expr(:call, ex.args[1], make_kw_params(kw_args), ex.args[2:end]...) end end ## function generation function make_kw_params(kw_args) kw_params = [Expr(:kw, arg...) for arg in kw_args] return Expr(:parameters, kw_params...) end function make_func_expr(name, args, kw_args, body) ex = :(function name() end) |> sanitize # set name ex.args[1].args[1] = name # set kw arguments if !isempty(kw_args) push!(ex.args[1].args, make_kw_params(kw_args)) end # set arguments push!(ex.args[1].args, args...) if isa(body, Expr) && body.head == :block push!(ex.args[2].args, body.args...) else push!(ex.args[2].args, body) end return ex end # haskeyexact # function haskeyexact(d::Dict, key) # for (k, v) in d # if k == key && typeof(k) == typeof(key) # return true # end # end # return false # end function make_elementwise(ex; lhs_is_scalar=false) new_ex = macroexpand(@__MODULE__, :(@. $ex)) if isa(new_ex, Expr) && new_ex.head == :.= && lhs_is_scalar new_ex.head = :(=) # can't use :.= if LHS is scalar end return new_ex end ## force bitness force_bitness(x::AbstractFloat, ::Val{32}) = Float32(x) force_bitness(x::AbstractFloat, ::Val{64}) = Float64(x) force_bitness(x::AT, ::Val{64}) where {AT <: AbstractArray{T,N}} where {T <: AbstractFloat, N} = convert(AbstractArray{Float64, N}, x) force_bitness(x::AT, ::Val{32}) where {AT <: AbstractArray{T,N}} where {T <: AbstractFloat, N} = convert(AbstractArray{Float32, N}, x) # don't touch integers since they normally don't affect bitness stability # e.g. try `rand(Float32, 10) * 2` force_bitness(x::Integer, ::Val{B}) where B = x ## fixes for Julia 0.7 # to_dict(t::NamedTuple) = Dict(zip(keys(t), t)) to_dict(x::Base.Iterators.Pairs) = Dict(x) ## handling of different modules const KNOWN_MODULES = Set([:Core, :Base, :MainInclude, :REPL, :Espresso, :XGrad]) function get_caller_module() s = stacktrace() for i=2:length(s) if s[i].linfo isa Core.MethodInstance mod = s[i].linfo.def.module if !in(nameof(mod), KNOWN_MODULES) return mod end end end return Main # error("Can't get module of a caller from the stacktrace") end # EinGraph deprecation function depwarn_eingraph(funcsym) Base.depwarn("Einstein notation is deprecated and will be removed in Espresso 0.4.0", funcsym) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
953
struct BufCodeGen eltyp::Type end BufCodeGen() = BufCodeGen(Float64) function buffer_expr(var, eltyp, buffer_var, sz) if isempty(sz) return :($var = $eltyp(0.0)) else return :($var = @get_or_create($buffer_var, $(Expr(:quote, var)), Array(zeros($eltyp, $sz)))) end end function generate_code(codegen::BufCodeGen, g::ExGraph, nd::ExNode) # nd = cast_const_type(nd, codegen.eltyp) ex = to_buffered(g, nd) return ex end function generate_code(codegen::BufCodeGen, g::ExGraph) g = eliminate_common(g) # g = cast_const_type(g, codegen.eltyp) ex = to_buffered(g) init_exs = [buffer_expr(var, codegen.eltyp, :mem, sz) for (var, sz) in g.ctx[:rsizes] if haskey(g, var) && getcategory(g[var]) != :input] res = Expr(:block, init_exs..., ex.args...) return res end eval_codegen(codegen::BufCodeGen) = VectorCodeGen(codegen.eltyp)
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
1563
struct CuCodeGen eltyp::Type end const FT = Float32 const CUDA_NATIVE_RULES = [ :(log.(x)) => :(CUDAnative.log.(x)), :(exp.(x)) => :(CUDAnative.exp.(x)), :(sqrt.(x)) => :(CUDAnative.sqrt.(x)), :(x .^ n) => :(CUDAnative.pow.(x, __FLOAT_TYPE__(n))), :(ones(n)) => :(CuArray(ones(__FLOAT_TYPE__, n))), # :(transpose(x)) => :(permutedims(x, (2,1))), -- seems to cauase segfault in complex cases ] function cuda_buffer_expr(var, eltyp, buffer_var, sz) if isempty(sz) return :($var = $eltyp(0.0)) else return :($var = @get_or_create($buffer_var, $(Expr(:quote, var)), CuArray(zeros($eltyp, $sz)))) end end function generate_code(codegen::CuCodeGen, g::ExGraph, nd::ExNode) # nd = cast_const_type(nd, codegen.eltyp) ex = to_buffered(g, nd) ex = rewrite_all(ex, CUDA_NATIVE_RULES; phs=[:x, :y, :z, :n]) ex = subs(ex, Dict(:__FLOAT_TYPE__ => codegen.eltyp)) return ex end function generate_code(codegen::CuCodeGen, g::ExGraph) g = eliminate_common(g) # g = cast_const_type(g, codegen.eltyp) ex = to_buffered(g) ex = rewrite_all(ex, CUDA_NATIVE_RULES; phs=[:x, :y, :z, :n]) ex = subs(ex, Dict(:__FLOAT_TYPE__ => codegen.eltyp)) init_exs = [cuda_buffer_expr(var, codegen.eltyp, :mem, sz) for (var, sz) in g.ctx[:rsizes] if haskey(g, var) && getcategory(g[var]) != :input] res = Expr(:block, init_exs..., ex.args...) return res end eval_codegen(codegen::CuCodeGen) = CuVecCodeGen(codegen.eltyp)
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
671
struct CuVecCodeGen eltyp::Type end function generate_code(codegen::CuVecCodeGen, g::ExGraph, nd::ExNode) # nd = cast_const_type(nd, codegen.eltyp) ex = to_expr_kw(nd) ex = rewrite_all(ex, CUDA_NATIVE_RULES; phs=[:x, :y, :z, :n]) ex = subs(ex, Dict(:__FLOAT_TYPE__ => codegen.eltyp)) return ex end function generate_code(codegen::CuVecCodeGen, g::ExGraph) g = eliminate_common(g) # g = cast_const_type(g, codegen.eltyp) ex = to_expr_kw(g) ex = rewrite_all(ex, CUDA_NATIVE_RULES; phs=[:x, :y, :z, :n]) ex = subs(ex, Dict(:__FLOAT_TYPE__ => codegen.eltyp)) return ex end eval_codegen(codegen::CuVecCodeGen) = codegen
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
263
struct GPUCodeGen buf_var_name::Symbol end function gpu_buffer_expr(var, buffer_var, sz_ex) gpu_sz_ex = matchingex(:(zeros(_...)), sz_ex) ? :(GPUArray($sz_ex)) : sz_ex return :($var = @get_or_create $buffer_var $(Expr(:quote, var)) $gpu_sz_ex) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
595
# type for generating vectorized code struct VectorCodeGen eltyp::Type end VectorCodeGen() = VectorCodeGen(Float64) function generate_code(codegen::VectorCodeGen, g::ExGraph, nd::ExNode) # nd = cast_const_type(nd, codegen.eltyp) ex = to_expr_kw(nd) return ex end function generate_code(codegen::VectorCodeGen, g::ExGraph) # g = cast_const_type(nd, codegen.eltyp) g = eliminate_common(g) ex = to_expr_kw(g) return ex end """ For buffered codegens, return unbuffered version that can be used in evaluate!() """ eval_codegen(codegen::VectorCodeGen) = codegen
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
1806
@testset "exgraph" begin let g = ExGraph() g = ExGraph(;ctx=[:foo => 42], x=1) @test g.ctx[:foo] == 42 @test getvalue(g[1]) == 1 end let g = ExGraph(:(z = (x + y)^2); x=1, y=1) @test length(g) == 5 # check that fuse_assigned() removed extra var @test varname(g[5]) == :z @test evaluate!(g) == 4 g = ExGraph(:(z = (x .+ y).^2); x=ones(3), y=ones(3)) @test evaluate!(g) == [4.0, 4.0, 4.0] end let ex = :(M = u'v) g = ExGraph(ex; u=rand(3), v=rand(3)) @test getcategory(g[3]) == :call @test getexpr(g[3]) == :(transpose(u)) end let g = ExGraph(:(x = u + v; z = 2x)) nd = ExNode{:call}(:y, :(x - 1)) insert!(g, 2, nd) @test varname(g[2]) == :y nds = ExGraph(:(t1 = u + x; t2 = t1 - x)).tape insert!(g, 3, nds) @test varname(g[3]) == :t1 @test varname(g[4]) == :t2 delete!(g, 3) @test length(g) == 5 delete!(g, :t2) @test length(g) == 4 end let # test graph with :opaque nodes g = ExGraph(:(y = 2x); x=rand(2)) push!(g, ExNode{:opaque}(:z, :(x .* 3y))) rep_g = reparse(g) @test getvar(g[3]) == getvar(rep_g[3]) @test evaluate!(g) == evaluate!(rep_g) rw_nd = rewrite(g[3], :(Z = X * Y), :(Z = X .* Y'); phs=[:X, :Y, :Z]) @test getcategory(rw_nd) == :opaque @test getvalue(rw_nd) == nothing # value should be cleared end end @testset "var renaming" begin ex = quote x = 0 x = x + 1 y = 4 x = 2x + y y = 5 z = x + y end g = ExGraph(ex) @test to_expr(g[end]) == :(z = x3 + y2) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
1596
@testset "exnode" begin @testset "basic ops" begin nd = ExNode{:call}(:z, :(x + y)) @test getvar(nd) == :z @test varname(nd) == :z @test varidxs(nd) == [] @test getexpr(nd) == :(x + y) @test getvalue(nd) == nothing setvar!(nd, :(z[i])) @test getvar(nd) == :(z[i]) @test varname(nd) == :z @test varidxs(nd) == [:i] setexpr!(nd, :(x[i] + y[i])) @test getexpr(nd) == :(x[i] + y[i]) setvalue!(nd, [1, 2, 3.]) @test getvalue(nd) == [1, 2, 3.] end @testset "simple node" begin nd = ExNode{:call}(:z, :(x + y)) @test to_expr(nd) == :(z = x + y) end @testset "indexed node" begin nd = ExNode{:call}(:(z[i]), :(x[i] + y[i])) @test to_expr(nd) == :(z[i] = x[i] + y[i]) end @testset "dependencies" begin @test dependencies(ExNode{:constant}(:z, 42)) == [] @test dependencies(ExNode{:input}(:z, 42)) == [] @test dependencies(ExNode{:(=)}(:z, :x)) == [:x] @test dependencies(ExNode{:(=)}(:(z[i]), :(x[i]))) == [:x] @test dependencies(ExNode{:call}(:z, :(x + y))) == [:x, :y] @test dependencies(ExNode{:call}(:(z[i]), :(x[i] + y[i]))) == [:x, :y] @test dependencies(ExNode{:bcast}(:z, :(f.(x)))) == [:x] end @testset "broadcasting" begin nd = ExNode{:bcast}(:z, :(f.(x))) @test isindexed(nd) == false nd = ExNode{:bcast}(:z, :(f.(x[i]))) @test isindexed(nd) == true end end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
1661
@testset "rewrite" begin phs = Set([:x]) @test matchex(:(_x ^ 2), :(a ^ 2)) == Dict(:_x => :a) @test matchex(:(x ^ 2), :(a ^ 2), phs=phs) == Dict(:x => :a) @test matchex(:(x ^ 2), :(a ^ 2)) == nothing phs = Set([:x, :y]) @test rewrite(:(a + 2b), :(_x + 2_y), :(_x * _y)) == :(a * b) @test rewrite(:(a + 2b), :(x + 2y), :(x * y); phs=phs) == :(a * b) set_default_placeholders(Set([:x, :y])) @test rewrite(:(a + 2b), :(x + 2y), :(x * y)) == :(a * b) set_default_placeholders(Set(Symbol[])) @test tryrewrite(:(a + 2b), :(x + 2y), :(x * y); phs=[:x, :y]) == :(a * b) @test tryrewrite(:(a + 2b), :(x + 3y), :(x * y); phs=[:x, :y]) == nothing @test without(:(x * (m == n)), :(_i == _j)) == :x @test subs(:(x^n); n=2) == :(x^2) @test subs(:(x^n), Dict(:n => 2)) == :(x^2) @test subs(:(_mod._op); _mod=:Main, _op=:inc) == :(Main.inc) phs = Set([:x, :I]) @test matchex(:(x[I...]), :(A[i,j,k]); phs=phs) == Dict(:x => :A, :I => [:i, :j, :k]) @test matchex(:(foo(_args...)), :(foo(x, y))) == Dict(:_args => [:x, :y]) ex = :(foo(bar(foo(A)))) rules = [:(foo(x)) => :(quux(x)), :(bar(x)) => :(baz(x))] @test rewrite_all(ex, rules; phs=[:x]) == :(quux(baz(quux(A)))) ex = :(foo(bar(foo(A)))) pat = :(foo(x)) rpat = :(quux(x)) @test rewrite_all(ex, pat, rpat; phs=[:x]) == :(quux(bar(quux(A)))) @test matchingex(:(_x + _y), :(a + a)) @test !matchingex(:(_x + _y), :(a + a); exact=true) ex = :(foo(a, b, c)) pat = :(foo(xs...)) rpat = :(bar(xs...)) @test rewrite(ex, pat, rpat; phs=[:xs]) == :(bar(a, b, c)) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
246
using Espresso using Test include("utils_test.jl") include("rewrite_test.jl") include("simplify_test.jl") include("exnode_test.jl") include("exgraph_test.jl") # include("tracked_test.jl") -- tracked arrays are discontinued, use Yota.jl instead
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
290
@testset "simplify" begin @test simplify(:(10 - 5)) == 5 @test simplify(:(u - 2)) == :(u - 2) @test simplify(:(1 * (u - 2))) == :(u - 2) @test simplify(:(1.0 * cos(x1))) == :(cos(x1)) @test simplify(:(2 * 3x)) == :(6x) @test simplify(:(x ^ 0 / 2)) == 1/2 end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
348
@testset "tracked" begin ex = quote x2 = W * x .+ b x3 = exp.(x2) x4 = reshape(x3, 15) y = sum(x4) end inputs = [:W => rand(3,4); :x => rand(4,5); :b => rand(3)] g1 = ExGraph(ex; inputs...) g2 = ExGraph(ex; ctx=Dict(:method => :track), inputs...) @test evaluate!(g1) == evaluate!(g2) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
code
501
@testset "utils" begin ex1 = :(foo(x, y=1, z=2)) ex2 = :(foo(x; y=1, z=2)) args, kw_args = parse_call_args(ex1) @test args == [:x] @test kw_args == Dict(:y => 1, :z => 2) @test without_keywords(ex1) == :(foo(x)) @test without_keywords(ex2) == :(foo(x)) @test with_keywords(:(foo(x)), Dict(:y => 1, :z => 2)) == ex2 @test parse_call_expr(ex1) == (:foo, [:x], Dict(:y => 1, :z => 2)) @test parse_call_expr(ex2) == (:foo, [:x], Dict(:y => 1, :z => 2)) end
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
docs
3273
# Espresso [![Build Status](https://travis-ci.org/dfdx/Espresso.jl.svg?branch=master)](https://travis-ci.org/dfdx/Espresso.jl) Expression transformation package. ## Symbolic manipulation Espresso provides functions for finding, matching, substituting and rewriting Julia AST. A few examples: Match power expression and extract its first argument ```julia pat = :(_x ^ 2) # anything starting with `_` is a placeholder, placeholder matches everything ex = :(A ^ 2) matchex(pat, ex) # ==> Dict{Symbol,Any} with 1 entry: # ==> :_x => :A -- placeholder _x captured symbol :A ``` Find all function calls with any number of arguments: ```julia pat = :(_f(_a...)) # `_a...` will match 0 or more arguments ex = quote x = foo(3, 5) y = bar(x) z = baz(y) end findex(pat, ex) # ==> 3-element Array{Any,1}: # ==> :(foo(3, 5)) # ==> :(bar(x)) # ==> :(baz(y)) ``` Substitute symbol `y` with `quux(x)`: ```julia ex = :(z = 2x + y) subs(ex, Dict(:y => :(quux(x)))) # ==> :(z = 2x + quux(x)) ``` Rewrite all function calls with corresponding broadcasting: ```julia ex = :(z = foo(x) + bar(y)) # take this expression pat = :(_f(_a...)) # match recursively to this pattern rpat = :(_f.(_a...)) # and rewrite to this pattern rewrite_all(ex, pat, rpat) # ==> :(z = (+).(foo.(x), bar.(y))) ``` See [rewrite.jl](https://github.com/dfdx/Espresso.jl/blob/master/src/rewrite.jl) for more expression transformation functions and their parameters. ## Expression graph Sometimes we need more sophisticated transformations including those depending on argument types. Espresso can parse expressions into a graph of basic calls and assignments using `ExGraph` type, e.g.: ```julia ex = :(z = x ^ 2 * (y + x ^ 2)) g = ExGraph(ex; x=3.0, y=2.0); # `x` and `y` are example values from which ExGraphs learns types of these vars evaluate!(g) # evaluate all expressions to fill values of intermediate nodes g # ==> ExGraph # ==> ExNode{input}(x = x | 3.0) # ==> ExNode{input}(y = y | 2.0) # ==> ExNode{constant}(tmp390 = 2 | 2) # ==> ExNode{call}(tmp391 = x ^ tmp390 | 9.0) # ==> ExNode{constant}(tmp392 = 2 | 2) # ==> ExNode{call}(tmp393 = x ^ tmp392 | 9.0) # ==> ExNode{call}(tmp394 = y + tmp393 | 11.0) # ==> ExNode{call}(z = tmp391 * tmp394 | 99.0) ``` Such representation, although somewhat cryptic, is more flexible. For example, using it we can easily get rid of common subexpressions (`x ^ 2`): ```julia g2 = eliminate_common(g) # ==> ExGraph # ==> ExNode{input}(x = x | 3.0) # ==> ExNode{input}(y = y | 2.0) # ==> ExNode{constant}(tmp390 = 2 | 2) # ==> ExNode{call}(tmp391 = x ^ tmp390 | 9.0) # ==> ExNode{call}(tmp394 = y + tmp391 | 11.0) # ==> ExNode{call}(z = tmp391 * tmp394 | 99.0) ``` `to_expr` and `to_expr_kw` construct a Julia expression back from `ExGraph`: ```julia to_expr_kw(g2) # ==> quote # ==> tmp390 = 2 # ==> tmp391 = x ^ tmp390 # ==> tmp394 = y + tmp391 # ==> z = tmp391 * tmp394 # ==> end ``` ## (Somewhat outdated) documentation [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://dfdx.github.io/Espresso.jl/stable) [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://dfdx.github.io/Espresso.jl/latest)
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.6.3
077f5b899ab7a0c62eaf7cd8b832c45119a9e859
docs
2784
Espresso ducumentation and thanks for all the fish # Espresso.jl Documentation ```@contents ``` ## Expression parsing and rewriting ### Expression matching `matchex` - match expression by pattern, extract matching elements. Elements of expression are matched to placeholders - symbols in pattern that start with '_' or any symbols passed in `phs` parameter. ```julia matchex(:(_x^2), :(u^2)) # Nullable(Dict{Symbol,Any}(:_x=>:u)) matchex(:(x^n), :(u^2); phs=Set([:x, :n])) # Nullable(Dict{Symbol,Any}(:x=>:u,:n=>2)) ``` See also `matchingex`. See also `findex`. ### Expression substitution `subs` - substitute elements of in expression according to substitution table: ```julia ex = :(x ^ n) subs(ex, x=2) # :(2 ^ n) ``` ### Expression rewriting `rewrite` - rewrite an expression matching it to a pattern and replacing corresponding placeholders in substitution expression. ```julia ex = :(u ^ v) pat = :(_x ^ _n) subex = :(_n * _x ^ (_n - 1)) rewrite(ex, pat, subex) # :(v * u ^ (v - 1)) ``` See also `tryrewrite`. ### Expression simplification `simplify` - simplify numeric expression if possible. ```julia simplify(:(2 - 1)) # 1 simplify(:(1 * (2x^1))) # :(2x) ``` ## Einstein indexing notation Espresso.jl also supports expressions in Einstein indexing notation and is mostly compatible with [Einsum.jl](https://github.com/ahwillia/Einsum.jl). The most important functions are: `to_einstein` - convert vectorized expression to Einstein notation. ```julia to_einstein(:(W*x + b); W=rand(3,4), x=rand(4), b=rand(3)) # quote # tmp1[i] = W[i,k] * x[k] # tmp2[i] = tmp1[i] + b[i] # end ``` Here `W=rand(3,4)`, `x=rand(4)` and `b=rand(3)` are _example values_ - anything that has the same type and dimensions as real expected values. `from_einstein` - convert an expression in Einstein notation to vectorized form if possible. ```julia from_einstein(:(W[i,k] * x[k] + b[i])) # quote # tmp1 = W * x # tmp2 = tmp1 + b # end ``` ## ExGraph On low-level many functions of Espresso.jl use `ExGraph` - expression graph, represented as a topologically sorted list of primitive expression. Example: ```julia g = ExGraph(:(W*x + b); W=rand(3,4), x=rand(4), b=rand(3)) # ExGraph # ExNode{input}(W = W | <Array{Float64,2}>) # ExNode{input}(x = x | <Array{Float64,1}>) # ExNode{input}(b = b | <Array{Float64,1}>) # ExNode{call}(tmp1 = W * x | nothing) # ExNode{call}(tmp2 = tmp1 + b | nothing) ``` The main advantage of using such representation is that each node represents exactly one simple enough expression such as assignment or function call. For example, `to_einstein` and `from_einstein` both use `ExGraph` to find rule for transforming between two notations. ## Functions ```@docs matchex(pat, ex) ``` ## Index ```@index ```
Espresso
https://github.com/dfdx/Espresso.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
668
push!(LOAD_PATH,"../src/") using GIFImages using Documenter DocMeta.setdocmeta!(GIFImages, :DocTestSetup, :(using GIFImages); recursive=true) makedocs(; modules=[GIFImages], authors="Ashwani Rathee", repo="github.com/ashwani-rathee/GIFImages.jl/blob/{commit}{path}#{line}", sitename="GIFImages.jl", format=Documenter.HTML(; prettyurls=Base.get(ENV, "CI", "false") == "true", canonical="https://ashwani-rathee.github.io/GIFImages.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/ashwani-rathee/GIFImages.jl", devbranch="main", push_preview = true )
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
402
using Clang.JLLEnvs using Clang.Generators using Giflib_jll include_dir = normpath(Giflib_jll.artifact_dir, "include") headers = [joinpath(include_dir, header) for header in readdir(include_dir) if endswith(header, ".h")] options = load_options(joinpath(@__DIR__, "generator.toml")) args = get_default_args() push!(args, "-I$include_dir") ctx = create_context(headers, args, options) build!(ctx)
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
412
using Clang.JLLEnvs using Clang.Generators using libgifextra_jll include_dir = normpath(libgifextra_jll.artifact_dir, "include") headers = [joinpath(include_dir, header) for header in readdir(include_dir) if endswith(header, ".h")] options = load_options(joinpath(@__DIR__, "generator2.toml")) args = get_default_args() push!(args, "-I$include_dir") ctx = create_context(headers, args, options) build!(ctx)
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
13470
module LibGif using Giflib_jll export Giflib_jll using CEnum const GifPixelType = Cuchar const GifRowType = Ptr{Cuchar} const GifByteType = Cuchar const GifPrefixType = Cuint const GifWord = Cint struct GifColorType Red::GifByteType Green::GifByteType Blue::GifByteType end struct ColorMapObject ColorCount::Cint BitsPerPixel::Cint SortFlag::Bool Colors::Ptr{GifColorType} end struct GifImageDesc Left::GifWord Top::GifWord Width::GifWord Height::GifWord Interlace::Bool ColorMap::Ptr{ColorMapObject} end struct ExtensionBlock ByteCount::Cint Bytes::Ptr{GifByteType} Function::Cint end struct SavedImage ImageDesc::GifImageDesc RasterBits::Ptr{GifByteType} ExtensionBlockCount::Cint ExtensionBlocks::Ptr{ExtensionBlock} end function Base.getproperty(x::Ptr{SavedImage}, f::Symbol) f === :ImageDesc && return Ptr{GifImageDesc}(x + 0) f === :RasterBits && return Ptr{Ptr{GifByteType}}(x + 32) f === :ExtensionBlockCount && return Ptr{Cint}(x + 40) f === :ExtensionBlocks && return Ptr{Ptr{ExtensionBlock}}(x + 48) return getfield(x, f) end function Base.setproperty!(x::Ptr{SavedImage}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end struct GifFileType SWidth::GifWord SHeight::GifWord SColorResolution::GifWord SBackGroundColor::GifWord AspectByte::GifByteType SColorMap::Ptr{ColorMapObject} ImageCount::Cint Image::GifImageDesc SavedImages::Ptr{SavedImage} ExtensionBlockCount::Cint ExtensionBlocks::Ptr{ExtensionBlock} Error::Cint UserData::Ptr{Cvoid} Private::Ptr{Cvoid} end function Base.getproperty(x::Ptr{GifFileType}, f::Symbol) f === :SWidth && return Ptr{GifWord}(x + 0) f === :SHeight && return Ptr{GifWord}(x + 4) f === :SColorResolution && return Ptr{GifWord}(x + 8) f === :SBackGroundColor && return Ptr{GifWord}(x + 12) f === :AspectByte && return Ptr{GifByteType}(x + 16) f === :SColorMap && return Ptr{Ptr{ColorMapObject}}(x + 24) f === :ImageCount && return Ptr{Cint}(x + 32) f === :Image && return Ptr{GifImageDesc}(x + 40) f === :SavedImages && return Ptr{Ptr{SavedImage}}(x + 72) f === :ExtensionBlockCount && return Ptr{Cint}(x + 80) f === :ExtensionBlocks && return Ptr{Ptr{ExtensionBlock}}(x + 88) f === :Error && return Ptr{Cint}(x + 96) f === :UserData && return Ptr{Ptr{Cvoid}}(x + 104) f === :Private && return Ptr{Ptr{Cvoid}}(x + 112) return getfield(x, f) end function Base.setproperty!(x::Ptr{GifFileType}, f::Symbol, v) unsafe_store!(getproperty(x, f), v) end @cenum GifRecordType::UInt32 begin UNDEFINED_RECORD_TYPE = 0 SCREEN_DESC_RECORD_TYPE = 1 IMAGE_DESC_RECORD_TYPE = 2 EXTENSION_RECORD_TYPE = 3 TERMINATE_RECORD_TYPE = 4 end # typedef int ( * InputFunc ) ( GifFileType * , GifByteType * , int ) const InputFunc = Ptr{Cvoid} # typedef int ( * OutputFunc ) ( GifFileType * , const GifByteType * , int ) const OutputFunc = Ptr{Cvoid} struct GraphicsControlBlock DisposalMode::Cint UserInputFlag::Bool DelayTime::Cint TransparentColor::Cint end function EGifOpenFileName(GifFileName, GifTestExistence, Error) ccall((:EGifOpenFileName, libgif), Ptr{GifFileType}, (Ptr{Cchar}, Bool, Ptr{Cint}), GifFileName, GifTestExistence, Error) end function EGifOpenFileHandle(GifFileHandle, Error) ccall((:EGifOpenFileHandle, libgif), Ptr{GifFileType}, (Cint, Ptr{Cint}), GifFileHandle, Error) end function EGifOpen(userPtr, writeFunc, Error) ccall((:EGifOpen, libgif), Ptr{GifFileType}, (Ptr{Cvoid}, OutputFunc, Ptr{Cint}), userPtr, writeFunc, Error) end function EGifSpew(GifFile) ccall((:EGifSpew, libgif), Cint, (Ptr{GifFileType},), GifFile) end function EGifGetGifVersion(GifFile) ccall((:EGifGetGifVersion, libgif), Ptr{Cchar}, (Ptr{GifFileType},), GifFile) end function EGifCloseFile(GifFile, ErrorCode) ccall((:EGifCloseFile, libgif), Cint, (Ptr{GifFileType}, Ptr{Cint}), GifFile, ErrorCode) end function EGifPutScreenDesc(GifFile, GifWidth, GifHeight, GifColorRes, GifBackGround, GifColorMap) ccall((:EGifPutScreenDesc, libgif), Cint, (Ptr{GifFileType}, Cint, Cint, Cint, Cint, Ptr{ColorMapObject}), GifFile, GifWidth, GifHeight, GifColorRes, GifBackGround, GifColorMap) end function EGifPutImageDesc(GifFile, GifLeft, GifTop, GifWidth, GifHeight, GifInterlace, GifColorMap) ccall((:EGifPutImageDesc, libgif), Cint, (Ptr{GifFileType}, Cint, Cint, Cint, Cint, Bool, Ptr{ColorMapObject}), GifFile, GifLeft, GifTop, GifWidth, GifHeight, GifInterlace, GifColorMap) end function EGifSetGifVersion(GifFile, gif89) ccall((:EGifSetGifVersion, libgif), Cvoid, (Ptr{GifFileType}, Bool), GifFile, gif89) end function EGifPutLine(GifFile, GifLine, GifLineLen) ccall((:EGifPutLine, libgif), Cint, (Ptr{GifFileType}, Ptr{GifPixelType}, Cint), GifFile, GifLine, GifLineLen) end function EGifPutPixel(GifFile, GifPixel) ccall((:EGifPutPixel, libgif), Cint, (Ptr{GifFileType}, GifPixelType), GifFile, GifPixel) end function EGifPutComment(GifFile, GifComment) ccall((:EGifPutComment, libgif), Cint, (Ptr{GifFileType}, Ptr{Cchar}), GifFile, GifComment) end function EGifPutExtensionLeader(GifFile, GifExtCode) ccall((:EGifPutExtensionLeader, libgif), Cint, (Ptr{GifFileType}, Cint), GifFile, GifExtCode) end function EGifPutExtensionBlock(GifFile, GifExtLen, GifExtension) ccall((:EGifPutExtensionBlock, libgif), Cint, (Ptr{GifFileType}, Cint, Ptr{Cvoid}), GifFile, GifExtLen, GifExtension) end function EGifPutExtensionTrailer(GifFile) ccall((:EGifPutExtensionTrailer, libgif), Cint, (Ptr{GifFileType},), GifFile) end function EGifPutExtension(GifFile, GifExtCode, GifExtLen, GifExtension) ccall((:EGifPutExtension, libgif), Cint, (Ptr{GifFileType}, Cint, Cint, Ptr{Cvoid}), GifFile, GifExtCode, GifExtLen, GifExtension) end function EGifPutCode(GifFile, GifCodeSize, GifCodeBlock) ccall((:EGifPutCode, libgif), Cint, (Ptr{GifFileType}, Cint, Ptr{GifByteType}), GifFile, GifCodeSize, GifCodeBlock) end function EGifPutCodeNext(GifFile, GifCodeBlock) ccall((:EGifPutCodeNext, libgif), Cint, (Ptr{GifFileType}, Ptr{GifByteType}), GifFile, GifCodeBlock) end function DGifOpenFileName(GifFileName, Error) ccall((:DGifOpenFileName, libgif), Ptr{GifFileType}, (Ptr{Cchar}, Ptr{Cint}), GifFileName, Error) end function DGifOpenFileHandle(GifFileHandle, Error) ccall((:DGifOpenFileHandle, libgif), Ptr{GifFileType}, (Cint, Ptr{Cint}), GifFileHandle, Error) end function DGifSlurp(GifFile) ccall((:DGifSlurp, libgif), Cint, (Ptr{GifFileType},), GifFile) end function DGifOpen(userPtr, readFunc, Error) ccall((:DGifOpen, libgif), Ptr{GifFileType}, (Ptr{Cvoid}, InputFunc, Ptr{Cint}), userPtr, readFunc, Error) end function DGifCloseFile(GifFile, ErrorCode) ccall((:DGifCloseFile, libgif), Cint, (Ptr{GifFileType}, Ptr{Cint}), GifFile, ErrorCode) end function DGifGetScreenDesc(GifFile) ccall((:DGifGetScreenDesc, libgif), Cint, (Ptr{GifFileType},), GifFile) end function DGifGetRecordType(GifFile, GifType) ccall((:DGifGetRecordType, libgif), Cint, (Ptr{GifFileType}, Ptr{GifRecordType}), GifFile, GifType) end function DGifGetImageHeader(GifFile) ccall((:DGifGetImageHeader, libgif), Cint, (Ptr{GifFileType},), GifFile) end function DGifGetImageDesc(GifFile) ccall((:DGifGetImageDesc, libgif), Cint, (Ptr{GifFileType},), GifFile) end function DGifGetLine(GifFile, GifLine, GifLineLen) ccall((:DGifGetLine, libgif), Cint, (Ptr{GifFileType}, Ptr{GifPixelType}, Cint), GifFile, GifLine, GifLineLen) end function DGifGetPixel(GifFile, GifPixel) ccall((:DGifGetPixel, libgif), Cint, (Ptr{GifFileType}, GifPixelType), GifFile, GifPixel) end function DGifGetExtension(GifFile, GifExtCode, GifExtension) ccall((:DGifGetExtension, libgif), Cint, (Ptr{GifFileType}, Ptr{Cint}, Ptr{Ptr{GifByteType}}), GifFile, GifExtCode, GifExtension) end function DGifGetExtensionNext(GifFile, GifExtension) ccall((:DGifGetExtensionNext, libgif), Cint, (Ptr{GifFileType}, Ptr{Ptr{GifByteType}}), GifFile, GifExtension) end function DGifGetCode(GifFile, GifCodeSize, GifCodeBlock) ccall((:DGifGetCode, libgif), Cint, (Ptr{GifFileType}, Ptr{Cint}, Ptr{Ptr{GifByteType}}), GifFile, GifCodeSize, GifCodeBlock) end function DGifGetCodeNext(GifFile, GifCodeBlock) ccall((:DGifGetCodeNext, libgif), Cint, (Ptr{GifFileType}, Ptr{Ptr{GifByteType}}), GifFile, GifCodeBlock) end function DGifGetLZCodes(GifFile, GifCode) ccall((:DGifGetLZCodes, libgif), Cint, (Ptr{GifFileType}, Ptr{Cint}), GifFile, GifCode) end function DGifGetGifVersion(GifFile) ccall((:DGifGetGifVersion, libgif), Ptr{Cchar}, (Ptr{GifFileType},), GifFile) end function GifErrorString(ErrorCode) ccall((:GifErrorString, libgif), Ptr{Cchar}, (Cint,), ErrorCode) end function GifMakeMapObject(ColorCount, ColorMap) ccall((:GifMakeMapObject, libgif), Ptr{ColorMapObject}, (Cint, Ptr{GifColorType}), ColorCount, ColorMap) end function GifFreeMapObject(Object) ccall((:GifFreeMapObject, libgif), Cvoid, (Ptr{ColorMapObject},), Object) end function GifUnionColorMap(ColorIn1, ColorIn2, ColorTransIn2) ccall((:GifUnionColorMap, libgif), Ptr{ColorMapObject}, (Ptr{ColorMapObject}, Ptr{ColorMapObject}, Ptr{GifPixelType}), ColorIn1, ColorIn2, ColorTransIn2) end function GifBitSize(n) ccall((:GifBitSize, libgif), Cint, (Cint,), n) end function GifApplyTranslation(Image, Translation) ccall((:GifApplyTranslation, libgif), Cvoid, (Ptr{SavedImage}, Ptr{GifPixelType}), Image, Translation) end function GifAddExtensionBlock(ExtensionBlock_Count, ExtensionBlocks, Function, Len, ExtData) ccall((:GifAddExtensionBlock, libgif), Cint, (Ptr{Cint}, Ptr{Ptr{ExtensionBlock}}, Cint, Cuint, Ptr{Cuchar}), ExtensionBlock_Count, ExtensionBlocks, Function, Len, ExtData) end function GifFreeExtensions(ExtensionBlock_Count, ExtensionBlocks) ccall((:GifFreeExtensions, libgif), Cvoid, (Ptr{Cint}, Ptr{Ptr{ExtensionBlock}}), ExtensionBlock_Count, ExtensionBlocks) end function GifMakeSavedImage(GifFile, CopyFrom) ccall((:GifMakeSavedImage, libgif), Ptr{SavedImage}, (Ptr{GifFileType}, Ptr{SavedImage}), GifFile, CopyFrom) end function GifFreeSavedImages(GifFile) ccall((:GifFreeSavedImages, libgif), Cvoid, (Ptr{GifFileType},), GifFile) end function DGifExtensionToGCB(GifExtensionLength, GifExtension, GCB) ccall((:DGifExtensionToGCB, libgif), Cint, (Csize_t, Ptr{GifByteType}, Ptr{GraphicsControlBlock}), GifExtensionLength, GifExtension, GCB) end function EGifGCBToExtension(GCB, GifExtension) ccall((:EGifGCBToExtension, libgif), Csize_t, (Ptr{GraphicsControlBlock}, Ptr{GifByteType}), GCB, GifExtension) end function DGifSavedExtensionToGCB(GifFile, ImageIndex, GCB) ccall((:DGifSavedExtensionToGCB, libgif), Cint, (Ptr{GifFileType}, Cint, Ptr{GraphicsControlBlock}), GifFile, ImageIndex, GCB) end function EGifGCBToSavedExtension(GCB, GifFile, ImageIndex) ccall((:EGifGCBToSavedExtension, libgif), Cint, (Ptr{GraphicsControlBlock}, Ptr{GifFileType}, Cint), GCB, GifFile, ImageIndex) end function GifDrawText8x8(Image, x, y, legend, color) ccall((:GifDrawText8x8, libgif), Cvoid, (Ptr{SavedImage}, Cint, Cint, Ptr{Cchar}, Cint), Image, x, y, legend, color) end function GifDrawBox(Image, x, y, w, d, color) ccall((:GifDrawBox, libgif), Cvoid, (Ptr{SavedImage}, Cint, Cint, Cint, Cint, Cint), Image, x, y, w, d, color) end function GifDrawRectangle(Image, x, y, w, d, color) ccall((:GifDrawRectangle, libgif), Cvoid, (Ptr{SavedImage}, Cint, Cint, Cint, Cint, Cint), Image, x, y, w, d, color) end function GifDrawBoxedText8x8(Image, x, y, legend, border, bg, fg) ccall((:GifDrawBoxedText8x8, libgif), Cvoid, (Ptr{SavedImage}, Cint, Cint, Ptr{Cchar}, Cint, Cint, Cint), Image, x, y, legend, border, bg, fg) end const _GIF_LIB_H_ = 1 const GIFLIB_MAJOR = 5 const GIFLIB_MINOR = 2 const GIFLIB_RELEASE = 1 const GIF_ERROR = 0 const GIF_OK = 1 const GIF_STAMP = "GIFVER" # Skipping MacroDefinition: GIF_STAMP_LEN sizeof ( GIF_STAMP ) - 1 const GIF_VERSION_POS = 3 const GIF87_STAMP = "GIF87a" const GIF89_STAMP = "GIF89a" const CONTINUE_EXT_FUNC_CODE = 0x00 const COMMENT_EXT_FUNC_CODE = 0xfe const GRAPHICS_EXT_FUNC_CODE = 0xf9 const PLAINTEXT_EXT_FUNC_CODE = 0x01 const APPLICATION_EXT_FUNC_CODE = 0xff const DISPOSAL_UNSPECIFIED = 0 const DISPOSE_DO_NOT = 1 const DISPOSE_BACKGROUND = 2 const DISPOSE_PREVIOUS = 3 const NO_TRANSPARENT_COLOR = -1 const E_GIF_SUCCEEDED = 0 const E_GIF_ERR_OPEN_FAILED = 1 const E_GIF_ERR_WRITE_FAILED = 2 const E_GIF_ERR_HAS_SCRN_DSCR = 3 const E_GIF_ERR_HAS_IMAG_DSCR = 4 const E_GIF_ERR_NO_COLOR_MAP = 5 const E_GIF_ERR_DATA_TOO_BIG = 6 const E_GIF_ERR_NOT_ENOUGH_MEM = 7 const E_GIF_ERR_DISK_IS_FULL = 8 const E_GIF_ERR_CLOSE_FAILED = 9 const E_GIF_ERR_NOT_WRITEABLE = 10 const D_GIF_SUCCEEDED = 0 const D_GIF_ERR_OPEN_FAILED = 101 const D_GIF_ERR_READ_FAILED = 102 const D_GIF_ERR_NOT_GIF_FILE = 103 const D_GIF_ERR_NO_SCRN_DSCR = 104 const D_GIF_ERR_NO_IMAG_DSCR = 105 const D_GIF_ERR_NO_COLOR_MAP = 106 const D_GIF_ERR_WRONG_RECORD = 107 const D_GIF_ERR_DATA_TOO_BIG = 108 const D_GIF_ERR_NOT_ENOUGH_MEM = 109 const D_GIF_ERR_CLOSE_FAILED = 110 const D_GIF_ERR_NOT_READABLE = 111 const D_GIF_ERR_IMAGE_DEFECT = 112 const D_GIF_ERR_EOF_TOO_SOON = 113 const GIF_FONT_WIDTH = 8 const GIF_FONT_HEIGHT = 8 end # module
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
1534
module LibGifExtra using libgifextra_jll export libgifextra_jll using CEnum function LoadRGB(FileName, InFileName, OneFileFlag, RedBuffer, GreenBuffer, BlueBuffer, Width, Height) ccall((:LoadRGB, libgifextra), Cvoid, (Ptr{Cchar}, Ptr{Cchar}, Cint, Ptr{Ptr{Cint}}, Ptr{Ptr{Cint}}, Ptr{Ptr{Cint}}, Cint, Cint), FileName, InFileName, OneFileFlag, RedBuffer, GreenBuffer, BlueBuffer, Width, Height) end function GIF2RGB(NumFiles, FileName, OneFileFlag, OutFileName) ccall((:GIF2RGB, libgifextra), Cvoid, (Cint, Ptr{Cchar}, Bool, Ptr{Cchar}), NumFiles, FileName, OneFileFlag, OutFileName) end function DumpScreen2RGB(FileName, OneFileFlag, ColorMap, ScreenBuffer, ScreenWidth, ScreenHeight) ccall((:DumpScreen2RGB, libgifextra), Cvoid, (Ptr{Cchar}, Cint, Ptr{Cint}, Ptr{Cint}, Cint, Cint), FileName, OneFileFlag, ColorMap, ScreenBuffer, ScreenWidth, ScreenHeight) end function RGB2GIF(OneFileFlag, NumFiles, FileName, InFileName, ExpNumOfColors, Width, Height) ccall((:RGB2GIF, libgifextra), Cvoid, (Bool, Cint, Ptr{Cchar}, Ptr{Cchar}, Cint, Cint, Cint), OneFileFlag, NumFiles, FileName, InFileName, ExpNumOfColors, Width, Height) end function SaveGif(FileName, OutputBuffer, Width, Height, ExpColorMapSize, OutputColorMap) ccall((:SaveGif, libgifextra), Cvoid, (Ptr{Cchar}, Ptr{Cint}, Cint, Cint, Cint, Ptr{Cint}), FileName, OutputBuffer, Width, Height, ExpColorMapSize, OutputColorMap) end function returnGIF(FileName) ccall((:returnGIF, libgifextra), Ptr{Cint}, (Ptr{Cchar},), FileName) end end # module
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
551
module GIFImages include("../lib/LibGif.jl") include("../lib/LibGifExtra.jl") using .LibGif using .LibGifExtra using ColorTypes using ColorVectorSpace using FixedPointNumbers using StatsBase using RegionTrees, StaticArrays using HistogramThresholding using DataStructures using ImageCore include("decode.jl") include("encode.jl") include("quantizers.jl") export gif_decode, gif_encode export mediancutquantisation, mediancutquantisation! export octreequantisation, octreequantisation! export kdtreequantisation, kdtreequantisation! end # module
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
2936
""" gif_decode(filepath::AbstractString; use_localpalette=false) Decode the GIF image as colorant matrix. The source data needs to be a filename. #### Arguments - `filepath::AbstractString` : Path to the gif file - `use_localpalette::Bool=false` : While decoding, using this argument use of local colormap or global colormap for a particular slice can be specified. Gif files are palette based and have a global colormap(max `256 colors`) but slices/images in gif can have their own local colormap specific to a particular slice/image. #### Examples ```jl julia> using GIFImages, Downloads julia> path = "test/data/fire.gif" "test/data/fire.gif" julia> img = gif_decode(path) 60×30×33 Array{RGB{N0f8},3} with eltype RGB{N0f8} """ function gif_decode(filepath::AbstractString; use_localpalette=false) error1 = Cint(0) gif = LibGif.DGifOpenFileName(filepath, Ref(error1)) try gif == C_NULL && error("failed to open the gif file: null pointer") slurp_return = LibGif.DGifSlurp(gif) if (slurp_return == LibGif.GIF_ERROR) error("failed to read .gif file") end loaded_gif = unsafe_load(gif) img_count = loaded_gif.ImageCount components = unsafe_wrap(Array, loaded_gif.SavedImages, loaded_gif.ImageCount) # Gif's are palette based and can have upto 256 colors in a image colormap = unsafe_load(loaded_gif.SColorMap) # global colormap palette = unsafe_wrap(Array, colormap.Colors, colormap.ColorCount) final = zeros(RGB{N0f8}, loaded_gif.SHeight, loaded_gif.SWidth, loaded_gif.ImageCount) # read the images for i = 1:img_count img = unsafe_wrap(Array, components[i].RasterBits, loaded_gif.SWidth * loaded_gif.SHeight) desc = components[i].ImageDesc @debug "Image $i at [$(desc.Left), $(desc.Top)] and size [$(desc.Width), $(desc.Height)]" * ((desc.ColorMap !=C_NULL) ? " and has a local colormap.\n" : " and doesn't have a local colormap.\n") # support for using local colormaps if desc.ColorMap !=C_NULL && use_localpalette == true localcolormap = unsafe_load(desc.ColorMap) @debug "Image $i : using Local ColorMap with $(localcolormap.ColorCount) colors." lpalette = unsafe_wrap(Array, localcolormap.Colors, localcolormap.ColorCount) colortypes = map(x -> lpalette[x+1], img) else colortypes = map(x -> palette[x+1], img) end res = map(x -> RGB{N0f8}(x.Red / 255, x.Green / 255, x.Blue / 255), colortypes) res = reshape(res, Int(loaded_gif.SWidth), Int(loaded_gif.SHeight)) res = res' final[:, :, i] = res end # return the final matrix return final finally LibGif.DGifCloseFile(gif, Ref(error1)) end end
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
2818
""" gif_encode(filepath::AbstractString, img::AbstractArray; num::Int = 64) Encode the GIF colorant matrix to file. #### Arguments - `filepath` : Name of the file to which image is written. - `img` : 3D GIF colorant matrix which has structure of height*width*numofimags and all the images are present as slices of the 3D matrix - `colormapnum` : Specifies the number of colors to be used for the global colormap ### Examples ```jl julia> using GIFImages, Downloads julia> path = "test/data/fire.gif" "test/data/fire.gif" julia> img = gif_decode(path) 60×30×33 Array{RGB{N0f8},3} with eltype RGB{N0f8} julia> gif_encode("fire.gif", img) ``` """ function gif_encode(filepath::AbstractString, img::AbstractArray; colormapnum::Int = 256) if(eltype(img)!= RGB{N0f8}) throw(ErrorException("gif_encode requires img to be in RGB{N0f8} colorspace currently")) end error1 = Cint(0) gif_file = LibGif.EGifOpenFileName(filepath, 0, Ref(error1)) colors = [] shape = size(img) gif_file == C_NULL && throw(ErrorException("EGifOpenFileName() failed to open the gif file: null pointer")) (colormapnum < 1 || colormapnum > 256) && throw(BoundsError("colormapnum is out of range and needs to be in range 1-256(both inclusive)")) (ndims(img) != 3) && throw(DimensionMismatch("Image Array needs to be in Height, Width, NumImages format.")) try # generation of a colormap # this changes the image directly for now palette = kdtreequantisation!(img; numcolors=colormapnum, precheck=true) append!(colors, palette) mapping = Dict() for (i, j) in enumerate(colors) mapping[j] = UInt8(i-1) end # defining the global colormap colors = map(x -> LibGif.GifColorType(x.r, x.g, x.b), colors * 255) colormap = LibGif.GifMakeMapObject(colormapnum, colors) # features of the file gif_file.SWidth = shape[2] gif_file.SHeight = shape[1] gif_file.SColorResolution = 8 gif_file.SBackGroundColor = 0 gif_file.SColorMap = colormap # encoding # case of 512*512 for i = 1:shape[3] # flatten the image img1 = vec(collect(@view(img[:, :, i])')) pix = map(x -> mapping[x], img1) # saving a new image in gif_file desc = LibGif.GifImageDesc(0, 0, size(img)[2], size(img)[1], 0, C_NULL) c = LibGif.SavedImage(desc, pointer(pix), 0, C_NULL) LibGif.GifMakeSavedImage(gif_file, Ref(c)) end finally # proper file close if error happens # writing and closing the file if (LibGif.EGifSpew(gif_file) == LibGif.GIF_ERROR) throw(ErrorException("Failed to write to file!")) end end end
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
10462
# In this file, we have the color quantisation algorithms function mediancutquantisation!(img; numcolors = 256, precheck::Bool=false) if(eltype(img)!=RGB{N0f8}) error("Median Cut Algorithm requires img to be in RGB colorspace currently") end # checks if image has more colors than in numcolors if precheck == true unumcolors = length(unique(img)) # @show unumcolors if unumcolors <= numcolors @debug "Image has $unumcolors unique colors" return unique(img) end end idxs = collect(1:length(img)) function split_buckets(idxs, depth) if length(idxs) == 0 return end color = RGB.(0,0,0) # Buckets are same size, # means that each colors is assigned to # equal number of pixels here. if depth == 0 color = RGB{N0f8}.(mean(img[idxs])) img[idxs] .= color return end # find range of colors and pick color which # most difference in max val and min val rmin, rmax = 1.0N0f8, 0.0N0f8 gmin, gmax = 1.0N0f8, 0.0N0f8 bmin, bmax = 1.0N0f8, 0.0N0f8 for idx in idxs color = img[idx] if (color.r > rmax) rmax = color.r end if (color.g > gmax) gmax = color.g end if (color.b > bmax) bmax = color.b end if (color.r < rmin) rmin = color.r end if (color.g < gmin) gmin = color.g end if (color.b < bmin) bmin = color.b end end ind = findmax([rmax - rmin, gmax - gmin, bmax - bmin])[2] # sort on basis of max range color if ind == 1 sort!(idxs; by = c -> img[c].r) elseif ind == 2 sort!(idxs; by = c -> img[c].g) elseif ind == 3 sort!(idxs; by = c -> img[c].b) end # start diving on basis of median index medind = trunc(Int, (length(idxs) + 1) / 2) # two separate buckets split_buckets(@view(idxs[1:medind]), depth - 1) split_buckets(@view(idxs[medind+1:end]), depth - 1) end split_buckets(idxs, log2(numcolors)) end function mediancutquantisation(img;kwargs...) img1 = deepcopy(img) mediancutquantisation!(img1;kwargs...) return img1 end function octreequantisation!(img; numcolors = 256, precheck::Bool=false) # ensure the img is in RGB colorspace if(eltype(img)!=RGB{N0f8}) error("Octree Algorithm requires img to be in RGB colorspace") end # checks if image has more colors than in numcolors if precheck == true unumcolors = length(unique(img)) # @show unumcolors if unumcolors <= numcolors @debug "Image has $unumcolors unique colors" return unique(img) end end # step 1: creating the octree root = Cell(SVector(0.0, 0.0, 0.0), SVector(1.0, 1.0, 1.0), ["root", 0, [], RGB{N0f8}.(0.0, 0.0, 0.0), 0]) cases = map(p->[bitstring(UInt8(p))[6:end], 0, Vector{Int}([]), RGB{N0f8}.(0.0,0.0,0.0), 1], 1:8) split!(root, cases) inds = collect(1:length(img)) function putin(root, in) r, g, b = map(p->bitstring(UInt8(p*255)), channelview([img[in]])) rgb = r[1] * g[1] * b[1] # finding the entry to the tree ind = 0 for i = 1:8 if (root.children[i].data[1] == rgb) root.children[i].data[2] += 1 ind = i break end end curr = root.children[ind] for i = 2:8 cases = map(p->[bitstring(UInt8(p))[6:end], 0, Vector{Int}([]), RGB{N0f8}.(0.0,0.0,0.0), i], 1:8) rgb = r[i] * g[i] * b[i] if (isleaf(curr) == true && i <= 8) split!(curr, cases) end if (i == 8) for j = 1:8 if (curr.children[j].data[1] == rgb) curr = curr.children[j] curr.data[2] += 1 push!(curr.data[3], in) curr.data[4] = img[in] return end end end # handle 1:7 cases for rgb to handle first seven bits for j = 1:8 if (curr.children[j].data[1] == rgb) curr.children[j].data[2] += 1 curr = curr.children[j] break end end end end # build the tree for i in inds root.data[2]+=1 putin(root, i) end # step 2: reducing tree to a certain number of colors # there is scope for improvements in allleaves as it's found again n again leafs = [p for p in allleaves(root)] filter!(p -> !iszero(p.data[2]), leafs) tobe_reduced = leafs[1] while (length(leafs) > numcolors) parents = unique([parent(p) for p in leafs]) parents = sort(parents; by = c -> c.data[2]) tobe_reduced = parents[1] # @show tobe_reduced.data for i = 1:8 append!(tobe_reduced.data[3], tobe_reduced.children[i].data[3]) tobe_reduced.data[4] += tobe_reduced.children[i].data[4] * tobe_reduced.children[i].data[2] end tobe_reduced.data[4] /= tobe_reduced.data[2] tobe_reduced.children = nothing # we don't want to do this again n again leafs = [p for p in allleaves(root)] filter!(p -> !iszero(p.data[2]), leafs) end # step 3: palette formation and quantisation now da = [p.data for p in leafs] for i in da for j in i[3] img[j] = i[4] end end colors = [p[4] for p in da] return colors end function octreequantisation(img; kwargs...) img_copy = deepcopy(img) palette = octreequantisation!(img_copy; kwargs...) return img_copy, palette end function Otsu_N(histogram::AbstractArray, edges::AbstractRange) N = sum(histogram) pdf = histogram / N first_bin = firstindex(pdf) last_bin = lastindex(pdf) cumulative_zeroth_moment = cumsum(pdf) cumulative_first_moment = cumsum(float(edges) .* pdf) μ_T = cumulative_first_moment[end] maxval = zero(eltype(first(pdf))) # Equation (6) for determining the probability of the first class. function ω(k) let cumulative_zeroth_moment = cumulative_zeroth_moment return cumulative_zeroth_moment[k] end end # Equation (7) for determining the mean of the first class. function μ(k) let cumulative_first_moment = cumulative_first_moment return cumulative_first_moment[k] end end # Equation (18) for determining the between-cass variance. function σ²(k) let μ_T = μ_T return (μ_T * ω(k) - μ(k))^2 / (ω(k) * (1 - ω(k))) end end t = first_bin for k = first_bin:last_bin-1 val = σ²(k) if val > maxval maxval = val t = k end end return t end mutable struct kdtreenode inds::Vector{Int} axis::Int splitpoint::Float64 leftChild::Union{kdtreenode,Nothing} rightChild::Union{kdtreenode,Nothing} end function kdtreequantisation!(img::AbstractArray; numcolors::Int = 256, precheck::Bool=false) # ensure the img is in RGB colorspace if(eltype(img)!=RGB{N0f8}) error("KDtree Algorithm requires img to be in RGB colorspace currently") end # checks if image has more colors than in numcolors if precheck == true unumcolors = length(unique(img)) # @show unumcolors if unumcolors <= numcolors @debug "Image has $unumcolors unique colors" return unique(img) end end # basic setup of img data, PriorityQueue to maintain variances for making splits n_channels = length(channelview([img[1]])) data = collect(reshape(channelview(img), n_channels, :)) inds = collect(1:length(img)) pq = PriorityQueue(Base.Order.Reverse) variance(edges::AbstractRange, count::AbstractArray) = sum((((edges .- mean(edges)) .^ 2) .* count) / (sum(count) - 1)) # To calculate max variance along a axis function varmax(inds::Vector{Int}) maxval = -Inf ind = 0 edgesd = 0 for i = 1:n_channels # error that needs to be fixed ArgumentError: reducing over an empty collection is not allowed edges, count = build_histogram(data[i,inds], 256) t = Otsu_N(count[1:end], edges) curr = variance(edges[1:end], count[1:end]) - variance(edges[1:t], count[1:t])- variance(edges[t:end], count[t:end]) if (curr > maxval) maxval = curr ind = i edgesd = edges[t] end end return maxval, ind, edgesd end # To split of a node into its children based on max variance reduction infromation function split(x) indsleft = Vector{Int}([]) indsright = Vector{Int}([]) for i in x.inds if data[:,i][x.axis] <= x.splitpoint push!(indsleft, i) else push!(indsright, i) end end return indsleft, indsright end # root of tree set up maxvar, axis, splitpoint = varmax(inds) root = kdtreenode(inds, axis, splitpoint, nothing, nothing) enqueue!(pq, root => maxvar) while length(pq) < numcolors # split using axis with highest variance change x, maxvar = dequeue_pair!(pq) if maxvar == 0 @debug "Variance dropped to 0 while splitting, number of colors in Image: $(length(pq))" break end indsleft, indsright = split(x) maxvar, axis, splitpoint = varmax(indsleft) enqueue!(pq, kdtreenode(indsleft, axis, splitpoint, nothing, nothing) => maxvar) maxvar, axis, splitpoint = varmax(indsright) enqueue!(pq, kdtreenode(indsright, axis, splitpoint, nothing, nothing) => maxvar) end # Update the image numcol = length(pq) colors = Vector{eltype(img)}([]) for i = 1:numcol x = dequeue!(pq) color = eltype(img).(mean(img[x.inds])) push!(colors, color) img[x.inds] .= color end return colors end function kdtreequantisation(img; kwargs...) img_copy = deepcopy(img) palette = kdtreequantisation!(img_copy; kwargs...) return img_copy, palette end
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
1400
@testset "GIFImages.jl" begin path = get_example("fire.gif") @testset "Basics" begin @test typeof(gif_decode(path)) == Array{ColorTypes.RGB{FixedPointNumbers.N0f8}, 3} @test eltype(gif_decode(path)) == ColorTypes.RGB{FixedPointNumbers.N0f8} end @testset "Output Shapes" begin @test size(gif_decode(get_example("fire.gif"))) == (60,30,33) @test size(gif_decode(get_example("gifgrid.gif")))== (100,100,1) @test size(gif_decode(get_example("porsche.gif"))) == (200,320,1) @test size(gif_decode(get_example("solid2.gif"))) == (400,640,1) @test size(gif_decode(get_example("treescap-interlaced.gif"))) == (40,40,1) @test size(gif_decode(get_example("treescap.gif"))) == (40,40,1) @test size(gif_decode(get_example("welcome2.gif"))) == (48,290,6) @test size(gif_decode(get_example("x-trans.gif"))) == (100,100,1) end @testset "Local ColorMaps" begin img1 = gif_decode(get_example("welcome2.gif"); use_localpalette=true) img2 = gif_decode(get_example("welcome2.gif")) @test img1 != img2 # only certain images in welcome2.gif have local palette # need to ensure the global and local color palettes are maintained separately @test img1[:,:,1] == img1[:,:,1] @test img1[:,:,2] == img1[:,:,2] @test img1[:,:,3] == img1[:,:,3] end end
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
2501
using ImageQualityIndexes @testset "Encoding" begin @testset "Basic Encoding" begin img1 = gif_decode(get_example("fire.gif")) gif_encode("test1.gif", img1) @test size(gif_decode("test1.gif")) == (60,30,33) img1 = gif_decode(get_example("gifgrid.gif")) gif_encode("test1.gif", img1) @test size(gif_decode("test1.gif")) == (100,100,1) end @testset "Encode, Decode compatibility" begin QUALITY = 100 # ensure encodes are same as what was decoded img = gif_decode(get_example("fire.gif")) gif_encode("test12.gif", img) @test assess_psnr(gif_decode("test12.gif"), img) > QUALITY img = gif_decode(get_example("gifgrid.gif")) gif_encode("test12.gif", img) @test assess_psnr(gif_decode("test12.gif"), img) > QUALITY img = gif_decode(get_example("porsche.gif")) gif_encode("test12.gif", img) @test assess_psnr(gif_decode("test12.gif"), img) > QUALITY img = gif_decode(get_example("solid2.gif")) gif_encode("test12.gif", img) @test assess_psnr(gif_decode("test12.gif"), img) > QUALITY img = gif_decode(get_example("treescap-interlaced.gif")) gif_encode("test12.gif", img) @test assess_psnr(gif_decode("test12.gif"), img) > QUALITY img = gif_decode(get_example("treescap.gif")) gif_encode("test12.gif", img) @test assess_psnr(gif_decode("test12.gif"), img) > QUALITY img = gif_decode(get_example("welcome2.gif")) gif_encode("test12.gif", img) @test assess_psnr(gif_decode("test12.gif"), img) > QUALITY img = gif_decode(get_example("x-trans.gif")) gif_encode("test12.gif", img) @test assess_psnr(gif_decode("test12.gif"), img) > QUALITY end # restricting colorspace to RGB for now @testset "ColorSpaces" begin img = BGR.(gif_decode(get_example("x-trans.gif"))) @test_throws ErrorException gif_encode("test12.gif", img) end @testset "Other Exceptions" begin # colormap number out of range img = gif_decode(get_example("x-trans.gif")) @test_throws BoundsError gif_encode("test12.gif", img; colormapnum= 270) # dimension error img = testimage("mandrill") @test_throws DimensionMismatch gif_encode("test12.gif", img) img = gif_decode(get_example("welcome2.gif")) @test_throws ErrorException gif_encode("", img) end end
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
2387
@testset "Quantizers" begin @testset "Median Cut Color Quantizer" begin #known issue # this has some issues with number of colors generated img = gif_decode(get_example("fire.gif")) # cuz this has less number of colors @test length(unique(mediancutquantisation(img; numcolors=32))) == 16 # images with ample number of distinct colors img = testimage("mandrill") @test length(unique(mediancutquantisation(img; numcolors=256))) == 256 # test on different color ColorTypes img = BGR.(testimage("mandrill")) @test_throws ErrorException mediancutquantisation(img; numcolors=256) # test on unique colors less than asked amount img = gif_decode(get_example("fire.gif")) mediancutquantisation!(img; numcolors=256, precheck = true) @test length(unique(img)) == 231 end @testset "Octree Color Quantizer" begin img = gif_decode(get_example("fire.gif")) octreequantisation!(img; numcolors=120) @test length(unique(img)) == 120 img = gif_decode(get_example("fire.gif")) octreequantisation!(img; numcolors=256, precheck = true) @test length(unique(img)) == 231 img = BGR.(testimage("mandrill")) @test_throws ErrorException octreequantisation(img; numcolors=256) end @testset "KDtree Color Quantizer" begin img = gif_decode(get_example("fire.gif")) kdtreequantisation!(img; numcolors=32) @test length(unique(img)) == 32 img = gif_decode(get_example("fire.gif")) kdtreequantisation!(img; numcolors=256, precheck = true) @test length(unique(img)) == 231 # has around 15k colors n color quantiser brings it to 256 img = testimage("mandrill") kdtreequantisation!(img; numcolors=256) @test length(unique(img)) == 256 img = testimage("mandrill") palette = kdtreequantisation!(img; numcolors=256) @test length(palette) == 256 @test eltype(palette) == RGB{N0f8} img = testimage("mandrill") img_copy, palette = kdtreequantisation(img; numcolors=256) @test length(palette) == 256 @test eltype(palette) == RGB{N0f8} img = BGR.(testimage("mandrill")) @test_throws ErrorException kdtreequantisation(img; numcolors=256) end end
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
code
332
using GIFImages using GIFImages.LibGif using Test using Downloads using ColorTypes using FixedPointNumbers using TestImages _wrap(name) = "https://github.com/ashwani-rathee/gif-sampleimages/blob/main/$(name)?raw=true" get_example(x) = Downloads.download(_wrap(x)) include("decode.jl") include("encode.jl") include("quantizers.jl")
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
docs
3088
![Link](https://s4.gifyu.com/images/GIFImages.jl-1.gif) --- GIFImages.jl provides support for decoding and encoding GIF images by wrapping LibGif. GIF(Graphics Interchange Format) supports up to 8 bits per pixel for each image, allowing a single image to reference its own palette of up to 256 different colors chosen from the 24-bit RGB color space. It also supports animations and allows a separate palette which are known as local colormap of up to 256 colors for each frame. GIF is palette based, is very widely used and is a loseless data compression format. [![Docs-dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://ashwani-rathee.github.io/GIFImages.jl) [![Slack](https://img.shields.io/badge/chat-slack-e01e5a)](https://join.slack.com/t/julialang/shared_invite/zt-1hxxb5ryp-Ts_egJ7FRN2muQ7nkTtCNQ) [![License: MIT](https://img.shields.io/badge/License-MIT-success.svg)](https://opensource.org/licenses/MIT) [![Downloads](https://shields.io/endpoint?url=https://pkgs.genieframework.com/api/v1/badge/GIFImages)](https://pkgs.genieframework.com?packages=GIFImages) ### Installation If you have not yet installed Julia, please follow the [instructions](https://julialang.org/downloads/platform/) for your operating system. Stable Version ```julia # Enter ']' from the REPL to enter Pkg mode. pkg> add GIFImages.jl ``` Dev Version ```julia using Pkg # Enter ']' from the REPL to enter Pkg mode. pkg> add https://github.com/ashwani-rathee/GIFImages.jl.git ``` ### Usage For decoding purposes, GIFImages.jl currently supports `gif_decode` which decode the GIF image as colorant matrix. The source data needs to be a filename. #### Arguments - `filepath::AbstractString` : Path to the gif file - `use_localpalette::Bool=false` : While decoding, using this argument use of local colormap or global colormap for a particular slice can be specified. Gif files are palette based and have a global colormap(max `256 colors`) but slices/images in gif can have their own local colormap specific to a particular slice/image. These colormap can be used to decode a image if `use_localpalette` as `true`. #### Examples ```jl julia> using GIFImages, Downloads julia> path = "test/data/fire.gif" "test/data/fire.gif" julia> img = gif_decode(path) 60×30×33 Array{RGB{N0f8},3} with eltype RGB{N0f8} ``` --- For encoding, GIFImages.jl provides `gif_encode` which encode the GIF colorant matrix to file. #### Arguments - `filepath` : Name of the file to which image is written. - `img` : 3D GIF colorant matrix which has structure of height* width * numofimages and all the images are present as slices of the 3D matrix - `colormapnum` : Specifies the number of colors to be used for the global colormap #### Examples ```jl julia> using GIFImages, Downloads julia> path = "test/data/fire.gif" "test/data/fire.gif" julia> img = gif_decode(path) 60×30×33 Array{RGB{N0f8},3} with eltype RGB{N0f8} julia> gif_encode("fire.gif", img) ``` ### Contributions and Issues: If you have questions about GIFImages.jl, feel free to get in touch via Slack or open an issue :hearts:
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
184ddb5441f9635c0f45bf74c16a534e4beff7ec
docs
1719
```@meta CurrentModule = GIFImages ``` # GIFImages This is the documentation for [GIFImages](https://github.com/ashwani-rathee/GIFImages.jl). GIFImages.jl provides support for decoding and encoding GIF images. # Usage For decoding purposes, GIFImages.jl currently supports `gif_decode` which decode the GIF image as colorant matrix. The source data needs to be a filename. #### Arguments - `filepath::AbstractString` : Path to the gif file - `use_localpalette::Bool=false` : While decoding, using this argument use of local colormap or global colormap for a particular slice can be specified. Gif files are palette based and have a global colormap(max `256 colors`) but slices/images in gif can have their own local colormap specific to a particular slice/image. These colormap can be used to decode a image if `use_localpalette` as `true`. #### Examples ```jl julia> using GIFImages, Downloads julia> path = "test/data/fire.gif" "test/data/fire.gif" julia> img = gif_decode(path) 60×30×33 Array{RGB{N0f8},3} with eltype RGB{N0f8} ``` --- For encoding, GIFImages.jl provides `gif_encode` which encode the GIF colorant matrix to file. #### Arguments - `filepath` : Name of the file to which image is written. - `img` : 3D GIF colorant matrix which has structure of height* width * numofimages and all the images are present as slices of the 3D matrix - `colormapnum` : Specifies the number of colors to be used for the global colormap ### Examples ```jl julia> using GIFImages, Downloads julia> path = "test/data/fire.gif" "test/data/fire.gif" julia> img = gif_decode(path) 60×30×33 Array{RGB{N0f8},3} with eltype RGB{N0f8} julia> gif_encode("fire.gif", img) ``` ```@autodocs Modules = [GIFImages] ```
GIFImages
https://github.com/JuliaIO/GIFImages.jl.git
[ "MIT" ]
0.1.0
548c7276bd79fde0577bfdc37684c3688b2e1417
code
1171
# # Local nonparametric quantile regression # This Julia package implements the nonparametric # [quantile regression approach](https://arxiv.org/abs/2012.01758) # of Ye and Padilla (2020). # ## Usage # The following example simulates heteroscedastic data and estimates # the 20th, 50th,and 80th conditional quantiles. ENV["GKSwstype"] = "nul" #hide using QuantileNN, Plots, StableRNGs, LaTeXStrings, Statistics, Printf, Distributions rng = StableRNG(123) n = 1000 p = 3 X = randn(rng, n, p) X[:, 1] .= 1 y = X[:, 2] + (1 .+ 2*abs.(X[:, 2])) .* randn(n) pp = [0.2, 0.5, 0.8] mm = [fit(QNN, X, y; p=p) for p in pp] x = range(-2, 2, 20) bw = 1.0 yy = [[predict_smooth(m, [0, v, 0], [bw]) for v in x] for m in mm] ps = [@sprintf("%.2f", p) for p in pp] plt = plot(x, yy[1], label=ps[1], xlabel=L"$x$", ylabel=L"$y$", size=(400,300)) plt = plot!(plt, x, yy[2], label=ps[2]) plt = plot!(plt, x, yy[3], label=ps[3]) Plots.savefig(plt, "./assets/readme1.svg") # ![Example plot 1](assets/readme1.svg) # ## References # [1] Steven Siwei Ye and Oscar Hernan Madrid Padilla. Non-parametric Quantile # Regression via the K-NN Fused Lasso. https://arxiv.org/abs/2012.01758
QuantileNN
https://github.com/kshedden/QuantileNN.jl.git
[ "MIT" ]
0.1.0
548c7276bd79fde0577bfdc37684c3688b2e1417
code
1106
using QuantileNN, UnicodePlots, Distributions function example1() n = 1000 x = randn(n, 2) ey = x[:, 1] .^ 2 y = ey + randn(n) qr = qregnn(y, x; dofit=false) for p in [0.25, 0.5, 0.75] fit!(qr, p) for mode in [1, 2] # True quantiles yq = ey .+ quantile(Normal(), p) fv = if mode == 1 # Predict using local averaging [predict(qr, r; k=10) for r in eachrow(x)] else # Predict using local linear fitting [predict_smooth(qr, r, [0.1, 10]) for r in eachrow(x)] end plt = lineplot([-3, 3], [-3, 3], xlim=(-3, 3), ylim=(-3, 3)) scatterplot!(plt, yq, fv) println("Quantiles at probability p=", p) println(plt) end end end function example2() nrep = 20 n = 1000 p = 0.5 for j = 1:nrep for k in [1, 2] x = randn(n, k) y = x[:, 1] .^ 2 + randn(n) qr = qregnn(y, x) la, pa = bic_search(qr, p, lam_max = 1e6) x = [z[2] for z in pa] x = x .- minimum(x) plt = lineplot(x[3:end]) println(plt) end end end
QuantileNN
https://github.com/kshedden/QuantileNN.jl.git
[ "MIT" ]
0.1.0
548c7276bd79fde0577bfdc37684c3688b2e1417
code
188
module QuantileNN import StatsAPI: fit, predict, RegressionModel, fitted export QNN, fit, fit!, predict, predict_smooth, fitted export bic_search include("qregnn.jl") end # module
QuantileNN
https://github.com/kshedden/QuantileNN.jl.git
[ "MIT" ]
0.1.0
548c7276bd79fde0577bfdc37684c3688b2e1417
code
5505
using JuMP using Tulip using Random using Statistics using NearestNeighbors using LightGraphs using MathOptInterface using LinearAlgebra using StatsAPI # Implement the nonparametric quantile regression approach described here: # https://arxiv.org/abs/2012.01758 # Representation of a fitted model mutable struct QNN <: RegressionModel # The outcome variable y::Vector{Float64} # The covariates used to define the nearest neighbors x::Matrix{Float64} # Indices of the nearest neighbors nn::Matrix{Int} # A tree for finding neighbors kt::KDTree # The optimization model model::JuMP.Model # The fitted values from the most recent call to fit fit::Vector{Float64} # The probability point for the most recent fit p::Float64 # Retain these references from the optimization model rpos::Array{JuMP.VariableRef,1} rneg::Array{JuMP.VariableRef,1} dcap::Array{JuMP.VariableRef,2} rfit::Array{JuMP.VariableRef,1} end # Returns the degrees of freedom of the fitted model, which is the # number of connected components of the graph defined by all edges # of the covariate graph that are fused in the regression fit. function degf(qr::QNN; e = 1e-2) nn = qr.nn fv = qr.fit g = SimpleGraph(size(nn, 1)) for i = 1:size(nn, 1) for j = 1:size(nn, 2) if abs(fv[i] - fv[nn[i, j]]) < e add_edge!(g, i, nn[i, j]) end end end return length(connected_components(g)) end # Returns the BIC for the given fitted model. function bic(qr::QNN)::Tuple{Float64,Int} d = degf(qr) p = qr.p resid = qr.y - qr.fit pos = sum(x -> clamp(x, 0, Inf), resid) neg = -sum(x -> clamp(x, -Inf, 0), resid) check = p * pos + (1 - p) * neg sig = (1 - abs(1 - 2 * p)) / 2 n = length(qr.y) return tuple(2 * check / sig + d * log(n), d) end function fitted(qr::QNN) return qr.fit end # Predict the quantile at the point z using k nearest neighbors. function predict(qr::QNN, z::AbstractVector; k = 5) ii, _ = knn(qr.kt, z, k) return mean(qr.fit[ii]) end """ predict_smooth(qr::QNN, z::AbstractVector, bw::AbstractVector) Predict a quantile at the point z for the fitted model qr. The vector bw contains bandwidths, which can either be the same length of z (a bandwidth for each variable), or a vector of length 1 (the same bandwidth for all variables). """ function predict_smooth(qr::QNN, z::AbstractVector, bw::AbstractVector) if minimum(bw) <= 0 throw(ArgumentError("Bandwidth must be positive")) end f = qr.fit x = qr.x n, r = size(x) xtx = zeros(r + 1, r + 1) xty = zeros(r + 1) xr = ones(r + 1) for i = 1:n xr[2:end] = x[i, :] - z e2 = sum(abs2, xr[2:end] ./ bw) w = exp(-e2 / 2) xtx .= xtx + w * xr * xr' xty .= xty + w * f[i] * xr end b = pinv(xtx) * xty return b[1] end function fit(::Type{QNN}, X::AbstractMatrix, y::AbstractVector; p=0.5, k=5, lam=0.1) n = length(y) # Build the nearest neighbor tree, exclude each point from its own # neighborhood. kt = KDTree(X') nx, _ = knn(kt, X', k + 1, true) nn = hcat(nx...)' nn = nn[:, 2:end] model = Model(Tulip.Optimizer) # The estimated quantile for each row of the design matrix. @variable(model, rfit[1:n]) # The residuals y - rfit are decomposed into their positive # and negative parts. rpos = @variable(model, rpos[1:n]) rneg = @variable(model, rneg[1:n]) # The distance between the fitted value of each point # and its nearest neighbor is bounded by dcap. dcap = @variable(model, dcap[1:n, 1:k]) @constraint(model, rpos - rneg .== y - rfit) @constraint(model, rpos .>= 0) @constraint(model, rneg .>= 0) @constraint(model, dcap .>= 0) for j = 1:k @constraint(model, rfit - rfit[nn[:, j]] .<= dcap[:, j]) @constraint(model, rfit[nn[:, j]] - rfit .<= dcap[:, j]) end qr = QNN(y, X, nn, kt, model, Vector{Float64}(), -1, rpos, rneg, dcap, rfit) fit!(qr, p; lam=lam) return qr end # Estimate the p'th quantiles for the population represented by the data # in qr. lam is a penalty parameter controlling the smoothness of the # fit. function fit!(qr::QNN, p::Float64; lam::Float64=0.1) @objective(qr.model, Min, sum(p * qr.rpos + (1 - p) * qr.rneg) + lam * sum(qr.dcap)) optimize!(qr.model) if termination_status(qr.model) != MathOptInterface.OPTIMAL @warn("QNN fit did not converge") end qr.fit = value.(qr.rfit) end # Search for a tuning parameter based on BIC. Starting from # lambda=0.1, increase the tuning parameter sequentially # by a factor of 'fac'. The iterations stop when the current # BIC is greater than the previous BIC, or when the degrees of # freedom is less than or equal to 'dof_min', or when the value of # lambda is greater than 'lam_max'. The path is returned as an array # of triples containing the tuning parameter value, the BIC # value, and the degrees of freedom. function bic_search(qr::QNN, p::Float64; fac = 1.2, lam_max = 1e6, dof_min = 2) pa = [] lam = 0.1 while lam < lam_max _ = fit!(qr, p; lam=lam) b, d = bic(qr) push!(pa, [lam, b, d]) if (d <= dof_min) || (length(pa) > 1 && b > pa[end-1][2]) break end lam = lam * fac end la = minimum([x[2] for x in pa]) return tuple(la, pa) end
QuantileNN
https://github.com/kshedden/QuantileNN.jl.git
[ "MIT" ]
0.1.0
548c7276bd79fde0577bfdc37684c3688b2e1417
code
875
using Test using QuantileNN using StableRNGs using Statistics @testset "test1" begin rng = StableRNG(123) n = 2000 X = randn(rng, n, 2) y = X[:, 1] + randn(rng, n) qr1 = fit(QNN, X, y; p=0.25) qr2 = fit(QNN, X, y; p=0.5) qr3 = fit(QNN, X, y; p=0.75) yq = zeros(n, 3) yq[:, 1] = fitted(qr1) yq[:, 2] = fitted(qr2) yq[:, 3] = fitted(qr3) ax = [-0.67, 0, 0.67] # True intercepts for j = 1:3 c = cov(yq[:, j], X[:, 1]) b = c / var(X[:, 1]) a = mean(yq[:, j]) - b * mean(X[:, 1]) @test abs(b - 1) < 0.1 # True slope is 1 @test abs(a - ax[j]) < 0.15 end bw = Float64[2, 2] @test abs(predict_smooth(qr1, [0.0, 0.0], bw) - ax[1]) < 0.15 @test abs(predict_smooth(qr2, [0.0, 0.0], bw) - ax[2]) < 0.15 @test abs(predict_smooth(qr3, [0.0, 0.0], bw) - ax[3]) < 0.15 end
QuantileNN
https://github.com/kshedden/QuantileNN.jl.git
[ "MIT" ]
0.1.0
548c7276bd79fde0577bfdc37684c3688b2e1417
docs
1231
# Local nonparametric quantile regression This Julia package implements the nonparametric [quantile regression approach](https://arxiv.org/abs/2012.01758) of Ye and Padilla (2020). ## Usage The following example simulates heteroscedastic data and estimates the 20th, 50th,and 80th conditional quantiles. ````julia using QuantileNN, Plots, StableRNGs, LaTeXStrings, Statistics, Printf, Distributions rng = StableRNG(123) n = 1000 p = 3 X = randn(rng, n, p) X[:, 1] .= 1 y = X[:, 2] + (1 .+ 2*abs.(X[:, 2])) .* randn(n) pp = [0.2, 0.5, 0.8] mm = [fit(QNN, X, y; p=p) for p in pp] x = range(-2, 2, 20) bw = 1.0 yy = [[predict_smooth(m, [0, v, 0], [bw]) for v in x] for m in mm] ps = [@sprintf("%.2f", p) for p in pp] plt = plot(x, yy[1], label=ps[1], xlabel=L"$x$", ylabel=L"$y$", size=(400,300)) plt = plot!(plt, x, yy[2], label=ps[2]) plt = plot!(plt, x, yy[3], label=ps[3]) Plots.savefig(plt, "./assets/readme1.svg") ```` ![Example plot 1](assets/readme1.svg) ## References [1] Steven Siwei Ye and Oscar Hernan Madrid Padilla. Non-parametric Quantile Regression via the K-NN Fused Lasso. https://arxiv.org/abs/2012.01758 --- *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
QuantileNN
https://github.com/kshedden/QuantileNN.jl.git
[ "MIT" ]
0.2.0
3ed67384a353e88a9140db8bf274aee75af9d36a
code
201
module ComoniconTypes export Maybe, ComoniconExpr, Description, LeafCommand, NodeCommand, Entry, Argument, Option, Flag, print_cmd include("types.jl") include("printing.jl") include("utils.jl") end
ComoniconTypes
https://github.com/comonicon/ComoniconTypes.jl.git
[ "MIT" ]
0.2.0
3ed67384a353e88a9140db8bf274aee75af9d36a
code
6815
tab(n::Int) = " "^n ignore_type(type) = type in [Any, String] || type <: AbstractString function has_args(cmd::LeafCommand) !isempty(cmd.args) || !isnothing(cmd.vararg) end section(io) = print(io, "\n\n") function section(io::IO, title) section(io) printstyled(io, title; bold=true) section(io) end Base.@kwdef mutable struct Indent text::Int = 0 desc::Int = 0 end Base.@kwdef mutable struct Color name::Symbol = :light_blue args::Symbol = :light_magenta dash::Symbol = :light_cyan end Base.@kwdef mutable struct Terminal width::Int = displaysize(stdout)[2] left::Int = floor(Int, 0.4 * width) # left column max width right::Int = floor(Int, 0.4 * width) # right column max width color::Color = Color() indent::Indent = Indent() brief::Bool = true end Base.show(io::IO, ::MIME"text/plain", cmd::ComoniconExpr) = print_cmd(io, cmd) function Base.show(io::IO, ::MIME"text/plain", cmd::Description) printstyled(io, "brief:\n"; color=:light_black) println(io, cmd.brief) printstyled(io, "content:\n"; color=:light_black) print(io, cmd.content) end print_cmd(cmd) = print_cmd(stdout, cmd) print_cmd(io::IO, cmd) = print_cmd(io, cmd, Terminal()) print_cmd(cmd, t::Terminal) = print_cmd(stdout, cmd, t) function print_cmd(io::IO, arg::Argument, t::Terminal) color = t.color.args arg.require || printstyled(io, "["; color) arg.require && printstyled(io, "<"; color) printstyled(io, arg.name; color) if !ignore_type(arg.type) printstyled(io, "::", arg.type; color) end arg.vararg && printstyled(io, "..."; color) arg.require && printstyled(io, ">"; color) arg.require || printstyled(io, "]"; color) return end print_cmd(io::IO, cmd::Flag, t::Terminal) = _print_dash(io, cmd, t) function print_cmd(io::IO, cmd::Option, t::Terminal) _print_dash(io, cmd, t) isnothing(cmd.hint) || printstyled(io, tab(1), "<", cmd.hint, ">"; color=t.color.args) return end function _print_dash(io::IO, cmd::Union{Option, Flag}, t::Terminal) color = t.color.dash if cmd.short printstyled(io, "-", first(cmd.name), ", "; color) end printstyled(io, "--", cmd.name; color) end function print_content(io::IO, desc::Description, t::Terminal) isnothing(desc.content) || print_within(io, desc.content, t.width, 0) return end function print_cmd(io::IO, cmd::Entry, t::Terminal) section(io) printstyled(io, tab(2), cmd.root.name; color=t.color.name, bold=true) isnothing(cmd.version) || print(io, " v", cmd.version) section(io) t.brief = false # print description ahead print_content(io, cmd.root.description, t) section(io, "Usage") print_head(io, cmd, t) print_body(io, cmd, t) end function print_cmd(io::IO, cmd::NodeCommand, t::Terminal) section(io) print_head(io, cmd, t) section(io) print_content(io, cmd.description, t) print_body(io, cmd, t) end function print_cmd(io::IO, cmd::LeafCommand, t::Terminal) section(io) print_head(io, cmd, t) section(io) print_content(io, cmd.description, t) print_body(io, cmd, t) end print_head(io::IO, cmd::Entry, t::Terminal) = print_head(io, cmd.root, t) function print_head(io::IO, cmd::NodeCommand, t::Terminal) print(io, tab(2)) print_signature(io, cmd, t) end function print_head(io::IO, cmd::LeafCommand, t::Terminal) print(io, tab(2)) print_name(io, cmd, t) if has_args(cmd) printstyled(io, tab(1), "<args>"; color=t.color.args) end isempty(cmd.args) || printstyled(io, tab(1), "[options]"; color = t.color.dash) isempty(cmd.flags) || printstyled(io, tab(1), "[flags]"; color = t.color.dash) return end function print_name(io::IO, cmd, t::Terminal) printstyled(io, cmd.name; color=t.color.name, bold=true) end function print_signature(io::IO, cmd, t::Terminal) print_cmd(io, cmd, t) end function print_signature(io::IO, cmd::NodeCommand, t::Terminal) print_name(io, cmd, t) printstyled(io, tab(1), "<command>"; color=t.color.name) end function print_signature(io::IO, cmd::LeafCommand, t::Terminal) print_name(io, cmd, t) for each in cmd.args print(io, tab(1)) print_cmd(io, each, t) end if !isnothing(cmd.vararg) print(io, tab(1)) print_cmd(io, cmd.vararg, t) end end function print_body(io::IO, cmd::Entry, t::Terminal) print_body(io, cmd.root, t) version_flag = "-V, --version" printstyled(io, tab(2), version_flag; color=t.color.dash) print_indent_content(io, "print version information", t, length(version_flag)+2) println(io) end function print_body(io::IO, cmd::NodeCommand, t::Terminal) section(io, "Commands") for each in values(cmd.subcmds) print_sig_brief(io, each, t) println(io) end section(io, "Flags") print_help(io, t) return end function print_body(io::IO, cmd::LeafCommand, t::Terminal) if has_args(cmd) section(io, "Args") end for each in cmd.args print_sig_brief(io, each, t) println(io) end if !isnothing(cmd.vararg) print_sig_brief(io, cmd.vararg, t) println(io) end if !isempty(cmd.options) section(io, "Options") for each in unique(values(cmd.options)) print_sig_brief(io, each, t) println(io) end end section(io, "Flags") for each in unique(values(cmd.flags)) print_sig_brief(io, each, t) section(io) end print_help(io, t) end function print_help(io::IO, t::Terminal) help_flag = "-h, --help" printstyled(io, tab(2), help_flag; color=t.color.dash) print_indent_content(io, "print this help message", t, length(help_flag)+2) println(io) end function print_sig_brief(io::IO, cmd, t::Terminal) buf = IOBuffer() print_signature(buf, cmd, t) s = String(take!(buf)) print(io, tab(2)) print_signature(io, cmd, t) isnothing(cmd.description.brief) && return print_indent_content(io, cmd.description.brief, t, length(s)+2) return end function print_indent_content(io::IO, text::String, t::Terminal, firstline::Int) middle = t.width - t.left - t.right lines = splitlines(text, t.width) isempty(lines) && return print(io, tab(t.left - firstline + middle), lines[1]) for i in 2:length(lines) print(io, tab(t.width - t.right), lines[i]) if i !== lastindex(lines) println(io) end end return end function print_within(io::IO, text::String, width::Int, indent::Int) lines = splitlines(text, width - indent) for i in eachindex(lines) print(io, tab(indent), lines[i]) if i !== lastindex(lines) println(io) end end end
ComoniconTypes
https://github.com/comonicon/ComoniconTypes.jl.git
[ "MIT" ]
0.2.0
3ed67384a353e88a9140db8bf274aee75af9d36a
code
2957
const Maybe{T} = Union{Nothing, T} abstract type ComoniconExpr end Base.@kwdef struct Description <: ComoniconExpr brief::Union{Nothing, String} = nothing content::Union{Nothing, String} = nothing end Base.convert(::Type{Description}, ::Nothing) = Description() Base.convert(::Type{Description}, x::String) = Description(x) Base.convert(::Type{Description}, x::AbstractString) = Description(String(x)) Description(::Nothing) = Description(nothing, nothing) function Description(text::String) return Description(brief(text), text) end Base.@kwdef struct Argument <: ComoniconExpr name::String type = Any vararg::Bool = false require::Bool = true # this is only for docs, since Julia # function will handle the actual default # value default::Maybe{String} = nothing description::Description = Description() line::Maybe{LineNumberNode} = nothing function Argument(name, type, vararg, require, default, description, line) require = vararg ? false : require # force require=false for vararg new(name, type, vararg, require, default, description, line) end end Base.@kwdef struct Option <: ComoniconExpr sym::Symbol name::String = replace(string(sym), '_'=>'-') hint::Maybe{String} = nothing type = Any short::Bool = false description::Description = Description() line::Maybe{LineNumberNode} = nothing end Base.@kwdef struct Flag <: ComoniconExpr sym::Symbol name::String = replace(string(sym), '_'=>'-') short::Bool = false description::Description = Description() line::Maybe{LineNumberNode} = nothing end Base.@kwdef struct NodeCommand <: ComoniconExpr name::String subcmds::Dict{String, Any} description::Description = Description() line::Maybe{LineNumberNode} = nothing function NodeCommand(name, subcmds, description, line) !isempty(subcmds) || error("list of subcommands should not be empty") new(name, subcmds, description, line) end end Base.@kwdef struct LeafCommand <: ComoniconExpr fn::Any name::String args::Vector{Argument} = Argument[] nrequire::Int = count(x->x.require, args) vararg::Maybe{Argument} = nothing flags::Dict{String, Flag} = Dict{String, Flag}() options::Dict{String, Option} = Dict{String, Option}() description::Description = Description() line::Maybe{LineNumberNode} = nothing function LeafCommand(fn, name, arg, nrequire, vararg, flags, options, description, line) isnothing(vararg) || vararg.vararg == true || error("expect vararg $(vararg.name) " * "to have property vararg=true") new(fn, name, arg, nrequire, vararg, flags, options, description, line) end end Base.@kwdef struct Entry <: ComoniconExpr root::Union{NodeCommand, LeafCommand} version::Maybe{VersionNumber} = nothing line::Maybe{LineNumberNode} = nothing end
ComoniconTypes
https://github.com/comonicon/ComoniconTypes.jl.git
[ "MIT" ]
0.2.0
3ed67384a353e88a9140db8bf274aee75af9d36a
code
1933
""" splittext(s) Split the text in string `s` into an array, but keep all the separators attached to the preceding word. !!! note this is copied from Luxor/text.jl """ function splittext(s::String) # split text into array, keeping all separators # hyphens stay with first word result = Array{String,1}() iobuffer = IOBuffer() for c in s if isspace(c) push!(result, String(take!(iobuffer))) iobuffer = IOBuffer() elseif c == '-' # hyphen splits words but needs keeping print(iobuffer, c) push!(result, String(take!(iobuffer))) iobuffer = IOBuffer() else print(iobuffer, c) end end push!(result, String(take!(iobuffer))) return result end """ splitlines(s, width = 80) Split a given string into lines of width `80` characters. """ function splitlines(s, width = 80) words = splittext(s) lines = String[] current_line = String[] space_left = width for word in words word == "" && continue word_width = length(word) if space_left < word_width # start a new line push!(lines, strip(join(current_line))) current_line = String[] space_left = width end if endswith(word, "-") push!(current_line, word) space_left -= word_width else push!(current_line, word * " ") space_left -= word_width + 1 end end isempty(current_line) || push!(lines, strip(join(current_line))) return lines end """ brief(text::String) Use the first sentence as the brief description. """ function brief(text::String) index = findfirst(". ", text) if index === nothing index = findfirst(".", text) end if index === nothing return text else return text[1:first(index)] end end
ComoniconTypes
https://github.com/comonicon/ComoniconTypes.jl.git
[ "MIT" ]
0.2.0
3ed67384a353e88a9140db8bf274aee75af9d36a
code
2219
using ComoniconTypes using Test using Faker desc = Description(Faker.text()) @test endswith(desc.brief, ".") # brief should be a sentence arg = Argument(;name="arg", type=Int) macro test_show(mime, ex) Meta.isexpr(ex, :block) || error("expect begin ... end") ret = Expr(:block) for each in ex.args if Meta.isexpr(each, :call) && each.args[1] === :in @gensym buf object push!(ret.args, :($buf = IOBuffer())) push!(ret.args, :($object = $(each.args[3]))) push!(ret.args, :(show($buf, $mime(), $object))) push!(ret.args, :(@test occursin($(each.args[2]), String(take!($buf))))) else push!(ret.args, each) end end return esc(ret) end @testset "convert(Description, ...)" begin @test Description(nothing) == Description() @test convert(Description, nothing) == Description() @test convert(Description, "nothing") == Description("nothing") @test convert(Description, split("abcd. efdasdas.", '.')[1]) == Description("abcd") end @test_show MIME"text/plain" begin "<arg>" in Argument(;name="arg") "[arg...]" in Argument(;name="arg", vararg=true) "<arg::Int64>" in Argument(;name="arg", type=Int) "--option-a" in Option(;sym=:option_a) "--option-a <hint>" in Option(;sym=:option_a, hint="hint") "--flag-a" in Flag(;sym=:flag_a) end leaf = LeafCommand(; fn=identity, name="leaf", args=[Argument(;name="arg", description=Faker.text())], flags=Dict( "flag-a" => Flag(; sym=:flag_a, description="flag a." ), "flag-b" => Flag(; sym=:flag_b, description="flag b." ) ), description=Faker.text(), ) @test_show MIME"text/plain" begin " leaf <args> [options] [flags]" in leaf "Args\n\n" in leaf " <arg>" in leaf "Flags\n\n" in leaf end @test_throws ErrorException NodeCommand(;name="abc", subcmds=Dict{String, Any}()) node = NodeCommand(;name="foo", subcmds=Dict("leaf"=>leaf)) @test_show MIME"text/plain" begin " foo <command>" in node "Commands\n\n" in node " leaf <arg>" in node "Flags\n\n" in node "-h, --help" in node end
ComoniconTypes
https://github.com/comonicon/ComoniconTypes.jl.git
[ "MIT" ]
0.2.0
3ed67384a353e88a9140db8bf274aee75af9d36a
docs
344
# ComoniconTypes [![Build Status](https://github.com/comonicon/ComoniconTypes.jl/workflows/CI/badge.svg)](https://github.com/comonicon/ComoniconTypes.jl/actions) [![codecov](https://codecov.io/gh/comonicon/ComoniconTypes.jl/branch/main/graph/badge.svg?token=g0FlmB4YLj)](https://codecov.io/gh/comonicon/ComoniconTypes.jl) Comonicon IR types.
ComoniconTypes
https://github.com/comonicon/ComoniconTypes.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
1588
## A simple 2D example for fluid-flow simulation using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using LinearAlgebra using PyPlot ## grid size n = (30, 1, 15) d = (30.0, 30.0, 30.0) ## permeability K0 = 200 * md * ones(n) K = deepcopy(K0) K[:,:,1:2:end] .*= 100 ϕ = 0.25 model = jutulModel(n, d, ϕ, K1to3(K)) ## simulation time steppings tstep = 50 * ones(10) tot_time = sum(tstep) ## injection & production inj_loc = (15, 1, 10) .* d irate = 5e-3 q = jutulVWell(irate, (450., 30.); startz = 270., endz = 330.) ## set up modeling operator S = jutulModeling(model, tstep) ## simulation Trans = KtoTrans(CartesianMesh(model), K1to3(K)) Trans0 = KtoTrans(CartesianMesh(model), K1to3(K0)) @time states = S(log.(Trans), q) @time states0 = S(log.(Trans0), q) ## plotting fig=figure(figsize=(20,12)); subplot(1,2,1); imshow(reshape(Saturations(states.states[end]), n[1], n[end])'); colorbar(); title("saturation") subplot(1,2,2); imshow(reshape(Pressure(states.states[end]), n[1], n[end])'); colorbar(); title("pressure") ## plotting fig=figure(figsize=(20,12)); subplot(1,2,1); imshow(reshape(Saturations(states0.states[end]), n[1], n[end])'); colorbar(); title("saturation") subplot(1,2,2); imshow(reshape(Pressure(states0.states[end]), n[1], n[end])'); colorbar(); title("pressure") exist_co2 = sum(Saturations(states.states[end]) .* states.states[end].state[:Reservoir][:PhaseMassDensities][1,:] .* model.ϕ) * prod(model.d) inj_co2 = JutulDarcyRules.ρCO2 * q.irate * JutulDarcyRules.day * sum(tstep) norm(exist_co2-inj_co2)/norm(exist_co2+inj_co2)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
1558
## A simple 2D example for fluid-flow simulation using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using LinearAlgebra using PyPlot ## grid size n = (30, 1, 15) d = (30.0, 30.0, 30.0) ## permeability K0 = 200 * md * ones(n) K = deepcopy(K0) K[:,:,1:2:end] .*= 100 ϕ = 0.25 model = jutulModel(n, d, ϕ, K1to3(K)) ## simulation time steppings tstep = 50 * ones(10) tot_time = sum(tstep) ## injection & production inj_loc = (15, 1, 10) .* d irate = 5e-3 q = jutulForce(irate, [inj_loc]) ## set up modeling operator S = jutulModeling(model, tstep) ## simulation Trans = KtoTrans(CartesianMesh(model), K1to3(K)) Trans0 = KtoTrans(CartesianMesh(model), K1to3(K0)) @time states = S(log.(Trans), q) @time states0 = S(log.(Trans0), q) ## plotting fig=figure(figsize=(20,12)); subplot(1,2,1); imshow(reshape(Saturations(states.states[end]), n[1], n[end])'); colorbar(); title("saturation") subplot(1,2,2); imshow(reshape(Pressure(states.states[end]), n[1], n[end])'); colorbar(); title("pressure") ## plotting fig=figure(figsize=(20,12)); subplot(1,2,1); imshow(reshape(Saturations(states0.states[end]), n[1], n[end])'); colorbar(); title("saturation") subplot(1,2,2); imshow(reshape(Pressure(states0.states[end]), n[1], n[end])'); colorbar(); title("pressure") exist_co2 = sum(Saturations(states.states[end]) .* states.states[end].state[:Reservoir][:PhaseMassDensities][1,:] .* model.ϕ) * prod(model.d) inj_co2 = JutulDarcyRules.ρCO2 * q.irate * JutulDarcyRules.day * sum(tstep) norm(exist_co2-inj_co2)/norm(exist_co2+inj_co2)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
5107
## A 2D compass example using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using LinearAlgebra using PyPlot using Flux using LineSearches using JLD2 using JUDI using Statistics sim_name = "2D-K-inv" exp_name = "compass" mkpath(datadir()) mkpath(plotsdir()) ## grid size JLD2.@load datadir("BGCompass_tti_625m.jld2") m d; d = (6., 6.) m = m[200:450,181:end] h = 180 * d[end] v = Float64.(sqrt.(1f0./m)); function downsample(v::Matrix{T}, factor::Int) where T v_out_size = div.(size(v), factor) v_out = zeros(T, v_out_size) for i = 1:v_out_size[1] for j = 1:v_out_size[2] v_out[i,j] = mean(v[factor*i-factor+1:factor*i, factor*j-factor+1:factor*j]) end end return v_out end factor = 2 v = 1.0./downsample(1.0./v, factor) d = Float64.(d) .* factor; function VtoK(v::Matrix{T}, d::Tuple{T, T}; α::T=T(20)) where T n = size(v) idx_wb = find_water_bottom(v.-minimum(v)) idx_ucfmt = find_water_bottom((v.-T(3.5)).*(v.>T(3.5))) Kh = zeros(T, n) capgrid = Int(round(T(50)/d[2])) for i = 1:n[1] Kh[i,1:idx_wb[i]-1] .= T(1e-10) # water layer Kh[i,idx_wb[i]:idx_ucfmt[i]-capgrid-1] .= α*exp.(v[i,idx_wb[i]:idx_ucfmt[i]-capgrid-1]) Kh[i,idx_ucfmt[i]-capgrid:idx_ucfmt[i]-1] .= T(1e-3) Kh[i,idx_ucfmt[i]:end] .= α*exp.(v[i,idx_ucfmt[i]:end]) .- α*exp(T(3.5)) end return Kh end Kh = VtoK(v, d); K = Float64.(Kh * md); n = (size(K,1), 1, size(K,2)) d = (d[1], 2000.0, d[2]) ϕ = 0.25 model = jutulModel(n, d, ϕ, K1to3(K; kvoverkh=0.36); h=h) ## simulation time steppings tstep = 365.25 * ones(15) tot_time = sum(tstep) ## injection & production inj_loc = (Int(round(n[1]/2)), 1, n[end]-20) .* d irate = 0.3 q = jutulForce(irate, [inj_loc]) ## set up modeling operator S = jutulModeling(model, tstep) ## simulation mesh = CartesianMesh(model) T(x) = log.(KtoTrans(mesh, K1to3(exp.(x); kvoverkh=0.36))) logK = log.(K) @time state = S(T(logK), q) #### inversion logK0 = deepcopy(logK) logK0[v.>3.5] .= mean(logK[v.>3.5]) logK0[logK0.==minimum(logK0)] .= mean(logK[v.>3.5]) logK_init = deepcopy(logK0) state_init = S(T(logK_init), q) f(logK) = .5 * norm(S(T(logK),q)[1:length(tstep)*prod(n)]-state[1:length(tstep)*prod(n)])^2 ls = BackTracking(order=3, iterations=10) lower, upper = 1.1*minimum(logK), 0.9*maximum(logK) prj(x) = max.(min.(x,upper),lower) # Main loop niterations = 100 fhistory = zeros(niterations) for j=1:niterations @time fval, gs = Flux.withgradient(() -> f(logK0), Flux.params(logK0)) g = gs[logK0] p = -g/norm(g, Inf) println("Inversion iteration no: ",j,"; function value: ",fval) fhistory[j] = fval # linesearch function f_(α) misfit = f(prj(logK0 .+ α * p)) @show α, misfit return misfit end step, fval = ls(f_, 1e-1, fval, dot(g, p)) # Update model and bound projection global logK0 = prj(logK0 .+ step .* p) fig_name = @strdict j n d ϕ tstep irate niterations lower upper inj_loc ### plotting fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(exp.(logK)'./md, vmin=minimum(exp.(logK))./md, vmax=maximum(exp.(logK)./md)); colorbar(); title("true permeability") subplot(1,3,2); imshow(exp.(logK0)'./md, vmin=minimum(exp.(logK))./md, vmax=maximum(exp.(logK)./md)); colorbar(); title("inverted permeability") subplot(1,3,3); imshow(exp.(logK)'./md.-exp.(logK0)'./md, vmin=minimum(exp.(logK)), vmax=maximum(exp.(logK)./md)); colorbar(); title("diff") suptitle("Flow Inversion at iter $j") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_diff.png"), fig); close(fig) state_predict = S(T(logK0), q) ## data fitting fig = figure(figsize=(20,12)); for i = 1:5 subplot(4,5,i); imshow(reshape(Saturations(state_init.states[3*i]), n[1], n[end])', vmin=0, vmax=0.9); colorbar(); title("initial prediction at snapshot $(3*i)") subplot(4,5,i+5); imshow(reshape(Saturations(state.states[3*i]), n[1], n[end])', vmin=0, vmax=0.9); colorbar(); title("true at snapshot $(3*i)") subplot(4,5,i+10); imshow(reshape(Saturations(state_predict.states[3*i]), n[1], n[end])', vmin=0, vmax=0.9); colorbar(); title("predict at snapshot $(3*i)") subplot(4,5,i+15); imshow(5*abs.(reshape(Saturations(state.states[3*i]), n[1], n[end])'-reshape(Saturations(state_predict.states[3*i]), n[1], n[end])'), vmin=0, vmax=0.9); colorbar(); title("5X diff at snapshot $(3*i)") end suptitle("Flow Inversion at iter $j") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_co2.png"), fig); close(fig) ## loss fig = figure(figsize=(20,12)); plot(fhistory[1:j]);title("loss=$(fhistory[j])"); suptitle("Flow Inversion at iter $j") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_loss.png"), fig); close(fig) end JLD2.@save "compass-inv.jld2" logK logK0 state
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
8173
## A 64×64 2D example for end-to-end inversion of a tortuous channel using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using LinearAlgebra using PyPlot using Flux using LineSearches using JLD2 using JUDI using Random Random.seed!(2023) sim_name = "end-to-end-inv" exp_name = "tortuous" # patchy saturation model include("utils.jl") mkpath(datadir()) mkpath(plotsdir()) ## grid size JLD2.@load datadir("K.jld2") K K0; K = Float64.(K * md); K0 = Float64.(K0 * md); n = size(K) d = (15.0, 15.0) ϕ = 0.25 model0 = jutulModel((n[1], 1, n[2]), (d[1], 10.0, d[2]), ϕ, K1to3(K0)) model = jutulModel((n[1], 1, n[2]), (d[1], 10.0, d[2]), ϕ, K1to3(K)) ## simulation time steppings tstep = 40 * ones(51) tot_time = sum(tstep) # observation vintages nv = 11 survey_indices = Int.(round.(range(1, stop=length(tstep), length=nv))) ## injection & production inj_loc = (3, 1, 32) .* (d[1], 10.0, d[2]) prod_loc = (62, 1, 32) .* (d[1], 10.0, d[2]) irate = 5e-3 f = jutulForce(irate, [inj_loc, prod_loc]) ## set up modeling operator S = jutulModeling(model, tstep) ## simulation mesh = CartesianMesh(model) T(x) = log.(KtoTrans(mesh, K1to3(exp.(x)))) logK0 = log.(K0) logK = log.(K) logK_init = deepcopy(logK0) @time state0 = S(T(logK0), f) @time state = S(T(logK), f) ### observed states O(state::AbstractVector) = Float32.(permutedims(reshape(state[1:length(tstep)*prod(n)], n[1], n[end], length(tstep)), [3,1,2])[survey_indices,:,:]) sw_true = O(state) # set up rock physics vp = 3500 * ones(Float32,n) # p-wave phi = 0.25f0 * ones(Float32,n) # porosity rho = 2200 * ones(Float32,n) # density R(c::AbstractArray{Float32,3}) = Patchy(c,vp,rho,phi)[1] vps = R(sw_true) # time-varying vp ## upsampling upsample = 2 u(x::Vector{Matrix{Float32}}) = [repeat(x[i], inner=(upsample,upsample)) for i = 1:nv] vpups = u(vps) ##### Wave equation nw = n.*upsample dw = (15f0/upsample, 15f0/upsample) # discretization for wave equation o = (0f0, 0f0) # origin nsrc = 32 # num of sources nrec = 960 # num of receivers models = [Model(nw, dw, o, (1f3 ./ vpups[i]).^2f0; nb = 80) for i = 1:nv] # wave model timeS = timeR = 750f0 # recording time dtS = dtR = 1f0 # recording time sampling rate ntS = Int(floor(timeS/dtS))+1 # time samples ntR = Int(floor(timeR/dtR))+1 # source time samples # source locations -- half at the left hand side of the model, half on top xsrc = convertToCell(vcat(range(dw[1],stop=dw[1],length=Int(nsrc/2)),range(dw[1],stop=(nw[1]-1)*dw[1],length=Int(nsrc/2)))) ysrc = convertToCell(range(0f0,stop=0f0,length=nsrc)) zsrc = convertToCell(vcat(range(dw[2],stop=(nw[2]-1)*dw[2],length=Int(nsrc/2)),range(10f0,stop=10f0,length=Int(nsrc/2)))) # receiver locations -- half at the right hand side of the model, half on top xrec = vcat(range((nw[1]-1)*dw[1],stop=(nw[1]-1)*dw[1], length=Int(nrec/2)),range(dw[1],stop=(nw[1]-1)*dw[1],length=Int(nrec/2))) yrec = 0f0 zrec = vcat(range(dw[2],stop=(nw[2]-1)*dw[2],length=Int(nrec/2)),range(10f0,stop=10f0,length=Int(nrec/2))) # set up src/rec geometry srcGeometry = Geometry(xsrc, ysrc, zsrc; dt=dtS, t=timeS) recGeometry = Geometry(xrec, yrec, zrec; dt=dtR, t=timeR, nsrc=nsrc) # set up source f0 = 0.05f0 # kHz wavelet = ricker_wavelet(timeS, dtS, f0) q = judiVector(srcGeometry, wavelet) # set up simulation operators Fs = [judiModeling(models[i], srcGeometry, recGeometry) for i = 1:nv] # acoustic wave equation solver ## wave physics function F(v::Vector{Matrix{Float32}}) m = [vec(1f3./v[i]).^2f0 for i = 1:nv] return [Fs[i](m[i], q) for i = 1:nv] end # Define seismic data directory mkpath(datadir("seismic-data")) misc_dict = @strdict nsrc nrec upsample ### generate/load data if ~isfile(datadir("seismic-data", savename(misc_dict, "jld2"; digits=6))) println("generating data") global d_obs = [Fs[i]*q for i = 1:nv] seismic_dict = @strdict nsrc nrec upsample d_obs q srcGeometry recGeometry model @tagsave( datadir("seismic-data", savename(seismic_dict, "jld2"; digits=6)), seismic_dict; safe=true ) else println("loading data") JLD2.@load datadir("seismic-data", savename(misc_dict, "jld2"; digits=6)) d_obs global d_obs = d_obs end ## add noise noise_ = deepcopy(d_obs) for i = 1:nv for j = 1:nsrc noise_[i].data[j] = randn(Float32, ntR, nrec) end end snr = 10f0 noise_ = noise_/norm(noise_) * norm(d_obs) * 10f0^(-snr/20f0) d_obs = d_obs + noise_ ls = BackTracking(order=3, iterations=10) lower, upper = 1.1*minimum(logK), 0.9*maximum(logK) box_logK(x::AbstractArray{T}) where T = max.(min.(x,T(upper)),T(lower)) # Main loop niterations = 100 fhistory = zeros(niterations) ### add box to co2 and velocity box_co2(x::AbstractArray{T}) where T = max.(min.(x,T(1)),T(0)) box_v(x::AbstractMatrix{T}) where T = max.(min.(x,T(3501)),T(3200)) box_v(x::AbstractVector) = [box_v(x[i]) for i = 1:length(x)] y_init = box_co2(O(S(T(logK_init), f))) # objective function for inversion fval = Inf32 function obj(logK) c = box_co2(O(S(T(logK), f))); v = R(c); v_up = box_v(u(v)); dpred = F(v_up); global fval = .5f0 * norm(dpred-d_obs)^2f0 @show fval return fval end for j=1:niterations global fval = fval Base.flush(Base.stdout) ## AD by Flux @time g = gradient(()->obj(logK0), Flux.params(logK0))[logK0] fhistory[j] = fval p = -g println("Inversion iteration no: ",j,"; function value: ", fhistory[j]) # linesearch function f_(α) misfit = obj(box_logK(logK0 .+ α .* p)) @show α, misfit return misfit end step, fval = ls(f_, 3e-3, fhistory[j], dot(g, p)) # Update model and bound projection global logK0 = box_logK(logK0 .+ step .* p) ### plotting y_predict = box_co2(O(S(T(logK0), f))) ### save intermediate results save_dict = @strdict j snr logK0 step niterations nv nsrc nrec survey_indices fhistory @tagsave( joinpath(datadir(sim_name, exp_name), savename(save_dict, "jld2"; digits=6)), save_dict; safe=true ) ## save figure fig_name = @strdict j snr niterations nv nsrc nrec survey_indices ## compute true and plot SNR = -2f1 * log10(norm(K-exp.(logK0))/norm(K)) fig = figure(figsize=(20,12)); subplot(2,2,1); imshow(exp.(logK0)'./md,vmin=20,vmax=120);title("inversion by NN, $(j) iter");colorbar(); subplot(2,2,2); imshow(K'./md,vmin=20,vmax=120);title("GT permeability");colorbar(); subplot(2,2,3); imshow(exp.(logK_init)'./md,vmin=20,vmax=120);title("initial permeability");colorbar(); subplot(2,2,4); imshow(abs.(K'-exp.(logK0)')./md,vmin=20,vmax=120);title("error, SNR=$SNR");colorbar(); suptitle("End-to-end Inversion at iter $j, seismic data snr=$snr") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_K.png"), fig); close(fig) ## loss fig = figure(figsize=(20,12)); plot(fhistory[1:j]);title("loss=$(fhistory[j])"); suptitle("Learned Coupled Inversion at iter $j, seismic data snr=$snr") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_loss.png"), fig); close(fig) ## data fitting fig = figure(figsize=(20,12)); for i = 1:5 subplot(4,5,i); imshow(y_init[2*i,:,:]', vmin=0, vmax=1); title("initial prediction at snapshot $(survey_indices[2*i])") subplot(4,5,i+5); imshow(sw_true[2*i,:,:]', vmin=0, vmax=1); title("true at snapshot $(survey_indices[2*i])") subplot(4,5,i+10); imshow(y_predict[2*i,:,:]', vmin=0, vmax=1); title("predict at snapshot $(survey_indices[2*i])") subplot(4,5,i+15); imshow(5*abs.(sw_true[2*i,:,:]'-y_predict[2*i,:,:]'), vmin=0, vmax=1); title("5X diff at snapshot $(survey_indices[2*i])") end suptitle("Learned Coupled Inversion at iter $j, seismic data snr=$snr") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_saturation.png"), fig); close(fig) end
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
5326
## A simple 2D example for permeability inversion using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using LinearAlgebra using PyPlot using Flux using LineSearches sim_name = "2D-K-inv" exp_name = "channel" mkpath(datadir()) mkpath(plotsdir()) ## grid size n = (30, 1, 15) d = (30.0, 30.0, 30.0) ## permeability K0 = 20 * md * ones(n) K = deepcopy(K0) K[:,:,8:10] .*= 6.0 ϕ = 0.25 model0 = jutulModel(n, d, ϕ, K1to3(K0)) model = jutulModel(n, d, ϕ, K1to3(K)) ## simulation time steppings tstep = 40 * ones(50) tot_time = sum(tstep) ## injection & production inj_loc = (3, 1, 9) .* d prod_loc = (28, 1, 9) .* d irate = 5e-3 q = jutulForce(irate, [inj_loc, prod_loc]) ## set up modeling operator S = jutulModeling(model, tstep) ## simulation mesh = CartesianMesh(model) T(x) = log.(KtoTrans(mesh, K1to3(x))) K_init = deepcopy(K0) @time state0 = S(T(K0), q) @time state = S(T(K), q) state_init = deepcopy(state0) f(K) = .5 * norm(S(T(K),q)[1:length(tstep)*prod(n)]-state[1:length(tstep)*prod(n)])^2 ls = BackTracking(order=3, iterations=10) lower, upper = 0.9*minimum(K), 1.1*maximum(K) prj(x) = max.(min.(x,upper),lower) # Main loop niterations = 50 fhistory = zeros(niterations) for j=1:niterations fval = f(K0) g = gradient(()->f(K0), Flux.params(K0))[K0] p = -g/norm(g, Inf) * norm(K_init, Inf) println("Inversion iteration no: ",j,"; function value: ",fval) fhistory[j] = fval # linesearch function f_(α) misfit = f(prj(K0 .+ α * p)) @show α, misfit return misfit end step, fval = ls(f_, 1.0, fval, dot(g, p)) # Update model and bound projection global K0 = prj(K0 .+ step .* p) end ## plotting state0 = S(T(K0), q) fig_name = @strdict n d ϕ tstep irate niterations lower upper inj_loc prod_loc fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(K_init[:,1,:]', vmin=minimum(K), vmax=maximum(K)); colorbar(); title("initial permeability") subplot(1,3,2); imshow(K0[:,1,:]', vmin=minimum(K), vmax=maximum(K)); colorbar(); title("inverted permeability") subplot(1,3,3); imshow(K[:,1,:]', vmin=minimum(K), vmax=maximum(K)); colorbar(); title("true permeability") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_K.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(reshape(state_init.states[end].Saturations, n[1], n[end])', vmin=0, vmax=1); colorbar(); title("initial saturation") subplot(1,3,2); imshow(reshape(state0.states[end].Saturations, n[1], n[end])', vmin=0, vmax=1); colorbar(); title("inverted saturation") subplot(1,3,3); imshow(reshape(state.states[end].Saturations, n[1], n[end])', vmin=0, vmax=1); colorbar(); title("true saturation") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_saturation.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(reshape(state_init.states[end].Pressure, n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("initial pressure") subplot(1,3,2); imshow(reshape(state0.states[end].Pressure, n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("inverted pressure") subplot(1,3,3); imshow(reshape(state.states[end].Pressure, n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("true pressure") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_pressure.png"), fig); close(fig) fig=figure(figsize=(20,12)); plot(fhistory); title("loss") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_loss.png"), fig); close(fig) x0 = T(K0) x_init = T(K_init) x = T(K) ## plotting trans_x = reshape(x[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z = reshape(x[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) trans_x0 = reshape(x0[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z0 = reshape(x0[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) trans_x_init = reshape(x_init[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z_init = reshape(x_init[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(trans_x_init', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("initial transmissibility x") subplot(1,3,2); imshow(trans_x0', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("inverted transmissibility x") subplot(1,3,3); imshow(trans_x', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("true transmissibility x") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_transx.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(trans_z_init', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("initial transmissibility z") subplot(1,3,2); imshow(trans_z0', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("inverted transmissibility z") subplot(1,3,3); imshow(trans_z', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("true transmissibility z") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_transz.png"), fig); close(fig)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
5422
## A simple 2D example for permeability inversion using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using LinearAlgebra using PyPlot using Flux using LineSearches sim_name = "2D-K-inv" exp_name = "channel" mkpath(datadir()) mkpath(plotsdir()) ## grid size n = (30, 1, 15) d = (30.0, 30.0, 30.0) ## permeability K0 = 20 * md * ones(n) K = deepcopy(K0) K[:,:,8:10] .*= 6.0 ϕ = 0.25 model0 = jutulModel(n, d, ϕ, K1to3(K0)) model = jutulModel(n, d, ϕ, K1to3(K)) ## simulation time steppings tstep = 40 * ones(50) tot_time = sum(tstep) ## injection & production inj_loc = (15, 1, 9) .* d irate = 5e-3 q = jutulForce(irate, [inj_loc]) ## set up modeling operator S = jutulModeling(model, tstep) ## simulation mesh = CartesianMesh(model) T(x) = log.(KtoTrans(mesh, K1to3(exp.(x)))) logK0 = log.(K0) logK = log.(K) logK_init = deepcopy(logK0) @time state0 = S(T(logK0), q) @time state = S(T(logK), q) state_init = deepcopy(state0) f(logK) = .5 * norm(S(T(logK),q)[1:length(tstep)*prod(n)]-state[1:length(tstep)*prod(n)])^2 ls = BackTracking(order=3, iterations=10) lower, upper = 1.1*minimum(logK), 0.9*maximum(logK) prj(x) = max.(min.(x,upper),lower) # Main loop niterations = 100 fhistory = zeros(niterations) for j=1:niterations @time fval, gs = Flux.withgradient(() -> f(logK0), Flux.params(logK0)) g = gs[logK0] p = -g/norm(g, Inf) println("Inversion iteration no: ",j,"; function value: ", fval) fhistory[j] = fval # linesearch function f_(α) misfit = f(prj(logK0 .+ α * p)) @show α, misfit return misfit end step, fval = ls(f_, 1e-1, fval, dot(g, p)) # Update model and bound projection global logK0 = prj(logK0 .+ step .* p) end ## plotting state0 = S(T(logK0), q) K0 = exp.(logK0) K_init = exp.(logK_init) fig_name = @strdict n d ϕ tstep irate niterations lower upper inj_loc fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(K_init[:,1,:]', vmin=minimum(K), vmax=maximum(K)); colorbar(); title("initial permeability") subplot(1,3,2); imshow(K0[:,1,:]', vmin=minimum(K), vmax=maximum(K)); colorbar(); title("inverted permeability") subplot(1,3,3); imshow(K[:,1,:]', vmin=minimum(K), vmax=maximum(K)); colorbar(); title("true permeability") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_K.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(reshape(Saturations(state_init.states[end]), n[1], n[end])', vmin=0, vmax=1); colorbar(); title("initial saturation") subplot(1,3,2); imshow(reshape(Saturations(state0.states[end]), n[1], n[end])', vmin=0, vmax=1); colorbar(); title("inverted saturation") subplot(1,3,3); imshow(reshape(Saturations(state.states[end]), n[1], n[end])', vmin=0, vmax=1); colorbar(); title("true saturation") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_saturation.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(reshape(Pressure(state_init.states[end]), n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("initial pressure") subplot(1,3,2); imshow(reshape(Pressure(state0.states[end]), n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("inverted pressure") subplot(1,3,3); imshow(reshape(Pressure(state.states[end]), n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("true pressure") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_pressure.png"), fig); close(fig) fig=figure(figsize=(20,12)); plot(fhistory); title("loss") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_loss.png"), fig); close(fig) x0 = T(logK0) x_init = T(logK_init) x = T(logK) ## plotting trans_x = reshape(x[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z = reshape(x[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) trans_x0 = reshape(x0[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z0 = reshape(x0[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) trans_x_init = reshape(x_init[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z_init = reshape(x_init[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(trans_x_init', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("initial transmissibility x") subplot(1,3,2); imshow(trans_x0', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("inverted transmissibility x") subplot(1,3,3); imshow(trans_x', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("true transmissibility x") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_transx.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(trans_z_init', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("initial transmissibility z") subplot(1,3,2); imshow(trans_z0', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("inverted transmissibility z") subplot(1,3,3); imshow(trans_z', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("true transmissibility z") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_transz.png"), fig); close(fig)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
5469
## A 64×64 2D example for permeability inversion of a tortuous channel using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using LinearAlgebra using PyPlot using Flux using LineSearches using JLD2 sim_name = "2D-K-inv" exp_name = "tortuous" mkpath(datadir()) mkpath(plotsdir()) ## grid size JLD2.@load datadir("K.jld2") K K0; K = Float64.(K * md); K0 = Float64.(K0 * md); n = (size(K,1), 1, size(K,2)) d = (15.0, 10.0, 15.0) ϕ = 0.25 model0 = jutulModel(n, d, ϕ, K1to3(K0)) model = jutulModel(n, d, ϕ, K1to3(K)) ## simulation time steppings tstep = 40 * ones(50) tot_time = sum(tstep) ## injection & production inj_loc = (3, 1, 32) .* d prod_loc = (62, 1, 32) .* d irate = 5e-3 q = jutulForce(irate, [inj_loc, prod_loc]) ## set up modeling operator S = jutulModeling(model, tstep) ## simulation mesh = CartesianMesh(model) T(x) = log.(KtoTrans(mesh, K1to3(exp.(x)))) logK0 = log.(K0) logK = log.(K) logK_init = deepcopy(logK0) @time state0 = S(T(logK0), q) @time state = S(T(logK), q) state_init = deepcopy(state0) f(logK) = .5 * norm(S(T(logK),q)[1:length(tstep)*prod(n)]-state[1:length(tstep)*prod(n)])^2 ls = BackTracking(order=3, iterations=10) lower, upper = 1.1*minimum(logK), 0.9*maximum(logK) prj(x) = max.(min.(x,upper),lower) # Main loop niterations = 100 fhistory = zeros(niterations) for j=1:niterations fval = f(logK0) @time g = gradient(()->f(logK0), Flux.params(logK0))[logK0] p = -g println("Inversion iteration no: ",j,"; function value: ",fval) fhistory[j] = fval # linesearch function f_(α) misfit = f(prj(logK0 .+ α * p)) @show α, misfit return misfit end step, fval = ls(f_, 1e-1, fval, dot(g, p)) # Update model and bound projection global logK0 = prj(logK0 .+ step .* p) end ## plotting state0 = S(T(logK0), q) K0 = exp.(logK0) K_init = exp.(logK_init) fig_name = @strdict n d ϕ tstep irate niterations lower upper inj_loc prod_loc fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(K_init', vmin=minimum(K), vmax=maximum(K)); colorbar(); title("initial permeability") subplot(1,3,2); imshow(K0', vmin=minimum(K), vmax=maximum(K)); colorbar(); title("inverted permeability") subplot(1,3,3); imshow(K', vmin=minimum(K), vmax=maximum(K)); colorbar(); title("true permeability") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_K.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(reshape(state_init.states[end].Saturations, n[1], n[end])', vmin=0, vmax=1); colorbar(); title("initial saturation") subplot(1,3,2); imshow(reshape(state0.states[end].Saturations, n[1], n[end])', vmin=0, vmax=1); colorbar(); title("inverted saturation") subplot(1,3,3); imshow(reshape(state.states[end].Saturations, n[1], n[end])', vmin=0, vmax=1); colorbar(); title("true saturation") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_saturation.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(reshape(state_init.states[end].Pressure, n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("initial pressure") subplot(1,3,2); imshow(reshape(state0.states[end].Pressure, n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("inverted pressure") subplot(1,3,3); imshow(reshape(state.states[end].Pressure, n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("true pressure") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_pressure.png"), fig); close(fig) fig=figure(figsize=(20,12)); plot(fhistory); title("loss") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_loss.png"), fig); close(fig) x0 = T(logK0) x_init = T(logK_init) x = T(logK) ## plotting trans_x = reshape(x[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z = reshape(x[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) trans_x0 = reshape(x0[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z0 = reshape(x0[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) trans_x_init = reshape(x_init[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z_init = reshape(x_init[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(trans_x_init', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("initial transmissibility x") subplot(1,3,2); imshow(trans_x0', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("inverted transmissibility x") subplot(1,3,3); imshow(trans_x', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("true transmissibility x") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_transx.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(trans_z_init', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("initial transmissibility z") subplot(1,3,2); imshow(trans_z0', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("inverted transmissibility z") subplot(1,3,3); imshow(trans_z', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("true transmissibility z") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_transz.png"), fig); close(fig)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
4836
## A simple 2D example for transmissibility inversion using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using LinearAlgebra using PyPlot using Flux using LineSearches sim_name = "2D-trans-inv" exp_name = "channel" mkpath(datadir()) mkpath(plotsdir()) ## grid size n = (30, 1, 15) d = (30.0, 30.0, 30.0) ## permeability K0 = 20 * md * ones(n) K = deepcopy(K0) K[:,:,8:10] .*= 6.0 ϕ = 0.25 model0 = jutulModel(n, d, ϕ, K1to3(K0)) model = jutulModel(n, d, ϕ, K1to3(K)) ## simulation time steppings tstep = 40 * ones(50) tot_time = sum(tstep) ## injection & production inj_loc = (3, 1, 9) .* d prod_loc = (28, 1, 9) .* d irate = 5e-3 q = jutulForce(irate, [inj_loc, prod_loc]) ## set up modeling operator S = jutulModeling(model, tstep) ## simulation mesh = CartesianMesh(model) T(x) = log.(KtoTrans(mesh, K1to3(x))) K_init = deepcopy(K0) x0 = T(K0) x = T(K) x_init = T(K_init) @time state0 = S(x0, q) @time state = S(x, q) state_init = deepcopy(state0) f(x) = .5 * norm(S(x,q)[1:length(tstep)*prod(n)]-state[1:length(tstep)*prod(n)])^2 ls = BackTracking(order=3, iterations=10) lower, upper = 1.1*minimum(x), 0.9*maximum(x) prj(x) = max.(min.(x,upper),lower) # Main loop niterations = 100 fhistory = zeros(niterations) for j=1:niterations fval = f(x0) g = gradient(()->f(x0), Flux.params(x0))[x0] p = -g/norm(g, Inf) * norm(x_init, Inf) println("Inversion iteration no: ",j,"; function value: ",fval) fhistory[j] = fval # linesearch function f_(α) misfit = f(prj(x0 .+ α * p)) @show α, misfit return misfit end step, fval = ls(f_, 1e-1, fval, dot(g, p)) # Update model and bound projection global x0 = prj(x0 .+ step .* p) end ## plotting state0 = S(x0, q) fig_name = @strdict n d ϕ tstep irate niterations lower upper inj_loc prod_loc fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(reshape(state_init.states[end].Saturations, n[1], n[end])', vmin=0, vmax=1); colorbar(); title("initial saturation") subplot(1,3,2); imshow(reshape(state0.states[end].Saturations, n[1], n[end])', vmin=0, vmax=1); colorbar(); title("inverted saturation") subplot(1,3,3); imshow(reshape(state.states[end].Saturations, n[1], n[end])', vmin=0, vmax=1); colorbar(); title("true saturation") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_saturation.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(reshape(state_init.states[end].Pressure, n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("initial pressure") subplot(1,3,2); imshow(reshape(state0.states[end].Pressure, n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("inverted pressure") subplot(1,3,3); imshow(reshape(state.states[end].Pressure, n[1], n[end])', vmin=minimum(state.states[end].Pressure), vmax=maximum(state.states[end].Pressure)); colorbar(); title("true pressure") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_pressure.png"), fig); close(fig) fig=figure(figsize=(20,12)); plot(fhistory); title("loss") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_loss.png"), fig); close(fig) ## plotting trans_x = reshape(x[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z = reshape(x[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) trans_x0 = reshape(x0[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z0 = reshape(x0[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) trans_x_init = reshape(x_init[1:(n[1]-1)*n[end]], n[1]-1, n[end]) trans_z_init = reshape(x_init[(n[1]-1)*n[end]+1:end], n[1], n[end]-1) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(trans_x_init', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("initial transmissibility x") subplot(1,3,2); imshow(trans_x0', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("inverted transmissibility x") subplot(1,3,3); imshow(trans_x', vmin=minimum(trans_x), vmax=maximum(trans_x)); colorbar(); title("true transmissibility x") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_transx.png"), fig); close(fig) fig=figure(figsize=(20,12)); subplot(1,3,1); imshow(trans_z_init', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("initial transmissibility z") subplot(1,3,2); imshow(trans_z0', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("inverted transmissibility z") subplot(1,3,3); imshow(trans_z', vmin=minimum(trans_z), vmax=maximum(trans_z)); colorbar(); title("true transmissibility z") tight_layout() safesave(joinpath(plotsdir(sim_name, exp_name), savename(fig_name; digits=6)*"_transz.png"), fig); close(fig)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
1110
using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using Flux using LinearAlgebra using Optim nx = 30 ny = 1 nz = 15 dims = (nx, ny, nz) g = CartesianMesh(dims, (30.0, 30.0, 30.0) .* dims) nc = prod(dims) Kx = 20 * md * ones(nx, nz) Kxtrue = deepcopy(Kx) Kxtrue[:, 6:8] .*= 6 Trans_true = KtoTrans(g, K1to3(Kxtrue)) Kx = 10 * md * ones(prod(g.dims)) @time grad = gradient(() -> .5 * norm(KtoTrans(g, K1to3(Kx))-Trans_true)^2f0, Flux.params(Kx))[Kx] # ## Set up L-BFGS function fg(F, G, x) grads = gradient(Flux.params(x)) do F = .5 * norm(KtoTrans(g, K1to3(x))-Trans_true)^2 / norm(Trans_true)^2 end G .= grads[x] return F end method = LBFGS() optimopt = Optim.Options(iterations = 200, store_trace = true, show_trace = true, show_every = 1) result = optimize(Optim.only_fg!(fg), Kx, method, optimopt) Kxinv = result.minimizer println(norm(Kxinv-vec(Kxtrue))/norm(Kxtrue)) @time Kxinv1 = TransToK(g, Trans_true) println(norm(Kxinv1-K1to3(Kxtrue))/norm(K1to3(Kxtrue))) println(norm(KtoTrans(g, Kxinv1)-Trans_true)/norm(Trans_true))
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
1098
## A simple 2D example for fluid-flow simulation using DrWatson @quickactivate "JutulDarcyRules-example" using JutulDarcyRules using LinearAlgebra using PyPlot ## grid size n = (30, 1, 15) d = (30.0, 30.0, 30.0) ## permeability K = 20 * md * ones(n) ϕ = 0.25 * ones(n) model = jutulModel(n, d, vec(ϕ), K1to3(K)) ## simulation time steppings tstep = 40 * ones(50) tot_time = sum(tstep) ## injection & production inj_loc = (3, 1, 9) .* d prod_loc = (28, 1, 9) .* d irate = 5e-3 q = jutulSource(irate, [inj_loc, prod_loc]) ## set up modeling operator S = jutulModeling(model, tstep) ## simulation Trans = KtoTrans(CartesianMesh(model), K1to3(K)) @time result = S(log.(Trans), q; info_level=1) @time result = S(log.(Trans), q) ## plotting fig=figure(figsize=(20,12)); subplot(1,2,1); imshow(reshape(Saturations(result.states[end]), n[1], n[end])', vmin=0, vmax=1); colorbar(); title("saturation") subplot(1,2,2); imshow(reshape(Pressure(result.states[end]), n[1], n[end])', vmin=minimum(Pressure(result.states[end])), vmax=maximum(Pressure(result.states[end]))); colorbar(); title("pressure")
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
1334
#### Patchy saturation model function Patchy(sw::AbstractMatrix{T}, vp::AbstractMatrix{T}, rho::AbstractMatrix{T}, phi::AbstractMatrix{T}; bulk_min::T=T(36.6f9), bulk_fl1::T=T(2.735f9), bulk_fl2::T=T(0.125f9), ρw::T=T(501.9f0), ρo::T=T(1053.0f0)) where T ### works for channel problem vs = vp./sqrt(3f0) bulk_sat1 = rho .* (vp.^2f0 - 4f0/3f0 .* vs.^2f0) shear_sat1 = rho .* (vs.^2f0) patch_temp = bulk_sat1 ./(bulk_min .- bulk_sat1) - bulk_fl1 ./ phi ./ (bulk_min .- bulk_fl1) + bulk_fl2 ./ phi ./ (bulk_min .- bulk_fl2) bulk_sat2 = bulk_min./(1f0./patch_temp .+ 1f0) bulk_new = 1f0./( (1f0.-sw)./(bulk_sat1+4f0/3f0*shear_sat1) + sw./(bulk_sat2+4f0/3f0*shear_sat1) ) - 4f0/3f0*shear_sat1 rho_new = rho + phi .* sw * (ρw - ρo) Vp_new = sqrt.((bulk_new+4f0/3f0*shear_sat1)./rho_new) return Vp_new, rho_new end function Patchy(sw::AbstractArray{T, 3}, vp::AbstractMatrix{T}, rho::AbstractMatrix{T}, phi::AbstractMatrix{T}; bulk_min::T=T(36.6f9), bulk_fl1::T=T(2.735f9), bulk_fl2::T=T(0.125f9), ρw::T=T(501.9f0), ρo::T=T(1053.0f0)) where T stack = [Patchy(sw[i,:,:], vp, rho, phi; bulk_min=bulk_min, bulk_fl1=bulk_fl1, bulk_fl2=bulk_fl2, ρw = ρw, ρo=ρo) for i = 1:size(sw,1)] return [stack[i][1] for i = 1:size(sw,1)], [stack[i][2] for i = 1:size(sw,1)] end
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
1143
__precompile__() module JutulDarcyRules export JutulDarcyRulesPATH, Darcy, md using LinearAlgebra using Statistics using JutulDarcy using Jutul using Optim using Flux using ChainRulesCore import Jutul: JutulGeometry, get_facepos, compute_face_trans, compute_half_face_trans, expand_perm import Jutul: SimulationModel, select_output_variables! import Jutul: optimization_targets, variable_mapper, optimization_limits, print_parameter_optimization_config import Jutul: objective_opt!, gradient_opt!, objective_and_gradient_opt! import Base: +, -, *, /, == import Base: display, length, size, getindex, setindex!, IndexStyle, vec, firstindex, lastindex import LinearAlgebra: norm, dot import ChainRulesCore: rrule JutulDarcyRulesPATH = dirname(pathof(JutulDarcyRules)) visCO2 = 1e-4 visH2O = 1e-3 ρCO2 = 7e2 ρH2O = 1e3 bar = 1e5 const Darcy = 9.869232667160130e-13 const md = Darcy * 1e-3 const day = 24*3600.0 include("PropertyConversion/PropertyConversion.jl") include("FlowRules/FlowRules.jl") end # module JutulDarcyRules
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
279
### types include("Types/jutulModel.jl") include("Types/jutulForce.jl") include("Types/jutulVWell.jl") include("Types/jutulSource.jl") include("Types/jutulState.jl") include("Types/type_utils.jl") ### operators include("Operators/jutulModeling.jl") include("Operators/rrule.jl")
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
3283
export jutulModeling struct jutulModeling{D, T} model::jutulModel{D, T} tstep::Vector{T} end display(M::jutulModeling{D, T}) where {D, T} = println("$(D)D jutulModeling structure with $(sum(M.tstep)) days in $(length(M.tstep)) time steps") function (S::jutulModeling{D, T})(LogTransmissibilities::AbstractVector{T}, ϕ::AbstractVector{T}, f::Union{jutulForce{D, N}, jutulVWell{D, N}}; state0=nothing, visCO2::T=T(visCO2), visH2O::T=T(visH2O), ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), info_level::Int64=-1) where {D, T, N} Transmissibilities = exp.(LogTransmissibilities) ### set up simulation time tstep = day * S.tstep ### set up simulation configurations model, parameters, state0_, forces = setup_well_model(S.model, f, tstep; visCO2=visCO2, visH2O=visH2O, ρCO2=ρCO2, ρH2O=ρH2O) model.models.Reservoir.data_domain[:porosity] = ϕ parameters[:Reservoir][:Transmissibilities] = Transmissibilities parameters[:Reservoir][:FluidVolume] .= prod(S.model.d) .* ϕ isnothing(state0) || (state0_[:Reservoir] = get_Reservoir_state(state0)) ### simulation sim, config = setup_reservoir_simulator(model, state0_, parameters); states, report = simulate!(sim, tstep, forces = forces, config = config, max_timestep_cuts = 1000, info_level=info_level); output = jutulStates(states) return output end function (S::jutulModeling{D, T})(LogTransmissibilities::AbstractVector{T}, ϕ::AbstractVector{T}, f::jutulSource{D, N}; state0=nothing, visCO2::T=T(visCO2), visH2O::T=T(visH2O), ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), info_level::Int64=-1) where {D, T, N} Transmissibilities = exp.(LogTransmissibilities) forces = source(S.model, f; ρCO2=ρCO2) ### set up simulation time tstep = day * S.tstep model = simple_model(S.model; ρCO2=ρCO2, ρH2O=ρH2O) model.data_domain[:porosity] = ϕ parameters = setup_parameters(model, PhaseViscosities = [visCO2, visH2O]); parameters[:Transmissibilities] = Transmissibilities parameters[:FluidVolume] .= prod(S.model.d) .* ϕ state0_ = jutulSimpleState(S.model) isnothing(state0) || (state0_ = state0) states, _ = simulate(dict(state0_), model, tstep, parameters = parameters, forces = forces, info_level = info_level, max_timestep_cuts = 1000) return jutulSimpleStates(states) end function (S::jutulModeling{D, T})(f::Union{jutulForce{D, N}, jutulVWell{D, N}, jutulSource{D, N}}; LogTransmissibilities::AbstractVector{T}=KtoTrans(CartesianMesh(S.model), S.model.K), ϕ::AbstractVector{T}=S.model.ϕ, state0=nothing, visCO2::T=T(visCO2), visH2O::T=T(visH2O), ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), info_level::Int64=-1) where {D, T, N} return S(LogTransmissibilities, ϕ, f; state0=state0, visCO2=visCO2, visH2O=visH2O, ρCO2=ρCO2, ρH2O=ρH2O, info_level=info_level) end function (S::jutulModeling{D, T})(LogTransmissibilities::AbstractVector{T}, f::Union{jutulForce{D, N}, jutulVWell{D, N}, jutulSource{D, N}}; ϕ::AbstractVector{T}=S.model.ϕ, state0=nothing, visCO2::T=T(visCO2), visH2O::T=T(visH2O), ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), info_level::Int64=-1) where {D, T, N} return S(LogTransmissibilities, ϕ, f; state0=state0, visCO2=visCO2, visH2O=visH2O, ρCO2=ρCO2, ρH2O=ρH2O, info_level=info_level) end
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
9374
function rrule(S::jutulModeling{D, T}, LogTransmissibilities::AbstractVector{T}, ϕ::AbstractVector{T}, f::Union{jutulForce{D, N}, jutulVWell{D, N}}; state0=nothing, visCO2::T=T(visCO2), visH2O::T=T(visH2O), ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), info_level::Int64=-1) where {D, T, N} Transmissibilities = exp.(LogTransmissibilities) ### set up simulation time tstep = day * S.tstep ### set up simulation configurations model, parameters, state0_, forces = setup_well_model(S.model, f, tstep; visCO2=visCO2, visH2O=visH2O, ρCO2=ρCO2, ρH2O=ρH2O) model.models.Reservoir.data_domain[:porosity] = ϕ parameters[:Reservoir][:Transmissibilities] = Transmissibilities parameters[:Reservoir][:FluidVolume] .= prod(S.model.d) .* ϕ isnothing(state0) || (state0_[:Reservoir] = get_Reservoir_state(state0)) ### simulation sim, config = setup_reservoir_simulator(model, state0_, parameters); states, reports = simulate!(sim, tstep, forces = forces, config = config, max_timestep_cuts = 1000, info_level=info_level); output = jutulStates(states) ### optimization framework cfg = optimization_config(model, parameters, Dict(:Reservoir => [:FluidVolume, :Transmissibilities], :Injector => [:FluidVolume])) cfg[:Reservoir][:Transmissibilities][:scaler] = :log function pullback(dy) states_ref_ = output(vec(output)-dy) check_valid_state(states_ref_) states_ref = dict(states_ref_) mass_mismatch = (m, state, dt, step_no, forces) -> loss_per_step(m, state, dt, step_no, forces, states_ref) F_o, dF_o, F_and_dF, x0, lims, data = setup_parameter_optimization( states, reports, model, state0_, parameters, tstep, forces, mass_mismatch, cfg, param_obj = true, print = info_level, config = config, use_sparsity = false); g = dF_o(similar(x0), x0); n_faces = length(LogTransmissibilities) n_cells = prod(S.model.n) dLogTransmissibilities = g[1:n_faces] dϕ = g[n_faces + 1 : n_faces + n_cells] * prod(S.model.d) return NoTangent(), dLogTransmissibilities, dϕ, NoTangent() end return output, pullback end function rrule(S::jutulModeling{D, T}, LogTransmissibilities::AbstractVector{T}, ϕ::AbstractVector{T}, f::jutulSource{D, N}; state0=nothing, visCO2::T=T(visCO2), visH2O::T=T(visH2O), ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), info_level::Int64=-1) where {D, T, N} Transmissibilities = exp.(LogTransmissibilities) forces = source(S.model, f; ρCO2=ρCO2) ### set up simulation time tstep = day * S.tstep model = simple_model(S.model; ρCO2=ρCO2, ρH2O=ρH2O) model.data_domain[:porosity] = ϕ parameters = setup_parameters(model, PhaseViscosities = [visCO2, visH2O]); parameters[:Transmissibilities] = Transmissibilities parameters[:FluidVolume] .= prod(S.model.d) .* ϕ state0_ = jutulSimpleState(S.model) isnothing(state0) || (state0_ = state0) states, reports = simulate(dict(state0_), model, tstep, parameters = parameters, forces = forces, info_level = info_level, max_timestep_cuts = 1000) output = jutulSimpleStates(states) cfg = optimization_config(model, parameters, use_scaling = false, rel_min = 0., rel_max = Inf) for (ki, vi) in cfg if ki in [:TwoPointGravityDifference, :PhaseViscosities] vi[:active] = false end if ki == :Transmissibilities vi[:scaler] = :log end end function pullback(dy) states_dy = output(dy) states_ref = dict(output-states_dy) function mass_mismatch(m, state, dt, step_no, forces) state_ref = states_ref[step_no] fld = :Saturations fld2 = :Pressure val = state[fld] val2 = state[fld2] ref = state_ref[fld] ref2 = state_ref[fld2] return 0.5 * sum((val[1,:] - ref[1,:]).^2) + 0.5 * sum((val2-ref2).^2) end mass_mismatch = (m, state, dt, step_no, forces) -> loss_per_step_simple(m, state, dt, step_no, forces, states_ref) Jutul.evaluate_objective(mass_mismatch, model, states_ref, tstep, forces) F_o, dF_o, F_and_dF, x0, lims, data = setup_parameter_optimization(states, reports, model, dict(state0_), parameters, tstep, forces, mass_mismatch, cfg, print = -1, param_obj = true); g = dF_o(similar(x0), x0); n_faces = length(LogTransmissibilities) n_cells = prod(S.model.n) dLogTransmissibilities = g[1:n_faces] dϕ = g[n_faces + 1 : n_faces + n_cells] * prod(S.model.d) return NoTangent(), dLogTransmissibilities, dϕ, NoTangent() end return output, pullback end function loss_per_step(m, state, dt, step_no, forces, states_ref) state_ref = states_ref[step_no] fld = :Saturations fld2 = :Pressure val = state[:Reservoir][fld] val2 = state[:Reservoir][fld2] ref = state_ref[:Reservoir][fld] ref2 = state_ref[:Reservoir][fld2] return inner_mismatch(val, ref, val2, ref2) end function loss_per_step_simple(m, state, dt, step_no, forces, states_ref) state_ref = states_ref[step_no] fld = :Saturations fld2 = :Pressure val = state[fld] val2 = state[fld2] ref = state_ref[fld] ref2 = state_ref[fld2] return inner_mismatch(val, ref, val2, ref2) end function inner_mismatch(val, ref, val2, ref2) mismatch_s = zero(eltype(val)) for i in axes(val, 2) mismatch_s += (val[1,i] - ref[1,i])^2 end mismatch_p = zero(eltype(val2)) for i in eachindex(val2) mismatch_p += (val2[i] - ref2[i])^2 end return eltype(val)(0.5) * mismatch_s + eltype(val2)(0.5) * mismatch_p end function setup_parameter_optimization(precomputed_states, reports, model, state0, param, dt, forces, G, arg...; kwarg...) case = JutulCase(model, dt, forces, state0 = state0, parameters = param) return setup_parameter_optimization(precomputed_states, reports, case, G, arg...; kwarg...) end function setup_parameter_optimization(precomputed_states, reports, case::JutulCase, G, opt_cfg = optimization_config(case.model, case.parameters); grad_type = :adjoint, config = nothing, print = 1, copy_case = true, param_obj = false, use_sparsity = true, kwarg...) if copy_case case = Jutul.duplicate(case) end # Pick active set of targets from the optimization config and construct a mapper (; model, state0, parameters) = case if print isa Bool if print print = 1 else print = Inf end end verbose = print > 0 && isfinite(print) targets = optimization_targets(opt_cfg, model) if grad_type == :numeric @assert length(targets) == 1 @assert model isa SimulationModel else @assert grad_type == :adjoint end mapper, = variable_mapper(model, :parameters, targets = targets, config = opt_cfg) lims = optimization_limits(opt_cfg, mapper, parameters, model) if verbose print_parameter_optimization_config(targets, opt_cfg, model) end x0 = vectorize_variables(model, parameters, mapper, config = opt_cfg) for k in eachindex(x0) low = lims[1][k] high = lims[2][k] @assert low <= x0[k] "Computed lower limit $low for parameter #$k was larger than provided x0[k]=$(x0[k])" @assert high >= x0[k] "Computer upper limit $hi for parameter #$k was smaller than provided x0[k]=$(x0[k])" end data = Dict() data[:n_objective] = 1 data[:n_gradient] = 1 data[:obj_hist] = zeros(0) sim = Simulator(case) if isnothing(config) config = simulator_config(sim; info_level = -1, kwarg...) elseif !verbose config[:info_level] = -1 config[:end_report] = false end data[:sim] = sim data[:sim_config] = config if grad_type == :adjoint adj_storage = setup_adjoint_storage(model, state0 = state0, parameters = parameters, targets = targets, use_sparsity = use_sparsity, param_obj = param_obj) data[:adjoint_storage] = adj_storage grad_adj = zeros(adj_storage.n) else grad_adj = similar(x0) end data[:case] = case data[:grad_adj] = grad_adj data[:mapper] = mapper data[:G] = G data[:targets] = targets data[:mapper] = mapper data[:config] = opt_cfg data[:last_obj] = Inf data[:x_hash] = hash(x0) data[:states] = precomputed_states data[:reports] = reports F = x -> objective_opt!(x, data, print) dF = (dFdx, x) -> gradient_opt!(dFdx, x, data) F_and_dF = (F, dFdx, x) -> objective_and_gradient_opt!(F, dFdx, x, data, print) return (F! = F, dF! = dF, F_and_dF! = F_and_dF, x0 = x0, limits = lims, data = data) end
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
613
export jutulForce struct jutulForce{D, T} irate::T name::Vector{Symbol} loc::Vector{NTuple{D, T}} end jutulForce(irate::T, loc::NTuple{D, T}) where {D, T} = jutulForce(irate, [loc]) jutulForce(irate::T, loc::Vector{NTuple{D, T}}) where {D, T}= jutulForce(irate, vcat(:Injector, [:Producer for i = 1:length(loc)]), loc) display(f::jutulForce{D, T}) where {D, T} = println("$(D)D jutulForce structure with $(length(f.loc)) injection/production wells and rate $(f.irate) m^3/s") ==(A::jutulForce{D, T}, B::jutulForce{D, T}) where {D,T} = (A.irate == B.irate && A.name == B.name && A.loc == B.loc)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
1039
export jutulModel, CartesianMesh struct jutulModel{D, T} n::NTuple{D, Int64} d::NTuple{D, T} ϕ::Vector{T} K::Union{Matrix{T}, T} h::T # depth of the top grid end function jutulModel(n::NTuple{D, Int64}, d::NTuple{D, T}, ϕ::T, K::Union{Matrix{T}, T}; h::T=T(0), pad::Bool=true) where {D, T} ϕ_full = ϕ * ones(T, n) if pad ϕ_full[1,:,:] .= 1e8 ϕ_full[end,:,:] .= 1e8 ϕ_full[:,:,1] .= ϕ * (h/d[end] + T(1)) ϕ_full[:,:,end] .= 1e8 end ϕ = vec(ϕ_full) return jutulModel(n, d, ϕ, K, h) end jutulModel(n::NTuple{D, Int64}, d::NTuple{D, T}, ϕ::Vector{T}, K::Union{Matrix{T}, T}) where {D, T} = jutulModel(n, d, ϕ, K, T(0)) display(M::jutulModel{D, T}) where {D, T} = println("$(D)D jutulModel with size $(M.n) and grid spacing $(M.d) at depth $(M.h) m") CartesianMesh(M::jutulModel{D, T}) where {D, T} = CartesianMesh(M.n, M.d .* M.n) ==(A::jutulModel{D, T}, B::jutulModel{D, T}) where {D,T} = (A.n == B.n && A.d == B.d && A.ϕ == B.ϕ && A.K == B.K && A.h == B.h)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
673
export jutulSource struct jutulSource{D, T} irate::Vector{T} name::Vector{Symbol} loc::Vector{NTuple{D, T}} end jutulSource(irate::T, loc::NTuple{D, T}) where {D, T} = jutulSource(irate, [loc]) jutulSource(irate::T, loc::Vector{NTuple{D, T}}) where {D, T} = jutulSource([(-T(1))^(i+1)*irate for i = 1:length(loc)], vcat(:Injector, [:Producer for i = 1:length(loc)]), loc) display(f::jutulSource{D, T}) where {D, T} = println("$(D)D jutulSource structure with $(length(f.loc)) injection/production wells and rate $(f.irate[1]) m^3/s") ==(A::jutulSource{D, T}, B::jutulSource{D, T}) where {D,T} = (A.irate == B.irate && A.name == B.name && A.loc == B.loc)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
8571
export jutulState, jutulStates, jutulSimpleState, jutulSimpleStates, dict, Saturations, Pressure abstract type jutulAllState{T} <: DenseVector{T} end abstract type jutulSimpleOrMultiModelStates{T} <: jutulAllState{T} end abstract type jutulSimpleOrMultiModelState{T} <: jutulAllState{T} end struct jutulState{T} <: jutulSimpleOrMultiModelState{T} state::Dict end struct jutulStates{T} <: jutulSimpleOrMultiModelStates{T} states::Vector{jutulState{T}} end struct jutulSimpleState{T} <: jutulSimpleOrMultiModelState{T} state::Dict end struct jutulSimpleStates{T} <: jutulSimpleOrMultiModelStates{T} states::Vector{jutulSimpleState{T}} end state_T(T) = Dict{Symbol, T} complex_state_T(T) = Union{Dict{Symbol, T}, AbstractVector{Dict{Symbol, T}}} display(state::jutulAllState{T}) where T = println("$(typeof(state))") jutulState(state::Dict) = jutulState{eltype(state[:Reservoir][:Saturations])}(state) jutulStates(states::Vector{S}) where {T, S<:complex_state_T(T)} = jutulStates{eltype(states[1][:Reservoir][:Saturations])}([jutulState(states[i]::state_T(T)) for i = 1:length(states)]) jutulSimpleState(state::state_T(T)) where T = jutulSimpleState{eltype(state[:Saturations])}(state) jutulSimpleStates(states::Vector{S}) where {T, S<:complex_state_T(T)} = jutulSimpleStates{eltype(states[1][:Saturations])}([jutulSimpleState(states[i]::state_T(T)) for i = 1:length(states)]) Saturations(state::jutulState) = state.state[:Reservoir][:Saturations][1,:] Pressure(state::jutulState) = state.state[:Reservoir][:Pressure] Saturations(state::jutulSimpleState) = state.state[:Saturations][1,:] Pressure(state::jutulSimpleState) = state.state[:Pressure] Saturations(state::jutulSimpleOrMultiModelStates) = vcat([Saturations(state.states[i]) for i = 1:get_nt(state)]...) Pressure(state::jutulSimpleOrMultiModelStates) = vcat([Pressure(state.states[i]) for i = 1:get_nt(state)]...) get_Reservoir_state(state::jutulState) = state.state[:Reservoir] get_Reservoir_state(state::jutulSimpleState) = state.state get_Reservoir_state(state::jutulSimpleOrMultiModelStates) = get_Reservoir_state(state.states[end]) get_nt(state::jutulSimpleOrMultiModelStates) = length(state.states) get_nn(state::jutulSimpleOrMultiModelState) = length(Saturations(state)) get_nn(state::jutulSimpleOrMultiModelStates) = get_nn(state.states[1]) ###### turn jutulStates to state dictionary dict(state::jutulSimpleOrMultiModelState) = state.state dict(state::jutulSimpleOrMultiModelStates) = [dict(state.states[i]) for i = 1:get_nt(state)] dict(state::Dict) = state ###### AbstractVector length(state::jutulSimpleOrMultiModelState) = length(Saturations(state)) + length(Pressure(state)) length(state::jutulSimpleOrMultiModelStates) = sum([length(state.states[i]) for i = 1:get_nt(state)]) size(state::jutulAllState) = (length(state),) vec(state::jutulAllState) = vcat(Saturations(state), Pressure(state)) IndexStyle(::jutulAllState) = IndexLinear() function getindex(state::jutulState, i::Int) if i <= get_nn(state) ## getindex for saturation return state.state[:Reservoir][:Saturations][1,i] else ## getindex for pressure return state.state[:Reservoir][:Pressure][i-get_nn(state)] end end function getindex(state::jutulSimpleState, i::Int) if i <= get_nn(state) ## getindex for saturation return state.state[:Saturations][1,i] else ## getindex for pressure return state.state[:Pressure][i-get_nn(state)] end end function setindex!(state::jutulState{T}, v, i::Int) where T if i <= get_nn(state) ## setindex for saturation state.state[:Reservoir][:Saturations][1,i] = T(v) state.state[:Reservoir][:Saturations][2,i] = T(1) - T(v) else ## setindex for pressure state.state[:Reservoir][:Pressure][i-get_nn(state)] = T(v) end end function setindex!(state::jutulSimpleState{T}, v, i::Int) where T if i <= get_nn(state) ## setindex for saturation state.state[:Saturations][1,i] = T(v) state.state[:Saturations][2,i] = T(1) - T(v) else ## setindex for pressure state.state[:Pressure][i-get_nn(state)] = T(v) end end function getindex(states::jutulStates, i::Int) idx_t = div(i-1, get_nn(states)) + 1 idx_n = mod(i-1, get_nn(states)) + 1 if idx_t <= get_nt(states) ## getindex for saturation return states.states[idx_t].state[:Reservoir][:Saturations][1,idx_n] else ## getindex for pressure return states.states[idx_t-get_nt(states)].state[:Reservoir][:Pressure][idx_n] end end function getindex(states::jutulSimpleStates, i::Int) idx_t = div(i-1, get_nn(states)) + 1 idx_n = mod(i-1, get_nn(states)) + 1 if idx_t <= get_nt(states) ## getindex for saturation return states.states[idx_t].state[:Saturations][1,idx_n] else ## getindex for pressure return states.states[idx_t-get_nt(states)].state[:Pressure][idx_n] end end function setindex!(states::jutulStates{T}, v, i::Int) where T idx_t = div(i-1, get_nn(states)) + 1 idx_n = mod(i-1, get_nn(states)) + 1 if idx_t <= get_nt(states) ## setindex for saturation states.states[idx_t].state[:Reservoir][:Saturations][1,idx_n] = T(v) else ## setindex for pressure states.states[idx_t-get_nt(states)].state[:Reservoir][:Pressure][idx_n] = T(v) end end function setindex!(states::jutulSimpleStates{T}, v, i::Int) where T idx_t = div(i-1, get_nn(states)) + 1 idx_n = mod(i-1, get_nn(states)) + 1 if idx_t <= get_nt(states) ## setindex for saturation states.states[idx_t].state[:Saturations][1,idx_n] = T(v) else ## setindex for pressure states.states[idx_t-get_nt(states)].state[:Pressure][idx_n] = T(v) end end getindex(state::jutulAllState, i...) = getindex(vec(state), i...) firstindex(A::jutulAllState) = 1 lastindex(A::jutulAllState) = length(A) norm(A::jutulAllState, order::Real=2) = norm(vec(A), order) dot(A::jutulAllState, B::jutulAllState) = dot(vec(A), vec(B)) dot(A::jutulAllState, B::AbstractArray) = dot(vec(A), vec(B)) dot(A::AbstractArray, B::jutulAllState) = dot(vec(A), vec(B)) function (states::jutulState{T})(x::AbstractArray) where T @assert length(states) == length(x) states_ = deepcopy(states) states_ .= T.(x) states_.state[:Reservoir][:Saturations][2,:] = T(1) .- states_.state[:Reservoir][:Saturations][1,:] return states_ end function (states::jutulSimpleState{T})(x::AbstractArray) where T @assert length(states) == length(x) states_ = deepcopy(states) states_ .= T.(x) states_.state[:Saturations][2,:] = T(1) .- states_.state[:Saturations][1,:] return states_ end function (states::jutulStates{T})(x::AbstractArray) where T @assert length(states) == length(x) states_ = deepcopy(states) states_ .= T.(x) for i = 1:get_nt(states) states_.states[i].state[:Reservoir][:Saturations][2,:] = T(1) .- states_.states[i].state[:Reservoir][:Saturations][1,:] end return states_ end function (states::jutulSimpleStates{T})(x::AbstractArray) where T @assert length(states) == length(x) states_ = deepcopy(states) states_ .= T.(x) for i = 1:get_nt(states) states_.states[i].state[:Saturations][2,:] = T(1) .- states_.states[i].state[:Saturations][1,:] end return states_ end function jutulSimpleState(M::jutulModel{D, T}; ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), g::T=T(10.0)) where {D, T} ## default state at time 0 with all water Z = repeat((1:M.n[end])*M.d[end], inner = prod(M.n[1:2])) p0 = ρH2O * g * (Z .+ M.h) # rho * g * h state0 = setup_state(simple_model(M; ρCO2=ρCO2, ρH2O=ρH2O), Pressure = p0, Saturations = [0.0, 1.0]) return jutulSimpleState(state0) end for op in [:+, :-, :*, :/] @eval function $(op)(A::jutulAllState{T}, B::jutulAllState{T}) where T return A(broadcast($(op), vec(A), vec(B))) end end ==(A::jutulAllState{T}, B::jutulAllState{T}) where {T} = vec(A) == vec(B) function check_valid_state(states::jutulState{T}) where T @assert all(isapprox.(sum(states.state[:Reservoir][:Saturations], dims=1),1; rtol=sqrt(eps(T)))) end function check_valid_state(states::jutulSimpleState{T}) where T @assert all(isapprox.(sum(states.state[:Saturations], dims=1),1; rtol=sqrt(eps(T)))) end function check_valid_state(states::jutulSimpleOrMultiModelStates{T}) where T for i = 1:get_nt(states) check_valid_state(states.states[i]) end end
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
727
export jutulVWell struct jutulVWell{D, T} irate::T name::Vector{Symbol} loc::Vector startz endz end jutulVWell(irate::T, loc::NTuple{D, T}; startz=nothing, endz=nothing) where {D, T} = jutulVWell(irate, [loc]; startz=startz, endz=endz) jutulVWell(irate::T, loc::Vector{NTuple{D, T}}; startz=nothing, endz=nothing) where {D, T}= jutulVWell{D+1, T}(irate, vcat(:Injector, [:Producer for i = 1:length(loc)]), loc, startz, endz) display(f::jutulVWell{D, T}) where {D, T} = println("$(D)D jutulVWell structure with $(length(f.loc)) injection/production wells and rate $(f.irate) m^3/s") ==(A::jutulVWell{D, T}, B::jutulVWell{D, T}) where {D,T} = (A.irate == B.irate && A.name == B.name && A.loc == B.loc)
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
4449
function force(M::jutulModel{D, T}, w::jutulForce{D, T}, tstep::Vector{T}; ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), g::T=T(10.0)) where {D, T} ## set up well information cell_loc = [Int.(round.(w.loc[i] ./ M.d[1:length(w.loc[1])])) for i = 1:length(w.loc)] Is = [setup_well(CartesianMesh(M), M.K, [cell_loc[i]], name = w.name[i]) for i = 1:length(w.loc)] ctrls = [w.name[i]==:Injector ? InjectorControl(TotalRateTarget(w.irate), [1.0, 0.0], density = ρCO2) : ProducerControl(BottomHolePressureTarget(50*bar)) for i = 1:length(w.loc)] controls = Dict() for i = 1:length(w.loc) controls[w.name[i]] = ctrls[i] end return Is, controls end function force(M::jutulModel{D, T}, w::jutulVWell{D, T}, tstep::Vector{T}; ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), g::T=T(10.0)) where {D, T} ## set up well information cell_loc = [Int.(round.(w.loc[i] ./ M.d[1:length(w.loc[1])])) for i = 1:length(w.loc)] heel = [isnothing(w.startz) ? 1 : Int(div(w.startz[i], M.d[end])) for i = 1:length(w.loc)] toe = [isnothing(w.endz) ? M.n[end] : Int(div(w.endz[i], M.d[end])) for i = 1:length(w.loc)] Is = [setup_vertical_well(CartesianMesh(M), M.K, cell_loc[i]..., name = w.name[i]; heel = heel[i], toe = toe[i]) for i = 1:length(w.loc)] ctrls = [w.name[i]==:Injector ? InjectorControl(TotalRateTarget(w.irate), [1.0, 0.0], density = ρCO2) : ProducerControl(BottomHolePressureTarget(50*bar)) for i = 1:length(w.loc)] controls = Dict() for i = 1:length(w.loc) controls[w.name[i]] = ctrls[i] end return Is, controls end function setup_well_model(M::jutulModel{D, T}, f::Union{jutulForce{D, T}, jutulVWell{D, T}}, tstep::Vector{T}; visCO2::T=T(visCO2), visH2O::T=T(visH2O), ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O), g::T=T(10.0)) where {D, T} ### set up well controls Is, controls = force(M, f, tstep; ρCO2=ρCO2, ρH2O=ρH2O, g=g) ### set up model, parameters sys = ImmiscibleSystem((VaporPhase(), AqueousPhase()), reference_densities = [ρCO2, ρH2O]) domain_spec = reservoir_domain(CartesianMesh(M), porosity = M.ϕ, permeability = M.K) domain = discretized_domain_tpfv_flow(domain_spec) model_parameters = Dict(:Reservoir => Dict(:PhaseViscosities=> [visCO2, visH2O])) model, parameters = setup_reservoir_model(domain_spec, sys, wells = Is, parameters=model_parameters) select_output_variables!(model.models.Reservoir, :all) ρ = ConstantCompressibilityDensities(p_ref = 150*bar, density_ref = [ρCO2, ρH2O], compressibility = [1e-4/bar, 1e-6/bar]) replace_variables!(model, PhaseMassDensities = ρ) replace_variables!(model, RelativePermeabilities = BrooksCoreyRelPerm(sys, [2.0, 2.0], [0.1, 0.1], 1.0)) for x ∈ keys(model.models) Jutul.select_output_variables!(model.models[x], :all) end ### forces forces = setup_reservoir_forces(model, control = controls) ### initial state Z = repeat((1:M.n[end])*M.d[end], inner = prod(M.n[1:2])) p0 = ρH2O * g * (Z .+ M.h) # rho * g * h state0 = setup_reservoir_state(model, Pressure = p0, Saturations = [0.0, 1.0]) return model, parameters, state0, forces end function source(M::jutulModel{D, T}, f::jutulSource{D, T}; ρCO2::T=T(ρCO2)) where {D, T} model = simple_model(M; ρCO2=ρCO2) cell_loc = [Int.(round.(f.loc[i] ./ M.d)) for i = 1:length(f.loc)] cell = [sum([(cell_loc[i][d]-1) * prod(M.n[1:d-1]) for d = length(cell_loc[i]):-1:1]) + 1 for i = 1:length(cell_loc)] src = [SourceTerm(cell[i], f.irate[i] * ρCO2, fractional_flow = [T(f.irate[i] > 0), T(1)-T(f.irate[i] > 0)]) for i = 1:length(f.loc)] return setup_forces(model, sources = src) end function simple_model(M::jutulModel{D, T}; ρCO2::T=T(ρCO2), ρH2O::T=T(ρH2O)) where {D, T} sys = ImmiscibleSystem((VaporPhase(), AqueousPhase())) g = CartesianMesh(M.n, M.d .* M.n) domain_spec = reservoir_domain(g, porosity = M.ϕ, permeability = M.K) G = discretized_domain_tpfv_flow(domain_spec) model = SimulationModel(domain_spec, sys, output_level = :all) model.primary_variables[:Pressure] = JutulDarcy.Pressure(minimum = -Inf, max_rel = nothing) ρ = ConstantCompressibilityDensities(p_ref = 150*bar, density_ref = [ρCO2, ρH2O], compressibility = [1e-4/bar, 1e-6/bar]) replace_variables!(model, PhaseMassDensities = ρ) replace_variables!(model, RelativePermeabilities = BrooksCoreyRelPerm(sys, [2.0, 2.0], [0.1, 0.1], 1.0)) return model end
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
1516
export TransToK, KtoTrans, K1to3 K1to3(Kx::AbstractArray{T}; kvoverkh::T=T(1)) where T = vcat(vec(Kx)', vec(Kx)', kvoverkh * vec(Kx)') function TransToK(g::CartesianMesh, Trans::AbstractVector{T}) where T<:Number # ## Set up L-BFGS function fg(F, G, x) grads = gradient(Flux.params(x)) do F = norm(KtoTrans(g, x)-Trans)^2 / norm(Trans)^2 end G .= grads[x] return F end Kx = vcat([vec(g.deltas[i]^2 / prod(g.deltas) * mean(Trans) * ones(prod(g.dims)))' for i = 1:3]...) result = optimize(Optim.only_fg!(fg), Kx, LBFGS(), Optim.Options(f_tol=T(0))) Kxinv = result.minimizer return Kxinv end function KtoTrans(g::CartesianMesh, K::AbstractArray{T}) where {T<:Number} d = g.deltas n = g.dims return vcat(vec(KtoTransx(reshape(K[1,:], n), d)), vec(KtoTransy(reshape(K[2,:], n), d)), vec(KtoTransz(reshape(K[3,:], n), d))) end function KtoTransx(K::AbstractArray{T, 3}, d::NTuple{3, T}) where {T<:Number} Kreci = T(1) ./ K return T(2) * prod(d) / d[1]^2 ./ (Kreci[1:end-1,:,:] + Kreci[2:end,:,:]) end function KtoTransy(K::AbstractArray{T, 3}, d::NTuple{3, T}) where {T<:Number} Kreci = T(1) ./ K return permutedims(T(2) .* prod(d) / d[2]^2 ./ (Kreci[:,1:end-1,:] + Kreci[:,2:end,:]), [1,3,2]) end function KtoTransz(K::AbstractArray{T, 3}, d::NTuple{3, T}) where {T<:Number} Kreci = T(1) ./ K return T(2) .* prod(d) / d[3]^2 ./ (Kreci[:,:,1:end-1] + Kreci[:,:,2:end]) end
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
4799
mean(x) = sum(x)/length(x) function log_division(a, b) if b == 0 return a == 0 ? NaN : Inf end return log(a / b) end """ grad_test(J, x0, Δx, dJdx; ΔJ=nothing, maxiter=6, h0=5e-2, stol=1e-1, hfactor=8e-1) Test the gradient using Taylor series convergence. Compute a series of residuals using zeroth order and first order Taylor approximations. Each perturbed computation J(x₀ + hᵢ Δx) is compared to J(x₀) and J(x₀) + hᵢ ΔJ, where hᵢ = hfactor * hᵢ₋₁ and ΔJ = dJdx ⋅ Δx by default. If the computation of J and dJdx is correct, J is sufficiently smooth, and h is sufficiently small, the zeroth order approximation should converge linearly and the first order approximation should converge quadratically. It can be difficult to obtain the correct convergence, so we average the convergence factors across maxiter values of h and test that the convergence factor is more than correct convergence factor minus the stol parameter. # Mathematical basis For J sufficiently smooth, the value of a point at a small perturbation from x₀ can be computed using the Taylor series expansion. ```math J(x₀ + h Δx) = J(x₀) + h (dJ/dx) Δx + h² (d²J/dx²) : (Δx Δxᵀ) + O(h³) ``` If d²J/dx² is non-zero and h is small enough, the value of the first-order Taylor approximation differs from the true value by approximately a constant proportional to h². ```math err(h) = |J(x₀ + h Δx) - J(x₀) - h (dJ/dx) Δx| ≈ h²c ``` If we consider the error for two different values of h, the unknown constant can be eliminated. ```math err(h₁) / err(h₂) ≈ (h₁ / h₂)^2 ``` So if h₁ is divided by a factor α, then the ratio of the errors should be divided by a factor α². Or we can compute the exponent for the rate of convergence using logarithms. ```math log(err(h₁) / err(h₂)) / log (h₁ / h₂) ≈ 2 ``` """ function grad_test(J, x0, Δx, dJdx; ΔJ=nothing, maxiter=6, h0=5e-2, stol=1e-1, hfactor=8e-1, unittest=:test) if !xor(isnothing(dJdx), isnothing(ΔJ)) error("Must specify either dJdx or ΔJ") end if isnothing(ΔJ) ΔJ = dot(dJdx, Δx) end J0 = J(x0) h = h0 log_factor = log(hfactor) expected_f1 = 1e0 / hfactor expected_f2 = 1e0 / hfactor ^2e0 err1 = zeros(Float64, maxiter) err2 = zeros(Float64, maxiter) Js = zeros(Float64, maxiter) @printf("%11s, %12s | %11s, %11s | %11s, %11s | %12s, %12s | %12s %12s %12s \n", "h", "ΔJ", "e1", "e2", "factor1", "factor2", "rate1", "rate2", "Finite-diff", "T1 approx", "T2 approx") @printf("%11s, % 12.5e | %11s, %11s | %11.5e, %11.5e | % 12.5e, % 12.5e | \n", "", ΔJ, "0", "0", expected_f1, expected_f2, 1, 2) @printf("%11s, %12s | %11s, %11s | %11s, %11s | % 12s, % 12s \n", "___________", "___________", "___________", "___________", "___________", "___________", "____________", "____________") all_info = [] for j=1:maxiter Jh = J(x0 + h*Δx) Js[j] = Jh err1[j] = norm(Jh - J0, 1) err2[j] = norm(Jh - J0 - h*ΔJ, 1) j == 1 ? prev = 1 : prev = j - 1 dJ_est = (Jh - J0) / h α = expected_f2 dJ_est1 = (α*Js[prev] - Jh + (1-α)*J0) / (h * (α/hfactor - 1)) α = -expected_f2 dJ_est2 = (α*Js[prev] - Jh + (1-α)*J0) / (h * (α/hfactor - 1)) rate1 = log_division(err1[j], err1[prev]) / log_factor rate2 = log_division(err2[j], err2[prev]) / log_factor info = (h, h*norm(ΔJ, 1), err1[j], err2[j], err1[prev]/err1[j], err2[prev]/err2[j], rate1, rate2, dJ_est, dJ_est1, dJ_est2) push!(all_info, info) @printf("%11.5e, % 12.5e | %11.5e, %11.5e | %11.5e, %11.5e | % 12.5e, % 12.5e | % 12.5e, % 12.5e, % 12.5e \n", info...) h = h * hfactor end println() @printf("%11s, %12s | %11s, %11s | %11s, %11s | %12s, %12s | %12s %12s %12s \n", "h", "ΔJ", "e1", "e2", "factor1", "factor2", "rate1", "rate2", "Finite-diff", "T1 approx", "T2 approx") @printf("%11s, % 12.5e | %11s, %11s | %11.5e, %11.5e | % 12.5e, % 12.5e | \n", "", ΔJ, "0", "0", expected_f1, expected_f2, 1, 2) @printf("%11s, %12s | %11s, %11s | %11s, %11s | % 12s, % 12s \n", "___________", "___________", "___________", "___________", "___________", "___________", "____________", "____________") for j=1:maxiter info = all_info[j] @printf("%11.5e, % 12.5e | %11.5e, %11.5e | %11.5e, %11.5e | % 12.5e, % 12.5e | % 12.5e, % 12.5e, % 12.5e \n", info...) h = h * hfactor end factor1 = err1[1:end-1]./err1[2:end] factor2 = err2[1:end-1]./err2[2:end] @test mean(factor1) ≥ expected_f1 - stol if unittest == :skip @test mean(factor2) ≥ expected_f2 - stol skip=true elseif unittest == :broken @test mean(factor2) ≥ expected_f2 - stol broken=true else @test mean(factor2) ≥ expected_f2 - stol end end
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
399
using Test using Jutul using JutulDarcyRules using Flux using Printf using Random using LinearAlgebra Random.seed!(2023) include("test_utils.jl") include("test_model_parameter.jl") include("test_gradient.jl") include("test_conversion.jl") include("test_jutulState.jl") include("test_jutulForce.jl") include("test_jutulSource.jl") include("test_jutulModel.jl") include("test_jutulModeling.jl")
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git
[ "MIT" ]
0.2.8
da37b282ff5919181ee4c1eae2ad7665e9af3702
code
356
nx = 30 ny = 10 nz = 15 dims = (nx, ny, nz) g1 = CartesianMesh(dims, (5.0, 8.0, 10.0) .* dims) g = tpfv_geometry(g1) K1 = vcat(vec(rand(nx, ny, nz))', vec(rand(nx, ny, nz))', vec(rand(nx, ny, nz))') @testset "Test conversion" begin @info "compute transmissibility from permeability" @test isapprox(KtoTrans(g1, K1), compute_face_trans(g, K1)) end
JutulDarcyRules
https://github.com/slimgroup/JutulDarcyRules.jl.git