text:
"""
    logtp_equal_rates_equal_time(i, j)

Evaluate the logarithm of a transition probability of a simple birth and death
process when the death rate `μ` is equal to the birth rate `λ` and the time `t`
is equal to `1 / λ`. It is a very unlikely event (let's say impossible) but it
simplifies into a special case.
"""
@inline function logtp_equal_rates_equal_time(
  i::I,
  j::I
) where {
  I <: Integer
}
  lgamma(i + j) - lgamma(i) - lgamma(j + 1) - (i + j) * log(2)
end

"""
    logtp_equal_rates(i, j, t, λ)

Evaluate the logarithm of a transition probability of a simple birth and death
process.
"""
@inline function logtp_equal_rates(
  i::I,
  j::I,
  t::F,
  λ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  a::F, b::F = (j <= i) ? (i, j) : (j, i)

  θ = λ * t

  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + (i + j) * log(θ / (1 + θ)) +
  log_hypergeometric(a, b, logexpm1(-2 * log(θ)))
end

"""
    logtp_equal_rates_alternating(i, j, t, λ)

Evaluate the logarithm of a transition probability of a simple birth and death
process when terms are alternating in sign.
"""
@inline function logtp_equal_rates_alternating(
  i::I,
  j::I,
  t::F,
  λ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  a::F, b::F = (j <= i) ? (i, j) : (j, i)

  θ = λ * t

  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + (i + j) * log(θ / (1 + θ)) +
  log_meixner_ortho_poly(a, b, 2 * log(θ))
end

"""
    logtp_equal_rates_equal_time_extinction(i)

Evaluate the logarithm of a transition probability of a simple birth and death
process when the death rate `μ` is equal to the birth rate `λ`, time `t` is
equal to `1 / λ`, and 'j' is equal to zero. It is a very unlikely event
(let's say impossible) but it simplifies into a special case.
"""
@inline function logtp_equal_rates_equal_time_extinction(
  i::I
) where {
  I <: Integer
}
  - i * log(2)
end

"""
    logtp_equal_rates_extinction(i, t, λ)

Evaluate the logarithm of the probability of extinction for a simple birth and
death process when the death rate `μ` is equal to the birth rate `λ`.
"""
@inline function logtp_equal_rates_extinction(
  i::I,
  t::F,
  λ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  i * log((λ * t) / (1 + λ * t))
end

"""
    logtp_pure_birth(i, j, t, λ)

Evaluate the logarithm of the transition probability of a pure-birth process.
"""
@inline function logtp_pure_birth(
  i::I,
  j::I,
  t::F,
  λ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  lgamma(j) + (j - i) * logexpm1(λ * t) -
  (lgamma(i) + lgamma(j - i + 1) + j * λ * t)
end

"""
    logtp_pure_death(i, j, t, μ)

Evaluate the logarithm of the transition probability of a pure-death process.
"""
@inline function logtp_pure_death(
  i::I,
  j::I,
  t::F,
  μ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  lgamma(i + 1) + (i - j) * logexpm1(μ * t) -
  (lgamma(j + 1) + lgamma(i - j + 1) + i * μ * t)
end

"""
    logtp_equal_time(i, j, λ, μ)

Evaluate the logarithm of a transition probability of a simple birth and death
process when the time `t` is equal to `log(λ / μ) / (λ - μ)`. It is a very
unlikely event (let's say impossible) but it simplifies into a special case.
"""
@inline function logtp_equal_time(
  i::I,
  j::I,
  λ::F,
  μ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  lgamma(i + j) + i * log(μ) + j * log(λ) -
  (lgamma(i) + lgamma(j + 1) + (i + j) * log(λ + μ))
end

"""
    logtp_sum(i, j, t, λ, μ)

Evaluate the logarithm of a transition probability of a simple birth and death
process.
"""
@inline function logtp_sum(
  i::I,
  j::I,
  t::F,
  λ::F,
  μ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  a::F, b::F = (j <= i) ? (i, j) : (j, i)

  θ = (λ - μ) * t
  ω = log(λ / μ)

  x = if λ < μ
    logexpm1(θ - ω) + log1mexp(θ + ω) - 2 * log1mexp(θ)
  else
    logexpm1(θ + ω) + log1mexp(θ - ω) - 2 * logexpm1(θ)
  end

  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + j * ω +
  (i + j) * log(expm1(θ) / expm1(θ + ω)) +
  log_hypergeometric(a, b, x)
end

"""
    logtp_sum_alternating(i, j, t, λ, μ)

Evaluate the logarithm of a transition probability of a simple birth and death
process when terms are alternating in sign.
"""
@inline function logtp_sum_alternating(
  i::I,
  j::I,
  t::F,
  λ::F,
  μ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  a::F, b::F = (j <= i) ? (i, j) : (j, i)

  θ = (λ - μ) * t
  ω = log(λ / μ)

  x = log(2 * λ * μ) +
      logexpm1(log1pexp(2 * θ) - (θ + log(F(2)))) -
      log((λ - μ)^2)

  lgamma(i + j) - lgamma(i) - lgamma(j + 1) + j * ω +
  (i + j) * log(expm1(θ) / expm1(θ + ω)) +
  log_meixner_ortho_poly(a, b, x)
end

"""
    logtp_equal_time_extinction(i, t, λ, μ)

Evaluate the logarithm of the probability of extinction for a simple birth and
death process when `t = log(λ / μ) / (λ - μ)`.
"""
@inline function logtp_equal_time_extinction(
  i::I,
  λ::F,
  μ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  i * log(μ / (λ + μ))
end

"""
    logtp_extinction(i, t, λ, μ)

Evaluate the logarithm of the probability of extinction for a simple birth and
death process.
"""
@inline function logtp_extinction(
  i::I,
  t::F,
  λ::F,
  μ::F
)::F where {
  I <: Integer,
  F <: AbstractFloat
}
  i * log(expm1((λ - μ) * t) / expm1(log(λ / μ) + (λ - μ) * t))
end

"""
    trans_prob(i, j, t, λ, μ; log_value)

Evaluate the transition probability of a simple birth and death process, i.e.
the probability of moving from `i` to `j` in `t` time when the birth rate is
equal to `λ` and the death rate is equal to `μ`.

The minimum amount of units `i` allowed at time 0 is 1 but `j` is allowed to be
0. Time `t`, birth rate `λ`, and death rate `μ` cannot be negative.

Let ``α = (μ e^{(λ - μ) t} - μ) / (λ e^{(λ - μ) t} - μ)`` and
``β = (λ e^{(λ - μ) t} - λ) / (λ e^{(λ - μ) t} - μ)``. Transition probability
is equal to (Bailey, 1964):
``\\sum_{h = 0}^{\\min(i, j)} \\binom{i}{h} \\binom{i + j - h - 1}{i - 1}
α^{i - h} β^{j - h} (1 - α - β)^{h}``.

# References:

Bailey, N. T. J. (1964). The elements of stochastic processes with applications
to the natural sciences. Wiley, New York, NY, USA. ISBN 0-471-04165-3.
"""
function trans_prob(
  i::I,
  j::I,
  t::Real,
  η::Vector{R};
  log_value::Bool=true
) where {
  I <: Integer,
  R <: Real
}
  if i < 1
    msg = "Initial population size 'i' must be greater than zero."
    throw(DomainError(i, msg))
  end

  if j < 0
    msg = "Final population size 'j' must be greater than or equal to zero."
    throw(DomainError(j, msg))
  end

  if t < 0
    msg = "Time 't' must be greater than or equal to zero."
    throw(DomainError(t, msg))
  end

  if η[1] < 0
    msg = "Birth rate 'η[1]' must be greater than or equal to zero."
    throw(DomainError(η[1], msg))
  end

  if η[2] < 0
    msg = "Death rate 'η[2]' must be greater than or equal to zero."
    throw(DomainError(η[2], msg))
  end

  # promote values to the appropriate float
  F = float(R)
  t, λ, μ = F(t), F(η[1]), F(η[2])
  ϵ = floatmin(F)

  log_trans_prob::F = if (t < ϵ) || ((λ < ϵ) && (μ < ϵ))
    if i == j
      0
    else
      -Inf
    end
  elseif λ ≈ μ
    ξ = 1 / λ

    if j > 0
      if t ≈ ξ
        logtp_equal_rates_equal_time(i, j)
      elseif t < ξ
        logtp_equal_rates(i, j, t, λ)
      else
        logtp_equal_rates_alternating(i, j, t, λ)
      end
    else
      if t ≈ ξ
        logtp_equal_rates_equal_time_extinction(i)
      else
        logtp_equal_rates_extinction(i, t, λ)
      end
    end
  elseif μ < ϵ
    if j >= i
      logtp_pure_birth(i, j, t, λ)
    else
      -Inf
    end
  elseif λ < ϵ
    if j <= i
      logtp_pure_death(i, j, t, μ)
    else
      -Inf
    end
  else
    ξ = log(λ / μ) / (λ - μ)

    if j > 0
      if t ≈ ξ
        logtp_equal_time(i, j, λ, μ)
      elseif t < ξ
        logtp_sum(i, j, t, λ, μ)
      else
        logtp_sum_alternating(i, j, t, λ, μ)
      end
    else
      if t ≈ ξ
        logtp_equal_time_extinction(i, λ, μ)
      else
        logtp_extinction(i, t, λ, μ)
      end
    end
  end

  if log_value
    log_trans_prob
  else
    exp(log_trans_prob)
  end
end


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct SecurityRulePropertiesFormat <: SwaggerModel
    description::Any # spec type: Union{ Nothing, String } # spec name: description
    protocol::Any # spec type: Union{ Nothing, String } # spec name: protocol
    sourcePortRange::Any # spec type: Union{ Nothing, String } # spec name: sourcePortRange
    destinationPortRange::Any # spec type: Union{ Nothing, String } # spec name: destinationPortRange
    sourceAddressPrefix::Any # spec type: Union{ Nothing, String } # spec name: sourceAddressPrefix
    destinationAddressPrefix::Any # spec type: Union{ Nothing, String } # spec name: destinationAddressPrefix
    access::Any # spec type: Union{ Nothing, String } # spec name: access
    priority::Any # spec type: Union{ Nothing, Int32 } # spec name: priority
    direction::Any # spec type: Union{ Nothing, String } # spec name: direction
    provisioningState::Any # spec type: Union{ Nothing, String } # spec name: provisioningState

    function SecurityRulePropertiesFormat(;description=nothing, protocol=nothing, sourcePortRange=nothing, destinationPortRange=nothing, sourceAddressPrefix=nothing, destinationAddressPrefix=nothing, access=nothing, priority=nothing, direction=nothing, provisioningState=nothing)
        o = new()
        validate_property(SecurityRulePropertiesFormat, Symbol("description"), description)
        setfield!(o, Symbol("description"), description)
        validate_property(SecurityRulePropertiesFormat, Symbol("protocol"), protocol)
        setfield!(o, Symbol("protocol"), protocol)
        validate_property(SecurityRulePropertiesFormat, Symbol("sourcePortRange"), sourcePortRange)
        setfield!(o, Symbol("sourcePortRange"), sourcePortRange)
        validate_property(SecurityRulePropertiesFormat, Symbol("destinationPortRange"), destinationPortRange)
        setfield!(o, Symbol("destinationPortRange"), destinationPortRange)
        validate_property(SecurityRulePropertiesFormat, Symbol("sourceAddressPrefix"), sourceAddressPrefix)
        setfield!(o, Symbol("sourceAddressPrefix"), sourceAddressPrefix)
        validate_property(SecurityRulePropertiesFormat, Symbol("destinationAddressPrefix"), destinationAddressPrefix)
        setfield!(o, Symbol("destinationAddressPrefix"), destinationAddressPrefix)
        validate_property(SecurityRulePropertiesFormat, Symbol("access"), access)
        setfield!(o, Symbol("access"), access)
        validate_property(SecurityRulePropertiesFormat, Symbol("priority"), priority)
        setfield!(o, Symbol("priority"), priority)
        validate_property(SecurityRulePropertiesFormat, Symbol("direction"), direction)
        setfield!(o, Symbol("direction"), direction)
        validate_property(SecurityRulePropertiesFormat, Symbol("provisioningState"), provisioningState)
        setfield!(o, Symbol("provisioningState"), provisioningState)
        o
    end
end # type SecurityRulePropertiesFormat

const _property_map_SecurityRulePropertiesFormat = Dict{Symbol,Symbol}(Symbol("description")=>Symbol("description"), Symbol("protocol")=>Symbol("protocol"), Symbol("sourcePortRange")=>Symbol("sourcePortRange"), Symbol("destinationPortRange")=>Symbol("destinationPortRange"), Symbol("sourceAddressPrefix")=>Symbol("sourceAddressPrefix"), Symbol("destinationAddressPrefix")=>Symbol("destinationAddressPrefix"), Symbol("access")=>Symbol("access"), Symbol("priority")=>Symbol("priority"), Symbol("direction")=>Symbol("direction"), Symbol("provisioningState")=>Symbol("provisioningState"))
const _property_types_SecurityRulePropertiesFormat = Dict{Symbol,String}(Symbol("description")=>"String", Symbol("protocol")=>"String", Symbol("sourcePortRange")=>"String", Symbol("destinationPortRange")=>"String", Symbol("sourceAddressPrefix")=>"String", Symbol("destinationAddressPrefix")=>"String", Symbol("access")=>"String", Symbol("priority")=>"Int32", Symbol("direction")=>"String", Symbol("provisioningState")=>"String")
Base.propertynames(::Type{ SecurityRulePropertiesFormat }) = collect(keys(_property_map_SecurityRulePropertiesFormat))
Swagger.property_type(::Type{ SecurityRulePropertiesFormat }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_SecurityRulePropertiesFormat[name]))}
Swagger.field_name(::Type{ SecurityRulePropertiesFormat }, property_name::Symbol) =  _property_map_SecurityRulePropertiesFormat[property_name]

const _allowed_SecurityRulePropertiesFormat_protocol = ["Tcp", "Udp", "*"]

const _allowed_SecurityRulePropertiesFormat_access = ["Allow", "Deny"]

const _allowed_SecurityRulePropertiesFormat_direction = ["Inbound", "Outbound"]

function check_required(o::SecurityRulePropertiesFormat)
    (getproperty(o, Symbol("sourceAddressPrefix")) === nothing) && (return false)
    (getproperty(o, Symbol("destinationAddressPrefix")) === nothing) && (return false)
    true
end

function validate_property(::Type{ SecurityRulePropertiesFormat }, name::Symbol, val)
    if name === Symbol("protocol")
        Swagger.validate_param(name, "SecurityRulePropertiesFormat", :enum, val, _allowed_SecurityRulePropertiesFormat_protocol)
    end
    if name === Symbol("access")
        Swagger.validate_param(name, "SecurityRulePropertiesFormat", :enum, val, _allowed_SecurityRulePropertiesFormat_access)
    end
    if name === Symbol("direction")
        Swagger.validate_param(name, "SecurityRulePropertiesFormat", :enum, val, _allowed_SecurityRulePropertiesFormat_direction)
    end
end

ext: jl


text:
##### Steady State Transmittance from a Slab #####
# Taken from Eqn. 46 from Contini 1997

function DA_transslabCW(ρ::Float64, β::Array{Float64,1},ndet::Float64, nmed::Float64, s::Float64)
	#s is slab thickness

	n::Float64 = nmed/ndet
    μa::Float64 = β[1]
    μsp::Float64 = β[2]
    D::Float64 = 1/3μsp
	ν::Float64 = 29.9792345/nmed
	xs::UnitRange{Int64} = -10:10

	z1m = Array{Float64}(undef, length(xs))
	z2m = Array{Float64}(undef, length(xs))

    Rt1 = Array{Float64}(undef, length(xs))
    Rt2 = Array{Float64}(undef, length(xs))

	if n == 1.0
		A= 1.0
	elseif n > 1.0
		A = 504.332889 - 2641.00214n + 5923.699064n^2 - 7376.355814n^3 +
		 5507.53041n^4 - 2463.357945n^5 + 610.956547n^6 - 64.8047n^7
	else
		A = 3.084635 - 6.531194n + 8.357854n^2 - 5.082751n^3
	end

	zs::Float64 = 1/μsp
    ze::Float64 = 2A*D

    z1m = Float64[(1 .- 2m).*s .- 4m.*ze .- zs for m in xs]
    z2m = Float64[(1 .- 2m).*s .- (4m .- 2).*ze .+ zs for m in xs]

    R1 = @. (z1m*(ρ^2 + z1m^2)^(-3/2))*(1+(μa*(ρ^2 +z1m^2))^(1/2))*exp(-(μa*(ρ^2 +z1m^2)/D)^(1/2))
    R2 = @. (z2m*(ρ^2 + z2m^2)^(-3/2))*(1+(μa*(ρ^2 +z2m^2))^(1/2))*exp(-(μa*(ρ^2 +z2m^2)/D)^(1/2))

    Rt = 1/(4π)*(sum(R1) - sum(R2))

	return Rt
end

max_stars_repo_name: sammzer/LightPropagation

max_issues_repo_name: sammzer/LightPropagation

max_forks_repo_name: sammzer/LightPropagation


text:
using RadauBVP, Plots
pyplot()

ProjDir = dirname(@__FILE__)
cd(ProjDir) do

  if !isdefined(Main, :bc!)
    function bc!(y0, yn, r)
      r[1] = y0[1] - 0.0
      r[2] = yn[2] - (-1.0)
    end

    function dbc!(y0, yn, jac)
      jac[:,:] = 0.0
      jac[1,1] = 1.0
      jac[2,4] = 1.0
    end

    function odeeq!(t, y, dydt)
      dydt[1] = y[2]
      dydt[2] = -y[1]
    end

    function dodeeq!(t, y, jac)
      jac[1,1] = 0.0
      jac[1,2] = 1.0
      jac[2,1] = -1.0
      jac[2,2] = 0.0
    end
  end

  nt = 5
  const y0 = zeros(Float64, (2, 3*(nt-1)+1))

  for n=1:3*(nt-1)+1
    y0[:, n] = [0.0, 1.0]
  end

  @time (conv, ttot, ytot, result) =
    RadauBVP.radau3(bc!, odeeq!, dbc!, dodeeq!, y0, 0.0, convert(Float64, π))

  result |> display

  yres = ytot[1,:]
  vres = ytot[2,:]

  let t = linspace(0.0, π, 100)

    global possol = sin.(t)
    global vsol = cos.(t)
    global ysol = Array(Float64, 2*100)

    ysol[1:2:end-1] = possol
    ysol[2:2:end] = vsol
  end

  p1 = plot(
  linspace(0.0, π, 100),
  possol,
  title = "Coordinate (n = $nt)",
  label = "Exact")
  plot!(ttot, yres, label = "Numerical", linetype = :scatter)

  p2 = plot(
  linspace(0.0, π, 100),
  vsol,
  title = "Velocity (n = $nt)",
  label = "Exact")
  plot!(ttot, vres, label = "Numerical", linetype = :scatter)

  plot(p1,p2)
  savefig("radau.png")
  plot(p1,p2)

end


text:
# Some limited serialization to json.

function json{T}(xs::Vector{T})
    @sprintf("[%s]", join([json(x) for x in xs], ","))
end

function json{T <: Union(Symbol, String), S}(xs::Dict{T, S})
    @sprintf("{%s}", join([@sprintf("%s:%s", quote_string(k), v)
                           for (k, v) in xs], ","))
end

json(x::String)  = quote_string(x)
json(x::Int)     = string(x)
json(x::Real)    = string(x)
json(i::Nothing) = "null"
json(x::Any)     = quote_string(string(x))


text:
@deprecate ordered isordered

@deprecate compact compress
@deprecate uncompact decompress

@deprecate CategoricalArray{T, N}(::Type{T}, dims::NTuple{N,Int}; ordered=false) CategoricalArray{T}(dims, ordered=ordered)
@deprecate CategoricalArray{T}(::Type{T}, dims::Int...; ordered=false) CategoricalArray{T}(dims, ordered=ordered)

@deprecate NullableCategoricalArray{T, N}(::Type{T}, dims::NTuple{N,Int}; ordered=false) NullableCategoricalArray{T}(dims, ordered=ordered)
@deprecate NullableCategoricalArray{T}(::Type{T}, dims::Int...; ordered=false) NullableCategoricalArray{T}(dims, ordered=ordered)

@deprecate CategoricalVector{T}(::Type{T}, m::Integer; ordered=false) CategoricalVector{T}(m, ordered=ordered)
@deprecate NullableCategoricalVector{T}(::Type{T}, m::Integer; ordered=false) NullableCategoricalVector{T}(m, ordered=ordered)

@deprecate CategoricalMatrix{T}(::Type{T}, m::Int, n::Int; ordered=false) CategoricalMatrix{T}(m, n, ordered=ordered)
@deprecate NullableCategoricalMatrix{T}(::Type{T}, m::Int, n::Int; ordered=false) NullableCategoricalMatrix{T}(m, n, ordered=ordered)


text:
include("catlab_simpler.jl")
using Catlab
using Catlab.Theories
using Catlab.Syntax
using Metatheory, Metatheory.EGraphs

using Test

# ============================================================
# GATExpr TO TAGGED EXPR
# ============================================================

# WE HAVE TO REDEFINE THE SYNTAX TO AVOID ASSOCIATIVITY AND N-ARY FUNCTIONS
import Catlab.Theories: id, compose, otimes, ⋅, braid, σ, ⊗, Ob, Hom
@syntax SMC{ObExpr,HomExpr} SymmetricMonoidalCategory begin
end

A, B, C, D = Ob(SMC, :A, :B, :C, :D)
X, Y, Z = Ob(SMC, :X, :Y, :Z)

f = Hom(:f, A, B)
g = Hom(:g, B, C)
h = Hom(:h, C, D)

gat_to_expr(x) = x

gat_to_expr(A)

A isa ObExpr{H} where {H}

gat_to_expr(id(Z)) == :(id(Z)~(Hom(Z,Z)))

gat_to_expr(id(Z) ⋅ f)

gat_to_expr(id(A ⊗ B))

gat_to_expr(id(A) ⊗ id(B))

gat_to_expr(compose(compose(f, g), h))

gat_to_expr(f)

gat_to_expr(A ⊗ B)

# BUG
gat_to_expr(otimes(f, g))

# ============================================================
# Type tagging axioms
# ============================================================

A, B, C, D = Ob(SMC, :A, :B, :C, :D)
X, Y, Z = Ob(SMC, :X, :Y, :Z)

tt = theory(SymmetricMonoidalCategory) ;
ax = tt.axioms[10] ;
get_concrete_type_expr(tt, ax.left, ax.context)
tag_expr(ax.left, ax, tt)
ax = tt.axioms[4]
get_concrete_type_expr(tt, ax.left, ax.context)
tag_expr(ax.left, ax, tt)

tt = theory(Category)

tag_expr(tt.axioms[1].left, tt.axioms[1], tt) == gat_to_expr(compose(compose(f, g), h))

# ====================================================

tt = theory(Category)

A, B, C, D = Ob(SMC, :A, :B, :C, :D)
X, Y, Z = Ob(SMC, :X, :Y, :Z)

f = Hom(:f, A, B)
g = Hom(:g, B, C)
h = Hom(:h, C, D)

rules = gen_theory(tt)
expr = gat_to_expr(id(A) ⋅ id(A) ⋅ f ⋅ id(B))
G = EGraph(expr)
saturate!(G, rules)
@test extract!(G, astsize)  == :(f ~ Hom(A,B))

tt = theory(SymmetricMonoidalCategory)

rules = Rule[axiom_to_rule(tt, ax) for ax in tt.axioms]

# push!(rules, EqualityRule( @pat(otimes(Hom(A, B), Hom(X, Y))), @pat(Hom(otimes(A, X), otimes(B, Y))) ))

gats = [
    σ(A,B⊗C),
    (σ(A,B) ⊗ id(C)) ⋅ (id(B) ⊗ σ(A,C))
]

exprs = [gat_to_expr(i) for i in gats]

# push!(rules, RewriteRule(Pattern(l), Pattern(r)))
G = EGraph()

ecs = [addexpr!(G, i) for i in exprs]

saturate!(G, rules)
extract!(G, astsize; root=ecs[2].id)

@test in_same_class(G, ecs[1], ecs[2])

# YANG BAXTER EQUATION

gats = [
    (σ(A,B) ⊗ id(C)) ⋅ (id(B) ⊗ σ(C,A)) ⋅ (σ(B,C) ⊗ id(A)),
    σ(A, B ⊗ C) ⋅ (σ(B,C) ⊗ id(A)),
    (id(A) ⊗ σ(B,C)) ⋅ σ(A, C⊗B),
    (id(A) ⊗ σ(B,C)) ⋅ (σ(A,C) ⊗ id(B)) ⋅ (id(C) ⊗ σ(A,B))
]

exprs = [gat_to_expr(i) for i in gats]

# push!(rules, RewriteRule(Pattern(l), Pattern(r)))
G = EGraph()

ecs = [addexpr!(G, i) for i in exprs]

saturate!(G, rules, SaturationParams(timeout=1))
extract!(G, astsize; root=ecs[2].id)

[ in_same_class(G, ecs[i], ecs[i+1]) for i in 1:length(gats)-1 ]

# ========================================================================================

tt = theory(CartesianCategory)
A, B, C, D = Ob(FreeCartesianCategory, :A, :B, :C, :D)
f = Hom(:f, A, B)
g = Hom(:g, B, C)
h = Hom(:h, C, D)

l = pair(proj1(A, B), proj2(A, B))
r = id(A ⊗ B)

rules = [axiom_to_rule(tt, ax) for ax in tt.axioms]

l = gat_to_expr(l)
r = gat_to_expr(r)

G = EGraph(l)
rc, _ = addexpr!(G, r)

# TODO identify the rules where there are more patvars on the lhs than the rhs
# and use regular rewrite rules instead of (==) rules
saturate!(G, rules)
extract!(G, astsize)
extract!(G, astsize; root=rc.id)

l = f ⋅ delete(B)

G = EGraph(gat_to_expr(l))
saturate!(G, rules)
extract!(G, astsize)
#TODO expr to gat

# ====================================================
# TEST
mu = FreeCartesianCategory.munit(FreeCartesianCategory.Ob)

l = σ(A, mu)
r = id(A)

rules = [axiom_to_rule(tt, ax) for ax in tt.axioms]

l = gat_to_expr(l)
r = gat_to_expr(r)

G = EGraph(l)
rc, _ = addexpr!(G, r)

# TODO identify the rules where there are more patvars on the lhs than the rhs
# and use regular rewrite rules instead of (==) rules
saturate!(G, rules)
extract!(G, astsize; root=rc.id)
extract!(G, astsize)

l = σ(A, B) ⋅ σ(B, A)
r = id(A ⊗ B)

rules = [axiom_to_rule(tt, ax) for ax in tt.axioms]

l = gat_to_expr(l)
r = gat_to_expr(r)

G = EGraph(l)
rc, _ = addexpr!(G, r)

# TODO identify the rules where there are more patvars on the lhs than the rhs
# and use regular rewrite rules instead of (==) rules
saturate!(G, rules)
extract!(G, astsize; root=rc.id) == extract!(G, astsize)

l = σ(A, mu)
r = id(A)

rules = [axiom_to_rule(tt, ax) for ax in tt.axioms]

l = gat_to_expr(l)
r = gat_to_expr(r)

G = EGraph(l)
rc, _ = addexpr!(G, r)

# TODO identify the rules where there are more patvars on the lhs than the rhs
# and use regular rewrite rules instead of (==) rules
saturate!(G, rules)
# extract!(G, astsize; root=rc.id) ==
extract!(G, astsize)


text:
import JUDI.split

export H5SeisCon

struct H5SeisCon
  seis::PyCall.PyObject
  xkey::String
  ykey::String
  zkey::String
  pkey::String
  pkeyvals::Array{Float64,1}
end

function H5SeisCon(;
  seis::PyCall.PyObject=nothing,
  xkey::String="GRPX",
  ykey::String="GRPY",
  zkey::String="RGE",
  pkey::String="SP",
  pkeyvals=nothing)
  if isnothing(seis)
    @error "Seis is Nothing"
    return
  end

  if isnothing(pkey) || isnothing(xkey) || isnothing(ykey) || isnothing(zkey)
    @error "pkey/xkey/ykey/zkey is Nothing"
    return
  end

  if isnothing(pkeyvals)
    pkeyvals = seis.getPKeyValues(pkey)
  end

  return H5SeisCon(seis, xkey, ykey, zkey, pkey, pkeyvals)
end

size(con::H5SeisCon) = size(con.pkeyvals)
length(con::H5SeisCon) = length(con.pkeyvals)

function getindex(con::H5SeisCon, a::TA) where {TA<:Union{Array{<:Integer,1}, AbstractRange, Integer}}
  read_H5SeisCon(con, a)
end

function getindex(con::H5SeisCon, a::Colon)
  read_H5SeisCon(con, 1:length(con))
end

function split(s::H5SeisCon, inds::Union{Vector{Ti}, AbstractRange{Ti}}) where {Ti<:Integer}
  return H5SeisCon(s.seis, s.xkey, s.ykey, s.zkey, s.pkey, view(s.pkeyvals, inds))
end

split(s::H5SeisCon, inds::Integer) = split(s, [inds])

subsample(a::Array{H5SeisCon,1}, i::Int64) = a[i]


text:
#### Implementing the interface of Tables.jl

Tables.istable(::Type{<:FunctionalTable}) = true

Tables.rowaccess(::Type{<:FunctionalTable}) = true

Tables.rows(ft::FunctionalTable) = ft

Tables.schema(ft::FunctionalTable) =
    Tables.Schema(keys(columns(ft)), map(eltype, values(columns(ft))))

Tables.columnaccess(::Type{<:FunctionalTable}) = true

Tables.columns(ft::FunctionalTable) = map(collect, columns(ft))


text:
const libccv = Pkg.dir("CCV", "deps", "ccv", "lib", "libccv.so")

include("const.jl")
include("utils.jl")
include("common.jl")
include("densematrix.jl")
include("array.jl")
include("scd.jl")
include("io.jl")


text:
using EMIRT
include(joinpath(Pkg.dir(), "EMIRT/plugins/emshow.jl"))
using Gadfly

if length(ARGS)>0
    sgm = readsgm(ARGS[1])
else
    sgm = readsgm("/tmp/sgm.h5")
end

if length(ARGS)>1
    lbl = readseg(ARGS[2])
else
    lbl = readseg("/tmp/lbl.h5")
end

ec = sgm2ec(sgm, lbl)

ecs = ScoreCurves()
ecs[:ec] = ec
df = ecs2df(ecs)

plot(df, x="thd", y="re")


text:
@testset "Foo" begin
    @test 1+1 == 2
end


text:
mutable struct UnfoldUpdateState{T,U}
    init_state::T
    weight::Float64
    score::Float64
    noise::Float64
    subtraces::PersistentVector{U}
    retval::PersistentVector{T}
    discard::DynamicChoiceMap
    num_nonempty::Int
    updated_retdiffs::Dict{Int,Diff}
end

function process_retained!(gen_fn::Unfold{T,U}, params::Tuple,
                           choices::ChoiceMap, key::Int, kernel_argdiffs::Tuple,
                           state::UnfoldUpdateState{T,U}) where {T,U}
    local subtrace::U
    local prev_subtrace::U
    local prev_state::T
    local new_state::T

    submap = get_submap(choices, key)
    prev_state = (key == 1) ? state.init_state : state.retval[key-1]
    kernel_args = (key, prev_state, params...)

    # get new subtrace with recursive call to update()
    prev_subtrace = state.subtraces[key]
    (subtrace, weight, retdiff, discard) = update(
        prev_subtrace, kernel_args, kernel_argdiffs, submap)

    # retrieve retdiff
    if retdiff != NoChange()
        state.updated_retdiffs[key] = retdiff
    end

    # update state
    state.weight += weight
    set_submap!(state.discard, key, discard)
    state.score += (get_score(subtrace) - get_score(prev_subtrace))
    state.noise += (project(subtrace, EmptySelection()) - project(subtrace, EmptySelection()))
    state.subtraces = assoc(state.subtraces, key, subtrace)
    new_state = get_retval(subtrace)
    state.retval = assoc(state.retval, key, new_state)
    subtrace_empty = isempty(get_choices(subtrace))
    prev_subtrace_empty = isempty(get_choices(prev_subtrace))
    if !subtrace_empty && prev_subtrace_empty
        state.num_nonempty += 1
    elseif subtrace_empty && !prev_subtrace_empty
        state.num_nonempty -= 1
    end

    retdiff
end

function process_new!(gen_fn::Unfold{T,U}, params::Tuple, choices, key::Int,
                      state::UnfoldUpdateState{T,U}) where {T,U}
    local subtrace::U
    local prev_state::T
    local new_state::T

    submap = get_submap(choices, key)
    prev_state = (key == 1) ? state.init_state : state.retval[key-1]
    kernel_args = (key, prev_state, params...)

    # get subtrace and weight
    (subtrace, weight) = generate(gen_fn.kernel, kernel_args, submap)

    # update state
    state.weight += weight
    state.score += get_score(subtrace)
    new_state = get_retval(subtrace)
    @assert key > length(state.subtraces)
    state.subtraces = push(state.subtraces, subtrace)
    state.retval = push(state.retval, new_state)
    @assert length(state.subtraces) == key
    if !isempty(get_choices(subtrace))
        state.num_nonempty += 1
    end
end

function update(trace::VectorTrace{UnfoldType,T,U},
                args::Tuple, argdiffs::Tuple,
                choices::ChoiceMap) where {T,U}
    gen_fn = trace.gen_fn
    (new_length, init_state, params) = unpack_args(args)
    check_length(new_length)
    prev_args = get_args(trace)
    prev_length = prev_args[1]
    retained_and_constrained = get_retained_and_constrained(choices, prev_length, new_length)

    # handle removed applications
    (discard, num_nonempty, score_decrement, noise_decrement) = vector_update_delete(
        new_length, prev_length, trace)
    (subtraces, retval) = vector_remove_deleted_applications(
        trace.subtraces, trace.retval, prev_length, new_length)
    score = trace.score - score_decrement
    noise = trace.noise - noise_decrement

    # handle retained and new applications
    state = UnfoldUpdateState{T,U}(init_state, -score_decrement, score, noise,
        subtraces, retval, discard, num_nonempty, Dict{Int,Diff}())
    process_all_retained!(gen_fn, params, argdiffs, choices, prev_length, new_length,
                          retained_and_constrained, state)
    process_all_new!(gen_fn, params, choices, prev_length, new_length, state)

    # retdiff
    retdiff = vector_compute_retdiff(state.updated_retdiffs, new_length, prev_length)

    # new trace
    new_trace = VectorTrace{UnfoldType,T,U}(gen_fn, state.subtraces, state.retval, args,
        state.score, state.noise, new_length, state.num_nonempty)

    (new_trace, state.weight, retdiff, discard)
end

max_stars_repo_name: dendisuhubdy/Gen

max_issues_repo_name: kumsh/Gen

max_forks_repo_name: kumsh/Gen


text:
using BandedMatrices, LinearAlgebra, LazyArrays, Test
    import BandedMatrices: MemoryLayout, TriangularLayout, BandedColumnMajor

@testset "Triangular" begin
    @testset "Upper" begin
        A = UpperTriangular(brand(10,10,1,2))
        @test isbanded(A)
        @test MemoryLayout(A) == TriangularLayout{'U','N'}(BandedColumnMajor())
        @test bandwidths(A) == bandwidths(BandedMatrix(A)) == (0,2)
        @test bandwidth(A,2) == 2
        @test BandedMatrix(A) == A
        @test A[2,1] == 0

        x=rand(10)
        @test A*x ≈ BandedMatrix(A)*x ≈ Matrix(A)*x
        @test all(A*x .=== lmul!(A, copy(x)) .=== (similar(x) .= Mul(A,x)) .=== copyto!(similar(x), Mul(A,copy(x))) .===
                    BandedMatrices.tbmv!('U', 'N', 'N', 10, 2, parent(A).data, copy(x)))

        @test A\x ≈ Matrix(A) \ x ≈ BandedMatrix(A) \ x
        @test all((A \ x) .=== ldiv!(A, copy(x)) .=== copyto!(similar(x), Ldiv(A, x)) .=== (similar(x) .= Ldiv(A, x)) .===
                    BandedMatrices.tbsv!('U', 'N', 'N', 10, 2, parent(A).data, copy(x)))

        A = UnitUpperTriangular(brand(10,10,1,2))
        @test isbanded(A)
        @test MemoryLayout(A) == TriangularLayout{'U','U'}(BandedColumnMajor())
        @test bandwidths(A) == bandwidths(BandedMatrix(A)) == (0,2)
        @test bandwidth(A,2) == 2
        @test BandedMatrix(A) == A
        @test A[2,1] == 0
        @test A[2,2] == 1

        x=rand(10)
        @test A*x ≈ Matrix(A)*x
        @test all(A*x .=== lmul!(A, copy(x)) .=== (similar(x) .= Mul(A,x)) .=== copyto!(similar(x), Mul(A,copy(x))) .===
                    BandedMatrices.tbmv!('U', 'N', 'U', 10, 2, parent(A).data, copy(x)))

        @test A\x ≈ Matrix(A) \ x ≈ BandedMatrix(A) \ x
        @test all((A \ x) .=== ldiv!(A, copy(x)) .=== copyto!(similar(x), Ldiv(A, x)) .=== (similar(x) .= Ldiv(A, x)) .===
                    BandedMatrices.tbsv!('U', 'N', 'U', 10, 2, parent(A).data, copy(x)))
    end
    @testset "Lower" begin
        A = LowerTriangular(brand(10,10,1,2))
        @test isbanded(A)
        @test MemoryLayout(A) == TriangularLayout{'L','N'}(BandedColumnMajor())
        @test bandwidths(A) == bandwidths(BandedMatrix(A)) == (1,0)
        @test bandwidth(A,2) == 0
        @test BandedMatrix(A) == A
        @test A[1,2] == 0

        x=rand(10)
        @test A*x ≈ Matrix(A)*x
        @test all(A*x .=== lmul!(A, copy(x)) .=== copyto!(similar(x), Mul(A,copy(x))) .=== (similar(x) .= Mul(A,x)) .===
                    BandedMatrices.tbmv!('L', 'N', 'N', 10, 1, view(parent(A).data, 3:4,:), copy(x)))

        @test A\x ≈ Matrix(A) \ x ≈ BandedMatrix(A) \ x
        @test all((A \ x) .=== ldiv!(A, copy(x)) .=== copyto!(similar(x), Ldiv(A, x)) .=== (similar(x) .= Ldiv(A, x)) .===
                    BandedMatrices.tbsv!('L', 'N', 'N', 10, 1, view(parent(A).data, 3:4,:), copy(x)))

        A = UnitLowerTriangular(brand(10,10,1,2))
        @test isbanded(A)
        @test MemoryLayout(A) == TriangularLayout{'L','U'}(BandedColumnMajor())
        @test bandwidths(A) == bandwidths(BandedMatrix(A)) == (1,0)
        @test bandwidth(A,2) == 0
        @test BandedMatrix(A) == A
        @test A[1,2] == 0
        @test A[2,2] == 1

        x=rand(10)
        @test A*x ≈ Matrix(A)*x
        @test all(A*x .=== lmul!(A, copy(x)) .=== copyto!(similar(x), Mul(A,copy(x))) .=== (similar(x) .= Mul(A,x)) .===
                    BandedMatrices.tbmv!('L', 'N', 'U', 10, 1, view(parent(A).data, 3:4,:), copy(x)))

        @test A\x ≈ Matrix(A) \ x ≈ BandedMatrix(A) \ x
        @test all((A \ x) .=== ldiv!(A, copy(x)) .=== copyto!(similar(x), Ldiv(A, x)) .=== (similar(x) .= Ldiv(A, x)) .===
                    BandedMatrices.tbsv!('L', 'N', 'U', 10, 1, view(parent(A).data, 3:4,:), copy(x)))
    end
end


text:
using JuliaFormatter

handle("format") do data
  @destruct [
    text,
    dir || ".",
    indent || 4,
    margin || 92,
  ] = data

  options = if (config_path = search_up_file(JuliaFormatter.CONFIG_FILE_NAME, dir)) === nothing
    JuliaFormatter.kwargs((indent = indent, margin = margin)) # fallback
  else
    JuliaFormatter.kwargs(JuliaFormatter.parse_config(config_path))
  end

  try
    return (formattedtext = format_text′(text; options...),)
  catch err
    if err isa ErrorException && startswith(err.msg, "Parsing error")
      return (error = """
      Juno's formatter expects a text that can be parsed into a valid Julia expression.
      The given text below couldn't be parsed correctly:
      ```
      $(replace(strip(text), "```" => "\`\`\`"))
      ```
      """,)
    end
    return (error = """\n$(string(err))\n""",)
  end
end

const FORMAT_TEXT_KWARGS = @static if isdefined(JuliaFormatter, :Options)
  fieldnames(JuliaFormatter.Options)
else
  # HACK: extract keyword arguments of `format_text`; `Base.kwarg_decl` isn't available as of v1.0
  try
    s = filter!(collect(methods(format_text))) do m
      return m.module == JuliaFormatter &&
        length(m.sig.types) === 2
    end |> first |> string
    m = match(r";(.+)\)", s)
    m === nothing ? Symbol[] : Symbol.(strip.(split(m.captures[1]), Ref((' ', ','))))
  catch
    Symbol[]
  end
end

isempty(FORMAT_TEXT_KWARGS) && @warn """
Atom.jl failed to recognize the keyword arguments of `JuliaFormatter.format_text`.
The formatting options won't work when you format code via Juno's formatting interface.
"""

function format_text′(text; options...)
  # only pass valid keyword arguments to `format_text`
  valid_option_dict = filter(options) do (k, _)
    @static isempty(FORMAT_TEXT_KWARGS) ? false : in(k,FORMAT_TEXT_KWARGS)
  end
  return format_text(text; JuliaFormatter.kwargs(valid_option_dict)...)
end


text:
data = [554.4255448860487 252.25695182609456;
    563.2198518844277 266.393133656879;
    529.4069191555953  293.8378723522843;
    540.4542393161609 305.7810697735044;
    529.979807146737 316.8126082331031;
    504.904046118169 337.4825804687354;
    481.8704189162051 364.2838371680541;
    444.52860559075106 363.1246963316071;
    399.2429477714536 377.5681669353429;
    389.3711948977463 385.5186736607949;
    349.4010115271496 386.2628649432312;
    296.5840933162226 399.73317608469233;
    255.11250601488572 395.1411289783602;
    231.89205825187307 381.61074589981473;
    182.90013818617746 384.047826837435;
    144.59336259440926 391.4128662876713;
    97.60448452233265 391.35548699175257;
    76.28734052405164 369.8323364160187;
    25.345944215923343 367.78769391856787;
    -2.5177280792243053 339.56485858969074;
    -4.3254400982999766 305.06389938514843;
    -29.074863473090797 319.05942892395166;
    -48.73339406796903 288.8232699112716;
    -85.21858392682377 262.78052469826156;
    -77.7559980456105 255.63059999535096;
    -63.96460001891381 240.5558431574499;
    -47.50679886929984 221.79850196104366;
    -67.29391840704433 209.6724162607794;
    -23.86911438928088 176.9721535710241;
    -17.624006835223113 174.24367926036066;
    31.38415275933525 142.62191100176753;
    46.11460906558086 128.39144744279602;
    65.38963556066517 126.90848784795256;
    116.43356672461559 125.50674998521659;
    135.24857840307698 109.847540360864;
    212.24483407970993 105.53786425855019;
    227.26351500381813 101.51465346090531;
    255.18532643477042 107.83975623109346;
    306.56565641797596 100.03580557868527;
    355.07952555897765 143.5543623673256;
    376.5664452416278 116.9383797341007;
    416.266045280784 102.4712728975143;
    451.06342651230636 144.36320327683816;
    475.96962498992485  153.3519382363760;
    507.98479900085863 186.347765271335;
    522.3993024410767 181.1256514766796;
    544.0355186255582 222.30892095626606;
    561.1263519611979 205.47120976368097;
    581.8305025046524 241.94356048025762;
    546.5064585867074 232.51223747541997];


text:
function FieldUnivariateDerivative()
    return FieldUnivariateDerivative(())
end

function get_derivative(obj::FieldUnivariateDerivative, arg0::jint)
    return jcall(obj, "getDerivative", RealFieldElement, (jint,), arg0)
end

function get_free_parameters(obj::FieldUnivariateDerivative)
    return jcall(obj, "getFreeParameters", jint, ())
end

function get_partial_derivative(obj::FieldUnivariateDerivative, arg0::Vector{jint})
    return jcall(obj, "getPartialDerivative", RealFieldElement, (Vector{jint},), arg0)
end

function to_derivative_structure(obj::FieldUnivariateDerivative)
    return jcall(obj, "toDerivativeStructure", FieldDerivativeStructure, ())
end


text:
VERSION < v"0.4.0" && __precompile__()
module CoolProp

export PropsSI, PhaseSI, get_global_param_string, get_parameter_information_string,get_fluid_param_string,set_reference_stateS, get_param_index, get_input_pair_index, set_config_string, F2K, K2F, HAPropsSI, AbstractState_factory, AbstractState_free, AbstractState_set_fractions, AbstractState_update, AbstractState_specify_phase, AbstractState_unspecify_phase, AbstractState_keyed_output, AbstractState_output, AbstractState_update_and_common_out, AbstractState_update_and_1_out, AbstractState_update_and_5_out, AbstractState_set_binary_interaction_double, AbstractState_set_fluid_parameter_double

# Check the current Julia version to make this Julia 0.4 code compatible with older version
if VERSION <= VersionNumber(0,4)
  typealias UInt8 Uint8
  typealias Ref Ptr
  errcode = Array(Clong, 1)
  typealias AbstractString String
else
  errcode = Ref{Clong}(0)
end

const buffer_length = 10000
message_buffer = Array(UInt8, buffer_length)

# ---------------------------------
#        High-level functions
# ---------------------------------

# CoolProp::Props1SI(std::string, std::string)
function PropsSI(FluidName::AbstractString, Output::AbstractString)
  val = ccall( (:Props1SI, "CoolProp"), Cdouble, (Ptr{UInt8},Ptr{UInt8}), FluidName,Output)
  if val == Inf
    error("CoolProp: ", get_global_param_string("errstring"))
  end
  return val
end

# CoolProp::PropsSI(const std::string &, const std::string &, double, const std::string &, double, const std::string&)
function PropsSI(Output::AbstractString, Name1::AbstractString, Value1::Real, Name2::AbstractString, Value2::Real, Fluid::AbstractString)
  val = ccall( (:PropsSI, "CoolProp"), Cdouble, (Ptr{UInt8},Ptr{UInt8},Float64,Ptr{UInt8},Float64,Ptr{UInt8}), Output,Name1,Value1,Name2,Value2,Fluid)
  if val == Inf
    error("CoolProp: ", get_global_param_string("errstring"))
  end
  return val
end

# CoolProp::PhaseSI(const std::string &, double, const std::string &, double, const std::string&)
function PhaseSI(Name1::AbstractString, Value1::Real, Name2::AbstractString, Value2::Real, Fluid::AbstractString)
  val = ccall( (:PhaseSI, "CoolProp"), Int32, (Ptr{UInt8},Float64,Ptr{UInt8},Float64,Ptr{UInt8}, Ptr{UInt8}, Int), Name1,Value1,Name2,Value2,Fluid,message_buffer::Array{UInt8,1},buffer_length)
  val = bytestring(convert(Ptr{UInt8}, pointer(message_buffer::Array{UInt8,1})))
  if val == ""
    error("CoolProp: ", get_global_param_string("errstring"))
  end
  return val
end

# CoolProp::get_global_param_string
function get_global_param_string(Key::AbstractString)
  val = ccall( (:get_global_param_string, "CoolProp"), Clong, (Ptr{UInt8},Ptr{UInt8},Int), Key,message_buffer::Array{UInt8,1},buffer_length)
  if val == 0
    error("CoolProp: ", get_global_param_string("errstring"))
  end
  return bytestring(convert(Ptr{UInt8}, pointer(message_buffer::Array{UInt8,1})))
end

# CoolProp::get_parameter_information_string
function get_parameter_information_string(Key::AbstractString,OutType::AbstractString)
  message_buffer[1:length(OutType)+1] = [OutType.data; 0x00]
  val = ccall( (:get_parameter_information_string, "CoolProp"), Clong, (Ptr{UInt8},Ptr{UInt8},Int), Key,message_buffer::Array{UInt8,1},buffer_length)
  if val == 0
    error("CoolProp: ", get_global_param_string("errstring"))
  end
  return bytestring(convert(Ptr{UInt8}, pointer(message_buffer::Array{UInt8,1})))
end
function get_parameter_information_string(Key::AbstractString)
  return get_parameter_information_string(Key,"long")
end

# CoolProp::get_mixture_binary_pair_data
# Not valid yet
#function get_mixture_binary_pair_data(CAS1::AbstractString,CAS2::AbstractString,Key::AbstractString)
#  val = ccall( (:get_mixture_binary_pair_data, "CoolProp"), Clong, (Ptr{UInt8},Ptr{UInt8},Ptr{UInt8}), CAS1,CAS2,Key)
#  return val
#end

# CoolProp::get_fluid_param_string
function get_fluid_param_string(fluid::AbstractString,param::AbstractString)
  val = ccall( (:get_fluid_param_string, "CoolProp"), Clong, (Ptr{UInt8},Ptr{UInt8},Ptr{UInt8},Int), fluid,param,message_buffer::Array{UInt8,1},buffer_length)
  if val == 0
    error("CoolProp: ", get_global_param_string("errstring"))
  end
  return bytestring(convert(Ptr{UInt8}, pointer(message_buffer::Array{UInt8,1})))
end

# CoolProp::set_reference_stateS
function set_reference_stateS(Ref::AbstractString, reference_state::AbstractString)
  val = ccall( (:set_reference_stateS, "CoolProp"), Cint, (Ptr{UInt8},Ptr{UInt8}), Ref,reference_state)
  if val == 0
    error("CoolProp: ", get_global_param_string("errstring"))
  end
  return val
end

# Get the index for a parameter "T", "P", etc.
# returns the index as a long.
function get_param_index(param::AbstractString)
  val = ccall( (:get_param_index, "CoolProp"), Clong, (Ptr{UInt8},), param)
  if val == -1
    error("CoolProp: Unknown parameter: ", param)
  end
  return val
end

# Get the index for an input pair for AbstractState.update function
# returns the index as a long.
function get_input_pair_index(param::AbstractString)
  val = ccall( (:get_input_pair_index, "CoolProp"), Clong, (Ptr{UInt8},), param)
  if val == -1
    error("CoolProp: Unknown input pair: ", param)
  end
  return val
end

# Set configuration string
function set_config_string(key::AbstractString,val::AbstractString)
  ccall( (:set_config_string, "CoolProp"), Void, (Ptr{UInt8},Ptr{UInt8}), key,val)
  return get_global_param_string("errstring")
end

# Get the debug level
# returns level The level of the verbosity for the debugging output (0-10) 0: no debgging output
function get_debug_level()
  ccall( (:get_debug_level, "CoolProp"), Cint, () )
end

# Set the debug level
# param level The level of the verbosity for the debugging output (0-10) 0: no debgging output
function set_debug_level(level::Int)
  ccall( (:set_debug_level, "CoolProp"), Void, (Cint,), level)
end

function F2K(TF::Real)
  return ccall( (:F2K, "CoolProp"), Cdouble, (Cdouble,), TF)
end

function K2F(TK::Real)
  return ccall( (:K2F, "CoolProp"), Cdouble, (Cdouble,), TK)
end

# ---------------------------------
#        Humid Air Properties
# ---------------------------------

function HAPropsSI(Output::AbstractString, Name1::AbstractString, Value1::Real, Name2::AbstractString, Value2::Real, Name3::AbstractString, Value3::Real)
  val = ccall( (:HAPropsSI, "CoolProp"), Cdouble, (Ptr{UInt8},Ptr{UInt8},Float64,Ptr{UInt8},Float64,Ptr{UInt8},Float64), Output,Name1,Value1,Name2,Value2,Name3,Value3)
  if val == Inf
    error("CoolProp: ", get_global_param_string("errstring"))
  end
  return val
end

# ---------------------------------
#        Low-level access
# ---------------------------------

# Generate an AbstractState instance, return an integer handle to the state class generated to be used in the other low-level accessor functions
# param backend The backend you will use, "HEOS", "REFPROP", etc.
# param fluids '&' delimited list of fluids
# return A handle to the state class generated
function AbstractState_factory(backend::AbstractString, fluids::AbstractString)
  AbstractState = ccall( (:AbstractState_factory, "CoolProp"), Clong, (Ptr{UInt8},Ptr{UInt8},Ref{Clong},Ptr{UInt8},Clong), backend,fluids,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return AbstractState
end

# Release a state class generated by the low-level interface wrapper
# param handle The integer handle for the state class stored in memory
function AbstractState_free(handle::Clong)
  ccall( (:AbstractState_free, "CoolProp"), Void, (Clong,Ref{Clong},Ptr{UInt8},Clong), handle,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end

# Set the fractions (mole, mass, volume) for the AbstractState
# param handle The integer handle for the state class stored in memory
# param fractions The array of fractions
function AbstractState_set_fractions(handle::Clong,fractions::Array)
  ccall( (:AbstractState_set_fractions, "CoolProp"), Void, (Clong,Ptr{Cdouble},Clong,Ref{Clong},Ptr{UInt8},Clong), handle,fractions,length(fractions),errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end

# Update the state of the AbstractState
# param handle The integer handle for the state class stored in memory
# param input_pair The integer value for the input pair obtained from get_input_pair_index(param::AbstractString)
# param value1 The first input value
# param value2 The second input value
function AbstractState_update(handle::Clong,input_pair::Clong,value1::Real,value2::Real)
  ccall( (:AbstractState_update, "CoolProp"), Void, (Clong,Clong,Cdouble,Cdouble,Ref{Clong},Ptr{UInt8},Clong), handle,input_pair,value1,value2,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end
function AbstractState_update(handle::Clong,input_pair::AbstractString,value1::Real,value2::Real)
  AbstractState_update(handle::Clong,get_input_pair_index(input_pair),value1::Real,value2::Real)
  return nothing
end

# Specify the phase to be used for all further calculations
# handle The integer handle for the state class stored in memory
# phase The string with the phase to use
# errcode The errorcode that is returned (0 = no error, !0 = error)
# message_buffer A buffer for the error code
# buffer_length The length of the buffer for the error code
function AbstractState_specify_phase(handle::Clong,phase::AbstractString)
  ccall( (:AbstractState_specify_phase, "CoolProp"), Void, (Clong,Ptr{UInt8},Ref{Clong},Ptr{UInt8},Clong), handle,phase,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end

# Unspecify the phase to be used for all further calculations
# handle The integer handle for the state class stored in memory
# errcode The errorcode that is returned (0 = no error, !0 = error)
# message_buffer A buffer for the error code
# buffer_length The length of the buffer for the error code
function AbstractState_unspecify_phase(handle::Clong)
  ccall( (:AbstractState_unspecify_phase, "CoolProp"), Void, (Clong,Ref{Clong},Ptr{UInt8},Clong), handle,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end

# Get an output value from the AbstractState using an integer value for the desired output value
# param handle The integer handle for the state class stored in memory
# param param The integer value for the parameter you want
function AbstractState_keyed_output(handle::Clong, param::Clong)
  output = ccall( (:AbstractState_keyed_output, "CoolProp"), Cdouble, (Clong,Clong,Ref{Clong},Ptr{UInt8},Clong), handle,param,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  elseif output == -Inf
    error("CoolProp: no correct state has been set with AbstractState_update")
  end
  return output
end
function AbstractState_output(handle::Clong, param::AbstractString)
  return AbstractState_keyed_output(handle, get_param_index(param))
end

# Update the state of the AbstractState and get an output value five common outputs (temperature, pressure, molar density, molar enthalpy and molar entropy) from the AbstractState using pointers as inputs and output to allow array computation.
# handle The integer handle for the state class stored in memory
# input_pair The integer value for the input pair obtained from get_input_pair_index
# value1 The pointer to the array of the first input parameters
# value2 The pointer to the array of the second input parameters
# length The number of elements stored in the arrays (both inputs and outputs MUST be the same length)
# T The pointer to the array of temperature
# p The pointer to the array of pressure
# rhomolar The pointer to the array of molar density
# hmolar The pointer to the array of molar enthalpy
# smolar The pointer to the array of molar entropy
function AbstractState_update_and_common_out{R1<:Real,R2<:Real,F<:AbstractFloat}(handle::Clong, input_pair::Clong, value1::Array{R1}, value2::Array{R2}, length::Real, T::Array{F}, p::Array{F}, rhomolar::Array{F}, hmolar::Array{F}, smolar::Array{F})
  ccall( (:AbstractState_update_and_common_out, "CoolProp"), Void, (Clong,Clong,Ref{Cdouble},Ref{Cdouble},Clong,Ref{Cdouble},Ref{Cdouble},Ref{Cdouble},Ref{Cdouble},Ref{Cdouble},Ref{Clong},Ptr{UInt8},Clong), handle,input_pair,value1,value2,length,T,p,rhomolar,hmolar,smolar,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end
function AbstractState_update_and_common_out{R1<:Real,R2<:Real,F<:AbstractFloat}(handle::Clong, input_pair::AbstractString, value1::Array{R1}, value2::Array{R2}, length::Real, T::Array{F}, p::Array{F}, rhomolar::Array{F}, hmolar::Array{F}, smolar::Array{F})
  AbstractState_update_and_common_out(handle, get_input_pair_index(input_pair), value1, value2, length, T, p, rhomolar, hmolar, smolar)
  return nothing
end

# Update the state of the AbstractState and get one output value (temperature, pressure, molar density, molar enthalpy and molar entropy) from the AbstractState using pointers as inputs and output to allow array computation.
# handle The integer handle for the state class stored in memory
# input_pair The integer value for the input pair obtained from get_input_pair_index
# value1 The pointer to the array of the first input parameters
# value2 The pointer to the array of the second input parameters
# length The number of elements stored in the arrays (both inputs and outputs MUST be the same length)
# output The indice for the output desired
# out The pointer to the array for output
function AbstractState_update_and_1_out{R1<:Real,R2<:Real,F<:AbstractFloat}(handle::Clong, input_pair::Clong, value1::Array{R1}, value2::Array{R2}, length::Real, output::Clong, out::Array{F})
  ccall( (:AbstractState_update_and_1_out, "CoolProp"), Void, (Clong,Clong,Ref{Cdouble},Ref{Cdouble},Clong,Clong,Ref{Cdouble},Ref{Clong},Ptr{UInt8},Clong), handle,input_pair,value1,value2,length,output,out,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end
function AbstractState_update_and_1_out{R1<:Real,R2<:Real,F<:AbstractFloat}(handle::Clong, input_pair::AbstractString, value1::Array{R1}, value2::Array{R2}, length::Real, output::AbstractString, out::Array{F})
  AbstractState_update_and_1_out(handle, get_input_pair_index(input_pair), value1, value2, length, get_param_index(output), out)
  return nothing
end

# Update the state of the AbstractState and get an output value five common outputs (temperature, pressure, molar density, molar enthalpy and molar entropy) from the AbstractState using pointers as inputs and output to allow array computation.
# handle The integer handle for the state class stored in memory
# input_pair The integer value for the input pair obtained from get_input_pair_index
# value1 The pointer to the array of the first input parameters
# value2 The pointer to the array of the second input parameters
# length The number of elements stored in the arrays (both inputs and outputs MUST be the same length)
# outputs The 5-element vector of indices for the outputs desired
# out1 The pointer to the array for the first output
# out2 The pointer to the array for the second output
# out3 The pointer to the array for the third output
# out4 The pointer to the array for the fourth output
# out5 The pointer to the array for the fifth output
function AbstractState_update_and_5_out{R1<:Real,R2<:Real,F<:AbstractFloat}(handle::Clong, input_pair::Clong, value1::Array{R1}, value2::Array{R2}, length::Real, outputs::Array{Clong}, out1::Array{F}, out2::Array{F}, out3::Array{F}, out4::Array{F}, out5::Array{F})
  ccall( (:AbstractState_update_and_5_out, "CoolProp"), Void, (Clong,Clong,Ref{Cdouble},Ref{Cdouble},Clong,Ref{Clong},Ref{Cdouble},Ref{Cdouble},Ref{Cdouble},Ref{Cdouble},Ref{Cdouble},Ref{Clong},Ptr{UInt8},Clong), handle,input_pair,value1,value2,length,outputs,out1,out2,out3,out4,out5,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end
function AbstractState_update_and_5_out{R1<:Real,R2<:Real,S<:AbstractString,F<:AbstractFloat}(handle::Clong, input_pair::AbstractString, value1::Array{R1}, value2::Array{R2}, length::Real, outputs::Array{S}, out1::Array{F}, out2::Array{F}, out3::Array{F}, out4::Array{F}, out5::Array{F})
  outputs_key = Array(Clong,5)
  for k = 1:5
    outputs_key[k] = get_param_index(outputs[k])
  end
  AbstractState_update_and_5_out(handle, get_input_pair_index(input_pair), value1, value2, length, outputs_key, out1, out2, out3, out4, out5)
  return nothing
end

# Set binary interraction parrameter for mixtures
# handle The integer handle for the state class stored in memory
# i indice of the first fluid of the binary pair
# j indice of the second fluid of the binary pair
# parameter string wit the name of the parameter
# value the value of the binary interaction parameter
function AbstractState_set_binary_interaction_double(handle::Clong,i::Int, j::Int, parameter::AbstractString, value::Cdouble)
  ccall( (:AbstractState_set_binary_interaction_double, "CoolProp"), Void, (Clong,Clong,Clong,Ptr{UInt8},Cdouble,Ref{Clong},Ptr{UInt8},Clong), handle,i,j,parameter,value,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end

# Set some fluid parameter (ie volume translation for cubic)
# handle The integer handle for the state class stored in memory
# i indice of the fluid the parramter should be applied too (for mixtures)
# parameter string wit the name of the parameter
# value the value of the parameter
function AbstractState_set_fluid_parameter_double(handle::Clong, i::Int, parameter::AbstractString, value::Cdouble)
  ccall( (:AbstractState_set_fluid_parameter_double, "CoolProp"), Void, (Clong,Clong,Ptr{UInt8},Cdouble,Ref{Clong},Ptr{UInt8},Clong), handle,i,parameter,value,errcode,message_buffer::Array{UInt8,1},buffer_length)
  if errcode[] != 0
    if errcode[] == 1
      error("CoolProp: ", bytestring(convert(Ptr{UInt8}, pointer(message_buffer))))
    elseif errcode[] == 2
      error("CoolProp: message buffer too small")
    else # == 3
      error("CoolProp: unknown error")
    end
  end
  return nothing
end

end #module

max_stars_repo_name: BENGAL-TIGER/CoolPropMDA

max_issues_repo_name: BENGAL-TIGER/CoolPropMDA

max_forks_repo_name: BENGAL-TIGER/CoolPropMDA


text:
# IJulia hooks for displaying plots with RCall

# TODO: create a special graphics device. This would allow us to not accidently close devices opened by users, and display plots immediately as they appear.

ijulia_mime = nothing

"""
Set options for R plotting with IJulia.

The first argument should be a MIME object: currently supported are
* `MIME("image/png")` [default]
* `MIME("image/svg+xml")`

The remaining arguments (keyword only) are passed to the appropriate R graphics
device: see the relevant R help for details.
"""
function ijulia_setdevice(m::MIME;kwargs...)
    global ijulia_mime
    rcall(:options,rcalljl_device=rdevicename(m))
    ijulia_mime = m
    nothing
end
ijulia_setdevice(m::MIME"image/png") = ijulia_setdevice(m,width=6*72,height=5*72)
ijulia_setdevice(m::MIME"image/svg+xml") = ijulia_setdevice(m,width=6,height=5)

rdevicename(m::MIME"image/png") = :png
rdevicename(m::MIME"image/svg+xml") = :svg

function ijulia_displayfile(m::MIME"image/png", f)
    open(f) do f
        d = readbytes(f)
        display(m,d)
    end
end
function ijulia_displayfile(m::MIME"image/svg+xml", f)
    # R svg images use named defs, which cause problem when used inline, see
    # https://github.com/jupyter/notebook/issues/333
    # we get around this by renaming the elements.
    open(f) do f
        r = randstring()
        d = Compat.readstring(f)
        d = replace(d,"id=\"glyph","id=\"glyph"*r)
        d = replace(d,"href=\"#glyph","href=\"#glyph"*r)
        display(m,d)
    end
end

"""
Called after cell evaluation.
Closes graphics device and displays files in notebook.
"""
function ijulia_displayplots()
    if rcopy(Int,"dev.cur()") != 1
        rcopy(Int,"dev.off()")
        for fn in sort(readdir(ijulia_file_dir))
            ffn = joinpath(ijulia_file_dir,fn)
            ijulia_displayfile(ijulia_mime,ffn)
            rm(ffn)
        end
    end
end

# cleanup after error
function ijulia_cleanup()
    if rcopy(Int,"dev.cur()") != 1
        rcopy(Int,"dev.off()")
    end
    for fn in readdir(ijulia_file_dir)
        ffn = joinpath(ijulia_file_dir,fn)
        rm(ffn)
    end
end

function ijulia_init()
    global const ijulia_file_dir = mktempdir()
    ijulia_file_fmt = joinpath(ijulia_file_dir,"rij_%03d")
    rcall(:options,rcalljl_filename=ijulia_file_fmt)

    reval("options(device = function(filename=getOption('rcalljl_filename'),...) getOption('rcalljl_device')(filename,...))")

    Main.IJulia.push_postexecute_hook(ijulia_displayplots)
    Main.IJulia.push_posterror_hook(ijulia_cleanup)
    ijulia_setdevice(MIME"image/png"())
end


text:
"""
    movie(main; pre=nothing, post=nothing, kwargs...)

Create animation sequences and movies.

Full option list at [`movie`]($(GMTdoc)movie.html)

Parameters
----------

- **main** :: [Type => Str]

    Name of a stand-alone GMT.jl script that makes the frame-dependent plot.``
- **C** | **canvas** :: [Type => Str]

    Specify the canvas size used when composing the movie frames.
    ($(GMTdoc)movie.html#c)
- **N** | **name** :: [Type => Str]

    Determines the name of a sub-directory with frame images as well as the final movie file.
    ($(GMTdoc)movie.html#n)
- **T** | **frames** :: [Type => Int | Str]

    Either specify how many image frames to make or supply a file with a set of parameters, one record per frame (i.e., row).
    ($(GMTdoc)movie.html#t)
- **pre** :: [Type => Str]

	The optional *backgroundscript* file (a GMT.jl script) can be used one or two purposes: (1) It may create files
	(such as timefile) that will be needed by mainscript to make the movie, and (2) It may make a static background
	plot that should form the background for all frames.
    ($(GMTdoc)movie.html#s)
- **post** :: [Type => Str]

    The optional *foregroundscript* file (a GMT.jl script) can be used to make a static foreground plot that should be overlain on all frames.
    ($(GMTdoc)movie.html#s)
- **A** | **gif** :: [Type => Str]		``Args = [+l[n]][+sstride]``

    Build an animated GIF file. You may specify if the movie should play more than once and if so append how many times to repeat.
    ($(GMTdoc)movie.html#a)
- **D** | **frame_rate** :: [Type => Int]

    Set the display frame rate in frames per seconds for the final animation [24].
    ($(GMTdoc)movie.html#d)
- **E** | **titlepage** :: [Type => Str | tuple]

    Give a titlepage script that creates a static title page for the movie [no title].
    ($(GMTdoc)movie.html#e)
- **F** | **format** :: [Type => Str]	``Arg = format[+ooptions]``

    Set the format of the final video product. Choose either mp4 (MPEG-4 movie) or webm (WebM movie).
    ($(GMTdoc)movie.html#f)
- **G** | **fill** :: [Type => Str | Int | Touple]

    Set the canvas color or fill before plotting commences [none].
    ($(GMTdoc)movie.html#g)
- **H** | **scale** :: [Type => Number]

    Temporarily increases the effective dots-per-unit by factor, rasterizes the frame, then downsamples the image by the same factor at the end.
    ($(GMTdoc)movie.html#h)
- **I** | **includefile** :: [Type => Str]

    Insert the contents of includefile into the movie_init script that is accessed by all movie scripts.
    ($(GMTdoc)movie.html#i)
- **K** | **fading** :: [Type => Number | Str | Tuple]	``Arg = [+f[i|o]fade[s]][+gfill][+p] ]``

    Add fading in and out for the main animation sequence [no fading].
    ($(GMTdoc)movie.html#k)
- **L** | **label** :: [Type => Str]

    Automatic labeling of individual frames.
    ($(GMTdoc)movie.html#l)
- **M** | **cover_page** :: [Type => number]	``Arg = frame[,format]``

    Select a single frame for a cover page. This frame will be written to the current directory.
    ($(GMTdoc)movie.html#m)
- **P** | **progress** :: [Type => Str | Tuple]

    Automatic placement of progress indicator(s).
    ($(GMTdoc)movie.html#p)
- **Q** | **debug** :: [Type => Bool | Str]		``Arg = [s]``

    Debugging: Leave all files and directories we create behind for inspection.
    ($(GMTdoc)movie.html#q)
- **Sb** | **background** :: [Type => Str | Function]

    Optional background script or bg PS file [GMT6.1 only]
    ($(GMTdoc)movie.html#s)
- **Sf** | **foreground** :: [Type => Str | Function]

    Optional foreground script or fg PS file [GMT6.1 only]
    ($(GMTdoc)movie.html#s)
- **W** | **work_dir** :: [Type => Str]

	By default, all temporary files and frame PNG file are built in the subdirectory prefix set via **name**.
	You can override that by giving another workdir as a relative or full directory path.
    ($(GMTdoc)movie.html#w)
- **Z** | **clean** :: [Type => Bool]

    Erase the entire **name** directory after assembling the final movie [Default leaves directory with all images.
    ($(GMTdoc)movie.html#z)
- $(GMT.opt_V)
- $(GMT.opt_x)
"""
function movie(main; pre=nothing, post=nothing, kwargs...)

	d = KW(kwargs)
	help_show_options(d)		# Check if user wants ONLY the HELP mode

	(!isa(main, Function) && !isa(main, String)) && error("A main script is mandatory")
	((mainName = jl_sc_2_shell_sc(main, "main_script")) === nothing) && error("Main script has nothing useful")

	cmd, = parse_common_opts(d, "", [:V_params :x])
	cmd = parse_these_opts(cmd, d, [[:C :canvas], [:N :name]])
	cmd = parse_these_opts(cmd, d, [[:D :frame_rate], [:H :scale], [:I :includefile], [:L :label], [:M :cover_page],
	                                [:Q :debug], [:W :work_dir], [:Z :clean]])
	cmd = add_opt(d, cmd, "A", [:A :gif], (loop="+l", stride="+s"))
	cmd = add_opt(d, cmd, "E", [:E :titlepage], (title=("",arg2str,1), duration="+d", fade="+f", fill=("+g", add_opt_fill)))
	cmd = add_opt(d, cmd, "F", [:F :format], (format=("",arg2str,1), transparent="_+t", options="+o"))
	cmd = add_opt(d, cmd, "G", [:G :fill], (fill=("",add_opt_fill,1), pen=("+p", add_opt_pen)))
	cmd = add_opt(d, cmd, "K", [:K :fading], (fade="+f", fill=("+g", add_opt_fill), preserve="_+p"))
	cmd = add_opt(d, cmd, "P", [:P :progress],
				  (indicator=("1", nothing, 1), annot="+a", font=("+f", font), justify="+j", offset=("+o", arg2str), width="+w", fill=("+g", add_opt_fill), Fill=("+G", add_opt_fill), pen=("+p", add_opt_pen), Pen=("+P", add_opt_pen)))
	cmd = add_opt(d, cmd, "T", [:T :frames],
				  (range=("", arg2str, 1), n_frames="_+n", nframes="_+n", first="+s", tag_width="+p", split_words="+w"))

	((val = find_in_dict(d, [:Sb :background])[1]) !== nothing) && (cmd = helper_fgbg(cmd, val, "bg_script", " -Sb"))
	((val = find_in_dict(d, [:Sf :foreground])[1]) !== nothing) && (cmd = helper_fgbg(cmd, val, "fg_script", " -Sf"))

	if (pre !== nothing && isa(pre, Function) || isa(pre, String))
		if ((preName = jl_sc_2_shell_sc(pre,  "pre_script"))  !== nothing)  cmd *= " -Sb" * preName  end
	end
	if (post !== nothing && isa(post, Function) || isa(post, String))
		if ((posName = jl_sc_2_shell_sc(post,  "pre_script"))  !== nothing)  cmd *= " -Sf" * posName  end
	end

	global cmds_history
	IamModern[1] = false; FirstModern[1] = false; convert_syntax[1] = false; cmds_history = [""]

	cmd = "movie " * mainName * cmd				# In any case we need this
	(dbg_print_cmd(d, cmd) !== nothing) && return cmd
	gmt(cmd)
end

# --------------------------------------------------------------------------------------------------
function helper_fgbg(cmd::String, val, sc_name::String, opt::String)
	# VAL is the contents of either -Sf or -Sb options
	# OPT = " -Sb" or " -Sf"
	if (isa(val, Function) || (isa(val, String) && endswith(val, ".jl")))
		((bg_sc = jl_sc_2_shell_sc(val, sc_name)) === nothing) && error("$sc_name script has nothing useful")
		cmd *= opt * bg_sc
	elseif (isa(val, String) && val != "")
		cmd *= opt * val
	end
	return cmd
end

# --------------------------------------------------------------------------------------------------
function jl_sc_2_shell_sc(name, name2::String)
	global cmds_history
	IamModern[1] = true; FirstModern[1] = true; convert_syntax[1] = true; cmds_history = [""]
	if (isa(name, String))
		include(name)	# This include plus the convert_syntax = true will put all cmds in 'name' into cmds_history
	else
		name()			# Run the function, which must be defined ...
	end
	fname = write_script(name2)
end

# -----------------------------------------------------------------------------------------------
function write_script(fname)
	if (cmds_history[1] != "")
		if (Sys.iswindows())  fname *= ".bat";	b = "%";	e = "%"
		else                  fname *= ".sh";	b = "\${";	e = "}"
		end
		par_list = ["MOVIE_DPU", "MOVIE_HEIGHT", "MOVIE_RATE", "MOVIE_NFRAMES", "MOVIE_FRAME", "MOVIE_TAG", "MOVIE_NAME", "MOVIE_WIDTH", "MOVIE_COL0", "MOVIE_COL1", "MOVIE_COL2", "MOVIE_COL4", "MOVIE_TEXT", "MOVIE_WORD0", "MOVIE_WORD1", "MOVIE_WORD2", "MOVIE_WORD3"]
		got_begin = false
		for cmd in cmds_history			# Check if we have a gmtbegin.
			if (occursin("gmtbegin", cmd))  got_begin = true;  break  end
		end
		fid = open(fname, "w")
		if (!got_begin) println(fid, "gmt begin")  end
		for cmd in cmds_history
			for par in par_list
				if (occursin(par, cmd))  cmd = replace(cmd, par => b * par * e)  end
			end
			println(fid, "\t gmt ",cmd)
		end
		if (!got_begin) println(fid, "gmt end")  end
		close(fid)
		return fname
	end
end


text:
using Base.Threads
mutable struct Seg_MicroTimeParaStruct
    StaticThreshold::Int # if equal to the typeMAxInt, the Static TH  does not be in  effect
    DynamicThreshold_CalTimePeriod::UInt ## in data Numbers # calculated from Seconds.seconds ,may be any time period ,between 10seconds and the cached data period(about 10 minutes above )

    DynamicThresHold_calCFactor::Int
    minTh::Int
    maxTh::Int
    microMergeTimePeriod::Int # in 0.426 seconds # calculated from :seconds * 0.426
    microFilterTimePeriod::Int # in 0.426 seconds # same as above
    function Seg_MicroTimeParaStruct()
        StaticThreshold= UInt( 0 )
        DynamicThreshold_CalTimePeriod=UInt(2*60) # about 1Minutes
        DynamicThresHold_calCFactor = 130 # about 1.3
        # dynamic_RTThreshold = Int(1500)
        microMergeTimePeriod = UInt(1 )
        microFilterTimePeriod = UInt(1)
        minTh=Int( 1000)
        maxTh=Int( 1000)
        new(StaticThreshold,DynamicThreshold_CalTimePeriod,DynamicThresHold_calCFactor, minTh,maxTh,
            microMergeTimePeriod, microFilterTimePeriod)
    end
end

mutable struct  Seg_MicroSpaceParaStruct
    microMergeSpaceLength::UInt # in Segment or  grain. Calculated from the space length and the segPermeters
    microFilterSpaceLength::UInt # in Segment   or  grain
    function Seg_MicroSpaceParaStruct()
        microMergeSpaceLength = UInt( 1 )
        microFilterSpaceLength = UInt( 2 )
        new(microMergeSpaceLength, microFilterSpaceLength)
    end
end

mutable struct  Seg_MacroSpaceParaStruct
    macroMaxSpaceLength::UInt # in Segment or  grain. Calculated from the space length and the segPermeters
    macroMinSpaceLength::UInt # in Segment   or  grain

    function Seg_MacroSpaceParaStruct()
        macroMaxSpaceLength = UInt( 100 )
        macroMinSpaceLength = UInt(2) #
        new(macroMaxSpaceLength, macroMinSpaceLength)
    end
end

mutable struct Seg_MacroTimeParaStruct
    macroMaxTimeInterval::UInt # in dataFrames
    macroMinTimeInterval::UInt # in  dataFrames
    function Seg_MacroTimeParaStruct()
        macroMaxTimeInterval= Int( 7 )
        macroMinTimeInterval=Int(3)
        new(macroMaxTimeInterval, macroMinTimeInterval)
    end
end

function getSegAlarmPara( SegAlarmParasDict::Array, SegID::Int)::NamedTuple
    try
        len1=length(SegAlarmParasDict )

        ret = SegAlarmParasDict[ SegID ];
        # println("---",SegID ," $len1 ,$ret ")
        return ret
    catch e
        println(":::$e===\r\n")
        println("-Error: SEgidout of range returned(1:8192) --",SegID )
	    exit();
       # return SegAlarmParasDict[0]
    end
end

function getSegStaticThPara(SegAlarmParasDict::Array, SegID::Int ) ::Int
 #   lock(glbAlarmParasdictLock)
    d1 = getSegAlarmPara( SegAlarmParasDict, SegID)
  #  unlock(glbAlarmParasdictLock)
    return d1.microtime.StaticThreshold
end

function getSegDynParaValue(SegAlarmParasDict::Array, SegID::Int )::Tuple
   # lock(glbAlarmParasdictLock)
        d1 = getSegAlarmPara( SegAlarmParasDict, SegID)
        a = (d1.microtime.DynamicThreshold_CalTimePeriod,d1.microtime.DynamicThresHold_calCFactor,d1.microtime.minTh,  d1.microtime.maxTh  )
   # unlock(glbAlarmParasdictLock)
    return a
end

function getSegMicroTimeParaValue(SegAlarmParasDict::Array, SegID::Int )::Tuple
  #  lock(glbAlarmParasdictLock)
        d1 = getSegAlarmPara( SegAlarmParasDict, SegID)
        a= (d1.microtime.microMergeTimePeriod, d1.microtime.microFilterTimePeriod)
    #unlock(glbAlarmParasdictLock)
    return a

end

function getSegMicroSpaceParaValue(SegAlarmParasDict::Array, SegID::Int ) ::Tuple
   # lock(glbAlarmParasdictLock)
        d1 = getSegAlarmPara( SegAlarmParasDict, SegID)
        a= (d1.microSpace.microMergeSpaceLength, d1.microSpace.microFilterSpaceLength)
   # unlock(glbAlarmParasdictLock)
    return a
end

function getSegMacroSpaceParaValue(SegAlarmParasDict::Array, SegID::Int ) ::Tuple
    #lock(glbAlarmParasdictLock)
        d1 = getSegAlarmPara( SegAlarmParasDict, SegID)
        a= (d1.macroSpace.macroMaxSpaceLength, d1.macroSpace.macroMinSpaceLength,)
    #unlock(glbAlarmParasdictLock)
    return a
end

function getSegMacroTimeParaValue(SegAlarmParasDict::Array, SegID::Int ) ::Tuple
    #lock(glbAlarmParasdictLock)
        d1 = getSegAlarmPara( SegAlarmParasDict, SegID)
        a= (d1.macroTime.macroMaxTimeInterval, d1.macroTime.macroMinTimeInterval,)
   # unlock(glbAlarmParasdictLock)
    return a
end

include("SegAlarmParas.jl")

max_stars_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_issues_repo_name: wangzhongtian/fiberAlarmAnalyseTool

max_forks_repo_name: wangzhongtian/fiberAlarmAnalyseTool


text:
Cassette.@context MetaheuristicLogging

function Cassette.overdub(ctx::MetaheuristicLogging, f::typeof(Polya.Δ), args...)
    logger = ctx.metadata
    ret = @timed f(args...)
    log!(logger, args[2], ret.value[2], ret.time)
    return ret.value
end

max_stars_repo_name: Michiel-VL/PolyaViz

max_issues_repo_name: Michiel-VL/PolyaViz


text:
using Test, ReferenceTests, BSON
using ParallelStencil
import ParallelStencil: @reset_parallel_stencil

ENV["USE_GPU"] = false
ENV["DO_VIZ"]  = false
ENV["DO_SAVE"] = false
ENV["DO_SAVE_VIZ"] = false
ENV["NX"] = 63
ENV["NY"] = 63
ENV["USE_RETURN"] = true

# Reference test using ReferenceTests.jl
comp(d1, d2) = keys(d1) == keys(d2) && all([ isapprox(v1, v2) for (v1,v2) in zip(values(d1), values(d2))])

## 2D tests
include("../scripts/Stokes2D.jl")
@reset_parallel_stencil()
indsx = Int.(ceil.(LinRange(1, length(xc), 12)))
indsy = Int.(ceil.(LinRange(1, length(yc), 12)))
d2d1  = Dict(:X=> xc[indsx], :P=>P[indsx,indsy])

include("../scripts/Stokes2D_ve.jl")
@reset_parallel_stencil()
indsx = Int.(ceil.(LinRange(1, length(xc), 12)))
indsy = Int.(ceil.(LinRange(1, length(yc), 12)))
d2d2  = Dict(:X=> xc[indsx], :P=>P[indsx,indsy])

include("../scripts/Stokes2D_ve_perf.jl")
@reset_parallel_stencil()
indsx = Int.(ceil.(LinRange(1, length(xc), 12)))
indsy = Int.(ceil.(LinRange(1, length(yc), 12)))
d2d3  = Dict(:X=> xc[indsx], :P=>P[indsx,indsy])

@testset "Reference-tests Stokes 2D" begin
    @test_reference "reftest-files/test_Stokes_2D_v.bson" d2d1 by=comp
    @test_reference "reftest-files/test_Stokes_2D_ve.bson" d2d2 by=comp
    @test_reference "reftest-files/test_Stokes_2D_ve_perf.bson" d2d3 by=comp
end

@reset_parallel_stencil()


text:
#  multi-value dictionary (multidict)

import Base: haskey, get, get!, getkey, delete!, pop!, empty!,
             insert!, getindex, length, isempty, start,
             next, done, keys, values, copy, similar,  push!,
             count, size, eltype

immutable MultiDict{K,V}
    d::Dict{K,Vector{V}}

    MultiDict() = new(Dict{K,Vector{V}}())
    MultiDict(kvs) = new(Dict{K,Vector{V}}(kvs))
    if VERSION >= v"0.4.0-dev+980"
        MultiDict(ps::Pair{K,Vector{V}}...) = new(Dict{K,Vector{V}}(ps...))
    end
end

MultiDict() = MultiDict{Any,Any}()
MultiDict(kv::Tuple{}) = MultiDict()
MultiDict(kvs) = multi_dict_with_eltype(kvs, eltype(kvs))

multi_dict_with_eltype{K,V}(kvs, ::Type{Tuple{K,Vector{V}}}) = MultiDict{K,V}(kvs)
function multi_dict_with_eltype{K,V}(kvs, ::Type{Tuple{K,V}})
    md = MultiDict{K,V}()
    for (k,v) in kvs
        insert!(md, k, v)
    end
    return md
end
multi_dict_with_eltype(kvs, t) = MultiDict{Any,Any}(kvs)

if VERSION >= v"0.4.0-dev+980"
    MultiDict{K,V<:AbstractArray}(ps::Pair{K,V}...) = MultiDict{K, eltype(V)}(ps)
    MultiDict{K,V}(kv::AbstractArray{Pair{K,V}})  = MultiDict(kv...)
    function  MultiDict{K,V}(ps::Pair{K,V}...)
        md = MultiDict{K,V}()
        for (k,v) in ps
            insert!(md, k, v)
        end
        return md
    end
end

## Functions

## Most functions are simply delegated to the wrapped Dict

@delegate MultiDict.d [ haskey, get, get!, getkey,
                        getindex, length, isempty, eltype,
                        start, next, done, keys, values]

sizehint!(d::MultiDict, sz::Integer) = (sizehint!(d.d, sz); d)
copy(d::MultiDict) = MultiDict(d)
similar{K,V}(d::MultiDict{K,V}) = MultiDict{K,V}()
==(d1::MultiDict, d2::MultiDict) = d1.d == d2.d
delete!(d::MultiDict, key) = (delete!(d.d, key); d)
empty!(d::MultiDict) = (empty!(d.d); d)

function insert!{K,V}(d::MultiDict{K,V}, k, v)
    if !haskey(d.d, k)
        d.d[k] = isa(v, AbstractArray) ? eltype(v)[] : V[]
    end
    if isa(v, AbstractArray)
        append!(d.d[k], v)
    else
        push!(d.d[k], v)
    end
    return d
end

function in{K,V}(pr::(Tuple{Any,Any}), d::MultiDict{K,V})
    k = convert(K, pr[1])
    v = get(d,k,Base.secret_table_token)
    (v !== Base.secret_table_token) && (isa(pr[2], AbstractArray) ? v == pr[2] : pr[2] in v)
end

function pop!(d::MultiDict, key, default)
    vs = get(d, key, Base.secret_table_token)
    if vs === Base.secret_table_token
        if default !== Base.secret_table_token
            return default
        else
            throw(KeyError(key))
        end
    end
    v = pop!(vs)
    (length(vs) == 0) && delete!(d, key)
    return v
end
pop!(d::MultiDict, key) = pop!(d, key, Base.secret_table_token)

if VERSION >= v"0.4.0-dev+980"
    push!(d::MultiDict, kv::Pair) = insert!(d, kv[1], kv[2])
    #push!(d::MultiDict, kv::Pair, kv2::Pair) = (push!(d.d, kv, kv2); d)
    #push!(d::MultiDict, kv::Pair, kv2::Pair, kv3::Pair...) = (push!(d.d, kv, kv2, kv3...); d)
end

push!(d::MultiDict, kv) = insert!(d, kv[1], kv[2])
#push!(d::MultiDict, kv, kv2...) = (push!(d.d, kv, kv2...); d)

count(d::MultiDict) = length(keys(d)) == 0 ? 0 : mapreduce(k -> length(d[k]), +, keys(d))
size(d::MultiDict) = (length(keys(d)), count(d::MultiDict))

# enumerate

immutable EnumerateAll
    d::MultiDict
end
enumerateall(d::MultiDict) = EnumerateAll(d)

length(e::EnumerateAll) = count(e.d)

function start(e::EnumerateAll)
    V = eltype(eltype(values(e.d)))
    vs = V[]
    (start(e.d.d), nothing, vs, start(vs))
end

function done(e::EnumerateAll, s)
    dst, k, vs, vst = s
    done(vs, vst) && done(e.d.d, dst)
end

function next(e::EnumerateAll, s)
    dst, k, vs, vst = s
    while done(vs, vst)
        ((k, vs), dst) = next(e.d.d, dst)
        vst = start(vs)
    end
    v, vst = next(vs, vst)
    ((k, v), (dst, k, vs, vst))
end


text:
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

@inline _wait_to_read(arr :: NDArray) =
  @mxcall(:MXNDArrayWaitToRead, (MX_handle,), arr)
@inline _wait_to_write(arr :: NDArray) =
  @mxcall(:MXNDArrayWaitToWrite, (MX_handle,), arr)

"""
    try_get_shared(arr; sync=:nop)

Try to create a Julia array by sharing the data with the underlying `NDArray`.

# Arguments:

* `arr::NDArray`: the array to be shared.

!!! note
    The returned array does not guarantee to share data with the underlying `NDArray`.
    In particular, data sharing is possible only when the `NDArray` lives on CPU.

* `sync::Symbol`: `:nop`,`:write`, `:read`
  On CPU, invoke `_wait_to_read` if `:read`;
  invoke `_wait_to_write` if `:write`.
"""
function try_get_shared(x::NDArray; sync::Symbol=:nop)
  if context(x).device_type == CPU
    # try to do data sharing
    if sync == :read
      _wait_to_read(x)
    elseif sync == :write
      _wait_to_write(x)
    end

    unsafe_wrap(Array, pointer(x), size(x))
  else
    # impossible to share, just copying
    copy(x)
  end
end

"""
    is_shared(j_arr, arr)

Test whether `j_arr` is sharing data with `arr`.

# Arguments:

* `j_arr::Array`: the Julia Array.
* `arr::NDArray`: the `NDArray`.
"""
is_shared(::Array, ::NDArray) = false

function is_shared(j_arr::Array{T}, arr::NDArray{T}) where {T<:DType}
  if length(j_arr) != length(arr)
    return false
  end
  if context(arr).device_type != CPU
    return false
  end
  pointer(j_arr) == pointer(arr)
end

"""
    load(filename, ::Type{NDArray})

Load NDArrays from binary file.

# Arguments:
* `filename::String`: the path of the file to load. It could be S3 or HDFS address.

Returns either `Dict{Symbol, NDArray}` or `Vector{NDArray}`.

`filename` can point to `s3` or `hdfs` resources if the `libmxnet` is built with the
corresponding components enabled. Examples:
* `s3://my-bucket/path/my-s3-ndarray`
* `hdfs://my-bucket/path/my-hdfs-ndarray`
* `/path-to/my-local-ndarray`
"""
function load(filename::AbstractString, ::Type{<:NDArray})
  out_size      = Ref{MX_uint}(0)
  out_hdrs      = Ref{Ptr{MX_handle}}(0)
  out_name_size = Ref{MX_uint}(0)
  out_names     = Ref{char_pp}(0)
  @mxcall(:MXNDArrayLoad, (char_p, Ref{MX_uint}, Ref{Ptr{MX_handle}}, Ref{MX_uint}, Ref{char_pp}),
          filename, out_size, out_hdrs, out_name_size, out_names)
  out_name_size = out_name_size[]
  out_size      = out_size[]
  if out_name_size == 0
    return [NDArray(MX_NDArrayHandle(hdr)) for hdr in unsafe_wrap(Array, out_hdrs[], out_size)]
  else
    @assert out_size == out_name_size
    return Dict([(Symbol(unsafe_string(k)), NDArray(MX_NDArrayHandle(hdr))) for (k,hdr) in
                 zip(unsafe_wrap(Array, out_names[], out_size), unsafe_wrap(Array, out_hdrs[], out_size))])
  end
end

"""
    save(filename::AbstractString, data)

Save NDarrays to binary file. Filename could be S3 or HDFS address, if `libmxnet` is built
with corresponding support (see `load`).

* `filename::String`: path to the binary file to write to.
* `data`: data to save to file. Data can be a`NDArray`, a `Vector` of `NDArray`,
  or a `Dict{Symbol}` contains `NDArray`s.
"""
save(filename::String, data::NDArray) = save(filename, [data])

save(filename::String, data::VecOfNDArray) =
  @mxcall(:MXNDArraySave, (char_p, MX_uint, Ptr{MX_handle}, char_pp),
          filename, length(data), MX_handle[data...], char_pp(0))

function save(filename::String, data::Dict{Symbol})
  names  = keys(data)
  arrays = MX_handle.(collect(values(data)))
  names  = String.(collect(names))

  @mxcall(:MXNDArraySave, (char_p, MX_uint, Ptr{MX_handle}, char_pp),
          filename, length(names), arrays, names)
end


text:
module testMPI
import MPI
using Base.Test
# mpi.jl: test local MPI.jl installation.
function main()
  MPI.Init()
  comm = MPI.COMM_WORLD
  println("Hello world, I am $(MPI.Comm_rank(comm)) of $(MPI.Comm_size(comm))")
  MPI.Barrier(comm)
  MPI.Finalize()
end #function
if isempty(ARGS)
  const nprocesses = 2
  println("Testing MPI installation runs (for Hypre installation.)")
  v = readall(`mpirun -np $nprocesses julia $(@__FILE__) go`)
  println(v)
  @test beginswith(v, "Hello world")
else
  main()
end
end


text:
@testset "alpha_func.jl" begin

end


text:
# ---
# title: 1630. Arithmetic Subarrays
# id: problem1630
# author: Tian Jun
# date: 2020-10-31
# difficulty: Medium
# categories: Sort
# link: <https://leetcode.com/problems/arithmetic-subarrays/description/>
# hidden: true
# ---
#
# A sequence of numbers is called **arithmetic** if it consists of at least two
# elements, and the difference between every two consecutive elements is the
# same. More formally, a sequence `s` is arithmetic if and only if `s[i+1] -
# s[i] == s[1] - s[0] `for all valid `i`.
#
# For example, these are **arithmetic** sequences:
#
#
#
#     1, 3, 5, 7, 9
#     7, 7, 7, 7
#     3, -1, -5, -9
#
# The following sequence is not **arithmetic** :
#
#
#
#     1, 1, 2, 5, 7
#
# You are given an array of `n` integers, `nums`, and two arrays of `m` integers
# each, `l` and `r`, representing the `m` range queries, where the `ith` query
# is the range `[l[i], r[i]]`. All the arrays are **0-indexed**.
#
# Return _a list of_`boolean` _elements_ `answer` _, where_ `answer[i]` _is_
# `true` _if the subarray_ `nums[l[i]], nums[l[i]+1], ... , nums[r[i]]` _can be
# **rearranged** to form an **arithmetic** sequence, and_ `false` _otherwise._
#
#
#
# **Example 1:**
#
#
#
#     Input: nums = [4,6,5,9,3,7], l = [0,0,2], r = [2,3,5]
#     Output: [true,false,true]
#     Explanation:
#     In the 0th query, the subarray is [4,6,5]. This can be rearranged as [6,5,4], which is an arithmetic sequence.
#     In the 1st query, the subarray is [4,6,5,9]. This cannot be rearranged as an arithmetic sequence.
#     In the 2nd query, the subarray is [5,9,3,7]. This can be rearranged as [3,5,7,9], which is an arithmetic sequence.
#
# **Example 2:**
#
#
#
#     Input: nums = [-12,-9,-3,-12,-6,15,20,-25,-20,-15,-10], l = [0,1,6,4,8,7], r = [4,4,9,7,9,10]
#     Output: [false,true,false,false,true,true]
#
#
#
#
# **Constraints:**
#
#   * `n == nums.length`
#   * `m == l.length`
#   * `m == r.length`
#   * `2 <= n <= 500`
#   * `1 <= m <= 500`
#   * `0 <= l[i] < r[i] < n`
#   * `-105 <= nums[i] <= 105`
#
#
## @lc code=start
using LeetCode

## add your code here:
## @lc code=end


text:
# T , TSSM_HANDLE

println("including tssm_fourier_bessel.jl for type ",T)

for (METHOD, SUF, COMPLEX_METHOD, DIM) in (
                 (:FourierBessel2D, :_fourier_bessel_2d, true, 2 ),
                 (:FourierBesselReal2D, :_fourier_bessel_real_2d, false, 2 ),
                )
println("    ", METHOD)
if T == :Float128
    SUF = Symbol(SUF, "_wf128")
end

@eval begin
    function ($METHOD)(T::Type{$T}, ntheta::Integer, nr::Integer, nfr::Integer;
                       rmax::Real=1.0, #one($T),
                       boundary_conditions::Integer = dirichlet,
                       quadrature_rule::Integer =
                       (boundary_conditions==neumann ? radau : lobatto))
        m = ($METHOD){$T}( ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"new",SUF))),
                       Ptr{Nothing}, (Int32, Int32, Int32, ($T), Int32, Int32),
                       ntheta, nr, nfr, rmax, boundary_conditions, quadrature_rule))
        finalizer(x -> ccall( Libdl.dlsym(($TSSM_HANDLE),
                       $(string(PRE,"finalize",SUF))), Nothing, (Ptr{Nothing},), x.m), m)
        m
    end

    function ($METHOD)(T::Type{$T}, filename::AbstractString)
        m = ($METHOD){$T}( ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"new_from_file",SUF))),
                       Ptr{Nothing}, (Cstring, Int32,), filename, length(filename) ))
        finalizer(x -> ccall( Libdl.dlsym(($TSSM_HANDLE),
                       $(string(PRE,"finalize",SUF))), Nothing, (Ptr{Nothing},), x.m), m)
        m
    end
end # eval
if T == :Float64
@eval begin
    function ($METHOD)(ntheta::Integer, nr::Integer, nfr::Integer;
                       rmax::Real=1.0, #one($T),
                       boundary_conditions::Integer = dirichlet,
                       quadrature_rule::Integer =
                       (boundary_conditions==neumann ? radau : lobatto))
        ($METHOD)(($T), ntheta, nr, nfr, rmax=rmax,
                  boundary_conditions=boundary_conditions,
                  quadrature_rule=quadrature_rule)
    end

    function ($METHOD)(filename::AbstractString)
        ($METHOD)(($T), filename)
    end

end # eval
end # if

@eval begin
    function get_ntheta(m::($METHOD){$T})
       ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_ntheta",SUF))), Int32,
             (Ptr{Nothing}, ), m.m )
    end

    function get_nr(m::($METHOD){$T})
       ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_nr",SUF))), Int32,
             (Ptr{Nothing}, ), m.m )
    end

    function get_nfr(m::($METHOD){$T})
       ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_nfr",SUF))), Int32,
             (Ptr{Nothing}, ), m.m )
    end

    function get_rmax(m::($METHOD){$T})
       ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_rmax",SUF))), ($T),
             (Ptr{Nothing}, ), m.m )
    end

    function get_weights(m::($METHOD){$T})
       dim =Array(Int32, 1)
       np = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_weights",SUF))), Ptr{$T},
             (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dim, 1 )
       n = pointer_to_array(np, dim[1], false)
       copy(n)
    end

    function get_transformation_matrices(m::($METHOD){$T}, unsafe_access::Bool=false)
       dims =Array(Int32, 3)
       Lp = ccall( Libdl.dlsym(tssm_handle, $(string(PRE,"get_L",SUF))), Ptr{$T},
             (Ptr{Nothing}, Ptr{Int32}), m.m, dims )
       L = pointer_to_array(Lp, (dims[1], dims[2], dims[3]), false)
       if unsafe_access
           return L
       else
           return copy(L)
       end
    end

    function save(m::($METHOD){$T}, filename::AbstractString)
       ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"save",SUF))), Nothing,
             (Ptr{Nothing}, Cstring, Int32,), m.m, filename, length(filename))
    end

end # eval

end # for

for (METHOD, SUF, COMPLEX_METHOD, DIM) in (
                 (:BesselRotSym1D, :_bessel_rotsym_1d, true, 1 ),
                 (:BesselRotSymReal1D, :_bessel_rotsym_real_1d, false, 1 ),
                )
println("    ", METHOD)
if T == :Float128
    SUF = Symbol(SUF, "_wf128")
end

@eval begin
    function ($METHOD)(T::Type{$T}, nr::Integer; rmax::Real=1.0, #one($T),
                       boundary_conditions::Integer = dirichlet)
        m = ($METHOD){$T}( ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"new",SUF))),
                       Ptr{Nothing}, (Int32, ($T), Int32),
                       nr,  rmax, boundary_conditions))
        finalizer(x -> ccall( Libdl.dlsym(($TSSM_HANDLE),
                       $(string(PRE,"finalize",SUF))), Nothing, (Ptr{Nothing},), x.m), n)
        m
    end
end # eval
if T == :Float64
@eval begin
    function ($METHOD)(nr::Integer; rmax::Real=1.0, #one($T),
                       boundary_conditions::Integer = dirichlet)
        ($METHOD)(($T), nr, rmax=rmax, boundary_conditions=boundary_conditions)
    end
end # eval
end # if

@eval begin
    function get_nr(m::($METHOD){$T})
       ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_nr",SUF))), Int32,
             (Ptr{Nothing}, ), m.m )
    end

    function get_rmax(m::($METHOD){$T})
       ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_rmax",SUF))), ($T),
             (Ptr{Nothing}, ), m.m )
    end

    function get_weights(m::($METHOD){$T})
       dim =Array(Int32, 1)
       np = ccall( Libdl.dlsym(($TSSM_HANDLE), $(string(PRE,"get_weights",SUF))), Ptr{$T},
            (Ptr{Nothing}, Ptr{Int32}, Int32), m.m, dim, 1 )
       n = pointer_to_array(np, dim[1], false)
       copy(n)
    end

    function get_transformation_matrices(m::($METHOD){$T}, unsafe_access::Bool=false)
       dims =Array(Int32, 2)
       Lp = ccall( dlsym(tssm_handle, $(string(PRE,"get_L",SUF))), Ptr{$T},
             (Ptr{Nothing}, Ptr{Int32}), m.m, dims )
       L = pointer_to_array(Lp, (dims[1], dims[2]), false)
       if unsafe_access
           return L
       else
           return copy(L)
       end
    end
end # eval

end # for


text:
using MASW
using JLD2
using Test

@testset "MASW.jl" begin
    # Write your own tests here.

    # Travis is not working with Pyplot.
    #Plots.pyplot()

    #===
    # example to run masw(). Example and SampleData are based on matlab script written by John Schuh.

    Matlab script: Copyright (c) 2018, John Schuh All rights reserved.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    •    John Schuh (2020). MASW Dispersion Curve (https://www.mathworks.com/matlabcentral/fileexchange/65138-masw-dispersion-curve), MATLAB Central File Exchange.
          Retrieved January 14, 2020.
    ===#
    curdir = pwd()
    fi = jldopen(curdir*"/../example/SampleData.jld", "r")
    U = fi["suma_sg"]
    close(fi)

    fs=1000; # sampling frequency Hz
    min_x = 1; # min offset [m] of reciever spread
    max_x = 100; # max offset [m] of reciever spread
    d_x = 2; # distance between receivers [m]

    x = min_x:d_x:max_x; # spatial sampling vector (receiver position)
    t=1/fs:1/fs:length(U[:,1])/fs;  # time vector in seconds

    # figdir = "./"
    # figname = "dispersionimage.png"

    ct=300:1:1200;
    freqlimits=(15.0, 80.0);

    (f, ct, Udisp, DispersionCurve)=masw(U, x, t, ct, plotfreqlimits=freqlimits)

    @test f[1] == 0.0
    @test ct[1] == 300
end