text:
const VALID_SERVER_REQ_TYPES = (FCGIHeaderType.ABORT_REQUEST, FCGIHeaderType.PARAMS, FCGIHeaderType.STDIN)
const SERVER_PARAMS = Dict{String,String}(
    "FCGI_MAX_CONNS"    =>  "100",
    "FCGI_MAX_REQS"     =>  "100",
    "FCGI_MPXS_CONNS"   =>  "1"
)

"""
Set server parameters this server should respond with.
Set values according to resources available on your system and the amount of load you wish this instance to take up.
"""
function set_server_param(name::String, value::String)
    SERVER_PARAMS[name] = value
    nothing
end

"""
The runner type to use. Set this with the `set_server_runner` method.
"""
FCGI_RUNNER = ProcessRunner

"""
Set the runner type to use: `FastCGI.ProcessRunner` or `FastCGI.FunctionRunner`.
"""
function set_server_runner(runnertype)
    @assert isa(runnertype, Function) || (supertype(runnertype) === Runner)
    global FCGI_RUNNER
    FCGI_RUNNER = runnertype
    nothing
end

"""
Process a single FastCGI client connection.
A client may send multiple requests over the same connection by setting the `keep` flag in the BEGIN_REQUEST message.
Handles all messages that are not specific to any request id (including the BEGIN_REQUEST message that initializes a request).
Initializes and maintains ServerRequest instances for each new request id.
All messages targeted to ongoing request ids are handled over to respective ServerRequest instances.
"""
mutable struct ServerConnection{T<:FCGISocket}
    asock::T
    out::Channel{FCGIRecord}
    requests::Dict{UInt16,ServerRequest}
    processorin::Union{Task,Nothing}
    processorout::Union{Task,Nothing}
    stopsignal::Bool
    onstop::Function
    lck::ReentrantLock
end
function ServerConnection(asock::T, onstop::Function) where {T<:FCGISocket}
    @debug("accepting server connection")
    conn = ServerConnection(asock, Channel{FCGIRecord}(128), Dict{UInt16,ServerRequest}(), nothing, nothing, false, onstop, ReentrantLock())
    conn.processorin = @async processin(conn)
    conn.processorout = @async processout(conn)
    conn
end
function stop(conn::ServerConnection{T}; checkinterval::Float64=0.01) where {T<:FCGISocket}
    @debug("stopping server connection")
    timedwait(checkinterval) do
        istaskdone(conn.processorout) || !isready(conn.out)
    end
    conn.stopsignal = true
    close(conn.out)
    wait(conn.processorout)
    flush(conn.asock)
    close(conn.asock)
    wait(conn.processorin)
    abandonallreq(conn)
    (conn.onstop)(conn)
    nothing
end
function abandonallreq(conn::ServerConnection)
    lock(conn.lck) do
        empty!(conn.requests)
    end
    nothing
end
function addreq(reqf, conn::ServerConnection, reqid::UInt16)
    lock(conn.lck) do
        conn.requests[reqid] = reqf()
    end
    nothing
end
function getreq(conn::ServerConnection, reqid::UInt16)
    lock(conn.lck) do
        get(conn.requests, reqid, nothing)
    end
end
function onclosereq(conn::ServerConnection{T}, reqid::UInt16, keepconn::Bool) where {T<:FCGISocket}
    @debug("connection onclosereq", reqid, keepconn)
    lock(conn.lck) do
        delete!(conn.requests, reqid)
        keepconn || stop(conn)
    end
    return
end
function processout(conn::ServerConnection{T}) where {T<:FCGISocket}
    # read out channel and write messages on sock
    while !conn.stopsignal && isopen(conn.asock)
        try
            resp = take!(conn.out)
            nbytes = fcgiwrite(conn.asock, resp)
            @debug("wrote response packet", type=reqtypetostring(resp.header.type), nbyteswritten=nbytes, contentlen=length(resp.content))
        catch ex
            if !isa(ex, InvalidStateException) && !(isa(ex, Base.IOError) && (ex.code == -103))
                @warn("ServerConnection output processor failed with exception", ex)
            end
            conn.stopsignal = true
            # ignore InvalidStateException and IOError as that signals closing of channel/socket and end of communication
            # cleanups are done by input processor
        end
    end
end
function processin(conn::ServerConnection{T}) where {T<:FCGISocket}
    while !conn.stopsignal && isopen(conn.asock)
        try
            record = FCGIRecord(conn.asock)
            reqid = requestid(record.header)
            @debug("read request packet", reqid, type=reqtypetostring(record.header.type))
            if record.header.type == FCGIHeaderType.BEGIN_REQUEST
                # instantiate request data
                begreq = FCGIBeginRequest(record.content)
                reqrole = role(begreq)
                (reqrole == FCGIRequestRole.RESPONDER) || error("FCGI feature not supported: role=$reqrole")
                # create a new entry in requests table
                @debug("beginning request", keep=keepconn(begreq))
                addreq(conn, reqid) do
                    ServerRequest(reqid, ()->onclosereq(conn, reqid, keepconn(begreq)), conn.out)
                end
            elseif record.header.type == FCGIHeaderType.GET_VALUES
                # respond with server params
                querynvs = FCGIParams(record.content)
                respnvs = FCGIParams()
                for querynv in querynvs.nvpairs
                    name = querynv.name
                    if name in keys(SERVER_PARAMS)
                        push!(respnvs.nvpairs, FCGINameValuePair(name, SERVER_PARAMS[name]))
                    else
                        @warn("FCGI feature not supported: FCGI_GET_VALUE", reqid, name)
                    end
                end
                put!(conn.out, FCGIRecord(FCGIHeaderType.GET_VALUES_RESULT, reqid, respnvs))
            elseif record.header.type in VALID_SERVER_REQ_TYPES
                # push record to process queue
                reqhandler = getreq(conn, reqid)
                if reqhandler === nothing
                    @warn("ignoring invalid request", reqid, type=record.header.type)
                else
                    push!(reqhandler.in, record)
                end
            else
                @warn("FCGI feature not supported: header", reqid, type=record.header.type)
                unk = FCGIUnknownType(record.header.type)
                put!(conn.out, FCGIRecord(FCGIHeaderType.UNKNOWN_TYPE, reqid, unk))
            end
        catch ex
            if (isa(ex, Base.IOError) && (ex.code == -103)) || isa(ex, Base.EOFError)
                @debug("connection closed")
            else
                @error("unhandled error in connection", ex)
            end
            close(conn.asock)
            close(conn.out)
            abandonallreq(conn)
            conn.stopsignal = true
        end
    end
    stop(conn)
end

"""
The FCGIServer sets up a listening socket on which it accepts incoming client connections.
For each incoming connection, creates a new ServerConnection instance and starts a separate
processing task for messages from that connection. Maintains a list of such connections.
"""
mutable struct FCGIServer{T<:FCGIServerSocket}
    addr::String
    lsock::T
    conns::Vector{ServerConnection}
    processor::Union{Task,Nothing}
    lck::ReentrantLock
end
function FCGIServer(path::String)
    server = FCGIServer(path, listen(path), Vector{ServerConnection}(), nothing, ReentrantLock())
    server.processor = @async process(server)
    server
end
function FCGIServer(ip::IPv4, port::Integer)
    server = FCGIServer("$(ip):$(Int(port))", listen(ip, port), Vector{ServerConnection}(), nothing, ReentrantLock())
    server.processor = @async process(server)
    server
end
show(io::IO, server::FCGIServer) = print(io, "FCGIServer(", server.addr, ", ", isopen(server.lsock) ? "open" : "closed", ", ", length(server.conns), " connections)")

""" Request stopping of the server by closing the listen socket """
function stop(server::FCGIServer)
    close(server.lsock)
    nothing
end

function delconn(server::FCGIServer, conn::ServerConnection)
    lock(server.lck) do
        filter!((x)->(x !== conn), server.conns)
    end
    nothing
end

""" Whether the server is running and listening for new connections """
isrunning(server::FCGIServer) = isopen(server.lsock)

"""
Processes incoming connections on the listen socket, by creating a separate asynchronous handler for each new connection.
Handling of messages on a connection is implemented in ServerConnection.
"""
function process(server::FCGIServer{T}) where {T<:FCGIServerSocket}
    while isopen(server.lsock)
        try
            asock = accept(server.lsock)
            lock(server.lck) do
                push!(server.conns, ServerConnection(asock, (conn)->delconn(server, conn)))
            end
        catch ex
            if !(isa(ex, Base.IOError) && (ex.code == -103))
                @error("unhandled error in server", ex)
                rethrow(ex)
            else
                @warn("stopping server")
            end
        end
    end
end


text:
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK
# Copyright (C) 2019 Samuel Powell

module Spinnaker

using FixedPointNumbers

using Libdl
import Base: unsafe_convert, show, length, getindex, size, convert, range, showerror

export System, Camera, CameraList, SpinError

const libSpinnaker_C = Ref{String}("")
const libSpinVideo_C = Ref{String}("")

const MAX_BUFFER_LEN = Csize_t(1023)

# include API wrapper
include("wrapper/CEnum.jl")
using .CEnum

include("wrapper/spin_common.jl")

struct SpinError <: Exception
  val::spinError
end
showerror(io::IO, ex::SpinError) = print(io, "Spinnaker SDK error: ", ex.val)

function checkerror(err::spinError)
  if err != spinError(0)
    throw(SpinError(err))
  end
  return nothing
end

include("wrapper/spin_api.jl")

# export everything spin*
foreach(names(@__MODULE__, all=true)) do s
  if startswith(string(s), "spin")
    @eval export $s
  end
end

# Include interface
include("SpinImage.jl")
include("CameraImage.jl")
include("System.jl")
include("Camera.jl")
include("CameraList.jl")
include("NodeMap.jl")
include("Nodes.jl")

# Create a System object at runtime
function __init__()
  @static if Sys.iswindows()
    paths = [joinpath(ENV["ProgramFiles"], "Point Grey Research", "Spinnaker", "bin", "vs2015")]
    libspinnaker = "SpinnakerC_v140.dll"
    libspinvideo = ""
  elseif Sys.islinux()
    paths = ["/usr/lib" "/opt/spinnaker/lib"]
    libspinnaker = "libSpinnaker_C.so"
    libspinvideo = "libSpinVideo_C.so"
  elseif Sys.isapple()
    paths = ["/usr/local/lib"]
    libspinnaker = "libSpinnaker_C.dylib"
    libspinvideo = "libSpinVideo_C.dylib"
  else
    @error "Spinnaker SDK only supported on Linux, Windows and MacOS platforms"
    return
  end
  libSpinnaker_C_path = ""
  libSpinVideo_C_path = ""
  for path in paths
    libSpinnaker_C_path = joinpath(path, libspinnaker)
    libSpinVideo_C_path = joinpath(path, libspinvideo)
    if isfile(libSpinnaker_C_path) && isfile(libSpinVideo_C_path)
      libSpinnaker_C[] = libSpinnaker_C_path
      libSpinVideo_C[] = libSpinVideo_C_path
    end
  end

  if libSpinnaker_C[] == "" || libSpinVideo_C[] == ""
    @error "Spinnaker SDK cannot be found. This package can be loaded, but will not be functional."
    return
  end
  try
    libSpinnaker_C_handle = dlopen(libSpinnaker_C[])
    !Sys.iswindows() && (libSpinVideo_C_handle = dlopen(libSpinVideo_C[]))
  catch ex
    bt = catch_backtrace()
    @error "Spinnaker SDK cannot be dlopen-ed"
    showerror(stderr, ex, bt)
  end
  try
    global spinsys = System()
  catch ex
    bt = catch_backtrace()
    @error "Spinnaker SDK loaded but Spinnaker.jl failed to initialize"
    showerror(stderr, ex, bt)
  end
end

end # module

ext: jl


text:
@testset "vector difference" begin
    modinds = [1, 2, 3, 4]
    addinds = [5, 6]
    reminds = [7, 8]
    modvals = [1, 2, 3, 4]
    addvals = [1, 2]
    remvals = [3, 4]
    a = VectorDifference(
        modinds, addinds, reminds, modvals, view(addvals, :), view(remvals, :)
    )
    b = VectorDifference(modinds, addinds, reminds, sparse(modvals), addvals, remvals)
    c = VectorDifference(modinds, addinds, reminds, modvals, addvals, remvals)

    @testset "constructors" begin
        @test isa(a, VectorDifference) && isa(b, VectorDifference)
        @test (
            a.modinds == modinds &&
            a.addinds == addinds &&
            a.reminds == reminds &&
            a.modvals == modvals &&
            a.addvals == addvals &&
            a.remvals == remvals
        )
        @test (
            b.modinds == modinds &&
            b.addinds == addinds &&
            b.reminds == reminds &&
            b.modvals == sparse(modvals) &&
            b.addvals == addvals &&
            b.remvals == remvals
        )
    end

    @testset "equality operator" begin
        @test a == a
        @test a == b && b == a
        @test a == b && b == c && a == c
    end

    @testset "hash" begin
        @test hash(a) == hash(a)
        @test a == b && hash(a) == hash(b)
    end

    @testset "accessors" begin
        @test modified_indices(a) == modinds
        @test added_indices(a) == addinds
        @test removed_indices(a) == reminds
        @test modified(a) == modvals
        @test added(a) == addvals
        @test removed(a) == remvals
    end

    @testset "difference" begin
        a = [1, 2, 5]
        b = [2, 3, 5, 7]
        ia = [1, 2, 5]
        ib = [2, 3, 5, 7]
        e = []
        ei = Int[]
        se = sparse(e)
        @test diff(e, e) == VectorDifference(ei, ei, ei, se, e, e)
        @test diff(e, a) == VectorDifference(ei, ei, ei, se, a, e)
        @test diff(a, e) == VectorDifference(ei, ei, ei, se, a, e)
        @test (diff(a, a) == VectorDifference([1, 2, 3], ei, ei, sparse([0, 0, 0]), e, e))
        @test (
            diff(a, b) == VectorDifference([1, 2, 3], [4], ei, sparse([-1, -1, 0]), [7], e)
        )
        @test (
            diff(b, a) == VectorDifference([1, 2, 3], ei, [4], sparse([1, 1, 0]), e, [7])
        )
        @test (
            diff(a, a, ia, ia) ==
            VectorDifference([1, 2, 5], ei, ei, sparse([0, 0, 0]), e, e)
        )
        @test (
            diff(a, b, ia, ib) ==
            VectorDifference([2, 5], [3, 7], [1], sparse([0, 0]), [3, 7], [1])
        )
        @test (
            diff(b, a, ib, ia) ==
            VectorDifference([2, 5], [1], [3, 7], sparse([0, 0]), [1], [3, 7])
        )
    end
end


text:
# prime fields =========================================================================== #
"""
    is_prime(n)

Return `true` if `n` is a prime number.
"""
Base.@pure function is_prime(n::Int)
    if iseven(n) || n < 2
        return n == 2
    else
        p = 3
        q = n ÷ p
        while p ≤ q
            iszero(n % p) && return false
            p += 2
            q = n ÷ p
        end
        return true
    end
end
# The following causes an error if you try to use anything other than Int as a modulus.
is_prime(::Any) = false

"""
    mod_prime(i, ::Val{M})

Like `mod`, but with prime `M`.
"""
function mod_prime(i, ::Val{M}) where {M}
    is_prime(M) || throw(DomainError(M, "modulus must be a prime number"))
    i = i % M
    return i + ifelse(signbit(i), M, 0)
end
mod_prime(i, ::Val{2}) = i & 1

"""
    Mod{M} <: Integer

`Mod{M}` is the default field used by Ripserer. It is a representation of a finite field
``\\mathbb{Z}_M``, integers modulo small, prime `M`. Supports field arithmetic and can be
converted to integer with `Int`.

Its values are not comparable on purpose.

# Example

```jldoctest
julia> Mod{3}(5)
2 mod 3

julia> Mod{3}(5) + 1
0 mod 3

```
"""
struct Mod{M} <: Integer
    value::Int

    # Check mod allows construction when you know you don't need to mod the number.
    function Mod{M}(value::Integer, check_mod=true) where {M}
        if check_mod
            return new{M}(mod_prime(value, Val(M)))
        else
            return new{M}(value)
        end
    end
end
Mod{M}(i::Mod{M}) where {M} = i

Base.Int(i::Mod) = i.value

Base.show(io::IO, i::Mod{M}) where {M} = print(io, Int(i), " mod ", M)

for op in (:+, :-, :*)
    @eval (Base.$op)(i::Mod{M}, j::Mod{M}) where {M} = Mod{M}($op(Int(i), Int(j)))
end

Base.:/(i::Mod{M}, j::Mod{M}) where {M} = i * inv(j)
Base.:-(i::Mod{M}) where {M} = Mod{M}(M - Int(i), false)
Base.zero(::Type{Mod{M}}) where {M} = Mod{M}(0, false)
Base.one(::Type{Mod{M}}) where {M} = Mod{M}(1, false)
Base.sign(i::M) where {M<:Mod} = ifelse(iszero(i), zero(M), one(M))

Base.promote_rule(::Type{Mod{M}}, ::Type{<:Integer}) where {M} = Mod{M}

Base.inv(i::Mod{M}) where {M} = Mod{M}(invmod(Int(i), M), false)


text:
using SimpleBirthDeathProcess;
using DelimitedFiles;
using Plots;

N = 1_000;
F = Float64;
I = 25;
J = 35;
T = 2;
L = F(1);
M = F(3);

# values obtained with Maple 2018.2
correct_values = readdlm("log_trans_prob_values_univariate.csv", ',', BigFloat);

μset = [M * F(n) / N for n = 1:N];
logp = [trans_prob(I, J, T, [L; F(μ)]) for μ = μset];

relative_error = abs.(1 .- logp ./ correct_values);

pl = plot(μset, relative_error, seriestype=:line, colour=:black,
          yscale=:log10, xlab="\\mu", ylab="Relative error",
          legend=false, size=(1920, 1080));

savefig(pl, "Figure_3.svg")


text:
using Distributions

fund_default_mcs = @defsim begin

    ##
    ## shared model parameters only need to call once and don't need component
    ##

    # none

    ##
    ## unshared model parameters, or parameters specific to only one component that are shared due to old set_param! usage
    ##

    scenariouncertainty.aceiadd = ["USA" => Normal(0.0,0.025), "CAN" => Normal(0.0,0.025), "WEU" => Normal(0.0,0.025), "JPK" => Normal(0.0,0.0375), "ANZ" => Normal(0.0,0.0375), "EEU" => Normal(0.0,0.025), "FSU" => Normal(0.0,0.025), "MDE" => Normal(0.0,0.0875), "CAM" => Normal(0.0,0.05625), "LAM" => Normal(0.0,0.05625), "SAS" => Normal(0.0,0.0875), "SEA" => Normal(0.0,0.0875), "CHI" => Normal(0.0,0.0375), "MAF" => Normal(0.0,0.11875), "SSA" => Normal(0.0,0.11875), "SIS" => Normal(0.0,0.05625)]
    scenariouncertainty.aeeiadd = ["USA" => Normal(0.0,0.0625), "CAN" => Normal(0.0,0.0625), "WEU" => Normal(0.0,0.0625), "JPK" => Normal(0.0,0.0625), "ANZ" => Normal(0.0,0.0625), "EEU" => Normal(0.0,0.1), "FSU" => Normal(0.0,0.1), "MDE" => Normal(0.0,0.15), "CAM" => Normal(0.0,0.15), "LAM" => Normal(0.0,0.15), "SAS" => Normal(0.0,0.15), "SEA" => Normal(0.0,0.15), "CHI" => Normal(0.0,0.175), "MAF" => Normal(0.0,0.15), "SSA" => Normal(0.0,0.15), "SIS" => Normal(0.0,0.15)]
    impactagriculture.agcbm = ["USA" => Truncated(Normal(0.089,0.1484), 0.0, Inf), "CAN" => Truncated(Normal(0.0402,0.065), 0.0, Inf), "WEU" => Truncated(Normal(0.1541,0.1183), 0.0, Inf), "JPK" => Truncated(Normal(0.2319,0.366), 0.0, Inf), "ANZ" => Truncated(Normal(0.1048,0.085), 0.0, Inf), "EEU" => Truncated(Normal(0.0952,0.0514), 0.0, Inf), "FSU" => Truncated(Normal(0.0671,0.0548), 0.0, Inf), "MDE" => Truncated(Normal(0.0943,0.0266), 0.0, Inf), "CAM" => Truncated(Normal(0.1641,0.0538), 0.0, Inf), "LAM" => Truncated(Normal(0.0596,0.0504), 0.0, Inf), "SAS" => Truncated(Normal(0.058,0.0164), 0.0, Inf), "SEA" => Truncated(Normal(0.0845,0.4181), 0.0, Inf), "CHI" => Truncated(Normal(0.1921,0.0613), 0.0, Inf), "MAF" => Truncated(Normal(0.0727,0.019), 0.0, Inf), "SSA" => Truncated(Normal(0.0505,0.022), 0.0, Inf), "SIS" => Truncated(Normal(0.2377,0.0864), 0.0, Inf)]
    impactagriculture.agel = Truncated(Normal(0.31,0.15), 0.0, 1.0)
    impactagriculture.aglparl = ["USA" => Truncated(Normal(0.0259810049019608,0.0213267435505035), 0.0, Inf), "CAN" => Truncated(Normal(0.0923560606060606,0.0800938684660319), 0.0, Inf), "WEU" => Truncated(Normal(0.021883487654321,0.00155285586012424), 0.0, Inf), "JPK" => Truncated(Normal(0.0462338709677419,0.0216697050990404), 0.0, Inf), "ANZ" => Truncated(Normal(0.0396465746205965,0.0707787669743405), 0.0, Inf), "EEU" => Truncated(Normal(0.0475721982758621,0.0973749246061888), 0.0, Inf), "FSU" => Truncated(Normal(0.0418566470712197,0.0751278509694302), 0.0, Inf), "MDE" => Truncated(Normal(0.0421993430741693,0.0705702013176662), 0.0, Inf), "CAM" => Truncated(Normal(0.0638352272727273,0.0428390811061973), 0.0, Inf), "LAM" => Truncated(Normal(0.003045,0.00495797624773007), 0.0, Inf), "SAS" => Truncated(Normal(0.025470079787234,0.0240282059284576), 0.0, Inf), "SEA" => Truncated(Normal(0.0135138888888889,0.00355503300856311), 0.0, Inf), "CHI" => Truncated(Normal(0.0430619429569277,0.0762567733933823), 0.0, Inf), "MAF" => Truncated(Normal(0.03346875,0.0426305042811185), 0.0, Inf), "SSA" => Truncated(Normal(0.0244802631578947,0.0340552582289858), 0.0, Inf), "SIS" => Truncated(Normal(0.0425735877466748,0.0769042893611385), 0.0, Inf)]
    impactagriculture.aglparq = ["USA" => Truncated(Normal(-0.0119178921568627,0.0182356597477236), -Inf, 0.0), "CAN" => Truncated(Normal(-0.0158143939393939,0.00945384554959497), -Inf, 0.0), "WEU" => Truncated(Normal(-0.0138503086419753,0.013197508099606), -Inf, 0.0), "JPK" => Truncated(Normal(-0.0235887096774194,0.029940084414887), -Inf, 0.0), "ANZ" => Truncated(Normal(-0.0155903909385135,0.0374712492013158), -Inf, 0.0), "EEU" => Truncated(Normal(-0.0181573275862069,0.0476884205159737), -Inf, 0.0), "FSU" => Truncated(Normal(-0.0163118735427424,0.0388313181355771), -Inf, 0.0), "MDE" => Truncated(Normal(-0.0165914930103618,0.0373495478918258), -Inf, 0.0), "CAM" => Truncated(Normal(-0.0303977272727273,0.0427671908556002), -Inf, 0.0), "LAM" => Truncated(Normal(-0.00435,0.00280772150262969), -Inf, 0.0), "SAS" => Truncated(Normal(-0.0112699468085106,0.018095882190896), -Inf, 0.0), "SEA" => Truncated(Normal(-0.00965277777777778,0.00843513605824223), -Inf, 0.0), "CHI" => Truncated(Normal(-0.0168265560310128,0.0396988494314158), -Inf, 0.0), "MAF" => Truncated(Normal(-0.0139453125,0.0265770062631446), -Inf, 0.0), "SSA" => Truncated(Normal(-0.0100328947368421,0.0201799487191507), -Inf, 0.0), "SIS" => Truncated(Normal(-0.0166147684550101,0.0399015737834891), -Inf, 0.0)]
    impactagriculture.agnl = Truncated(Normal(2.0,0.5), 0.0, Inf)
    impactagriculture.agrbm = ["USA" => Truncated(Normal(-0.00021,0.00176), -Inf, 0.0), "CAN" => Truncated(Normal(-0.00029,0.00073), -Inf, 0.0), "WEU" => Truncated(Normal(-0.00039,0.00138), -Inf, 0.0), "JPK" => Truncated(Normal(-0.00033,0.00432), -Inf, 0.0), "ANZ" => Truncated(Normal(-0.00015,0.00142), -Inf, 0.0), "EEU" => Truncated(Normal(-0.00027,0.00062), -Inf, 0.0), "FSU" => Truncated(Normal(-0.00018,0.00066), -Inf, 0.0), "MDE" => Truncated(Normal(-0.00022,0.00032), -Inf, 0.0), "CAM" => Truncated(Normal(-0.00034,0.00061), -Inf, 0.0), "LAM" => Truncated(Normal(-9.0e-5,0.0006), -Inf, 0.0), "SAS" => Truncated(Normal(-0.00014,0.00021), -Inf, 0.0), "SEA" => Truncated(Normal(-9.0e-5,0.00482), -Inf, 0.0), "CHI" => Truncated(Normal(-0.00013,0.00075), -Inf, 0.0), "MAF" => Truncated(Normal(-0.00016,0.00023), -Inf, 0.0), "SSA" => Truncated(Normal(-0.00011,0.00026), -Inf, 0.0), "SIS" => Truncated(Normal(-0.0005,0.00103), -Inf, 0.0)]
    impactagriculture.agtime = ["USA" => Truncated(Normal(10.0,5.0), 1.0, Inf), "CAN" => Truncated(Normal(10.0,5.0), 1.0, Inf), "WEU" => Truncated(Normal(10.0,5.0), 1.0, Inf), "JPK" => Truncated(Normal(10.0,5.0), 1.0, Inf), "ANZ" => Truncated(Normal(10.0,5.0), 1.0, Inf), "EEU" => Truncated(Normal(10.0,5.0), 1.0, Inf), "FSU" => Truncated(Normal(10.0,5.0), 1.0, Inf), "MDE" => Truncated(Normal(10.0,5.0), 1.0, Inf), "CAM" => Truncated(Normal(10.0,5.0), 1.0, Inf), "LAM" => Truncated(Normal(10.0,5.0), 1.0, Inf), "SAS" => Truncated(Normal(10.0,5.0), 1.0, Inf), "SEA" => Truncated(Normal(10.0,5.0), 1.0, Inf), "CHI" => Truncated(Normal(10.0,5.0), 1.0, Inf), "MAF" => Truncated(Normal(10.0,5.0), 1.0, Inf), "SSA" => Truncated(Normal(10.0,5.0), 1.0, Inf), "SIS" => Truncated(Normal(10.0,5.0), 1.0, Inf)]
    biodiversity.bioloss = Truncated(Normal(0.003,0.002), 0.0, Inf)
    biodiversity.biosens = Truncated(Normal(0.001,0.001), 0.0, Inf)
    impactbiodiversity.bioshare = TriangularDist(0.0, 1.0, 0.05)
    impactcardiovascularrespiratory.ccmlbm = ["USA" => Truncated(Normal(151.6768,3.4583), 0.0, Inf), "CAN" => Truncated(Normal(195.6424,3.4583), 0.0, Inf), "WEU" => Truncated(Normal(19.2327,1.2716), 0.0, Inf), "JPK" => Truncated(Normal(65.5934,3.5211), 0.0, Inf), "ANZ" => Truncated(Normal(67.1775,2.9403), 0.0, Inf), "EEU" => Truncated(Normal(61.484,1.5395), 0.0, Inf), "FSU" => Truncated(Normal(-3.4422,3.4583), -Inf, 0.0), "MDE" => Truncated(Normal(-2.4508,1.5732), -Inf, 0.0), "CAM" => Truncated(Normal(-0.6855,2.6117), -Inf, 0.0), "LAM" => Truncated(Normal(16.6942,1.8829), 0.0, Inf), "SAS" => Truncated(Normal(-1.6072,2.6242), -Inf, 0.0), "SEA" => Truncated(Normal(-0.6838,1.4722), -Inf, 0.0), "CHI" => Truncated(Normal(81.1077,3.4522), 0.0, Inf), "MAF" => Truncated(Normal(-1.9826,1.9196), -Inf, 0.0), "SSA" => Truncated(Normal(-1.0407,0.9609), -Inf, 0.0), "SIS" => Truncated(Normal(1.6035,1.1897), 0.0, Inf)]
    impactcardiovascularrespiratory.ccmqbm = ["USA" => Truncated(Normal(-155.1251,2.8292), -Inf, 0.0), "CAN" => Truncated(Normal(-199.0906,2.8292), -Inf, 0.0), "WEU" => Truncated(Normal(-21.7191,1.0403), -Inf, 0.0), "JPK" => Truncated(Normal(-67.185,2.8805), -Inf, 0.0), "ANZ" => Truncated(Normal(-68.9576,2.4054), -Inf, 0.0), "EEU" => Truncated(Normal(-65.2217,1.2594), -Inf, 0.0), "FSU" => Truncated(Normal(0.0473,2.8292), 0.0, Inf), "MDE" => Truncated(Normal(0.0457,1.287), 0.0, Inf), "CAM" => Truncated(Normal(-0.484,2.1366), -Inf, 0.0), "LAM" => Truncated(Normal(-18.2021,1.5404), -Inf, 0.0), "SAS" => Truncated(Normal(0.0473,2.1468), 0.0, Inf), "SEA" => Truncated(Normal(0.0413,1.2044), 0.0, Inf), "CHI" => Truncated(Normal(-84.8815,2.8242), -Inf, 0.0), "MAF" => Truncated(Normal(0.0473,1.5704), 0.0, Inf), "SSA" => Truncated(Normal(0.0448,0.7861), 0.0, Inf), "SIS" => Truncated(Normal(-2.3428,0.9733), -Inf, 0.0)]
    impactcardiovascularrespiratory.ccplbm = ["USA" => Truncated(Normal(-161.4521,62.3397), -Inf, 0.0), "CAN" => Truncated(Normal(-205.4176,62.3397), -Inf, 0.0), "WEU" => Truncated(Normal(-145.9539,23.8362), -Inf, 0.0), "JPK" => Truncated(Normal(-33.683,24.9641), -Inf, 0.0), "ANZ" => Truncated(Normal(-91.0606,53.2451), -Inf, 0.0), "EEU" => Truncated(Normal(-201.8789,27.0842), -Inf, 0.0), "FSU" => Truncated(Normal(-190.3936,62.3397), -Inf, 0.0), "MDE" => Truncated(Normal(-136.8033,30.2768), -Inf, 0.0), "CAM" => Truncated(Normal(-54.1635,45.5739), -Inf, 0.0), "LAM" => Truncated(Normal(-78.4126,32.7397), -Inf, 0.0), "SAS" => Truncated(Normal(-80.232,51.2055), -Inf, 0.0), "SEA" => Truncated(Normal(12.0899,12.0535), 0.0, Inf), "CHI" => Truncated(Normal(-66.6796,43.8249), -Inf, 0.0), "MAF" => Truncated(Normal(-102.4339,35.4522), -Inf, 0.0), "SSA" => Truncated(Normal(-49.97,16.5999), -Inf, 0.0), "SIS" => Truncated(Normal(-10.4503,7.4943), -Inf, 0.0)]
    impactcardiovascularrespiratory.ccpqbm = ["USA" => Truncated(Normal(2.8314,62.308), 0.0, Inf), "CAN" => Truncated(Normal(2.8314,62.308), 0.0, Inf), "WEU" => Truncated(Normal(2.8279,23.8241), 0.0, Inf), "JPK" => Truncated(Normal(1.2018,24.9514), 0.0, Inf), "ANZ" => Truncated(Normal(2.8314,53.218), 0.0, Inf), "EEU" => Truncated(Normal(2.8314,27.0704), 0.0, Inf), "FSU" => Truncated(Normal(2.8314,62.308), 0.0, Inf), "MDE" => Truncated(Normal(2.7443,30.2614), 0.0, Inf), "CAM" => Truncated(Normal(2.7085,45.5507), 0.0, Inf), "LAM" => Truncated(Normal(2.8094,32.723), 0.0, Inf), "SAS" => Truncated(Normal(2.8314,51.1794), 0.0, Inf), "SEA" => Truncated(Normal(-1.1081,12.0474), -Inf, 0.0), "CHI" => Truncated(Normal(2.0193,43.8025), 0.0, Inf), "MAF" => Truncated(Normal(2.8314,35.4341), 0.0, Inf), "SSA" => Truncated(Normal(2.6771,16.5915), 0.0, Inf), "SIS" => Truncated(Normal(0.5138,7.4905), 0.0, Inf)]
    impactcooling.cebm = ["USA" => Truncated(Normal(-0.00212,0.00212), -Inf, 0.0), "CAN" => Truncated(Normal(-0.00186,0.00186), -Inf, 0.0), "WEU" => Truncated(Normal(-0.00372,0.00372), -Inf, 0.0), "JPK" => Truncated(Normal(-0.00029,0.00029), -Inf, 0.0), "ANZ" => Truncated(Normal(-0.00021,0.00021), -Inf, 0.0), "EEU" => Truncated(Normal(-0.00185,0.00185), -Inf, 0.0), "FSU" => Truncated(Normal(-0.00674,0.00674), -Inf, 0.0), "MDE" => Truncated(Normal(-0.00233,0.00233), -Inf, 0.0), "CAM" => Truncated(Normal(-0.00239,0.00239), -Inf, 0.0), "LAM" => Truncated(Normal(-0.00259,0.00259), -Inf, 0.0), "SAS" => Truncated(Normal(-0.00384,0.00384), -Inf, 0.0), "SEA" => Truncated(Normal(-0.0074,0.0074), -Inf, 0.0), "CHI" => Truncated(Normal(-0.02891,0.02891), -Inf, 0.0), "MAF" => Truncated(Normal(-0.01892,0.01892), -Inf, 0.0), "SSA" => Truncated(Normal(-0.00797,0.00797), -Inf, 0.0), "SIS" => Truncated(Normal(-0.00239,0.00239), -Inf, 0.0)]
    impactcooling.ceel = Truncated(Normal(0.8,0.2), 0.0, 1.0)
    impactcooling.cenl = Truncated(Normal(1.5,0.5), 0.0, Inf)
    emissions.ch4add = Normal(0.0,6.8346)
    impactcardiovascularrespiratory.chmlbm = ["USA" => Truncated(Normal(1.0988,1.0738), 0.0, Inf), "CAN" => Truncated(Normal(1.0705,1.0738), 0.0, Inf), "WEU" => Truncated(Normal(0.4022,0.4226), 0.0, Inf), "JPK" => Truncated(Normal(1.0356,1.1234), 0.0, Inf), "ANZ" => Truncated(Normal(0.4493,0.9147), 0.0, Inf), "EEU" => Truncated(Normal(0.6119,0.4767), 0.0, Inf), "FSU" => Truncated(Normal(0.6468,1.0738), 0.0, Inf), "MDE" => Truncated(Normal(1.0931,0.4791), 0.0, Inf), "CAM" => Truncated(Normal(0.9144,0.8887), 0.0, Inf), "LAM" => Truncated(Normal(0.5893,0.5874), 0.0, Inf), "SAS" => Truncated(Normal(1.6317,0.8373), 0.0, Inf), "SEA" => Truncated(Normal(0.8545,0.4641), 0.0, Inf), "CHI" => Truncated(Normal(0.7565,1.0335), 0.0, Inf), "MAF" => Truncated(Normal(1.0409,0.5662), 0.0, Inf), "SSA" => Truncated(Normal(0.8682,0.3408), 0.0, Inf), "SIS" => Truncated(Normal(1.0227,0.4957), 0.0, Inf)]
    impactcardiovascularrespiratory.chmqbm = ["USA" => Truncated(Normal(0.0471,0.8815), 0.0, Inf), "CAN" => Truncated(Normal(0.0471,0.8815), 0.0, Inf), "WEU" => Truncated(Normal(0.0467,0.3469), 0.0, Inf), "JPK" => Truncated(Normal(0.0559,0.9223), 0.0, Inf), "ANZ" => Truncated(Normal(0.047,0.7509), 0.0, Inf), "EEU" => Truncated(Normal(0.047,0.3914), 0.0, Inf), "FSU" => Truncated(Normal(0.0471,0.8815), 0.0, Inf), "MDE" => Truncated(Normal(0.0452,0.3933), 0.0, Inf), "CAM" => Truncated(Normal(0.0471,0.7296), 0.0, Inf), "LAM" => Truncated(Normal(0.047,0.4823), 0.0, Inf), "SAS" => Truncated(Normal(0.047,0.6874), 0.0, Inf), "SEA" => Truncated(Normal(0.0411,0.381), 0.0, Inf), "CHI" => Truncated(Normal(0.0474,0.8485), 0.0, Inf), "MAF" => Truncated(Normal(0.0471,0.4648), 0.0, Inf), "SSA" => Truncated(Normal(0.044,0.2798), 0.0, Inf), "SIS" => Truncated(Normal(0.0324,0.407), 0.0, Inf)]
    impactcardiovascularrespiratory.chplbm = ["USA" => Truncated(Normal(34.9374,42.9155), 0.0, Inf), "CAN" => Truncated(Normal(27.328,42.9155), 0.0, Inf), "WEU" => Truncated(Normal(25.757,17.8447), 0.0, Inf), "JPK" => Truncated(Normal(8.2986,17.7713), 0.0, Inf), "ANZ" => Truncated(Normal(18.8372,36.7267), 0.0, Inf), "EEU" => Truncated(Normal(29.6249,18.8672), 0.0, Inf), "FSU" => Truncated(Normal(36.4415,42.9155), 0.0, Inf), "MDE" => Truncated(Normal(50.5493,20.6547), 0.0, Inf), "CAM" => Truncated(Normal(44.7697,34.4286), 0.0, Inf), "LAM" => Truncated(Normal(33.7621,23.0347), 0.0, Inf), "SAS" => Truncated(Normal(74.5092,36.2131), 0.0, Inf), "SEA" => Truncated(Normal(-18.7223,8.1867), -Inf, 0.0), "CHI" => Truncated(Normal(82.0355,29.0776), 0.0, Inf), "MAF" => Truncated(Normal(50.4842,23.0206), 0.0, Inf), "SSA" => Truncated(Normal(43.4397,13.5145), 0.0, Inf), "SIS" => Truncated(Normal(16.9938,8.0489), 0.0, Inf)]
    impactcardiovascularrespiratory.chpqbm = ["USA" => Truncated(Normal(1.7285,35.2319), 0.0, Inf), "CAN" => Truncated(Normal(1.7285,35.2319), 0.0, Inf), "WEU" => Truncated(Normal(1.7966,14.6498), 0.0, Inf), "JPK" => Truncated(Normal(0.7493,14.5895), 0.0, Inf), "ANZ" => Truncated(Normal(1.7286,30.1512), 0.0, Inf), "EEU" => Truncated(Normal(1.7531,15.4893), 0.0, Inf), "FSU" => Truncated(Normal(1.7285,35.2319), 0.0, Inf), "MDE" => Truncated(Normal(1.7011,16.9568), 0.0, Inf), "CAM" => Truncated(Normal(1.662,28.2646), 0.0, Inf), "LAM" => Truncated(Normal(1.7535,18.9106), 0.0, Inf), "SAS" => Truncated(Normal(1.7378,29.7296), 0.0, Inf), "SEA" => Truncated(Normal(-0.6683,6.721), -Inf, 0.0), "CHI" => Truncated(Normal(1.2095,23.8716), 0.0, Inf), "MAF" => Truncated(Normal(1.7096,18.8991), 0.0, Inf), "SSA" => Truncated(Normal(1.6578,11.0949), 0.0, Inf), "SIS" => Truncated(Normal(0.4223,6.6079), 0.0, Inf)]
    climatedynamics.climatesensitivity = Truncated(Gamma(6.47815626,0.547629469), 1.0, Inf)
    impactcardiovascularrespiratory.cvlin = Truncated(Normal(0.025901,0.009574), 0.0, Inf)
    impactvectorbornediseases.dfch = ["USA" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "CAN" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "WEU" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "JPK" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "ANZ" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "EEU" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "FSU" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "MDE" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "CAM" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "LAM" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "SAS" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "SEA" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "CHI" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "MAF" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "SSA" => Truncated(Normal(0.3534,0.0614), 0.0, Inf), "SIS" => Truncated(Normal(0.3534,0.0614), 0.0, Inf)]
    impactvectorbornediseases.dfnl = Truncated(Normal(1.0,0.5), 0.0, Inf)
    impactdiarrhoea.diamortel = Truncated(Normal(-1.578625,0.232507), -Inf, 0.0)
    impactdiarrhoea.diamortnl = Truncated(Normal(1.141714,0.508302), 0.0, Inf)
    impactdiarrhoea.diayldel = Truncated(Normal(-0.418406,0.119223), -1.0, 0.0)
    impactdiarrhoea.diayldnl = Truncated(Normal(0.699241,0.260643), 0.0, Inf)
    impactsealevelrise.dlbm = ["USA" => Truncated(Normal(20000.0,10000.0), 0.0, Inf), "CAN" => Truncated(Normal(970.0,970.0), 0.0, Inf), "WEU" => Truncated(Normal(4212.0,1273.0), 0.0, Inf), "JPK" => Truncated(Normal(2687.0,1213.0), 0.0, Inf), "ANZ" => Truncated(Normal(3135.0,2920.0), 0.0, Inf), "EEU" => Truncated(Normal(1889.0,860.0), 0.0, Inf), "FSU" => Truncated(Normal(15138.0,15138.0), 0.0, Inf), "MDE" => Truncated(Normal(1621.0,1025.0), 0.0, Inf), "CAM" => Truncated(Normal(12004.0,8033.0), 0.0, Inf), "LAM" => Truncated(Normal(29407.0,11847.0), 0.0, Inf), "SAS" => Truncated(Normal(81275.0,49361.0), 0.0, Inf), "SEA" => Truncated(Normal(157286.0,90170.0), 0.0, Inf), "CHI" => Truncated(Normal(35000.0,17500.0), 0.0, Inf), "MAF" => Truncated(Normal(8354.0,3478.0), 0.0, Inf), "SSA" => Truncated(Normal(126602.0,63820.0), 0.0, Inf), "SIS" => Truncated(Normal(1505.0,628.0), 0.0, Inf)]
    impactsealevelrise.drylandlossparam = ["USA" => Truncated(Normal(0.583433160330257,0.0310749451958314), 0.0, 1.0), "CAN" => Truncated(Normal(0.260515053189669,0.0137582984542109), 0.0, 1.0), "WEU" => Truncated(Normal(0.273314149409615,0.0146688810943221), 0.0, 1.0), "JPK" => Truncated(Normal(0.412066944374299,0.0268279386449215), 0.0, 1.0), "ANZ" => Truncated(Normal(0.548496484507909,0.0353090095289534), 0.0, 1.0), "EEU" => Truncated(Normal(0.193491238230705,0.0120297038764903), 0.0, 1.0), "FSU" => Truncated(Normal(0.555487676094765,0.0344126167165359), 0.0, 1.0), "MDE" => Truncated(Normal(0.628422279667412,0.00914652560895185), 0.0, 1.0), "CAM" => Truncated(Normal(0.678302864355753,0.0264748504908147), 0.0, 1.0), "LAM" => Truncated(Normal(0.756134247750368,0.0200692929944761), 0.0, 1.0), "SAS" => Truncated(Normal(0.929957316565567,0.0241559579142168), 0.0, 1.0), "SEA" => Truncated(Normal(0.81223935947527,0.0429547897395688), 0.0, 1.0), "CHI" => Truncated(Normal(0.707719142022655,0.0243920096916722), 0.0, 1.0), "MAF" => Truncated(Normal(0.336949623686827,0.0195350728174195), 0.0, 1.0), "SSA" => Truncated(Normal(0.798533208857799,0.0442837491243777), 0.0, 1.0), "SIS" => Truncated(Normal(0.667255915065629,0.0408474363982656), 0.0, 1.0)]
    impactsealevelrise.dvbm = Truncated(Normal(0.004,0.002), 0.0, Inf)
    impactsealevelrise.dvydl = Truncated(Normal(1.0,0.25), 0.0, Inf)
    scenariouncertainty.ecgradd = ["USA" => Truncated(Normal(0.0,0.28), -0.645266515499562, 1.35473348450044), "CAN" => Truncated(Normal(0.0,0.28), -0.645266515499562, 1.35473348450044), "WEU" => Truncated(Normal(0.0,0.2775), -0.645129685612399, 1.3548703143876), "JPK" => Truncated(Normal(0.0,0.2825), -0.645237785006474, 1.35476221499353), "ANZ" => Truncated(Normal(0.0,0.2825), -0.645237785006474, 1.35476221499353), "EEU" => Truncated(Normal(0.0,0.4825), -0.702791192885658, 1.29720880711434), "FSU" => Truncated(Normal(0.0,0.4825), -0.702791192885658, 1.29720880711434), "MDE" => Truncated(Normal(0.0,0.65), -0.751960508718775, 1.24803949128122), "CAM" => Truncated(Normal(0.0,0.65), -0.751960508718775, 1.24803949128122), "LAM" => Truncated(Normal(0.0,0.65), -0.751960508718775, 1.24803949128122), "SAS" => Truncated(Normal(0.0,0.65), -0.751960508718775, 1.24803949128122), "SEA" => Truncated(Normal(0.0,0.65), -0.751960508718775, 1.24803949128122), "CHI" => Truncated(Normal(0.0,0.7125), -0.761043730670382, 1.23895626932962), "MAF" => Truncated(Normal(0.0,0.65), -0.751960508718775, 1.24803949128122), "SSA" => Truncated(Normal(0.0,0.65), -0.751960508718775, 1.24803949128122), "SIS" => Truncated(Normal(0.0,0.65), -0.751960508718775, 1.24803949128122)]
    impactsealevelrise.emcst = Truncated(Normal(3.0,1.5), 0.0, Inf)
    impactextratropicalstorms.extratropicalstormsdamel = Truncated(Normal(-0.514,0.027), -1.0, 0.0)
    impactextratropicalstorms.extratropicalstormsdeadel = Truncated(Normal(-0.501,0.051), -1.0, 0.0)
    impactforests.forbm = ["USA" => Normal(5.325e-5,1.422e-5), "CAN" => Normal(1.123e-5,7.152e-5), "WEU" => Normal(2.528e-5,5.7e-6), "JPK" => Normal(4.173e-5,1.235e-5), "ANZ" => Normal(-0.0001211,3.255e-5), "EEU" => Normal(5.462e-5,2.472e-5), "FSU" => Normal(-2.348e-5,5.312e-5), "MDE" => Normal(0.0,3.386e-5), "CAM" => Normal(1.806e-5,3.429e-5), "LAM" => Normal(2.411e-5,1.195e-5), "SAS" => Normal(6.237e-5,2.294e-5), "SEA" => Normal(6.674e-5,2.772e-5), "CHI" => Normal(8.723e-5,3.22e-5), "MAF" => Normal(0.0,3.386e-5), "SSA" => Normal(1.141e-5,3.459e-5), "SIS" => Normal(0.0,3.386e-5)]
    impactforests.forco2 = Truncated(Normal(2.2972,1.1486), 0.0, Inf)
    impactforests.forel = Truncated(Normal(-0.31,0.2), -1.0, 0.0)
    scenariouncertainty.foremadd = ["USA" => Normal(0.0,0.2025), "CAN" => Normal(0.0,0.2025), "CAM" => Normal(0.0,3.185), "LAM" => Normal(0.0,28.66), "SAS" => Normal(0.0,4.0375), "SEA" => Normal(0.0,12.1125), "CHI" => Normal(0.0,1.2675), "SSA" => Normal(0.0,11.76)]
    impactforests.fornl = Truncated(Normal(1.0,0.5), 0.0, Inf)
    impactheating.hebm = ["USA" => Truncated(Normal(0.00429,0.00429), 0.0, Inf), "CAN" => Truncated(Normal(0.00378,0.00378), 0.0, Inf), "WEU" => Truncated(Normal(0.00241,0.00241), 0.0, Inf), "JPK" => Truncated(Normal(0.00207,0.00207), 0.0, Inf), "ANZ" => Truncated(Normal(0.00151,0.00151), 0.0, Inf), "EEU" => Truncated(Normal(0.00456,0.00456), 0.0, Inf), "FSU" => Truncated(Normal(0.01663,0.01663), 0.0, Inf), "MDE" => Truncated(Normal(0.02074,0.02074), 0.0, Inf), "CAM" => Truncated(Normal(0.00366,0.00366), 0.0, Inf), "LAM" => Truncated(Normal(0.00395,0.00395), 0.0, Inf), "SAS" => Truncated(Normal(0.00361,0.00361), 0.0, Inf), "SEA" => Truncated(Normal(0.00695,0.00695), 0.0, Inf), "CHI" => Truncated(Normal(0.03971,0.03971), 0.0, Inf), "MAF" => Truncated(Normal(0.00015,0.00015), 0.0, Inf), "SSA" => Truncated(Normal(6.0e-5,6.0e-5), 0.0, Inf), "SIS" => Truncated(Normal(0.00366,0.00366), 0.0, Inf)]
    impactheating.heel = Truncated(Normal(0.8,0.1), 0.0, 1.0)
    impactheating.henl = Truncated(Normal(0.5,0.5), 0.0, Inf)
    impacttropicalstorms.hurrdamel = Truncated(Normal(-0.514,0.027), -1.0, 0.0)
    impacttropicalstorms.hurrdeadel = Truncated(Normal(-0.501,0.051), -1.0, 0.0)
    impacttropicalstorms.hurrpar = Normal(0.04,0.005)
    impactsealevelrise.immcst = Truncated(Normal(0.4,0.2), 0.0, Inf)
    climatech4cycle.lifech4 = TriangularDist(8.0, 16.0, 12.0)
    climateco2cycle.lifeco2 = Truncated(Normal(363.0,90.75), 0.0, Inf)
    climateco2cycle.lifeco3 = Truncated(Normal(74.0,18.5), 0.0, Inf)
    climateco2cycle.lifeco4 = Truncated(Normal(17.0,4.25), 0.0, Inf)
    climateco2cycle.lifeco5 = Truncated(Normal(2.0,0.5), 0.0, Inf)
    climaten2ocycle.lifen2o = TriangularDist(100.0, 170.0, 114.0)
    ocean.lifesea = TriangularDist(250.0, 1000.0, 500.0)
    climatesf6cycle.lifesf6 = TriangularDist(1600.0, 4800.0, 3200.0)
    impactvectorbornediseases.malch = ["USA" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "CAN" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "WEU" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "JPK" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "ANZ" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "EEU" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "FSU" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "MDE" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "CAM" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "LAM" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "SAS" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "SEA" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "CHI" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "MAF" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "SSA" => Truncated(Normal(0.0794,0.0575), 0.0, Inf), "SIS" => Truncated(Normal(0.0794,0.0575), 0.0, Inf)]
    impactvectorbornediseases.malnl = Truncated(Normal(1.0,0.5), 0.0, Inf)
    impactcardiovascularrespiratory.maxcardvasc = Truncated(Normal(0.05,0.02), 0.0, Inf)
    impactsealevelrise.migrate = [["USA", "USA"] => Gamma(101.990195135928,0.00990195135927852), ["USA", "CAN"] => Gamma(1.0,0.05), ["USA", "WEU"] => Gamma(1.0,0.05), ["USA", "JPK"] => Gamma(1.0,0.05), ["USA", "ANZ"] => Gamma(1.0,0.05), ["USA", "EEU"] => Gamma(1.0,0.05), ["USA", "FSU"] => Gamma(1.0,0.05), ["USA", "MDE"] => Gamma(2.0,0.04), ["USA", "CAM"] => Gamma(2.0,0.1), ["USA", "LAM"] => Gamma(2.0,0.1), ["USA", "SAS"] => Gamma(2.0,0.04), ["USA", "SEA"] => Gamma(2.0,0.04), ["USA", "CHI"] => Gamma(2.0,0.04), ["USA", "MAF"] => Gamma(2.0,0.01), ["USA", "SSA"] => Gamma(2.0,0.03), ["USA", "SIS"] => Gamma(2.0,0.15), ["CAN", "USA"] => Gamma(1.0,0.05), ["CAN", "CAN"] => Gamma(101.990195135928,0.00990195135927852), ["CAN", "WEU"] => Gamma(1.0,0.02), ["CAN", "JPK"] => Gamma(1.0,0.02), ["CAN", "ANZ"] => Gamma(1.0,0.02), ["CAN", "EEU"] => Gamma(1.0,0.02), ["CAN", "FSU"] => Gamma(1.0,0.02), ["CAN", "MDE"] => Gamma(2.0,0.01), ["CAN", "CAM"] => Gamma(1.0,0.05), ["CAN", "LAM"] => Gamma(1.0,0.05), ["CAN", "SAS"] => Gamma(2.0,0.01), ["CAN", "SEA"] => Gamma(2.0,0.01), ["CAN", "CHI"] => Gamma(2.0,0.01), ["CAN", "MAF"] => Gamma(1.0,0.005), ["CAN", "SSA"] => Gamma(2.0,0.005), ["CAN", "SIS"] => Gamma(2.0,0.1), ["WEU", "USA"] => Gamma(1.0,0.02), ["WEU", "CAN"] => Gamma(1.0,0.02), ["WEU", "WEU"] => Gamma(101.990195135928,0.00990195135927852), ["WEU", "JPK"] => Gamma(1.0,0.02), ["WEU", "ANZ"] => Gamma(1.0,0.02), ["WEU", "EEU"] => Gamma(1.0,0.02), ["WEU", "FSU"] => Gamma(1.0,0.02), ["WEU", "MDE"] => Gamma(2.0,0.04), ["WEU", "CAM"] => Gamma(1.0,0.05), ["WEU", "LAM"] => Gamma(1.0,0.05), ["WEU", "SAS"] => Gamma(2.0,0.04), ["WEU", "SEA"] => Gamma(2.0,0.02), ["WEU", "CHI"] => Gamma(2.0,0.02), ["WEU", "MAF"] => Gamma(2.0,0.09), ["WEU", "SSA"] => Gamma(2.0,0.06), ["WEU", "SIS"] => Gamma(2.0,0.15), ["JPK", "USA"] => Gamma(1.0,0.01), ["JPK", "CAN"] => Gamma(1.0,0.01), ["JPK", "WEU"] => Gamma(1.0,0.01), ["JPK", "JPK"] => Gamma(101.990195135928,0.00990195135927852), ["JPK", "ANZ"] => Gamma(1.0,0.01), ["JPK", "EEU"] => Gamma(1.0,0.001), ["JPK", "FSU"] => Gamma(1.0,0.001), ["JPK", "MDE"] => Gamma(1.0,0.005), ["JPK", "CAM"] => Gamma(1.0,0.01), ["JPK", "LAM"] => Gamma(1.0,0.01), ["JPK", "SAS"] => Gamma(2.0,0.005), ["JPK", "SEA"] => Gamma(2.0,0.01), ["JPK", "CHI"] => Gamma(2.0,0.01), ["JPK", "MAF"] => Gamma(1.0,0.001), ["JPK", "SSA"] => Gamma(1.0,0.001), ["JPK", "SIS"] => Gamma(2.0,0.05), ["ANZ", "USA"] => Gamma(1.0,0.02), ["ANZ", "CAN"] => Gamma(1.0,0.02), ["ANZ", "WEU"] => Gamma(1.0,0.02), ["ANZ", "JPK"] => Gamma(1.0,0.02), ["ANZ", "ANZ"] => Gamma(101.990195135928,0.00990195135927852), ["ANZ", "EEU"] => Gamma(1.0,0.01), ["ANZ", "FSU"] => Gamma(1.0,0.01), ["ANZ", "MDE"] => Gamma(2.0,0.01), ["ANZ", "CAM"] => Gamma(1.0,0.01), ["ANZ", "LAM"] => Gamma(1.0,0.01), ["ANZ", "SAS"] => Gamma(2.0,0.005), ["ANZ", "SEA"] => Gamma(2.0,0.02), ["ANZ", "CHI"] => Gamma(2.0,0.02), ["ANZ", "MAF"] => Gamma(1.0,0.005), ["ANZ", "SSA"] => Gamma(2.0,0.005), ["ANZ", "SIS"] => Gamma(2.0,0.15), ["EEU", "USA"] => Gamma(1.0,0.001), ["EEU", "CAN"] => Gamma(1.0,0.001), ["EEU", "WEU"] => Gamma(1.0,0.001), ["EEU", "JPK"] => Gamma(1.0,0.001), ["EEU", "ANZ"] => Gamma(1.0,0.001), ["EEU", "EEU"] => Gamma(101.990195135928,0.00990195135927852), ["EEU", "FSU"] => Gamma(1.0,0.05), ["EEU", "MDE"] => Gamma(1.0,0.001), ["EEU", "CAM"] => Gamma(1.0,0.001), ["EEU", "LAM"] => Gamma(1.0,0.001), ["EEU", "SAS"] => Gamma(1.0,0.001), ["EEU", "SEA"] => Gamma(1.0,0.001), ["EEU", "CHI"] => Gamma(1.0,0.001), ["EEU", "MAF"] => Gamma(1.0,0.001), ["EEU", "SSA"] => Gamma(1.0,0.001), ["EEU", "SIS"] => Gamma(1.0,0.001), ["FSU", "USA"] => Gamma(1.0,0.001), ["FSU", "CAN"] => Gamma(1.0,0.001), ["FSU", "WEU"] => Gamma(1.0,0.001), ["FSU", "JPK"] => Gamma(1.0,0.001), ["FSU", "ANZ"] => Gamma(1.0,0.001), ["FSU", "EEU"] => Gamma(1.0,0.001), ["FSU", "FSU"] => Gamma(101.990195135928,0.00990195135927852), ["FSU", "MDE"] => Gamma(1.0,0.001), ["FSU", "CAM"] => Gamma(1.0,0.001), ["FSU", "LAM"] => Gamma(1.0,0.001), ["FSU", "SAS"] => Gamma(1.0,0.001), ["FSU", "SEA"] => Gamma(1.0,0.001), ["FSU", "CHI"] => Gamma(1.0,0.001), ["FSU", "MAF"] => Gamma(1.0,0.001), ["FSU", "SSA"] => Gamma(1.0,0.001), ["FSU", "SIS"] => Gamma(1.0,0.001), ["MDE", "USA"] => Gamma(1.0,0.001), ["MDE", "CAN"] => Gamma(1.0,0.001), ["MDE", "WEU"] => Gamma(1.0,0.001), ["MDE", "JPK"] => Gamma(1.0,0.001), ["MDE", "ANZ"] => Gamma(1.0,0.001), ["MDE", "EEU"] => Gamma(1.0,0.001), ["MDE", "FSU"] => Gamma(1.0,0.001), ["MDE", "MDE"] => Gamma(82.987950057818,0.0109772228646444), ["MDE", "CAM"] => Gamma(1.0,0.001), ["MDE", "LAM"] => Gamma(1.0,0.001), ["MDE", "SAS"] => Gamma(1.0,0.001), ["MDE", "SEA"] => Gamma(1.0,0.001), ["MDE", "CHI"] => Gamma(1.0,0.001), ["MDE", "MAF"] => Gamma(1.0,0.001), ["MDE", "SSA"] => Gamma(1.0,0.001), ["MDE", "SIS"] => Gamma(1.0,0.001), ["CAM", "USA"] => Gamma(1.0,0.001), ["CAM", "CAN"] => Gamma(1.0,0.001), ["CAM", "WEU"] => Gamma(1.0,0.001), ["CAM", "JPK"] => Gamma(1.0,0.001), ["CAM", "ANZ"] => Gamma(1.0,0.001), ["CAM", "EEU"] => Gamma(1.0,0.001), ["CAM", "FSU"] => Gamma(1.0,0.001), ["CAM", "MDE"] => Gamma(1.0,0.001), ["CAM", "CAM"] => Gamma(82.987950057818,0.0109772228646444), ["CAM", "LAM"] => Gamma(1.0,0.005), ["CAM", "SAS"] => Gamma(1.0,0.001), ["CAM", "SEA"] => Gamma(1.0,0.001), ["CAM", "CHI"] => Gamma(1.0,0.001), ["CAM", "MAF"] => Gamma(1.0,0.001), ["CAM", "SSA"] => Gamma(1.0,0.001), ["CAM", "SIS"] => Gamma(2.0,0.1), ["LAM", "USA"] => Gamma(1.0,0.001), ["LAM", "CAN"] => Gamma(1.0,0.001), ["LAM", "WEU"] => Gamma(1.0,0.001), ["LAM", "JPK"] => Gamma(1.0,0.001), ["LAM", "ANZ"] => Gamma(1.0,0.001), ["LAM", "EEU"] => Gamma(1.0,0.001), ["LAM", "FSU"] => Gamma(1.0,0.001), ["LAM", "MDE"] => Gamma(1.0,0.001), ["LAM", "CAM"] => Gamma(1.0,0.005), ["LAM", "LAM"] => Gamma(82.987950057818,0.0109772228646444), ["LAM", "SAS"] => Gamma(1.0,0.001), ["LAM", "SEA"] => Gamma(1.0,0.001), ["LAM", "CHI"] => Gamma(1.0,0.001), ["LAM", "MAF"] => Gamma(1.0,0.001), ["LAM", "SSA"] => Gamma(1.0,0.001), ["LAM", "SIS"] => Gamma(2.0,0.1), ["SAS", "USA"] => Gamma(1.0,0.001), ["SAS", "CAN"] => Gamma(1.0,0.001), ["SAS", "WEU"] => Gamma(1.0,0.001), ["SAS", "JPK"] => Gamma(1.0,0.001), ["SAS", "ANZ"] => Gamma(1.0,0.001), ["SAS", "EEU"] => Gamma(1.0,0.001), ["SAS", "FSU"] => Gamma(1.0,0.001), ["SAS", "MDE"] => Gamma(1.0,0.001), ["SAS", "CAM"] => Gamma(1.0,0.001), ["SAS", "LAM"] => Gamma(1.0,0.001), ["SAS", "SAS"] => Gamma(82.987950057818,0.0109772228646444), ["SAS", "SEA"] => Gamma(1.0,0.005), ["SAS", "CHI"] => Gamma(1.0,0.001), ["SAS", "MAF"] => Gamma(1.0,0.001), ["SAS", "SSA"] => Gamma(1.0,0.001), ["SAS", "SIS"] => Gamma(2.0,0.1), ["SEA", "USA"] => Gamma(1.0,0.001), ["SEA", "CAN"] => Gamma(1.0,0.001), ["SEA", "WEU"] => Gamma(1.0,0.001), ["SEA", "JPK"] => Gamma(1.0,0.001), ["SEA", "ANZ"] => Gamma(1.0,0.001), ["SEA", "EEU"] => Gamma(1.0,0.001), ["SEA", "FSU"] => Gamma(1.0,0.001), ["SEA", "MDE"] => Gamma(1.0,0.001), ["SEA", "CAM"] => Gamma(1.0,0.001), ["SEA", "LAM"] => Gamma(1.0,0.001), ["SEA", "SAS"] => Gamma(1.0,0.005), ["SEA", "SEA"] => Gamma(82.987950057818,0.0109772228646444), ["SEA", "CHI"] => Gamma(1.0,0.005), ["SEA", "MAF"] => Gamma(1.0,0.001), ["SEA", "SSA"] => Gamma(1.0,0.001), ["SEA", "SIS"] => Gamma(2.0,0.1), ["CHI", "USA"] => Gamma(1.0,0.001), ["CHI", "CAN"] => Gamma(1.0,0.001), ["CHI", "WEU"] => Gamma(1.0,0.001), ["CHI", "JPK"] => Gamma(1.0,0.001), ["CHI", "ANZ"] => Gamma(1.0,0.001), ["CHI", "EEU"] => Gamma(1.0,0.001), ["CHI", "FSU"] => Gamma(1.0,0.001), ["CHI", "MDE"] => Gamma(1.0,0.001), ["CHI", "CAM"] => Gamma(1.0,0.001), ["CHI", "LAM"] => Gamma(1.0,0.001), ["CHI", "SAS"] => Gamma(1.0,0.001), ["CHI", "SEA"] => Gamma(1.0,0.001), ["CHI", "CHI"] => Gamma(82.987950057818,0.0109772228646444), ["CHI", "MAF"] => Gamma(1.0,0.001), ["CHI", "SSA"] => Gamma(1.0,0.001), ["CHI", "SIS"] => Gamma(1.0,0.001), ["MAF", "USA"] => Gamma(1.0,0.001), ["MAF", "CAN"] => Gamma(1.0,0.001), ["MAF", "WEU"] => Gamma(1.0,0.001), ["MAF", "JPK"] => Gamma(1.0,0.001), ["MAF", "ANZ"] => Gamma(1.0,0.001), ["MAF", "EEU"] => Gamma(1.0,0.001), ["MAF", "FSU"] => Gamma(1.0,0.001), ["MAF", "MDE"] => Gamma(1.0,0.001), ["MAF", "CAM"] => Gamma(1.0,0.001), ["MAF", "LAM"] => Gamma(1.0,0.001), ["MAF", "SAS"] => Gamma(1.0,0.001), ["MAF", "SEA"] => Gamma(1.0,0.001), ["MAF", "CHI"] => Gamma(1.0,0.001), ["MAF", "MAF"] => Gamma(82.987950057818,0.0109772228646444), ["MAF", "SSA"] => Gamma(1.0,0.005), ["MAF", "SIS"] => Gamma(1.0,0.001), ["SSA", "USA"] => Gamma(1.0,0.001), ["SSA", "CAN"] => Gamma(1.0,0.001), ["SSA", "WEU"] => Gamma(1.0,0.001), ["SSA", "JPK"] => Gamma(1.0,0.001), ["SSA", "ANZ"] => Gamma(1.0,0.001), ["SSA", "EEU"] => Gamma(1.0,0.001), ["SSA", "FSU"] => Gamma(1.0,0.001), ["SSA", "MDE"] => Gamma(1.0,0.001), ["SSA", "CAM"] => Gamma(1.0,0.001), ["SSA", "LAM"] => Gamma(1.0,0.001), ["SSA", "SAS"] => Gamma(1.0,0.001), ["SSA", "SEA"] => Gamma(1.0,0.001), ["SSA", "CHI"] => Gamma(1.0,0.001), ["SSA", "MAF"] => Gamma(1.0,0.001), ["SSA", "SSA"] => Gamma(82.987950057818,0.0109772228646444), ["SSA", "SIS"] => Gamma(1.0,0.001), ["SIS", "USA"] => Gamma(1.0,0.001), ["SIS", "CAN"] => Gamma(1.0,0.001), ["SIS", "WEU"] => Gamma(1.0,0.001), ["SIS", "JPK"] => Gamma(1.0,0.001), ["SIS", "ANZ"] => Gamma(1.0,0.001), ["SIS", "EEU"] => Gamma(1.0,0.001), ["SIS", "FSU"] => Gamma(1.0,0.001), ["SIS", "MDE"] => Gamma(1.0,0.001), ["SIS", "CAM"] => Gamma(1.0,0.001), ["SIS", "LAM"] => Gamma(1.0,0.001), ["SIS", "SAS"] => Gamma(1.0,0.001), ["SIS", "SEA"] => Gamma(1.0,0.001), ["SIS", "CHI"] => Gamma(1.0,0.001), ["SIS", "MAF"] => Gamma(1.0,0.001), ["SIS", "SSA"] => Gamma(1.0,0.001), ["SIS", "SIS"] => Gamma(1.0,0.1)]
    emissions.n2oadd = Normal(0.0,0.0059)
    impactsealevelrise.pc = ["USA" => Truncated(Normal(95.3,95.3), 0.0, Inf), "CAN" => Truncated(Normal(13.0,13.0), 0.0, Inf), "WEU" => Truncated(Normal(153.9,52.6), 0.0, Inf), "JPK" => Truncated(Normal(75.5,54.7), 0.0, Inf), "ANZ" => Truncated(Normal(36.6,26.8), 0.0, Inf), "EEU" => Truncated(Normal(3.1,1.7), 0.0, Inf), "FSU" => Truncated(Normal(54.0,54.0), 0.0, Inf), "MDE" => Truncated(Normal(18.9,9.6), 0.0, Inf), "CAM" => Truncated(Normal(42.3,33.8), 0.0, Inf), "LAM" => Truncated(Normal(117.6,79.0), 0.0, Inf), "SAS" => Truncated(Normal(172.0,153.6), 0.0, Inf), "SEA" => Truncated(Normal(169.7,84.4), 0.0, Inf), "CHI" => Truncated(Normal(118.4,118.4), 0.0, Inf), "MAF" => Truncated(Normal(19.0,10.2), 0.0, Inf), "SSA" => Truncated(Normal(84.3,38.3), 0.0, Inf), "SIS" => Truncated(Normal(16.0,5.7), 0.0, Inf)]
    scenariouncertainty.pgadd = ["USA" => Normal(0.0,0.00625), "CAN" => Normal(0.0,0.00625), "WEU" => Normal(0.0,0.00625), "JPK" => Normal(0.0,0.01875), "ANZ" => Normal(0.0,0.01875), "EEU" => Normal(0.0,0.00625), "FSU" => Normal(0.0,0.00625), "MDE" => Normal(0.0,0.09375), "CAM" => Normal(0.0,0.0375), "LAM" => Normal(0.0,0.0375), "SAS" => Normal(0.0,0.09375), "SEA" => Normal(0.0,0.09375), "CHI" => Normal(0.0,0.01875), "MAF" => Normal(0.0,0.15625), "SSA" => Normal(0.0,0.15625), "SIS" => Normal(0.0,0.0375)]
    socioeconomic.plusel = Truncated(Normal(0.25,0.08), 0.0, Inf)
    impactcardiovascularrespiratory.rlbm = ["USA" => Normal(0.9452,6.7337), "CAN" => Normal(-1.9284,6.7337), "WEU" => Normal(-0.765,2.4863), "JPK" => Normal(0.4185,5.813), "ANZ" => Normal(0.2579,5.7279), "EEU" => Normal(-1.2946,2.9883), "FSU" => Normal(1.5277,6.7337), "MDE" => Normal(5.6711,3.069), "CAM" => Normal(3.8894,5.0789), "LAM" => Normal(1.0893,3.6563), "SAS" => Normal(10.2485,5.1264), "SEA" => Normal(4.8562,3.2809), "CHI" => Normal(4.4083,6.5634), "MAF" => Normal(5.198,3.7408), "SSA" => Normal(3.6196,1.8681), "SIS" => Normal(4.1354,2.033)]
    impactcardiovascularrespiratory.rlin = Truncated(Normal(0.001583,0.000457), 0.0, Inf)
    impactcardiovascularrespiratory.rqbm = ["USA" => Normal(0.4342,5.5281), "CAN" => Normal(0.4342,5.5281), "WEU" => Normal(0.4341,2.0412), "JPK" => Normal(0.4342,4.7723), "ANZ" => Normal(0.4342,4.7024), "EEU" => Normal(0.4342,2.4533), "FSU" => Normal(0.4342,5.5281), "MDE" => Normal(0.4194,2.5196), "CAM" => Normal(0.4342,4.1696), "LAM" => Normal(0.4335,3.0017), "SAS" => Normal(0.4342,4.2086), "SEA" => Normal(0.4339,2.6935), "CHI" => Normal(0.4319,5.3883), "MAF" => Normal(0.4341,3.0711), "SSA" => Normal(0.411,1.5337), "SIS" => Normal(0.2522,1.669)]
    ocean.seas = Gamma(6.0,0.4)
    emissions.sf6add = Normal(0.0,0.08)
    impactvectorbornediseases.smch = ["USA" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "CAN" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "WEU" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "JPK" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "ANZ" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "EEU" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "FSU" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "MDE" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "CAM" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "LAM" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "SAS" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "SEA" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "CHI" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "MAF" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "SSA" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0), "SIS" => Truncated(Normal(-0.1149,0.0614), -Inf, 0.0)]
    impactvectorbornediseases.smnl = Truncated(Normal(1.0,0.5), 0.0, Inf)
    impactbiodiversity.spbm = Truncated(Normal(50.0,50.0), 0.0, Inf)
    emissions.taxmp = ["USA" => Gamma(5.8284,0.2071), "CAN" => Gamma(5.8284,0.2071), "WEU" => Gamma(5.8284,0.2071), "JPK" => Gamma(5.8284,0.2071), "ANZ" => Gamma(5.8284,0.2071), "EEU" => Gamma(5.8284,0.2071), "FSU" => Gamma(5.8284,0.2071), "MDE" => Gamma(5.8284,0.2071), "CAM" => Gamma(5.8284,0.2071), "LAM" => Gamma(5.8284,0.2071), "SAS" => Gamma(5.8284,0.2071), "SEA" => Gamma(5.8284,0.2071), "CHI" => Gamma(5.8284,0.2071), "MAF" => Gamma(5.8284,0.2071), "SSA" => Gamma(5.8284,0.2071), "SIS" => Gamma(5.8284,0.2071)]
    climateco2cycle.terrco2sens = Gamma(4.92255,662.834125760029)
    impactbiodiversity.valinc = ["USA" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "CAN" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "WEU" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "JPK" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "ANZ" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "EEU" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "FSU" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "MDE" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "CAM" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "LAM" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "SAS" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "SEA" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "CHI" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "MAF" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "SSA" => Truncated(Normal(30000.0,10000.0), 0.0, Inf), "SIS" => Truncated(Normal(30000.0,10000.0), 0.0, Inf)]
    impactvectorbornediseases.vbel = Truncated(Normal(-2.65,0.69), -Inf, 0.0)
    vslvmorb.vmorbbm = Truncated(Normal(19970.090515545,29955.1357733176), 0.0, Inf)
    vslvmorb.vmorbel = Truncated(Normal(1.0,0.2), 0.0, Inf)
    vslvmorb.vslbm = Truncated(Normal(4.99252262888626e6,2.49626131444313e6), 0.0, Inf)
    vslvmorb.vslel = Truncated(Normal(1.0,0.2), 0.0, Inf)
    impactwaterresources.watechrate = Truncated(Normal(0.005,0.005), 0.0, Inf)
    impactsealevelrise.wlbm = ["USA" => Truncated(Normal(11400.0,5700.0), 0.0, Inf), "WEU" => Truncated(Normal(3210.0,1335.0), 0.0, Inf), "JPK" => Truncated(Normal(573.0,573.0), 0.0, Inf), "ANZ" => Truncated(Normal(256.0,256.0), 0.0, Inf), "EEU" => Truncated(Normal(38.0,18.0), 0.0, Inf), "CAM" => Truncated(Normal(14775.0,11171.0), 0.0, Inf), "LAM" => Truncated(Normal(27234.0,19016.0), 0.0, Inf), "SAS" => Truncated(Normal(14303.0,6005.0), 0.0, Inf), "SEA" => Truncated(Normal(50885.0,29599.0), 0.0, Inf), "CHI" => Truncated(Normal(5879.0,5879.0), 0.0, Inf), "MAF" => Truncated(Normal(2649.0,1989.0), 0.0, Inf), "SSA" => Truncated(Normal(27847.0,9024.0), 0.0, Inf), "SIS" => Truncated(Normal(1528.0,1067.0), 0.0, Inf)]
    impactsealevelrise.wmbm = ["USA" => Truncated(Normal(789.0,8344.0), 0.0, Inf), "WEU" => Truncated(Normal(903.0,2188.0), 0.0, Inf), "JPK" => Truncated(Normal(7.0,815.0), 0.0, Inf), "ANZ" => Truncated(Normal(183.0,508.0), 0.0, Inf), "EEU" => Truncated(Normal(0.0,26.0), 0.0, Inf), "CAM" => Truncated(Normal(238.0,15832.0), 0.0, Inf), "LAM" => Truncated(Normal(4748.0,28997.0), 0.0, Inf), "SAS" => Truncated(Normal(0.0,8492.0), 0.0, Inf), "SEA" => Truncated(Normal(4.0,41860.0), 0.0, Inf), "CHI" => Truncated(Normal(1779.0,9654.0), 0.0, Inf), "MAF" => Truncated(Normal(0.0,2814.0), 0.0, Inf), "SSA" => Truncated(Normal(345.0,12768.0), 0.0, Inf), "SIS" => Truncated(Normal(169.0,1516.0), 0.0, Inf)]
    impactwaterresources.wrbm = ["USA" => Normal(-0.00065,0.00065), "CAN" => Normal(-0.00057,0.00057), "WEU" => Normal(-0.00027,0.00027), "JPK" => Normal(3.0e-6,3.0e-6), "ANZ" => Normal(3.0e-6,3.0e-6), "EEU" => Normal(-0.00697,0.00697), "FSU" => Normal(-0.02754,0.02754), "MDE" => Normal(-0.00133,0.00133), "CAM" => Normal(-0.0013,0.0013), "LAM" => Normal(-0.0014,0.0014), "SAS" => Normal(-0.00156,0.00156), "SEA" => Normal(-0.00314,0.00314), "CHI" => Normal(0.00569,0.00569), "MAF" => Normal(-0.00902,0.00902), "SSA" => Normal(-0.0036,0.0036), "SIS" => Normal(-0.0013,0.0013)]
    impactwaterresources.wrel = Truncated(Normal(0.85,0.15), 0.0, 1.0)
    impactwaterresources.wrnl = Truncated(Normal(1.0,0.5), 0.0, Inf)
    impactwaterresources.wrpl = Truncated(Normal(0.85,0.15), 0.0, Inf)
    impactsealevelrise.wvbm = Truncated(Normal(0.00588,0.003927), 0.0, Inf)
    impactsealevelrise.wvel = Truncated(Normal(1.16,0.46), 0.0, Inf)
    impactsealevelrise.wvpdl = Truncated(Normal(0.47,0.12), 0.0, 1.0)
    impactsealevelrise.wvsl = Truncated(Normal(-0.11,0.05), -1.0, 0.0)

end

function getmcs()
    return deepcopy(fund_default_mcs)
end


text:
module DiffMesh

import Zygote
using NNlib, DiffEqFlux
using LinearAlgebra, SparseArrays, UnPack

using SEM
using SEM.FastGaussQuadrature

include("Tdg.jl")
include("reluHat.jl")

include("POU.jl")
include("BanachSpace.jl")
include("MeshNet.jl")

#--------------------------------------#
export iscallable
#--------------------------------------#
iscallable(op) = !isempty(methods(op))
#--------------------------------------#
export reluMin, reluMax
#--------------------------------------#
reluMin(a,b) = 0.5*(relu(a+b) - relu(-a-b)) -
               0.5*(relu(a-b) - relu( b-a))

reluMax(a,b) = 0.5*(relu(a+b) - relu(-a-b)) +
               0.5*(relu(a-b) + relu( b-a))
#--------------------------------------#
export TRI, TRI2
#--------------------------------------#
"""
 Triangular wave function with frequency p
"""
function TRI(x,p=1)
    y = @. 2*abs(p*x - floor(p*x + 0.5))
    return y
end
#--------------------------------------#
"""
 Quadratic wave function with frequency p
"""
function TRI2(x,p=1)
    return TRI(x,p) .* TRI(x,p)
end
#--------------------------------------#
end #module


text:
module juliaset

function createjuliaset{T,V,U}(x::Array{V,1}, y::Array{U,1}, n_iter::Int, escape_tol::Real, R::T)

if T==Function
  G = R;
elseif T<:Number
  function G(z)
    z^2 + R;
  end
else
  error("invalid function R")
end

if V<:Real
else
  error("invalid type in array x")
end

if U<:Real
else
  error("invalid type in array Y")
end

A = zeros(length(x), length(y))

for i in 1:length(x)
  for j in 1:length(y)
    z = x[i] + im * y[j]
    for k in 1:n_iter
      z = G(z)
      if abs(z) > escape_tol # diverged
        A[i,j] = k

        break
      end
    end
    if A[i,j] == 0 # didn't diverge
      A[i,j] = n_iter + 1

    end
  end
end

return A;
matshow(log(A))

end

export createjuliaset
end

max_stars_repo_name: asgoldin/juliaset

max_issues_repo_name: asgoldin/juliaset

max_forks_repo_name: asgoldin/juliaset


text:
using Test
using CSV
using DataFrames
using LRHousing
using GLM

#= basedir = joinpath(@__DIR__, "..") =#

#= train = LRHousing.read_data(joinpath(basedir, "data", "train.csv")) =#
#= pl = DataPipeline(train; ignore = ["Id"]) =#
#= train_p = pl(train) =#
#= fm = create_formula(pl,  :SalePrice) =#
#= model = lm(fm, train_p) =#
#= display(model) =#

#= test = LRHousing.read_data(joinpath(basedir, "data", "test.csv")) =#
#= # TODO, remove this constraint =#
#= test.SalePrice = fill(0, size(test, 1)) =#
#= test_p = pl(test) =#

#= # TODO, automatic exp if the functional term is in the respond =#
#= test.SalePrice = exp.(predict(model, test_p)) =#
#= display(test) =#

@testset "Transformation" begin
	x = rand() .+ 10
	for l1 in -5:0.01:5
		y = LRHousing.boxcox(x, l1)
		x′ = LRHousing.inv_boxcox(y, l1)
		@test x ≈ x′
	end
end


text:
import BoxRobots

immutable NullBoxRobotController <: BoxRobots.BoxRobotController end
immutable NullBoxRobotControllerData <: BoxRobots.BoxRobotControllerData{NullBoxRobotController} end

function BoxRobots.BoxRobotSimulationData(t::Float64, state::BoxRobots.BoxRobotState, input::BoxRobots.BoxRobotInput)
    BoxRobots.BoxRobotSimulationData(t, state, input, NullBoxRobotControllerData())
end

function Base.convert(::Type{BoxRobots.LimbState}, state::ContactPointState)
    pos = Vector(state.pos)
    vel = zeros(pos)
    in_contact = true # TODO
    BoxRobots.LimbState(pos, vel, in_contact)
end

function Base.convert(::Type{BoxRobots.BoxRobotState}, state::BoxRobotWithRotation2DState)
    comstate = BoxRobots.CentroidalDynamicsState(Vector(state.r), Vector(state.ṙ))
    limbstates = Dict(key => BoxRobots.LimbState(val) for (key, val) in state.contact_point_states)
    BoxRobots.BoxRobotState(comstate, limbstates)
end

function Base.convert(::Type{BoxRobots.LimbInput}, input::ContactPointInput)
    BoxRobots.LimbInput(Vector(input.vel), Vector(input.force), any(x -> x != zero(x), input.force), BoxRobots.ConstantVelocityLimbInput)
end

function Base.convert{B<:BoxRobots.BoxRobotInput, C<:ContactPointInput}(::Type{B}, inputs::Dict{Symbol, C})
    BoxRobots.BoxRobotInput(Dict(key => BoxRobots.LimbInput(val) for (key, val) in inputs))
end

# function Base.convert{S<:BoxRobots.Surface, N}(::Type{S}, region::EnvironmentRegion{N, Float64})
#     hrep = region.position # TODO
#     BoxRobots.Surface{N}(hrep)
# end
#
# function Base.convert{E<:BoxRobots.Environment, N}(::Type{E}, environment::Vector{EnvironmentRegion{N, Float64}})
#     surfaces = map(x -> convert(BoxRobots.Surface{N}, x), environment)
#     BoxRobots.Environment(surfaces)
# end


text:
"""
Library of electrical models.
This library contains electrical components to build up analog circuits.
"""
module Electrical

using ModelingToolkit, Symbolics, IfElse, OrdinaryDiffEq
using OffsetArrays

@parameters t
D = Differential(t)

include("utils.jl")
include("Analog/ideal_components.jl")
include("Analog/sensors.jl")
include("Analog/sources.jl")
# include("Digital/components.jl")
# include("Digital/gates.jl")
# include("Digital/tables.jl")
# include("Digital/sources.jl")

# TODO:
# - digital
# - machines
# - multi-phase

export #Interface
       Pin,
       # Analog Components
       Capacitor, Ground, Inductor, Resistor,
       Short, IdealOpAmp,
       # Analog Sensors
       CurrentSensor, PotentialSensor, VoltageSensor,
       PowerSensor, MultiSensor,
       #Analog Sources
       ConstantVoltage, SineVoltage, StepVoltage, RampVoltage,
       SquareVoltage, TriangularVoltage,
       CosineVoltage, ExpSineVoltage,
       ConstantCurrent, SineCurrent, StepCurrent, RampCurrent,
       SquareCurrent, TriangularCurrent,
       CosineCurrent, ExpSineCurrent

       # # Digital Gates
       # And, Or, Not, Xor, Nand, Nor, Xnor,
       # # Digital components
       # HalfAdder, FullAdder, MUX, DEMUX, Encoder, Decoder,
       # # Digital Sources
       # DigitalPin, Pulse, PulseDiff

end


text:
mutable struct SKenCarpConstantCache{F,N,Tab} <: StochasticDiffEqConstantCache
  uf::F
  nlsolve::N
  tab::Tab
end

function alg_cache(alg::SKenCarp,prob,u,ΔW,ΔZ,p,rate_prototype,noise_rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,f,t,::Type{Val{false}})
  @oopnlcachefields
  if uf !== nothing && typeof(f) <: SplitSDEFunction
    uf = DiffEqDiffTools.UDerivativeWrapper(f.f1,t,p)
  else
    uf = DiffEqDiffTools.UDerivativeWrapper(f,t,p)
  end
  tab = SKenCarpTableau(real(uBottomEltypeNoUnits),real(tTypeNoUnits))
  γ, c = tab.γ,tab.c3
  @oopnlsolve
  SKenCarpConstantCache(uf,nlsolve,tab)
end

@cache mutable struct SKenCarpCache{uType,rateType,uNoUnitsType,JType,WType,UF,JC,N,Tab,F,kType,randType,rateNoiseType} <: StochasticDiffEqMutableCache
  u::uType
  uprev::uType
  du1::rateType
  fsalfirst::rateType
  k::rateType
  z₁::uType
  z₂::uType
  z₃::uType
  z₄::uType
  k1::kType
  k2::kType
  k3::kType
  k4::kType
  dz::uType
  b::uType
  tmp::uType
  atmp::uNoUnitsType
  J::JType
  W::WType
  uf::UF
  jac_config::JC
  linsolve::F
  nlsolve::N
  tab::Tab
  chi2::randType
  g1::rateNoiseType
  g4::rateNoiseType
end

u_cache(c::SKenCarpCache)    = (c.z₁,c.z₂,c.z₃,c.z₄,c.dz)
du_cache(c::SKenCarpCache)   = (c.k,c.fsalfirst)

function alg_cache(alg::SKenCarp,prob,u,ΔW,ΔZ,p,rate_prototype,noise_rate_prototype,uEltypeNoUnits,uBottomEltypeNoUnits,tTypeNoUnits,uprev,f,t,::Type{Val{true}})
  @iipnlcachefields
  atmp = fill!(similar(u,uEltypeNoUnits),0)
  z₁ = similar(u); z₂ = similar(u)
  z₃ = similar(u); z₄ = z
  dz = similar(u)
  if typeof(f) <: SplitSDEFunction
    k1 = zero(u); k2 = zero(u)
    k3 = zero(u); k4 = zero(u)
    uf = DiffEqDiffTools.UJacobianWrapper(f.f1,t,p)
  else
    k1 = nothing; k2 = nothing
    k3 = nothing; k4 = nothing
    uf = DiffEqDiffTools.UJacobianWrapper(f,t,p)
  end
  linsolve = alg.linsolve(Val{:init},uf,u)
  jac_config = build_jac_config(alg,f,uf,du1,uprev,u,tmp,dz)

  if typeof(ΔW) <: Union{SArray,Number}
    chi2 = copy(ΔW)
  else
    chi2 = zero(ΔW)
  end

  g1 = zero(noise_rate_prototype); g4 = zero(noise_rate_prototype)

  tab = SKenCarpTableau(real(uBottomEltypeNoUnits),real(tTypeNoUnits))

  γ, c = tab.γ,tab.c3
  @iipnlsolve
  SKenCarpCache{typeof(u),typeof(rate_prototype),typeof(atmp),typeof(J),typeof(W),typeof(uf),
                typeof(jac_config),typeof(nlsolve),typeof(tab),typeof(linsolve),typeof(k1),
              typeof(chi2),typeof(g1)}(
              u,uprev,du1,fsalfirst,k,z₁,z₂,z₃,z₄,k1,k2,k3,k4,dz,b,tmp,atmp,J,
              W,uf,jac_config,linsolve,nlsolve,tab,chi2,g1,g4)
end


text:
const julia_version = v"1.6.0"
include("../common.jl")

max_stars_repo_name: singularitti/Yggdrasil

max_issues_repo_name: singularitti/Yggdrasil

max_forks_repo_name: singularitti/Yggdrasil


text:
# module Arrays

export
    pad_matrix,
    cross_product_operator,
    one_hot,
    wrap_idx,
    wrap_get

"""
    helper to pad a matrix with some value around the edges
"""
function pad_matrix(mat::Matrix{T}, pad_size::Tuple{Int,Int},pad_val::T) where T
    new_size = [size(mat)...] + 2*[pad_size...]
    A = fill!(typeof(mat)(undef,new_size[1],new_size[2]),pad_val)
    A[
        pad_size[1]+1:pad_size[1]+size(mat,1),
        pad_size[2]+1:pad_size[2]+size(mat,2)
    ] .= mat
    A
end

cross_product_operator(x) = SMatrix{3,3}(
    [0.0    -x[3]   x[2];
     x[3]   0.0     -x[1];
     -x[2]  x[1]    0.0]
)

"""
    one_hot(::Type{T},n::Int,i::Int) where {T}

Returns a Vector{T} of length n such that `v[i] == 1` and `v[j] .== 0` for all
`j != i`.
"""
function one_hot(::Type{T},n::Int,i::Int) where {T}
    @assert (i > 0 && n > 0) "i and n must be positive integers"
    if i > n
        return one_hot(T,i,n)
    end
    v = zeros(T,n)
    v[i] = T(1)
    return v
end
one_hot(n::Int,i::Int) = one_hot(Float64,n,i)

"""
    wrap_idx(n,idx)

Wrap index to a one-dimensional array of length `n`
"""
wrap_idx(n,idx) = mod(idx-1,n)+1

"""
    wrap_get

Index into array `a` by first wrapping the indices `idx`.
"""
function wrap_get(a::A,idxs) where {R,N,A<:AbstractArray{R,N}}
    a[map(i->wrap_idx(size(a,i),idxs[i]),1:N)...]
end

# end


text:
println("Compile libraries on main processor..."); flush(stdout)
include("imports.jl")
println("Finished loading libraries."); flush(stdout)

using Distributed
rmprocs(workers())
addprocs(20)
println("Compile libraries on workers ..."); flush(stdout)
@everywhere include("imports.jl")
println("Finished loading libraries."); flush(stdout)

sims = dict_list(Dict(:beta => collect(0:1),
                      :K => collect(2:6),
                      :snum => collect(1:4)))

# Run simulations in parallel.
@time res = pmap(run, sims, on_error=identity)

# Print results status.
foreach(z -> println("$(z[1]) => $(z[2])"), zip(sims, res))

# Post process
pp_res = pmap(postprocess, sims)
# postprocess(Dict(:beta=>1, :K=>5, :snum=>1))

# TODO: Combine results
for snum in [1,2,3,4]
  imdir = mkpath(joinpath(Info.resultsdir_simstudy, simname, "img"))
  dics = Float64[]
  for K in MCMC.ProgressBar([2,3,4,5,6])
    cr = combine_results(snum, K)
    append!(dics, cr.dic)
  end
  open(joinpath(imdir, "dics_snum=$(snum).txt"), "w") do io
    write(io, "DICs: $(dics) \n")
  end
  # Model comparisons
  plot(2:6, dics, marker=:square, ms=8, label=nothing)
  xlabel!("K")
  ylabel!("DIC")
  savefig(joinpath(imdir, "dic_snum=$(snum).pdf"))
  closeall()
end

# Send results to S3
Util.s3sync(from="$(Info.resultsdir_simstudy)/$(simname)",
            to="$(Info.awsbucket_simstudy)/$(simname)",
            tags=`--exclude '*.nfs'`)


text:
for f in (:SupersonicMachNumber,:SubsonicMachNumber,
          :SupersonicPOverP0,:SubsonicPOverP0)
  @eval $f(array::AbstractArray{T},args...;kwargs...) where T = map(x -> $f(x,args...;kwargs...),array)
end


text:
using ITensors,
      Test

@testset "sweepnext function" begin

  @testset "one site" begin
    N = 6
    count = 1
    output = [(1,1),(2,1),(3,1),(4,1),(5,1),(6,1),
              (6,2),(5,2),(4,2),(3,2),(2,2),(1,2)]
    for (b,ha) in sweepnext(N;ncenter=1)
      @test (b,ha) == output[count]
      count += 1
    end
    @test count == 2*N+1
  end

  @testset "two site" begin
    N = 6
    count = 1
    output = [(1,1),(2,1),(3,1),(4,1),(5,1),
              (5,2),(4,2),(3,2),(2,2),(1,2)]
    for (b,ha) in sweepnext(N)
      @test (b,ha) == output[count]
      count += 1
    end
    @test count == 2*(N-1)+1
  end

  @testset "three site" begin
    N = 6
    count = 1
    output = [(1,1),(2,1),(3,1),(4,1),
              (4,2),(3,2),(2,2),(1,2)]
    for (b,ha) in sweepnext(N;ncenter=3)
      @test (b,ha) == output[count]
      count += 1
    end
    @test count == 2*(N-2)+1
  end

end

nothing


text:
# copied from CUDAdrv/deps/build.jl

using Libdl

function version_hsa(libpath)
    lib = Libdl.dlopen(libpath)
    sym = Libdl.dlsym(lib, "hsa_system_get_info")
    major_ref = Ref{Cushort}(typemax(Cushort))
    minor_ref = Ref{Cushort}(typemax(Cushort))
    status = ccall(sym, Cint, (Cint, Ptr{Cushort}), 0, major_ref)
    @assert status == 0 "HSA error: $status"
    status = ccall(sym, Cint, (Cint, Ptr{Cushort}), 1, minor_ref)
    @assert status == 0 "HSA error: $status"
    return VersionNumber(major_ref[], minor_ref[])
end

function init_hsa(libpath)
    lib = Libdl.dlopen(libpath)
    sym = Libdl.dlsym(lib, "hsa_init")
    ccall(sym, Cint, ())
end

function shutdown_hsa(libpath)
    lib = Libdl.dlopen(libpath)
    sym = Libdl.dlsym(lib, "hsa_shut_down")
    ccall(sym, Cint, ())
end

## main

const config_path = joinpath(@__DIR__, "ext.jl")
const previous_config_path = config_path * ".bak"

function write_ext(config, path)
    open(path, "w") do io
        println(io, "# autogenerated file, do not edit")
        for (key,val) in config
            println(io, "const $key = $(repr(val))")
        end
    end
end

function read_ext(path)
    config = Dict{Symbol,Any}()
    r = r"^const (\w+) = (.+)$"
    open(path, "r") do io
        for line in eachline(io)
            m = match(r, line)
            if m != nothing
                config[Symbol(m.captures[1])] = eval(Meta.parse(m.captures[2]))
            end
        end
    end
    return config
end

function build_error(reason)
    println("$reason.")
    exit(1)
end

function find_roc_paths()
    paths = split(get(ENV, "LD_LIBRARY_PATH", ""), ":")
    paths = filter(path->path != "", paths)
    paths = map(Base.Filesystem.abspath, paths)
    push!(paths, "/opt/rocm/hsa/lib") # shim for Ubuntu rocm packages...
    paths = filter(isdir, paths)
    @show paths
    return paths
end

function find_hsa_library(lib, dirs)
    for dir in dirs
        files = readdir(dir)
        for file in files
            @info "$file: $(startswith(basename(file), lib * ".so"))"
            if startswith(basename(file), lib * ".so")
                return joinpath(dir, file)
            end
        end
    end
end

function find_ld_lld()
    paths = split(get(ENV, "PATH", ""), ":")
    paths = filter(path->path != "", paths)
    paths = map(Base.Filesystem.abspath, paths)
    ispath("/opt/rocm/hcc/bin/ld.lld") &&
        push!(paths, "/opt/rocm/hcc/bin/")
    ispath("/opt/rocm/opencl/bin/x86_64/ld.lld") &&
        push!(paths, "/opt/rocm/opencl/bin/x86_64/")
    for path in paths
        exp_ld_path = joinpath(path, "ld.lld")
        if ispath(exp_ld_path)
            try
                tmpfile = mktemp()
                run(pipeline(`$exp_ld_path -v`; stdout=tmpfile[1]))
                vstr = read(tmpfile[1], String)
                rm(tmpfile[1])
                vstr_splits = split(vstr, ' ')
                if VersionNumber(vstr_splits[2]) >= v"6.0.0"
                    @info "Found useable ld.lld at $exp_ld_path"
                    return exp_ld_path
                end
            catch
                @warn "Failed running ld.lld in $exp_ld_path"
            end
        end
    end
    return ""
end

function main()
    ispath(config_path) && mv(config_path, previous_config_path; force=true)
    config = Dict{Symbol,Any}(:configured => false)
    write_ext(config, config_path)

    ## discover stuff

    # check that we're running Linux
    if !Sys.islinux()
        build_error("Not running Linux, which is the only platform currently supported by the ROCm Runtime.")
    end

    roc_dirs = find_roc_paths()

    config[:libhsaruntime_path] = find_hsa_library("libhsa-runtime64", roc_dirs)
    if config[:libhsaruntime_path] == nothing
        build_error("Could not find HSA runtime library.")
    end
    config[:libhsaruntime_vendor] = "AMD"

    # initializing the library isn't necessary, but flushes out errors that otherwise would
    # happen during `version` or, worse, at package load time.
    status = init_hsa(config[:libhsaruntime_path])
    if status != 0
        build_error("Initializing HSA runtime failed with code $status.")
    end

    config[:libhsaruntime_version] = version_hsa(config[:libhsaruntime_path])

    # also shutdown just in case
    status = shutdown_hsa(config[:libhsaruntime_path])
    if status != 0
        build_error("Shutdown of HSA runtime failed with code $status.")
    end

    # find the ld.lld program for linking kernels
    # NOTE: This isn't needed by HSARuntime.jl directly, but other packages
    # (like AMDGPUnative.jl) will want it to be available, so we find it for
    # them
    ld_path = find_ld_lld()
    if ld_path == ""
        build_error("Couldn't find ld.lld.")
    end
    config[:ld_lld_path] = ld_path

    config[:configured] = true

    ## (re)generate ext.jl

    if isfile(previous_config_path)
        previous_config = read_ext(previous_config_path)

        if config == previous_config
            mv(previous_config_path, config_path; force=true)
            return
        end
    end

    write_ext(config, config_path)

    return
end

main()


text:
# ------------------------------------------------------------------
# Licensed under the ISC License. See LICENCE in the project root.
# ------------------------------------------------------------------

module GeoStatsImages

using DelimitedFiles: readdlm

export training_image

datadir = joinpath(dirname(@__FILE__),"data")
datafiles = filter(s -> occursin(r".*\.dat", s), readdir(datadir))

database = Dict()
for fname in datafiles
  push!(database, fname[1:end-4] => joinpath(datadir, fname))
end

identifiers = sort(collect(keys(database)))

function available()
  for identifier in identifiers
    println(identifier)
  end
end

function training_image(identifier::AbstractString)
  @assert identifier ∈ identifiers "training image not available"

  datafile = database[identifier]

  f = open(datafile)
  kind, nx, ny, nz = split(strip(readline(f)))
  nx = parse(Int, nx)
  ny = parse(Int, ny)
  nz = parse(Int, nz)
  data = readdlm(f)
  close(f)

  reshape(data, nx, ny, nz)
end

end # module


text:
void(x)=()

import Base.convert
#function convert(net::network,gpucpu::ASCIIString)
function convert(net::network,gpucpu::ASCIIString,eltype=Float64)

    #if (net.gpu & (gpucpu=="GPU")) | (!net.gpu & (gpucpu=="CPU"))
    #    return net
    #else
    #netout=deepcopy(net)
    netout=deepcopy(net)
    nds=net.validnodes
    netout.eltype=eltype
    #if gpucpu=="GPU" || gpucpu=="GPU32"
    if gpucpu=="GPU"
        netout.gpu=true
        for n in nds
            netout.value[n]=CudaArray(eltype,net.value[n])
            netout.gradient[n]=CudaArray(eltype,net.gradient[n])
            if isdefined(net.auxvalue,n)
                if isa(net.auxvalue[n],Tuple)
                    tmp=Array(Any,length(net.auxvalue[n]))
                    for i=1:length(net.auxvalue[n]) # can be a tuple, so iterate over elements
                        tmp[i]=nothing
                        if  ~isa(net.auxvalue[n][i],Void) && ~isempty(net.auxvalue[n][i])
                            tmp[i]=CudaArray(eltype,net.auxvalue[n][i])
                        end
                    end
                    netout.auxvalue[n]=tuple(tmp...)
                else
                    if  ~isa(net.auxvalue[n],Void) && ~isempty(net.auxvalue[n])
                        netout.auxvalue[n]=CudaArray(eltype,net.auxvalue[n])
                    end
                end
            end
        end
    end
    if gpucpu=="CPU"
        if eltype==Float32
            warning("CPU computations currently only defined for Float32")
        end
        netout.gpu=false
        for n in nds
            netout.value[n]=map(eltype,to_host(net.value[n]))
            netout.gradient[n]=map(eltype,to_host(net.gradient[n]))
            if isdefined(net.auxvalue,n)
                if  isa(net.auxvalue[n],CudaArray)
                    netout.auxvalue[n]=map(eltype,to_host(net.auxvalue[n]))
                end
            end
        end
    end
    return netout
#end
end
export convert

import Base.copy!
@gpu copy!(gB::CudaArray,gA::CudaArray)=CUBLAS.blascopy!(length(gA),gA,1,gB,1)
export copy!

@gpu axpy!(a::Real,x::CudaArray{Float32},y::CudaArray{Float32})=CUBLAS.axpy!(length(x),Float32(a),x,1,y,1)
@gpu axpy!(a::Real,x::CudaArray{Float64},y::CudaArray{Float64})=CUBLAS.axpy!(length(x),Float64(a),x,1,y,1)

axpy!(a,x::Array,y::Array)=BLAS.axpy!(a,x,y)
axpy!(a::Array{Real,1},x::Array,y::Array)=BLAS.axpy!(a[1],x,y)
export axpy!

function A_elmult_B_update!(alphascal,A,B,betascal,C)
#    broadcast!(*,C,A,B) # inplace Hadamard product updationg result in C
    m,n = size(A)
    @assert (m,n) == size(B)
    for j in 1:n
        for i in 1:m
            @inbounds C[i,j] = alphascal*A[i,j]*B[i,j]+betascal*C[i,j]
        end
    end
end
export A_elmult_B_update!

function axpy(a::Real,x::Array,y::Array)
    out=copy(y)
    axpy!(a,x,out)
    return out
end
export axpy

#@gpu using CUDArt, CUBLAS

if (PROC=="GPU") || (PROC=="GPU32")
    import Base.LinAlg.BLAS.scale!
    scale!(s,g::CudaArray{Float64})=CUBLAS.scal!(length(g),Float64(s),g,1)
    scale!(s,g::CudaArray{Float32})=CUBLAS.scal!(length(g),Float32(s),g,1)
    export scale!

    # CUDA modules:
    include("CUDAmodules.jl")

end # end of GPU stuff

sigma(x)=1.0./(1.0+exp(-x))

sigmoid(x)=sigma(x)  # TODO: replace sigma with sigmoid throughout

sigma(x)=1./(1.+exp(-x))

export sigma

if (PROC=="GPU") || (PROC=="GPU32")
    function extract(A::CudaArray)
    return to_host(A)
    end
end
extract(A)=A
export extract

function ensurearray(x)
    if isa(x,Vector)
        y=Array(typeof(x[1]),length(x),1)
        y[:]=x
        return y
    else
        return x
    end
end
export ensurearray

function converttype!(x,intype,outtype)
    for i=1:length(x)
        if typeof(x[i][1])==intype
            x[i]=convert(outtype,x[i])
        end
    end
end

function convert!(outtype,x::Array)
    for i=1:length(x)
        if isdefined(x,i)
            x[i]=convert(outtype,x[i])
        end
    end
end
export convert!

# find the max value of each column of a matrix:
function argcolmax(x)
    out=Array(Int,size(x,2))
    for i=1:length(out)
        out[i]=indmax(x[:,i])
    end
    return out
end
export argcolmax

softmax(x::Array{Real,2})=exp(x)./sum(exp(x),1)
export softmax

function logsumexp(x)
    xmax=maximum(x)
    return log(sum(exp(x-xmax),1))+xmax
end

p=10e-25
mylog(x)=log(x+ep)

function log1pexp(x)
    z=zeros(size(x))
    y=copy(x)
    z[x.>0]=x[x.>0]
    y[x.>0]=-x[x.>0]
    return z+log(1+exp(y))
end

isaScalar(x)=length(size(x))==0
export isaScalar

function printover(s::AbstractString, color::Symbol = :color_normal) # nicked from ProgressMeter
    print("\u1b[1G")   # go to first column
    print_with_color(color,  s)
    print("\u1b[K")    # clear the rest of the line
    end
    export printover

function numel(x)
    sum(map((x)->length(x),x))
    end
    export numel

#import Base.contains
function contains(haystack::Array{Int64,1},needle::Int64)
    # return true if haystack contains the specified needle
    return length(find(haystack.==needle))>0
end
export contains

targ(x,a)= isa(x,Tuple)? x[a] : x # tuple argument
export targ

function copyind!(dest,source,ind) # copy only specific components of source to dest
    for i in ind
        copy!(dest[i],source[i])
    end
end
export copyind!

function toposort(node::Array{ADnode,1}) # topological sort
    node2=deepcopy(node)
    idx=map(x->x.index,node)
    for i in idx
        node2[idx[i]]=node[i]
    end
    return node2
end
export toposort

# CUDArt deepcopy is buggy, hence:
function mydeepcopy(A)
    B=similar(A);
    map(i->B[i]=A[i],1:length(A))
    return B
end
export mydeepcopy

function IsScalarArray(A::ArrayOrCudaArray)
    if prod(size(A))==1
        return true
    else
        return false
    end
end
export IsScalarArray

max_stars_repo_name: davidbarber/AutoDiff

max_issues_repo_name: davidbarber/AutoDiff

max_forks_repo_name: davidbarber/AutoDiff


text:
using Test
using MPI
using CLIMA.Mesh.BrickMesh

function main()
  MPI.Init()
  comm = MPI.COMM_WORLD
  crank = MPI.Comm_rank(comm)
  csize = MPI.Comm_size(comm)

  @assert csize == 3

  (etv, etc, etb, fc) = brickmesh((0:4,5:9), (false,true),
                                  boundary=((1,2),(3,4),(5,6)),
                                  part=crank+1,
                                  numparts=csize)
  (etv, etc, etb, fc) = partition(comm, etv, etc, etb, fc)

  if crank == 0
    etv_expect = [1 2  7  6 11;
                  2 3  8  7 12;
                  6 7 12 11 16;
                  7 8 13 12 17]
    @test etv == etv_expect
    @test etc[:,:,1] == [0 1 0 1; 5 5 6 6]
    @test etc[:,:,2] == [1 2 1 2; 5 5 6 6]
    @test etc[:,:,3] == [1 2 1 2; 6 6 7 7]
    @test etc[:,:,4] == [0 1 0 1; 6 6 7 7]
    @test etc[:,:,5] == [0 1 0 1; 7 7 8 8]
    etb_expect = [1 0 0 1 1;
                  0 0 0 0 0;
                  0 0 0 0 0;
                  0 0 0 0 0]
    @test etb == etb_expect
    fc_expect = Array{Int64,1}[]
    @test fc == fc_expect
  elseif crank == 1
    etv_expect = [16 17 12 13 18;
                  17 18 13 14 19;
                  21 22 17 18 23;
                  22 23 18 19 24]
    @test etv == etv_expect
    @test etc[:,:,1] == [0 1 0 1; 8 8 9 9]
    @test etc[:,:,2] == [1 2 1 2; 8 8 9 9]
    @test etc[:,:,3] == [1 2 1 2; 7 7 8 8]
    @test etc[:,:,4] == [2 3 2 3; 7 7 8 8]
    @test etc[:,:,5] == [2 3 2 3; 8 8 9 9]
    etb_expect = [1 0 0 0 0;
                  0 0 0 0 0;
                  0 0 0 0 0;
                  0 0 0 0 0]
    @test etb == etb_expect
    fc_expect = Array{Int64,1}[[1, 4, 1, 2], [2, 4, 2, 3], [5, 4, 3, 4]]
    @test fc == fc_expect
  elseif crank == 2
    etv_expect = [19 14  9  8 3  4;
                  20 15 10  9 4  5;
                  24 19 14 13 8  9;
                  25 20 15 14 9 10]
    @test etv == etv_expect
    @test etc[:,:,1] == [3 4 3 4; 8 8 9 9]
    @test etc[:,:,2] == [3 4 3 4; 7 7 8 8]
    @test etc[:,:,3] == [3 4 3 4; 6 6 7 7]
    @test etc[:,:,4] == [2 3 2 3; 6 6 7 7]
    @test etc[:,:,5] == [2 3 2 3; 5 5 6 6]
    @test etc[:,:,6] == [3 4 3 4; 5 5 6 6]
    etb_expect = [0 0 0 0 0 0;
                  2 2 2 0 0 2;
                  0 0 0 0 0 0;
                  0 0 0 0 0 0]
    @test etb == etb_expect
    fc_expect = Array{Int64,1}[[1, 4, 4, 5]]
    @test fc == fc_expect
  end
end

main()

max_stars_repo_name: akshaysridhar/CLIMA

max_issues_repo_name: akshaysridhar/CLIMA

max_forks_repo_name: akshaysridhar/CLIMA


text:
# This file contains functions to calculate polygon centroid and mean center

"""
    meancenter(P)
Calculate the mean center of a polygon or vector of polygons ``P``.
"""
function meancenter end

function meancenter(P::Union{AbstractPolygon,AbstractMultiPolygon})::Tuple{Float64, Float64}
    xy = _getpointsPoligon(P)

    cx = mean(xy[1])
    cy = mean(xy[2])

    return cx, cy
end

function meancenter(P::Vector{T} where T <:Union{Missing,AbstractPolygon,AbstractMultiPolygon})::Tuple{Vector{Float64}, Vector{Float64}}
    cxy = meancenter.(P)

    cx = first.(cxy)
    cy = last.(cxy)

    return cx, cy
end

"""
    centroid(P)
Calculate the centroid of a polygon or vector of polygons ``P``.
"""
function centroid end

function centroid(P::Union{AbstractPolygon,AbstractMultiPolygon})::Tuple{Float64, Float64}
    xy = _getpointsPoligon(P)

    xo = xy[1]
    yo = xy[2]

    # Formula: https://en.wikipedia.org/wiki/Centroid#Of_a_polygon

    # If the last point is not equal to the first point, add a new point similar to the first point.
    if (xo[end] != xo[1]) | (yo[end] != yo[1])
        x = copy(xo)
        y = copy(yo)

        push!(x, x[1])
        push!(y, y[1])
    else
        x = xo
        y = yo
    end

    # Loop to calculate elements of A and centroids
    n = length(x)
    A = 0
    xprodsum = 0
    yprodsum = 0

    for i in 1:n-1
        xycross = x[i] * y[i + 1] - x[i + 1] * y[i]
        xprod = (x[i] + x[i + 1]) * xycross
        yprod = (y[i] + y[i + 1]) * xycross

        A += xycross
        xprodsum += xprod
        yprodsum += yprod
    end
    A = A / 2

    # Centroids
    cx = 1 / (6 * A) * xprodsum
    cy = 1 / (6 * A) * yprodsum

    return cx, cy
end

function centroid(P::Vector{T} where T <:Union{Missing,AbstractPolygon,AbstractMultiPolygon})::Tuple{Vector{Float64}, Vector{Float64}}
    cxy = centroid.(P)

    cx = first.(cxy)
    cy = last.(cxy)

    return cx, cy
end


text:
include("../imports.jl")

@testset "TabularPreprocessing" begin
    cols = [:col1, :col2, :col3, :col4, :col5]
    vals = [1, 2, 3, "a", "x"]
    row = NamedTuple(zip(cols, vals))

    catcols = (:col4, :col5)
    contcols = (:col1, :col2, :col3)

    col1_mean, col1_std = 10, 100
    col2_mean, col2_std = 100, 10
    col3_mean, col3_std = 15, 1

    normdict = Dict(
        :col1 => (col1_mean, col1_std),
        :col2 => (col2_mean, col2_std),
        :col3 => (col3_mean, col3_std)
    )

    tfm = TabularPreprocessing(
        NormalizeRow(normdict, contcols)
    )

    block = TableRow(
        catcols,
        contcols,
        Dict(:col4=>["a", "b"], :col5=>["x", "y", "z"])
    )

    testencoding(tfm, block, row)

    @testset ExtendedTestSet "" begin
        testencoding(setup(TabularPreprocessing, block, TableDataset(DataFrame([row, row]))), block, row)
    end
end


text:
using ViewerGL
using Distributed
using Pio3d
if nprocs() == 1
    addprocs(3)
end
using LarSurf

LarSurf.lsp_setup([64, 64, 64])

# segmentation = LarSurf.generate_truncated_sphere(10)
pth = Pio3d.datasets_join_path("medical/orig/3Dircadb1.1/MASKS_DICOM/liver")
datap = Pio3d.read3d(pth)
segmentation = datap["data3d"]
voxelsize_mm = datap["voxelsize_mm"]

V, FV = LarSurf.lsp_get_surface(segmentation, voxelsize_mm)
FVtri = LarSurf.triangulate_quads(FV)
objlines = LarSurf.Lar.lar2obj(V, FVtri, "tetris_tri.obj")

# ViewerGL.VIEW([
#     ViewerGL.GLGrid(V,FVtri,ViewerGL.Point4d(1,1,1,0.1))
# 	ViewerGL.GLAxis(ViewerGL.Point3d(-1,-1,-1),ViewerGL.Point3d(1,1,1))
# ])

Vs = LarSurf.Smoothing.smoothing_FV_taubin(V, FV, 0.5, -0.2, 40)

ViewerGL.VIEW([
    ViewerGL.GLGrid(Vs,FVtri,ViewerGL.Point4d(1,1,1,0.1))
	ViewerGL.GLAxis(ViewerGL.Point3d(-1,-1,-1),ViewerGL.Point3d(1,1,1))
])

objlines = LarSurf.Lar.lar2obj(Vs, FVtri, "liver.obj")