text:
module TestDataMigrations
using Test

using Catlab, Catlab.Theories, Catlab.Graphs, Catlab.CategoricalAlgebra
using Catlab.Programs.DiagrammaticPrograms
using Catlab.Graphs.BasicGraphs: TheoryGraph, TheoryWeightedGraph
using Catlab.Graphs.BipartiteGraphs: TheoryUndirectedBipartiteGraph

# Contravariant migration
#########################

# Pullback migration
#-------------------

@present TheoryDDS(FreeSchema) begin
  X::Ob
  Φ::Hom(X,X)
end

@abstract_acset_type AbstractDDS
@acset_type DDS(TheoryDDS, index=[:Φ]) <: AbstractDDS

h = Graph(3)
add_parts!(h, :E, 3, src = [1,2,3], tgt = [2,3,1])

# Identity data migration.
@test h == migrate(Graph, h, Dict(:V => :V, :E => :E),
                   Dict(:src => :src, :tgt => :tgt))

# Migrate DDS → Graph.
dds = DDS()
add_parts!(dds, :X, 3, Φ=[2,3,1])
X = TheoryDDS[:X]
@test h == migrate(Graph, dds, Dict(:V => :X, :E => :X),
                   Dict(:src => id(X), :tgt => :Φ))

h2 = copy(h)
migrate!(h2, dds, Dict(:V => :X, :E => :X),
                  Dict(:src => id(X), :tgt => :Φ))
@test h2 == ob(coproduct(h, h))

# Migrate DDS → DDS by advancing four steps.
@test dds == migrate(DDS, dds, Dict(:X => :X),
                     Dict(:Φ => [:Φ, :Φ, :Φ, :Φ]))

@present TheoryLabeledDDS <: TheoryDDS begin
  Label::AttrType
  label::Attr(X, Label)
end
@acset_type LabeledDDS(TheoryLabeledDDS, index=[:Φ, :label])

S, ϕ, Label, label = generators(TheoryLabeledDDS)
V, E, s, t, Weight, weight = generators(TheoryWeightedGraph)

ldds = LabeledDDS{Int}()
add_parts!(ldds, :X, 4, Φ=[2,3,4,1], label=[100, 101, 102, 103])

wg = WeightedGraph{Int}(4)
add_parts!(wg, :E, 4, src=[1,2,3,4], tgt=[2,3,4,1], weight=[101, 102, 103, 100])

@test wg == migrate(WeightedGraph{Int}, ldds,
  Dict(:V => :X, :E => :X, :Weight => :Label),
  Dict(:src => id(S), :tgt => :Φ, :weight => [:Φ, :label]))

@test Presentation(Graph(1)) == TheoryGraph
@test Presentation(ldds) == TheoryLabeledDDS

F = FinFunctor(
  Dict(V => S, E => S, Weight => Label),
  Dict(s => id(S), t => ϕ, weight => compose(ϕ, label)),
  TheoryWeightedGraph, TheoryLabeledDDS
)
ΔF = DeltaMigration(F, LabeledDDS{Int}, WeightedGraph{Int})
@test wg == ΔF(ldds)

idF = FinFunctor(
  Dict(X => X, Label => Label),
  Dict(ϕ => ϕ, label => label),
  TheoryLabeledDDS, TheoryLabeledDDS
)
@test ldds == migrate(LabeledDDS{Int}, ldds, idF)

# Conjunctive migration
#----------------------

# Graph whose edges are paths of length 2.
V, E, src, tgt = generators(TheoryGraph)
C = FinCat(TheoryGraph)
F_V = FinDomFunctor([V], FinCat(1), C)
F_E = FinDomFunctor(FreeDiagram(Cospan(tgt, src)), C)
F = FinDomFunctor(Dict(V => Diagram{op}(F_V),
                       E => Diagram{op}(F_E)),
                  Dict(src => DiagramHom{op}([(1, src)], F_E, F_V),
                       tgt => DiagramHom{op}([(2, tgt)], F_E, F_V)), C)
@test F isa DataMigrations.ConjSchemaMigration
g = path_graph(Graph, 5)
H = migrate(g, F, tabular=true)
@test length(H(V)) == 5
@test length(H(E)) == 3
@test H(src)((x1=2, x2=3, x3=3)) == (x1=2,)
@test H(tgt)((x1=2, x2=3, x3=3)) == (x1=4,)

# Same migration, but defining using the `@migration` macro.
F = @migration TheoryGraph TheoryGraph begin
  V => V
  E => @join begin
    v::V
    (e₁, e₂)::E
    tgt(e₁) == v
    src(e₂) == v
  end
  src => e₁ ⋅ src
  tgt => e₂ ⋅ tgt
end
H = migrate(g, F, tabular=true)
@test length(H(V)) == 5
@test length(H(E)) == 3
@test H(src)((v=3, e₁=2, e₂=3)) == (V=2,)
@test H(tgt)((v=3, e₁=2, e₂=3)) == (V=4,)

h = migrate(Graph, g, F)
@test (nv(h), ne(h)) == (5, 3)
@test sort!(collect(zip(h[:src], h[:tgt]))) == [(1,3), (2,4), (3,5)]

h = Graph(5)
migrate!(h, g, F)
@test (nv(h), ne(h)) == (10, 3)
@test sort!(collect(zip(h[:src], h[:tgt]))) == [(6,8), (7,9), (8,10)]

# Weighted graph whose edges are path of length 2 with equal weight.
F = @migration TheoryWeightedGraph TheoryWeightedGraph begin
  V => V
  E => @join begin
    v::V; (e₁, e₂)::E; w::Weight
    tgt(e₁) == v
    src(e₂) == v
    weight(e₁) == w
    weight(e₂) == w
  end
  Weight => Weight
  src => e₁ ⋅ src
  tgt => e₂ ⋅ tgt
  weight => w
end
g = path_graph(WeightedGraph{Float64}, 6, E=(weight=[0.5,0.5,1.5,1.5,1.5],))
h = migrate(WeightedGraph{Float64}, g, F)
@test (nv(h), ne(h)) == (6, 3)
@test sort!(collect(zip(h[:src], h[:tgt], h[:weight]))) ==
  [(1,3,0.5), (3,5,1.5), (4,6,1.5)]

# Graph whose vertices are paths of length 2 and edges are paths of length 3.
g = path_graph(Graph, 6)
h = @migrate Graph g begin
  V => @join begin
    v::V
    (e₁, e₂)::E
    (t: e₁ → v)::tgt
    (s: e₂ → v)::src
  end
  E => @join begin
    (v₁, v₂)::V
    (e₁, e₂, e₃)::E
    (t₁: e₁ → v₁)::tgt
    (s₁: e₂ → v₁)::src
    (t₂: e₂ → v₂)::tgt
    (s₂: e₃ → v₂)::src
  end
  src => (v => v₁; e₁ => e₁; e₂ => e₂; t => t₁; s => s₁)
  tgt => (v => v₂; e₁ => e₂; e₂ => e₃; t => t₂; s => s₂)
end
@test h == path_graph(Graph, 4)

# Gluing migration
#-----------------

# Free reflexive graph on a graph.
g = cycle_graph(Graph, 5)
h = @migrate ReflexiveGraph g begin
  V => V
  E => @cases (v::V; e::E)
  src => (e => src)
  tgt => (e => tgt)
  refl => v
end
@test h == cycle_graph(ReflexiveGraph, 5)

# Free symmetric graph on a graph.
g = star_graph(Graph, 5)
h = @migrate SymmetricGraph g begin
  V => V
  E => @cases (fwd::E; rev::E)
  src => (fwd => src; rev => tgt)
  tgt => (fwd => tgt; rev => src)
  inv => (fwd => rev; rev => fwd)
end
@test h == star_graph(SymmetricGraph, 5)

# Free symmetric weighted graph on a weighted graph.
weights = range(0, 1, length=5)
g = star_graph(WeightedGraph{Float64}, 6, E=(weight=weights,))
h = @migrate SymmetricWeightedGraph g begin
  V => V
  E => @cases (fwd::E; rev::E)
  Weight => Weight
  src => (fwd => src; rev => tgt)
  tgt => (fwd => tgt; rev => src)
  inv => (fwd => rev; rev => fwd)
  weight => (fwd => weight; rev => weight)
end
h′ = star_graph(SymmetricWeightedGraph{Float64}, 6)
h′[:weight] = vcat(weights, weights)
@test h == h′

# Free symmetric reflexive graph on a reflexive graph.
g = star_graph(ReflexiveGraph, 5)
h = @migrate SymmetricReflexiveGraph g begin
  V => V
  E => @glue begin
    (fwd, rev)::E
    v::V
    (refl_fwd: v → fwd)::refl
    (refl_rev: v → rev)::refl
  end
  src => (fwd => src; rev => tgt)
  tgt => (fwd => tgt; rev => src)
  refl => v
  inv => begin
    fwd => rev; rev => fwd; v => v;
    refl_fwd => refl_rev; refl_rev => refl_fwd
  end
end
@test is_isomorphic(h, star_graph(SymmetricReflexiveGraph, 5))

# Gluc migration
#---------------

# Graph with edges that are paths of length <= 2.
g = path_graph(Graph, 4)
h = @migrate Graph g begin
  V => V
  E => @cases begin
    v => V
    e => E
    path => @join begin
      v::V
      (e₁, e₂)::E
      tgt(e₁) == v
      src(e₂) == v
    end
  end
  src => (e => src; path => e₁⋅src)
  tgt => (e => tgt; path => e₂⋅tgt)
end
h′ = @acset Graph begin
  V = 4
  E = 9
  src = [1,2,3,4, 1,2,3, 1,2]
  tgt = [1,2,3,4, 2,3,4, 3,4]
end
@test h == h′

# Sigma migration
#################

V1B, V2B, EB = generators(TheoryUndirectedBipartiteGraph, :Ob)
srcB, tgtB = generators(TheoryUndirectedBipartiteGraph, :Hom)

VG, EG = generators(TheoryGraph, :Ob)
srcG, tgtG = generators(TheoryGraph, :Hom)

F = FinFunctor(
  Dict(V1B => VG, V2B => VG, EB => EG),
  Dict(srcB => srcG, tgtB => tgtG),
  TheoryUndirectedBipartiteGraph, TheoryGraph
)

idF = FinFunctor(
  Dict(VG => VG, EG => EG),
  Dict(srcG => srcG, tgtG => tgtG),
  TheoryGraph, TheoryGraph
)

ΣF = SigmaMigration(F, UndirectedBipartiteGraph, Graph)
X = UndirectedBipartiteGraph()

Y = ΣF(X)
@test nparts(Y, :V) == 0
@test nparts(Y, :E) == 0

X = @acset UndirectedBipartiteGraph begin
  V₁ = 4
  V₂ = 3
  E = 4
  src = [1,2,2,3]
  tgt = [1,1,2,3]
end

Y = ΣF(X)
@test nparts(Y, :V) == 7
@test nparts(Y, :E) == 4
@test length(Y[:src] ∩ Y[:tgt]) == 0

@test SigmaMigration(idF, Graph, Graph)(Y) == Y

@present ThSpan(FreeSchema) begin
  (L1, L2, A)::Ob
  l1::Hom(A, L1)
  l2::Hom(A, L2)
end
@acset_type Span(ThSpan, index=[:l1, :l2])

X = @acset Span begin
  L1 = 3
  L2 = 4
  A = 3
  l1 = [1,1,2]
  l2 = [1,2,3]
end

@present ThInitial(FreeSchema) begin
  I::Ob
end
@acset_type Initial(ThInitial)

L1, L2, A = generators(ThSpan, :Ob)
l1, l2 = generators(ThSpan, :Hom)
I = generators(ThInitial)[1]

bang = FinFunctor(
  Dict(L1 => I, L2 => I, A => I),
  Dict(l1 => id(I), l2 => id(I)),
  ThSpan, ThInitial
)

Σbang = SigmaMigration(bang, Span, Initial)
Y = Σbang(X)

@test nparts(Y, :I) == 4

vertex = FinFunctor(Dict(I => VG), Dict(), ThInitial, TheoryGraph)
edge = FinFunctor(Dict(I => EG), Dict(), ThInitial, TheoryGraph)

Z = SigmaMigration(vertex, Initial, Graph)(Y)
@test nparts(Z, :V) == 4
@test nparts(Z, :E) == 0

Z = SigmaMigration(edge, Initial, Graph)(Y)
@test nparts(Z, :V) == 8
@test nparts(Z, :E) == 4
@test Z[:src] ∪ Z[:tgt] == 1:8

# Yoneda embedding
#-----------------

yV, yE = Graph(1), path_graph(Graph, 2)
@test representable(Graph, :V) == yV
@test representable(Graph, :E) == yE

y_Graph = yoneda(Graph)
@test ob_map(y_Graph, :V) == yV
@test ob_map(y_Graph, :E) == yE
@test hom_map(y_Graph, :src) == ACSetTransformation(yV, yE, V=[1])
@test hom_map(y_Graph, :tgt) == ACSetTransformation(yV, yE, V=[2])

F = @migration TheoryGraph begin
  X => E
  (I, O) => V
  (i: X → I) => src
  (o: X → O) => tgt
end
G = colimit_representables(F, y_Graph) # Delta migration.
X = ob_map(G, :X)
@test X == path_graph(Graph, 2)
i, o = hom_map(G, :i), hom_map(G, :o)
@test only(collect(i[:V])) == 1
@test only(collect(o[:V])) == 2

F = @migration TheoryGraph begin
  X => @join begin
    (e₁, e₂)::E
    tgt(e₁) == src(e₂)
  end
  (I, O) => V
  (i: X → I) => src(e₁)
  (o: X → O) => tgt(e₂)
end
G = colimit_representables(F, y_Graph) # Conjunctive migration.
X = ob_map(G, :X)
@test is_isomorphic(X, path_graph(Graph, 3))
i, o = hom_map(G, :i), hom_map(G, :o)
@test isempty(inneighbors(X, only(collect(i[:V]))))
@test isempty(outneighbors(X, only(collect(o[:V]))))

end

max_forks_repo_name: epatters/CompCat


text: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

ext: jl

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
using MPIReco

@testset "system matrix center estimation" begin
  SFs = ["./data/SF_MP01", "./data/SF_MP02", "./data/SF_MP03", "./data/SF_MP04"]
  center = [[9.0,23.0,1.0],[9.0,10.0,1.0],[22.0,23.0,1.0],[22.0,10.0,1.0]]

  for (l,SF) in enumerate(SFs)
    bSF = MPIFile(SF)
    a = findCenterOfDfFov(bSF)
    @test a == center[l]
    S = getSF(bSF,2,0,0,2)
    exportImage("./img/Center1.png", abs.(S)[:,:,1])
    #p = imagesc(abs.(S)[:,:,1])
    #add(p, Points([a[2]-1],[a[1]-1],color="yellow",lw=5))
    #savefig(p, "./img/Center1.png")
  end

  for (l,SF) in enumerate(SFs)
    bSF = MPIFile(SF)
    a = findCenterOfDfFov(bSF)
    @test a == center[l]
    S = getSF(bSF,5,6,0,1)
    exportImage("./img/Center2.png", abs.(S)[:,:,1])
    #p = imagesc(abs.(S)[:,:,1])
    #add(p, Points([a[2]-1],[a[1]-1],color="yellow",lw=5))
    #savefig(p, "./img/Center2.png")
  end
end


text:
"""
    HilbertSpace

Abstract type for representing Hilbert spaces.
"""
abstract type HilbertSpace end
Base.hash(h::T, i::UInt) where T<:HilbertSpace = hash(T, hash(h.name, i))

abstract type ConcreteHilbertSpace <: HilbertSpace end

"""
    ProductSpace <: HilbertSpace

Stores a composite [`HilbertSpace`](@ref) consisting of multiple subspaces.
Generally created by computing the tensor product [`⊗`](@ref) of subspaces.
"""
struct ProductSpace{S} <: HilbertSpace
    spaces::S
    hash::UInt
    function ProductSpace(spaces::S) where S
        h = hash(ProductSpace, hash(spaces, zero(UInt)))
        new{S}(spaces, h)
    end
end
Base.:(==)(h1::T,h2::T) where T<:ProductSpace = isequal(h1.hash, h2.hash)
function Base.hash(p::ProductSpace, h::UInt)
    iszero(h) && return p.hash
    return hash(hash(p, zero(UInt)), h)
end

"""
    ⊗(spaces::HilbertSpace...)

Create a [`ProductSpace`](@ref) consisting of multiple subspaces.
Unicode `\\otimes<tab>` alias of [`tensor`](@ref)

Examples
=======
```
julia> hf = FockSpace(:f)
ℋ(f)

julia> ha = NLevelSpace(:a,2)
ℋ(a)

julia> h = hf⊗ha
ℋ(f) ⊗ ℋ(a)
```
"""
⊗(a::HilbertSpace,b::HilbertSpace) = ProductSpace([a,b])
⊗(a::HilbertSpace,b::ProductSpace) = ProductSpace([a;b.spaces])
⊗(a::ProductSpace,b::HilbertSpace) = ProductSpace([a.spaces;b])
⊗(a::ProductSpace,b::ProductSpace) = ProductSpace([a.spaces;b.spaces])
⊗(a::HilbertSpace, b::HilbertSpace, c::HilbertSpace...) = ⊗(a⊗b,c...)
⊗(a::HilbertSpace) = a

"""
    tensor(spaces::HilbertSpace...)

Create a [`ProductSpace`](@ref) consisting of multiple subspaces.
See also [`⊗`](@ref).
"""
tensor(args...) = ⊗(args...)

"""
    ClusterSpace <: HilbertSpace
    ClusterSpace(original_space,N,order)

A Hilbert space representing `N` identical copies of another Hilbert space, with
correlations up to a specified `order`.
"""
struct ClusterSpace{H<:ConcreteHilbertSpace,NType,M<:Integer,S} <: HilbertSpace
    original_space::H
    N::NType
    order::M
    op_name::S
end
Base.:(==)(h1::T,h2::T) where T<:ClusterSpace = (h1.original_space==h2.original_space && isequal(h1.N,h2.N) && h1.order==h2.order && isequal(h1.name, h2.name))
Base.hash(c::ClusterSpace, h::UInt) = hash(c.original_space, hash(c.N, hash(c.order, h)))
ClusterSpace(h,N,M) = ClusterSpace(h,N,M,Ref(:_NO_NAME))

"""
    ClusterAon(i,j)

When an operator acts on the Hilbert space `i` which is a [`ClusterSpace`](@ref),
the index `j` denotes which copy of the Hilbert space the operator acts on.
"""
struct ClusterAon{T<:Integer}
    i::T
    j::T
end

Base.isless(h1::HilbertSpace,h2::HilbertSpace) = isless(h1.name,h2.name)
Base.isless(h1::ProductSpace,h2::ProductSpace) = isless(h1.spaces,h2.spaces)

function Base.copy(h::T) where T<:HilbertSpace
    fields = [getfield(h, n) for n in fieldnames(T)]
    return T(fields...)
end

has_hilbert(::Type{T},::T,args...) where T<:HilbertSpace = true
has_hilbert(T::Type{<:HilbertSpace},h::ProductSpace,aon) = has_hilbert(T,h.spaces[aon])
has_hilbert(::Type{<:HilbertSpace},::HilbertSpace,args...) = false
has_hilbert(::Type{T},::ClusterSpace{<:T},args...) where T<:HilbertSpace = true


text:
VERSION < v"0.7.0-beta2.199" && __precompile__()

module ImageCore

using Reexport
using Requires
@reexport using FixedPointNumbers
@reexport using Colors
if isdefined(ColorTypes, :XRGB) && isdefined(ColorTypes, :RGB1)
    Base.@deprecate_binding RGB1 XRGB
    Base.@deprecate_binding RGB4 RGBX
end
# backward compatibility for ColorTypes < v0.9
if !isdefined(ColorTypes, :XRGB)
    const XRGB = RGB1
    const RGBX = RGB4
end

@reexport using MosaicViews
@reexport using PaddedViews
using MappedArrays, Graphics
using OffsetArrays # for show.jl
using .ColorTypes: colorant_string
using Colors: Fractional
using MappedArrays: AbstractMultiMappedArray

using Base: tail, @pure, Indices
import Base: float

import Graphics: width, height

# TODO: just use .+
# See https://github.com/JuliaLang/julia/pull/22932#issuecomment-330711997
plus(r::AbstractUnitRange, i::Integer) = broadcast(+, r, i)
plus(a::AbstractArray, i::Integer) = a .+ i

using .ColorTypes: AbstractGray, TransparentGray, Color3, Transparent3
Color1{T} = Colorant{T,1}
Color2{T} = Colorant{T,2}
Color4{T} = Colorant{T,4}
AColor{N,C,T} = AlphaColor{C,T,N}
ColorA{N,C,T} = ColorAlpha{C,T,N}
const NonparametricColors = Union{RGB24,ARGB32,Gray24,AGray32}
Color1Array{C<:Color1,N} = AbstractArray{C,N}
# Type that arises from reshape(reinterpret(To, A), sz):
const RRArray{To,From,N,M,P} = Base.ReshapedArray{To,N,Base.ReinterpretArray{To,M,From,P}}
const RGArray = Union{Base.ReinterpretArray{<:AbstractGray,M,<:Number,P}, Base.ReinterpretArray{<:Number,M,<:AbstractGray,P}} where {M,P}

# delibrately not export these constants to enable extensibility for downstream packages
const NumberLike = Union{Number,AbstractGray}
const Pixel = Union{Number,Colorant}
const GenericGrayImage{T<:NumberLike,N} = AbstractArray{T,N}
const GenericImage{T<:Pixel,N} = AbstractArray{T,N}

export
    ## Types
    HasDimNames,
    HasProperties,
    StackedView,
    ## constants
    zeroarray,
    ## functions
    # views
    channelview,
    colorview,
    permuteddimsview,
    rawview,
    normedview,
    reinterpretc,
    # conversions
#    float16,
    float32,
    float64,
    n0f8,
    n6f10,
    n4f12,
    n2f14,
    n0f16,
    # mapping values
    clamp01,
    clamp01!,
    clamp01nan,
    clamp01nan!,
    colorsigned,
    scaleminmax,
    scalesigned,
    takemap,
    # traits
    assert_timedim_last,
    coords_spatial,
    height,
    indices_spatial,
    namedaxes,
    nimages,
    pixelspacing,
    sdims,
    size_spatial,
    spacedirections,
    spatialorder,
    width,
    widthheight

include("colorchannels.jl")
include("stackedviews.jl")
include("convert_reinterpret.jl")
include("traits.jl")
include("map.jl")
include("show.jl")
include("deprecations.jl")

"""
    rawview(img::AbstractArray{FixedPoint})

returns a "view" of `img` where the values are interpreted in terms of
their raw underlying storage. For example, if `img` is an `Array{N0f8}`,
the view will act like an `Array{UInt8}`.

See also: [`normedview`](@ref)
"""
rawview(a::AbstractArray{T}) where {T<:FixedPoint} = mappedarray(reinterpret, y->T(y,0), a)
rawview(a::Array{T}) where {T<:FixedPoint} = reinterpret(FixedPointNumbers.rawtype(T), a)
rawview(a::AbstractArray{T}) where {T<:Real} = a

"""
    normedview([T], img::AbstractArray{Unsigned})

returns a "view" of `img` where the values are interpreted in terms of
`Normed` number types. For example, if `img` is an `Array{UInt8}`, the
view will act like an `Array{N0f8}`.  Supply `T` if the element
type of `img` is `UInt16`, to specify whether you want a `N6f10`,
`N4f12`, `N2f14`, or `N0f16` result.

See also: [`rawview`](@ref)
"""
normedview(::Type{T}, a::AbstractArray{S}) where {T<:FixedPoint,S<:Unsigned} = mappedarray(y->T(y,0),reinterpret, a)
normedview(::Type{T}, a::Array{S}) where {T<:FixedPoint,S<:Unsigned} = reinterpret(T, a)
normedview(::Type{T}, a::AbstractArray{T}) where {T<:Normed} = a
normedview(a::AbstractArray{UInt8}) = normedview(N0f8, a)
normedview(a::AbstractArray{T}) where {T<:Normed} = a

# PaddedViews support
# This make sure Colorants as `fillvalue` are correctly filled, for example, let
# `PaddedView(ARGB(0, 0, 0, 0), img)` correctly filled with transparent color even when
# `img` is of eltype `RGB`
function PaddedViews.filltype(::Type{FC}, ::Type{C}) where {FC<:Colorant, C<:Colorant}
    # rand(RGB, 4, 4) has eltype RGB{Any} but it isn't a concrete type
    # although the consensus[1] is to not make a concrete eltype, this op is needed to make a
    # type-stable colorant construction in _filltype without error; there's no RGB{Any} thing
    # [1]: https://github.com/JuliaLang/julia/pull/34948
    T = eltype(C) === Any ? eltype(FC) : eltype(C)
    _filltype(FC, base_colorant_type(C){T})
end
PaddedViews.filltype(::Type{FC}, ::Type{C}) where {FC<:Colorant, C<:Number} = base_color_type(FC){C}
PaddedViews.filltype(::Type{FC}, ::Type{<:Number}) where {FC<:Union{Gray24, AGray32, RGB24, ARGB32}} = FC
_filltype(::Type{<:Colorant}, ::Type{C}) where {C<:Colorant} = C
_filltype(::Type{FC}, ::Type{C}) where {FC<:Color3, C<:AbstractGray} =
    base_colorant_type(FC){promote_type(eltype(FC), eltype(C))}
_filltype(::Type{FC}, ::Type{C}) where {FC<:TransparentColor, C<:AbstractGray} =
    alphacolor(FC){promote_type(eltype(FC), eltype(C))}
_filltype(::Type{FC}, ::Type{C}) where {FC<:TransparentColor, C<:Color3} =
    alphacolor(C){promote_type(eltype(FC), eltype(C))}

# Support transpose
Base.transpose(a::AbstractMatrix{C}) where {C<:Colorant} = permutedims(a, (2,1))
function Base.transpose(a::AbstractVector{C}) where C<:Colorant
    ind = axes(a, 1)
    out = similar(Array{C}, (oftype(ind, Base.OneTo(1)), ind))
    outr = reshape(out, ind)
    copy!(outr, a)
    out
end

if VERSION >= v"1.4.2" # work around https://github.com/JuliaLang/julia/issues/34121
    include("precompile.jl")
    _precompile_()
end

function __init__()
    @require FFTW = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341" include("functions.jl")
end

end ## module


text:
using JuMP; using NCDatasets; using AxisArrays; using CalliopeJuMP.Util;

function load_dispatch_constraints(model_dict)

    sets = model_dict["sets"]
    constraint_dict = Dict()

    if haskey(sets, "loc_tech_carriers_carrier_production_max_constraint")
        constraint_dict["carrier_production_max_constraint"] = (
            build_constraint(
                ["loc_tech_carriers_carrier_production_max_constraint", "timesteps"],
                "carrier_production_max", model_dict
            )
        )
    end

    if haskey(sets, "loc_tech_carriers_carrier_production_min_constraint")
        constraint_dict["carrier_production_min_constraint"] = (
            build_constraint(
                ["loc_tech_carriers_carrier_production_min_constraint", "timesteps"],
                "carrier_production_min", model_dict
            )
        )
    end

    if haskey(sets, "loc_tech_carriers_carrier_consumption_max_constraint")
        constraint_dict["carrier_consumption_max_constraint"] = (
            build_constraint(
                ["loc_tech_carriers_carrier_consumption_max_constraint", "timesteps"],
                "carrier_consumption_max", model_dict
            )
        )
    end

    if haskey(sets, "loc_techs_resource_max_constraint")
        constraint_dict["resource_max_constraint"] = (
            build_constraint(
                ["loc_techs_resource_max_constraint", "timesteps"],
                "resource_max", model_dict
            )
        )
    end

    if haskey(sets, "loc_techs_storage_max_constraint")
        constraint_dict["storage_max_constraint"] = (
            build_constraint(
                ["loc_techs_storage_max_constraint", "timesteps"],
                "storage_max", model_dict
            )
        )
    end

    return constraint_dict
end

function carrier_production_max_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set maximum carrier production. All technologies.
    """
    loc_tech_carrier, timestep = set_indices
    variables = model_dict["variables"]
    loc_tech = get_loc_tech(loc_tech_carrier)
    carrier_prod = variables["carrier_prod"][loc_tech_carrier, timestep]
    timestep_resolution = model_dict["parameters"]["timestep_resolution"][timestep]
    parasitic_eff = get_param(model_dict, "parasitic_eff", [loc_tech], timestep)

    return @constraint(backend_model,
        carrier_prod <= variables["energy_cap"][loc_tech] * timestep_resolution * parasitic_eff
    )
end

function carrier_production_min_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set minimum carrier production. All technologies except conversion_plus
    """
    loc_tech_carrier, timestep = set_indices
    variables = model_dict["variables"]
    loc_tech = get_loc_tech(loc_tech_carrier)
    carrier_prod = variables["carrier_prod"][loc_tech_carrier, timestep]
    timestep_resolution = model_dict["parameters"]["timestep_resolution"][timestep]
    min_use = get_param(model_dict, "energy_cap_min_use", [loc_tech], timestep)

    return @constraint(backend_model, (
        carrier_prod >= variables["energy_cap"][loc_tech] * timestep_resolution * min_use
    ))
end

function carrier_consumption_max_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set maximum carrier consumption for demand, storage, and transmission techs
    """
    loc_tech_carrier, timestep = set_indices
    variables = model_dict["variables"]
    loc_tech = get_loc_tech(loc_tech_carrier)
    carrier_con = variables["carrier_con"][loc_tech_carrier, timestep]
    timestep_resolution = model_dict["parameters"]["timestep_resolution"][timestep]

    return @constraint(backend_model, (
        carrier_con >= -1 * variables["energy_cap"][loc_tech] * timestep_resolution
    ))
end

function resource_max_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set maximum resource consumed by supply_plus techs
    """
    loc_tech, timestep = set_indices
    variables = model_dict["variables"]
    timestep_resolution = model_dict["parameters"]["timestep_resolution"][timestep]

    return @constraint(backend_model, (
        variables["resource_con"][loc_tech, timestep] <=
        timestep_resolution * variables["resource_cap"][loc_tech]
    ))
end

function storage_max_constraint_rule(backend_model, set_indices, model_dict)
    """
    Set maximum stored energy. Supply_plus & storage techs only.
    """
    loc_tech, timestep = set_indices
    variables = model_dict["variables"]

    return @constraint(backend_model, (
        variables["storage"][loc_tech, timestep] <= variables["storage_cap"][loc_tech]
    ))
end

max_stars_repo_name: calliope-project/CalliopeJuMP

max_issues_repo_name: calliope-project/CalliopeJuMP

max_forks_repo_name: calliope-project/CalliopeJuMP


text:
struct VideoFile
    name::String
    start::DateTime
    duration::Millisecond

    function VideoFile(name, start, duration)
        @assert !isempty(name) "file name is empty"
        @assert start > DateTime(0) "starting date & time must be larger than zero"
        @assert duration > Millisecond(0) "zero duration is not supported"
        new(name, start, duration)
    end

end

VideoFile() = VideoFile("_", DateTime(1), Millisecond(1))

start(x::VideoFile) = x.start
duration(x::VideoFile) = x.duration

VideoFile(vf::VideoFile, args) = VideoFile(get(args, :name, vf.name), get(args, :start, start(vf)), get(args, :duration, duration(vf)))

abstract type AbstractTimeLine end

struct WholeVideo <: AbstractTimeLine
    file::VideoFile
    comment::String
end

WholeVideo() = WholeVideo(VideoFile(), "")

WholeVideo(wv::WholeVideo, args) = WholeVideo(get(args, :files, VideoFile(wv.file, args)), get(args, :comment, wv.comment))

files(x::WholeVideo) = SVector{1, VideoFile}(x.file)

struct FragmentedVideo{N, SV <: SVector{N, VideoFile}} <: AbstractTimeLine
    files::SV
    comment::String

    function FragmentedVideo{N, SV}(files, comment) where {N, SV <: SVector{N, VideoFile}}
        @assert N > 1 "video collection must include more than one file"
        last = stop(files[1])
        for file in files[2:N]
            @assert start(file) == last "there is a gap between two adjacent videos: $(start(file) - last)"
            last = stop(file)
        end
        @assert allunique(getfield.(files, :name)) "all file names must be unique"
        new(files, comment)
    end

end
FragmentedVideo(files::SV, comment::String) where {N, SV <: SVector{N, VideoFile}} = FragmentedVideo{N, SV}(files, comment)

function FragmentedVideo(files::T, comment::String) where {T <: AbstractVector{VideoFile}}
    n = length(files)
    FragmentedVideo(SVector{n, VideoFile}(files), comment)
end

function FragmentedVideo()
    v1 = VideoFile()
    v2 = VideoFile("__", stop(v1), Millisecond(1))
    FragmentedVideo([v1, v2], "")
end

FragmentedVideo(fv::FragmentedVideo, args) = FragmentedVideo(get(args, :files, fv.files), get(args, :comment, fv.comment))

struct DisjointVideo{N, SV <: SVector{N, VideoFile}} <: AbstractTimeLine
    files::SV
    comment::String

    function DisjointVideo{N, SV}(files, comment) where {N, SV <: SVector{N, VideoFile}}
        n = length(files)
        @assert n > 1 "video collection must include more than one file"
        last = stop(files[1])
        for file in files[2:end]
            @assert start(file) ≥ last "one file starts before the next one ends"
            last = stop(file)
        end
        @assert allunique(getfield.(files, :name)) "all file names must be unique"
        new(SVector{n}(files), comment)
    end

end
DisjointVideo(files::SV, comment::String) where {N, SV <: SVector{N, VideoFile}} = DisjointVideo{N, SV}(files, comment)

function DisjointVideo(files::T, comment::String) where {T <: AbstractVector{VideoFile}}
    n = length(files)
    DisjointVideo(SVector{n, VideoFile}(files), comment)
end

function DisjointVideo()
    v1 = VideoFile()
    v2 = VideoFile("__", stop(v1) + Millisecond(1), Millisecond(1))
    DisjointVideo([v1, v2], "")
end

DisjointVideo(fv::DisjointVideo, args) = DisjointVideo(get(args, :files, fv.files), get(args, :comment, fv.comment))

AbstractTimeLine(file::VideoFile, comment::String) = WholeVideo(file, comment)
function AbstractTimeLine(files::Vector{VideoFile}, comment::String)
    @assert !isempty(files) "must have some files"
    if length(files) == 1
        WholeVideo(files[], comment)
    else
        if all(stop(prev) == start(next) for (prev, next) in zip(files[1:end-1], files[2:end]))
            FragmentedVideo(files, comment)
        else
            DisjointVideo(files, comment)
        end
    end
end

files(x::AbstractTimeLine) = x.files

filenames(x::AbstractTimeLine) = getfield.(files(x), :name)

start(x::WholeVideo) = start(x.file)
start(x::AbstractTimeLine) = start(first(x.files))
duration(x::WholeVideo) = duration(x.file)
duration(x::FragmentedVideo) = sum(duration, x.files)
duration(x::DisjointVideo) = stop(last(x.files)) - start(first(x.files))


text:
import DifferentiablePhysics2D
import DifferentiablePhysics2D: DP2D
import PhysicsPrimitives2D
import PhysicsPrimitives2D: PP2D
import StaticArrays
const SA = StaticArrays
import LinearAlgebra
const LA = LinearAlgebra
import ForwardDiff
const FD = ForwardDiff
import Makie


text:
#-------------------------------------------------------------------
#* EMSO Model Library (EML) Copyright (C) 2004 - 2007 ALSOC.
#*
#* This LIBRARY is free software; you can distribute it and/or modify
#* it under the therms of the ALSOC FREE LICENSE as available at
#* http://www.enq.ufrgs.br/alsoc.
#*
#* EMSO Copyright (C) 2004 - 2007 ALSOC, original code
#* from http://www.rps.eng.br Copyright (C) 2002-2004.
#* All rights reserved.
#*
#* EMSO is distributed under the therms of the ALSOC LICENSE as
#* available at http://www.enq.ufrgs.br/alsoc.
#*
#*----------------------------------------------------------------------
#* File containg user models of columns
#*
#*
#* The default nomenclature is:
#*		Type_Column_reboilertype_condensertyper
#*
#* where:
#*	Type = refluxed or reboiled or section
#*	Column = Stripping, Absorption, Rectifier, Distillation
#*	Reboiler type (if exists) = kettle or thermosyphon
#*	Condenser type (if exists) = with subccoling or without subcooling
#*
#*-----------------------------------------------------------------------
#* Author: Based on Models written by Paula B. Staudt
#* $Id$
#*---------------------------------------------------------------------
# The complete documentation for these models needs to be updated !!!
#----------------------------------------------------------------------
#* Model of a  basic column section with:
#*	- NumberOfTrays=number of trays.
#*
#*---------------------------------------------------------------------
type User_Section_ColumnBasic
	User_Section_ColumnBasic()=begin
		PP=outers.PP
		NComp=outers.NComp
		[
			:(trays([1:NumberOfTrays]).OutletL.T = TopTemperature+(TbottomTemperature-TopTemperature)*(([1:NumberOfTrays]-1)/(NumberOfTrays-1))),
			:(trays([1:NumberOfTrays]).Level = LevelFraction*hw),
			:(trays([1:NumberOfTrays]).OutletL.z([1:NComp-1]) = TopComposition([1:NComp-1]) +(BottomComposition([1:NComp-1])-TopComposition([1:NComp-1]) )*(([1:NumberOfTrays]-1)/(NumberOfTrays-1))),
		],
		[
			"The initial temperature of the trays","The initial Level of the trays","The initial composition of the trays",
		],
		new(
			DanaPlugin(Dict{Symbol,Any}(
				:Brief=>"External Physical Properties",
				:Type=>"PP"
			)),
			DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Number of components"
			)),
			DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Number of trays",
				:Default=>8
			)),
			fill(DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Number of trays",
				:Default=>0,
				:Hidden=>true
			)),(NumberOfTrays)),
			fill(DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Number of trays",
				:Default=>0,
				:Hidden=>true
			)),(NumberOfTrays)),
			fill(DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Number of trays",
				:Default=>0,
				:Hidden=>true
			)),(NumberOfTrays)),
			DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Feed tray Location",
				:Default=>2
			)),
			DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Liquid Side Stream Location",
				:Default=>2
			)),
			DanaInteger(Dict{Symbol,Any}(
				:Brief=>"Vapour Side Stream Location",
				:Default=>2
			)),
			acceleration(Dict{Symbol,Any}(
				:Brief=>"Gravity Acceleration",
				:Default=>9.81,
				:Hidden=>true
			)),
			fill(molweight(Dict{Symbol,Any}(
				:Brief=>"Component Mol Weight",
				:Hidden=>true
			)),(NComp)),
			DanaSwitcher(Dict{Symbol,Any}(
				:Valid=>["Reepmeyer", "Feehery_Fv", "Roffel_Fv", "Klingberg", "Wang_Fv", "Elgue"],
				:Default=>"Reepmeyer"
			)),
			DanaSwitcher(Dict{Symbol,Any}(
				:Valid=>["default", "Wang_Fl", "Olsen", "Feehery_Fl", "Roffel_Fl"],
				:Default=>"default"
			)),
			volume(Dict{Symbol,Any}(
				:Brief=>"Total Volume of the tray"
			)),
			heat_rate(Dict{Symbol,Any}(
				:Brief=>"Rate of heat supply"
			)),
			area(Dict{Symbol,Any}(
				:Brief=>"Plate area = Atray - Adowncomer"
			)),
			area(Dict{Symbol,Any}(
				:Brief=>"Total holes area"
			)),
			length(Dict{Symbol,Any}(
				:Brief=>"Weir length"
			)),
			length(Dict{Symbol,Any}(
				:Brief=>"Weir height"
			)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Feeherys correlation coefficient",
				:Unit=>"1/m^4",
				:Default=>1
			)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Elgues correlation coefficient",
				:Unit=>"kg/m/mol^2",
				:Default=>1
			)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Olsens correlation coefficient",
				:Default=>1
			)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Number of liquid passes in the tray",
				:Default=>1
			)),
			temperature(),
			temperature(),
			fraction(Dict{Symbol,Any}(
				:Brief=>"Level Fraction"
			)),
			fill(fraction(Dict{Symbol,Any}(
				:Brief=>"Component Molar Fraction at Top"
			)),(NComp)),
			fill(fraction(Dict{Symbol,Any}(
				:Brief=>"Component Molar Fraction at Bottom"
			)),(NComp)),
			volume(Dict{Symbol,Any}(
				:Brief=>"Total Volume of the tray",
				:Hidden=>true
			)),
			heat_rate(Dict{Symbol,Any}(
				:Brief=>"Rate of heat supply",
				:Hidden=>true
			)),
			area(Dict{Symbol,Any}(
				:Brief=>"Plate area = Atray - Adowncomer",
				:Hidden=>true
			)),
			area(Dict{Symbol,Any}(
				:Brief=>"Total holes area",
				:Hidden=>true
			)),
			length(Dict{Symbol,Any}(
				:Brief=>"Weir length",
				:Hidden=>true
			)),
			length(Dict{Symbol,Any}(
				:Brief=>"Weir height",
				:Hidden=>true
			)),
			fraction(Dict{Symbol,Any}(
				:Brief=>"Aeration fraction"
			)),
			fraction(Dict{Symbol,Any}(
				:Brief=>"Dry pressure drop coefficient"
			)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Feeherys correlation coefficient",
				:Unit=>"1/m^4",
				:Default=>1,
				:Hidden=>true
			)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Elgues correlation coefficient",
				:Unit=>"kg/m/mol^2",
				:Default=>1,
				:Hidden=>true
			)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Olsens correlation coefficient",
				:Default=>1,
				:Hidden=>true
			)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Number of liquid passes in the tray",
				:Default=>1,
				:Hidden=>true
			)),
			DanaSwitcher(Dict{Symbol,Any}(
				:Valid=>["on", "off"],
				:Default=>"on",
				:Hidden=>true
			)),
			DanaSwitcher(Dict{Symbol,Any}(
				:Valid=>["on", "off"],
				:Default=>"on",
				:Hidden=>true
			)),
			stream(Dict{Symbol,Any}(
				:Brief=>"Feed stream",
				:PosX=>0,
				:PosY=>0.55
			)),
			flow_mol(Dict{Symbol,Any}(
				:Brief=>"Stream Molar Flow Rate"
			)),
			flow_mol(Dict{Symbol,Any}(
				:Brief=>"Stream Molar Flow Rate"
			)),
			fill(User_tray(Dict{Symbol,Any}(
				:Brief=>"Number of trays"
			)),(NumberOfTrays)),
			DanaReal(Dict{Symbol,Any}(
				:Brief=>"Murphree efficiency"
			)),
			[
				:(FeedTray.F*FeedTrayIndex= trays.Inlet.F),
				:(FeedTray.T = trays.Inlet.T),
				:(FeedTray.P = trays.Inlet.P),
				:(FeedTray.z = trays.Inlet.z),
				:(FeedTray.v = trays.Inlet.v),
				:(FeedTray.h = trays.Inlet.h),
				:(trays([1:NumberOfTrays]).OutletV.z = MurphreeEff * (trays([1:NumberOfTrays]).yideal - trays([1:NumberOfTrays]).InletV.z) + trays([1:NumberOfTrays]).InletV.z),
				:(trays([1:NumberOfTrays]).Level = trays([1:NumberOfTrays]).ML*trays([1:NumberOfTrays]).vL/Ap),
				:(V = trays([1:NumberOfTrays]).ML* trays([1:NumberOfTrays]).vL + trays([1:NumberOfTrays]).MV*trays([1:NumberOfTrays]).vV),
				:(trays([1:NumberOfTrays]).E = trays([1:NumberOfTrays]).ML*trays([1:NumberOfTrays]).OutletL.h + trays([1:NumberOfTrays]).MV*trays([1:NumberOfTrays]).OutletV.h - trays([1:NumberOfTrays]).OutletL.P*V),
				:(diff(trays([1:NumberOfTrays]).E) = ( trays([1:NumberOfTrays]).Inlet.F*trays([1:NumberOfTrays]).Inlet.h + trays([1:NumberOfTrays]).InletL.F*trays([1:NumberOfTrays]).InletL.h + trays([1:NumberOfTrays]).InletV.F*trays([1:NumberOfTrays]).InletV.h- trays([1:NumberOfTrays]).OutletL.F*trays([1:NumberOfTrays]).OutletL.h - trays([1:NumberOfTrays]).OutletV.F*trays([1:NumberOfTrays]).OutletV.h -trays([1:NumberOfTrays]).VapourSideStream.F*trays([1:NumberOfTrays]).VapourSideStream.h - trays([1:NumberOfTrays]).LiquidSideStream.F*trays([1:NumberOfTrays]).LiquidSideStream.h + Q )),
				:(trays([1:NumberOfTrays]).OutletL.F*trays([1:NumberOfTrays]).vL = 1.84*"1/s"*lw*((trays([1:NumberOfTrays]).Level-(beta*hw))/(beta))^2),
				:(trays([1:NumberOfTrays]).OutletL.F*trays([1:NumberOfTrays]).vL = 1.84*"m^0.5/s"*lw*((trays([1:NumberOfTrays]).Level-(beta*hw))/(beta))^1.5),
				:(trays([1:NumberOfTrays]).OutletL.F / "mol/s"= lw*Np*trays([1:NumberOfTrays]).rhoL/sum(Mw*trays([1:NumberOfTrays]).OutletV.z)/(0.665*fw)^1.5 * ((trays([1:NumberOfTrays]).ML*sum(Mw*trays([1:NumberOfTrays]).OutletL.z)/trays([1:NumberOfTrays]).rhoL/Ap)-hw)^1.5 * "m^0.5/mol"),
				:(trays([1:NumberOfTrays]).OutletL.F = lw*trays([1:NumberOfTrays]).rhoL/sum(Mw*trays([1:NumberOfTrays]).OutletL.z) * ((trays([1:NumberOfTrays]).Level-hw)/750/"mm")^1.5 * "m^2/s"),
				:(trays([1:NumberOfTrays]).OutletL.F = 2/3*sqrt(2*g)*trays([1:NumberOfTrays]).rhoL/sum(Mw*trays([1:NumberOfTrays]).OutletL.z)*lw*(2*trays([1:NumberOfTrays]).btemp-1)*(trays([1:NumberOfTrays]).ML*sum(Mw*trays([1:NumberOfTrays]).OutletL.z)/(Ap*1.3)/trays([1:NumberOfTrays]).rhoL/(2*trays([1:NumberOfTrays]).btemp-1))^1.5),
				:(trays([1:NumberOfTrays]).OutletL.F = 0 * "mol/h"),
				:(trays([1:NumberOfTrays]).btemp = 1 - 0.3593/"Pa^0.0888545"*abs(trays([1:NumberOfTrays]).OutletV.F*sum(Mw*trays([1:NumberOfTrays]).OutletV.z)/(Ap*1.3)/sqrt(trays([1:NumberOfTrays]).rhoV))^0.177709),
				:(trays([1:NumberOfTrays]).InletV.F*trays([1:NumberOfTrays]).vV = sqrt((trays([1:NumberOfTrays]).InletV.P - trays([1:NumberOfTrays]).OutletV.P)/(trays([1:NumberOfTrays]).rhoV*alfa))*Ah),
				:(trays([1:NumberOfTrays]).InletV.F = trays([1:NumberOfTrays]).rhoV/Ap/w/sum(Mw*trays([1:NumberOfTrays]).OutletV.z) * sqrt(((trays([1:NumberOfTrays]).InletV.P - trays([1:NumberOfTrays]).OutletV.P)-(trays([1:NumberOfTrays]).rhoV*g*trays([1:NumberOfTrays]).ML*trays([1:NumberOfTrays]).vL/Ap))/trays([1:NumberOfTrays]).rhoV)),
				:(trays([1:NumberOfTrays]).InletV.F^1.08 * 0.0013 * "kg/m/mol^1.08/s^0.92*1e5" = (trays([1:NumberOfTrays]).InletV.P - trays([1:NumberOfTrays]).OutletV.P)*1e5 - (beta*sum(trays([1:NumberOfTrays]).M*Mw)/(Ap*1.3)*g*1e5) * (trays([1:NumberOfTrays]).rhoV*Ah/sum(Mw*trays([1:NumberOfTrays]).OutletV.z))^1.08 * "m^1.08/mol^1.08"),
				:(trays([1:NumberOfTrays]).InletV.F * trays([1:NumberOfTrays]).vV = Ap * sqrt(((trays([1:NumberOfTrays]).InletV.P - trays([1:NumberOfTrays]).OutletV.P)-trays([1:NumberOfTrays]).rhoL*g*trays([1:NumberOfTrays]).Level)/trays([1:NumberOfTrays]).rhoV)),
				:(trays([1:NumberOfTrays]).InletV.F * trays([1:NumberOfTrays]).vV = Ap * sqrt(((trays([1:NumberOfTrays]).InletV.P - trays([1:NumberOfTrays]).OutletV.P)-trays([1:NumberOfTrays]).rhoL*g*trays([1:NumberOfTrays]).Level)/trays([1:NumberOfTrays]).rhoV*alfa)),
				:(trays([1:NumberOfTrays]).InletV.F = sqrt((trays([1:NumberOfTrays]).InletV.P - trays([1:NumberOfTrays]).OutletV.P)/btray)),
				:(trays([1:NumberOfTrays]).InletV.F = 0 * "mol/s"),
			],
			[
				"","","","","","","Murphree Efficiency","Level of clear liquid over the weir","Geometry Constraint","Energy Holdup","Energy Balance","Francis Equation","","","","","Low level","","","","","","","","",
			],
			[:PP,:NComp,:NumberOfTrays,:FeedTrayIndex,:LiqSideTrayIndex,:VapSideTrayIndex,:FeedTrayLocation,:LiquidSideStreamLocation,:VapourSideStreamLocation,:g,:Mw,:VapourFlowModel,:LiquidFlowModel,:VolumeOfTray,:HeatSupply,:PlateArea,:HolesArea,:WeirLength,:WeirHeight,:FeeheryCoeff,:ElgueCoeff,:OlsenCoeff,:TrayLiquidPasses,:TopTemperature,:TbottomTemperature,:LevelFraction,:TopComposition,:BottomComposition,:V,:Q,:Ap,:Ah,:lw,:hw,:beta,:alfa,:w,:btray,:fw,:Np,:VapourFlow,:LiquidFlow,],
			[:FeedTray,:VapourDrawOffFlow,:LiquidDrawOffFlow,:trays,:MurphreeEff,]
		)
	end
	PP::DanaPlugin
	NComp::DanaInteger
	NumberOfTrays::DanaInteger
	FeedTrayIndex::Array{DanaInteger}
	LiqSideTrayIndex::Array{DanaInteger}
	VapSideTrayIndex::Array{DanaInteger}
	FeedTrayLocation::DanaInteger
	LiquidSideStreamLocation::DanaInteger
	VapourSideStreamLocation::DanaInteger
	g::acceleration
	Mw::Array{molweight}
	VapourFlowModel::DanaSwitcher
	LiquidFlowModel::DanaSwitcher
	VolumeOfTray::volume
	HeatSupply::heat_rate
	PlateArea::area
	HolesArea::area
	WeirLength::length
	WeirHeight::length
	FeeheryCoeff::DanaReal
	ElgueCoeff::DanaReal
	OlsenCoeff::DanaReal
	TrayLiquidPasses::DanaReal
	TopTemperature::temperature
	TbottomTemperature::temperature
	LevelFraction::fraction
	TopComposition::Array{fraction}
	BottomComposition::Array{fraction}
	V::volume
	Q::heat_rate
	Ap::area
	Ah::area
	lw::length
	hw::length
	beta::fraction
	alfa::fraction
	w::DanaReal
	btray::DanaReal
	fw::DanaReal
	Np::DanaReal
	VapourFlow::DanaSwitcher
	LiquidFlow::DanaSwitcher
	FeedTray::stream
	VapourDrawOffFlow::flow_mol
	LiquidDrawOffFlow::flow_mol
	trays::Array{User_tray}
	MurphreeEff::DanaReal
	equations::Array{Expr,1}
	equationNames::Array{String,1}
	initials::Array{Expr,1}
	initialNames::Array{String,1}
	parameters::Array{Symbol,1}
	variables::Array{Symbol,1}
	attributes::Dict{Symbol,Any}
end
export User_Section_ColumnBasic
function set(in::User_Section_ColumnBasic)
	FeedTrayIndex(FeedTrayLocation) =1
	 VapSideTrayIndex(FeedTrayLocation) =1
	 LiqSideTrayIndex(FeedTrayLocation) =1
	 Mw = PP.MolecularWeight()
	 V=VolumeOfTray
	 Q=HeatSupply
	 Ap=PlateArea
	 Ah=HolesArea
	 lw=WeirLength
	 hw=WeirHeight
	 w=FeeheryCoeff
	 btray=ElgueCoeff
	 fw=OlsenCoeff
	 Np=TrayLiquidPasses

end
function setEquationFlow(in::User_Section_ColumnBasic)
	# Connecting Trays
	addEquation(1)
	addEquation(2)
	addEquation(3)
	addEquation(4)
	addEquation(5)
	addEquation(6)
	addEquation(7)
	addEquation(8)
	addEquation(9)
	addEquation(10)
	addEquation(11)
	let switch=LiquidFlow
		if LiquidFlow==trays(i).Level < (beta *hw)
			set(switch,"off")
		end
		if LiquidFlow==trays(i).Level > (beta * hw) + 1e-6*"m"
			set(switch,"on")
		end
		if switch=="on"
			let switch=LiquidFlowModel
				if switch=="default"
					addEquation(12)
				elseif switch=="Wang_Fl"
					addEquation(13)
				elseif switch=="Olsen"
					addEquation(14)
				elseif switch=="Feehery_Fl"
					addEquation(15)
				elseif switch=="Roffel_Fl"
					addEquation(16)
				end
			end
		elseif switch=="off"
			addEquation(17)
		end
	end
	addEquation(18)
	#/'(kg/m)^0.0888545/s^0.177709';
	let switch=VapourFlow
		if VapourFlow==trays(i).InletV.F < 1e-6 * "kmol/h"
			set(switch,"off")
		end
		if VapourFlow==trays(i).InletV.P > trays(i).OutletV.P + trays(i).Level*g*trays(i).rhoL + 1e-1 * "atm"
			set(switch,"on")
		end
		if switch=="on"
			let switch=VapourFlowModel
				if switch=="Reepmeyer"
					addEquation(19)
				elseif switch=="Feehery_Fv"
					addEquation(20)
				elseif switch=="Roffel_Fv"
					addEquation(21)
				elseif switch=="Klingberg"
					addEquation(22)
				elseif switch=="Wang_Fv"
					addEquation(23)
				elseif switch=="Elgue"
					addEquation(24)
				end
			end
		elseif switch=="off"
			addEquation(25)
		end
	end
end
function initial(in::User_Section_ColumnBasic)
	addEquation(1)
	addEquation(2)
	addEquation(3)
end
function atributes(in::User_Section_ColumnBasic,_::Dict{Symbol,Any})
	fields::Dict{Symbol,Any}=Dict{Symbol,Any}()
	fields[:Pallete]=false
	fields[:Icon]="icon/SectionColumn"
	fields[:Brief]="Model of a column section."
	fields[:Info]="== Model of a column section containing ==
* NumberOfTrays trays.

== Specify ==
* the feed stream of each tray (Inlet);
* the Murphree eficiency for each tray Emv;
* the InletL stream of the top tray;
* the InletV stream of the bottom tray.

== Initial Conditions ==
* the trays temperature (OutletL.T);
* the trays liquid level (Level) OR the trays liquid flow (OutletL.F);
* (NoComps - 1) OutletL (OR OutletV) compositions for each tray.
"
	drive!(fields,_)
	return fields
end
User_Section_ColumnBasic(_::Dict{Symbol,Any})=begin
	newModel=User_Section_ColumnBasic()
	newModel.attributes=atributes(newModel,_)
	newModel
end


text:
using Test, FinancialMonteCarlo, DualNumbers;
@show "Black Scholes Model"
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;

underlying_name = "ENJ"
underlying_name_2 = "ABPL"

underlying_ = underlying_name * "_" * underlying_name_2 * "_TESL"

Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8

rfCurve = ZeroRate(r);

FwdData = Forward(T)
EUData = EuropeanOptionND(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model_enj = BlackScholesProcess(sigma, Underlying(S0, d));
Model_abpl = BlackScholesProcess(sigma, Underlying(S0, d));
Model_tesl = BlackScholesProcess(sigma, Underlying(S0, d));
rho_1 = [1.0 0.0 0.1; 0.0 1.0 0.0; 0.1 0.0 1.0];
Model = GaussianCopulaNVariateProcess(rho_1, Model_enj, Model_abpl, Model_tesl)

display(Model)

mktdataset = underlying_ → Model
mktdataset_1 = underlying_name → Model_enj

portfolio_ = [EUData];
portfolio = underlying_ → EUData
portfolio_1 = underlying_name → AMData
price_mkt = FinancialMonteCarlo.delta(mktdataset, rfCurve, mc, portfolio, underlying_name, 1e-7)
price_mkt_1 = FinancialMonteCarlo.delta(mktdataset_1, rfCurve, mc, portfolio_1, underlying_name, 1e-7)

Model_enj_dual = BlackScholesProcess(sigma, Underlying(dual(S0, 1.0), d));
Model_dual = GaussianCopulaNVariateProcess(rho_1, Model_enj_dual, Model_abpl, Model_tesl)

mktdataset_dual = underlying_ → Model_dual
mktdataset_1_dual = underlying_name → Model_enj_dual
price_mkt_dual = pricer(mktdataset_dual, rfCurve, mc, portfolio)
price_mkt_1_dual = pricer(mktdataset_1_dual, rfCurve, mc, portfolio_1)

@test(abs(price_mkt_dual.epsilon - price_mkt) < 1e-4)
@test(abs(price_mkt_1_dual.epsilon - price_mkt_1) < 1e-4)
@test(abs(price_mkt_1_dual.epsilon - FinancialMonteCarlo.delta(Model_enj, rfCurve, mc, AMData, 1e-7)) < 1e-4)
@test(abs(price_mkt_1_dual.epsilon - FinancialMonteCarlo.delta(Model_enj, rfCurve, mc, AMData * 1.0, 1e-7)) < 1e-4)
@test(abs(price_mkt_1_dual.epsilon - FinancialMonteCarlo.delta(Model_enj, rfCurve, mc, [AMData], 1e-7)[1]) < 1e-4)

@test_throws(ErrorException, FinancialMonteCarlo.delta(mktdataset_1, rfCurve, mc, portfolio_1, underlying_, 1e-7))
@test(FinancialMonteCarlo.delta(mktdataset_1, rfCurve, mc, portfolio_1, "ciao", 1e-7) == 0.0)


text:
# Bogumił Kamiński, 2021

# Codes for appendix B

# the solutions for exercises from a given chapter assume that
# there are packages loaded, variables and functions defined in the user's
# Julia session in a state that reflects the point of computations
# at the position of the chapter where a given exercise is formulated

# Code for exercise 3.1

using BenchmarkTools
x = 1:10^6;
y = collect(x);
@btime sort($x);
@btime sort($y);
@edit sort(x)

# Code for exercise 4.1

using Statistics
using BenchmarkTools
aq = [10.0   8.04  10.0  9.14  10.0   7.46   8.0   6.58
       8.0   6.95   8.0  8.14   8.0   6.77   8.0   5.76
      13.0   7.58  13.0  8.74  13.0  12.74   8.0   7.71
       9.0   8.81   9.0  8.77   9.0   7.11   8.0   8.84
      11.0   8.33  11.0  9.26  11.0   7.81   8.0   8.47
      14.0   9.96  14.0  8.1   14.0   8.84   8.0   7.04
       6.0   7.24   6.0  6.13   6.0   6.08   8.0   5.25
       4.0   4.26   4.0  3.1    4.0   5.39  19.0  12.50
      12.0  10.84  12.0  9.13  12.0   8.15   8.0   5.56
       7.0   4.82   7.0  7.26   7.0   6.42   8.0   7.91
       5.0   5.68   5.0  4.74   5.0   5.73   8.0   6.89];
@benchmark [cor($aq[:, i], $aq[:, i+1]) for i in 1:2:7]
@benchmark [cor(view($aq, :, i), view($aq, :, i+1)) for i in 1:2:7]

# Code for exercise 4.2

function dice_distribution(dice1, dice2)
    distribution = Dict{Int, Int}()
    for i in dice1
        for j in dice2
            s = i + j
            if haskey(distribution, s)
                distribution[s] += 1
            else
                distribution[s] = 1
            end
        end
    end
    return distribution
end

function test_dice()
    all_dice = [[1, x2, x3, x4, x5, x6]
                for x2 in 2:11
                for x3 in x2:11
                for x4 in x3:11
                for x5 in x4:11
                for x6 in x5:11]

    two_standard = dice_distribution(1:6, 1:6)

    for d1 in all_dice, d2 in all_dice
        test = dice_distribution(d1, d2)
        if test == two_standard
            println(d1, " ", d2)
        end
    end
end

test_dice()

# Code for exercise 4.3

plot(scatter(data.set1.x, data.set1.y; legend=false),
     scatter(data.set2.x, data.set2.y; legend=false),
     scatter(data.set3.x, data.set3.y; legend=false),
     scatter(data.set4.x, data.set4.y; legend=false))

# Code for exercise 5.1

parse.(Int, ["1", "2", "3"])

# Code for exercise 5.2

Random.seed!(1234);
data5bis = [randn(100, 5) .- 0.4; randn(100, 5) .+ 0.4];
tsne = manifold.TSNE(n_components=2, init="random",
                     learning_rate="auto", random_state=1234);
data2bis = tsne.fit_transform(data5bis);
scatter(data2bis[:, 1], data2bis[:, 2];
        color=[fill("black", 100); fill("gold", 100)],
        legend=false)

# Code for exercise 6.1

years_table = freqtable(years)
plot(names(years_table, 1), years_table; legend=false,
           xlabel="year", ylabel="# of movies")

# Code for exercise 6.2

s3 = Symbol.(s1)
@btime sort($s3);
@btime unique($s1);
@btime unique($s2);
@btime unique($s3);

# Code for exercise 7.1

v = ["1", "2", missing, "4"]
[ismissing(x) ? missing : parse(Int, x) for x in v]
map(v) do x
    if ismissing(x)
        return missing
    else
        return parse(Int, x)
    end
end
using Missings
passmissing(parse).(Int, v)

# Code for exercise 7.2

using Dates
Date(2021, 1, 1):Month(1):Date(2021, 12, 1)
collect(Date(2021, 1, 1):Month(1):Date(2021, 12, 1))

# Code for exercise 7.3

query2 = "https://api.nbp.pl/api/exchangerates/rates/a/usd/" *
         "2020-06-01/2020-06-30/?format=json";
response2 = HTTP.get(query2);
json2 = JSON3.read(response2.body)
rates2 = [x.mid for x in json2.rates]
dates2 = [Date(x.effectiveDate) for x in json2.rates]
has_rate = rates .!== missing
rates2 == rates[has_rate]
dates2 == dates[has_rate]

# Code for exercise 8.1

using BenchmarkTools
@btime $puzzles."Rating";

# Code for exercise 9.1

using StatsBase
summarystats(puzzles[puzzles.Popularity .== 100, "NbPlays"])
summarystats(puzzles[puzzles.Popularity .== -100, "NbPlays"])

# Code for exercise 9.2

sum(length, values(rating_mapping))
nrow(good)

# Code for exercise 10.1

using BenchmarkTools
x = rand(10^6);
@btime DataFrame(x=$x);
@btime DataFrame(x=$x; copycols=false);

# Code for exercise 10.2

df1 = DataFrame(a=1,b=2)
df2 = DataFrame(b=3, a=4)
vcat(df1, df2)
vcat(df1, df2, cols=:orderequal)

# Code for exercise 10.3

function walk_unique_2ahead()
    walk = DataFrame(x=0, y=0)
    for _ in 1:10
        current = walk[end, :]
        push!(walk, sim_step(current))
    end
    return all(walk[i, :] != walk[i+2, :] for i in 1:9)
end
Random.seed!(2);
proptable([walk_unique_2ahead() for _ in 1:10^5])

# Code for exercise 11.1

@time wide = DataFrame(ones(1, 10_000), :auto);
@time Tables.columntable(wide);

# Code for exercise 11.2

using Statistics
Dict(key.city => mean(df.rainfall) for (key, df) in pairs(gdf_city))
combine(gdf_city, :rainfall => mean)

# Code for exercise 12.1

cg = complete_graph(37700)
Base.summarysize(cg)
@time deg_class(cg, classes_df.ml_target);

# Code for exercise 12.2

scatter(log1p.(agg_df.deg_ml),
        log1p.(agg_df.deg_web);
        zcolor=agg_df.web_mean,
        xlabel="degree ml", ylabel="degree web",
        markersize=2, markerstrokewidth=0, markeralpha=0.8,
        legend=:topleft, labels = "fraction web",
        xticks=gen_ticks(maximum(classes_df.deg_ml)),
        yticks=gen_ticks(maximum(classes_df.deg_web)))

# Code for exercise 12.3

glm(@formula(ml_target~log1p(deg_ml)+log1p(deg_web)),
    classes_df, Binomial(), ProbitLink())

# Code for exercise 12.4

df = DataFrame()
df.a = [1, 2, 3]
df.b = df.a
df.b === df.a
df.b = df[:, "b"]
df.b === df.a
df.b == df.a
df[1:2, "a"] .= 10
df

# Code for exercise 13.1

@rselect(owensboro,
    :arrest = :arrest_made,
    :day = dayofweek(:date),
    :type,
    :v1 = contains(:violation, agg_violation.v[1]),
    :v2 = contains(:violation, agg_violation.v[2]),
    :v3 = contains(:violation, agg_violation.v[3]),
    :v4 = contains(:violation, agg_violation.v[4]))

# Code for exercise 13.2

select(owensboro,
    :arrest_made => :arrest,
    :date => ByRow(dayofweek) => :day,
    :type,
    [:violation =>
     ByRow(x -> contains(x, agg_violation.v[i])) =>
     "v$i" for i in 1:4],
    :date => ByRow(dayname) => :dayname)

# Code for exercise 13.3

@chain owensboro2 begin
    groupby(:dayname, sort=true)
    combine(:arrest => mean)
end

@chain owensboro2 begin
    groupby([:dayname, :type], sort=true)
    combine(:arrest => mean)
    unstack(:dayname, :type, :arrest_mean)
end

# Code for exercise 13.4

train2 = owensboro2[owensboro2.train, :]
test2 = owensboro2[.!owensboro2.train, :]
test3, train3 = groupby(owensboro2, :train, sort=true)

# Code for exercise 14.1

@time mean(x -> x < 0, -10^6:10^6)
@time mean(x -> x < 0, -10^6:10^6)
@time mean(x -> x < 0, -10^6:10^6)
@time mean(<(0), -10^6:10^6)
@time mean(<(0), -10^6:10^6)
@time mean(<(0), -10^6:10^6)

lt0(x) = x < 0
@time mean(lt0, -10^6:10^6)
@time mean(lt0, -10^6:10^6)
@time mean(lt0, -10^6:10^6)

# Code for exercise 14.2

# web service code

using Genie
Genie.config.run_as_server = true
Genie.Router.route("/", method=POST) do
    message = Genie.Requests.jsonpayload()
    return try
        n = message["n"]
        Genie.Renderer.Json.json(rand(n))
    catch
        Genie.Responses.setstatus(400)
    end
end
Genie.startup()

# client code

using HTTP
using JSON3
req = HTTP.post("http://127.0.0.1:8000",
                ["Content-Type" => "application/json"],
                JSON3.write((n=3,)))
JSON3.read(req.body)
HTTP.post("http://127.0.0.1:8000",
                ["Content-Type" => "application/json"],
                JSON3.write((x=3,)))

max_stars_repo_name: Mo-Gul/JuliaForDataAnalysis

max_issues_repo_name: Mo-Gul/JuliaForDataAnalysis

max_forks_repo_name: Mo-Gul/JuliaForDataAnalysis


text:
@polly function kernel_gramschmidt(A,R,Q)
    m,n = size(A)
    for k = 1:n
        nrm = zero(eltype(A))
        for i = 1:m
            nrm += A[i,k] * A[i,k]
        end
        @fastmath R[k,k] = sqrt(nrm)
        for i = 1:m
            Q[i,k] = A[i,k] / R[k,k]
        end
        for j = (k+1):n
            R[k,j] = zero(eltype(R))
            for i = 1:m
                R[k,j] += Q[i,k] * A[i,j]
            end
            for i = 1:m
                A[i,j] = A[i,j] - Q[i,k] * R[k,j]
            end
        end
    end
end

let
    m = 1000
    n = 1200

    A = zeros(Float32,m,n)
    R = zeros(Float32,n,n)
    Q = zeros(Float32,m,n)

    for i = 1:m, j = 1:n
        A[i,j] = ((((i*j) % m) / m )*100) + 10
        Q[i,j] = zero(eltype(Q))
    end
    for i = 1:n, j = 1:n
        R[i,j] = zero(eltype(Q))
    end

    SUITE["gramschmidt"] = @benchmarkable kernel_gramschmidt(A, R, Q) setup = (A = copy($A); R = copy($R); Q = copy($Q))
end


text:
# License for this file: MIT (expat)
# Copyright 2017-2018, DLR Institute of System Dynamics and Control
#
# This file is part of module
#   Modia3D.Composition (Modia3D/Composition/_module.jl)
#

mutable struct SignalToFlangeAngle <: Modia3D.AbstractSignalAdaptor
    _internal::ModiaMath.ComponentInternal
    signal::Modia3D.AbstractSignal
    flange::Flange
    function SignalToFlangeAngle(phi::Union{ModiaMath.RealScalar,NOTHING}=nothing)
        if typeof(phi) != NOTHING
            flange = Flange(;phiCausality=ModiaMath.Output)
            signal = phi._internal.within
            flange.phi = phi
            new(ModiaMath.ComponentInternal(), signal, flange)
        else
            error("from Modia3D.SignalToFlangeAngle: There is no signal to convert.")
        end
    end
end

mutable struct SignalToFlangeTorque <: Modia3D.AbstractSignalAdaptor
    _internal::ModiaMath.ComponentInternal
    signal::Modia3D.AbstractSignal
    flange::Flange
    function SignalToFlangeTorque(tau::Union{ModiaMath.RealScalar,NOTHING}=nothing)
        if typeof(tau) != NOTHING
            flange = Flange(;tauCausality=ModiaMath.Output, tauFlow=true)
            signal = tau._internal.within
            tau.flow   = true
            flange.tau = tau
            new(ModiaMath.ComponentInternal(), signal, flange)
        else
            error("from Modia3D.SignalToFlangeTorque: There is no signal to convert.")
        end
    end
end

mutable struct AdaptorForceElementToFlange <: Modia3D.AbstractForceAdaptor
    _internal::ModiaMath.ComponentInternal
    forceElement::Modia3D.AbstractForceTorque
    flange::Flange
    function AdaptorForceElementToFlange(;phi::Union{ModiaMath.RealScalar,NOTHING}=nothing,
                                          w::Union{ModiaMath.RealScalar,NOTHING}=nothing,
                                          a::Union{ModiaMath.RealScalar,NOTHING}=nothing,
                                          tau::Union{ModiaMath.RealScalar,NOTHING}=nothing)
        flange = Flange()
        forceElement  = nothing
        forceElement1 = nothing
        forceElement2 = nothing
        forceElement3 = nothing
        forceElement4 = nothing
        if typeof(phi) != NOTHING
            flange.phi = phi
            forceElement1 = phi._internal.within
            forceElement  = forceElement1
        end
        if typeof(w) != NOTHING
            flange.w = w
            forceElement2 = w._internal.within
            ((typeof(forceElement)==NOTHING) ? (forceElement=forceElement2) : ( (typeof(forceElement)!=typeof(forceElement2)) ? (error("from Modia3D.AdaptorForceElementToFlange: all arguments should be of the same @forceElement.")) : () ) )
        end
        if typeof(a) != NOTHING
            flange.a = a
            forceElement3 = a._internal.within
            ((typeof(forceElement)==NOTHING) ? (forceElement=forceElement3) : ( (typeof(forceElement)!=typeof(forceElement3)) ? (error("from Modia3D.AdaptorForceElementToFlange: all arguments should be of the same @forceElement.")) : () ) )
        end
        if typeof(tau) != NOTHING
            tau.flow   = true
            flange.tau = tau
            forceElement4 = tau._internal.within
            ((typeof(forceElement)==NOTHING) ? (forceElement=forceElement4) : ( (typeof(forceElement)!=typeof(forceElement4)) ? (error("from Modia3D.AdaptorForceElementToFlange: all arguments should be of the same @forceElement.")) : () ) )
        end
        if typeof(forceElement) != NOTHING
            new(ModiaMath.ComponentInternal(),forceElement,flange)
        else
            error("from Modia3D.SignalToFlangeTorque: There is no forceElement to convert.")
        end
    end
end

mutable struct AdaptorForceElementToPFlange <: Modia3D.AbstractForceAdaptor
    _internal::ModiaMath.ComponentInternal
    forceElement::Modia3D.AbstractForceTorque
    flange::PFlange
    function AdaptorForceElementToPFlange(;s::Union{ModiaMath.RealScalar,NOTHING}=nothing,
                                           v::Union{ModiaMath.RealScalar,NOTHING}=nothing,
                                           a::Union{ModiaMath.RealScalar,NOTHING}=nothing,
                                           f::Union{ModiaMath.RealScalar,NOTHING}=nothing)
        flange = PFlange()
        forceElement  = nothing
        forceElement1 = nothing
        forceElement2 = nothing
        forceElement3 = nothing
        forceElement4 = nothing
        if typeof(s) != NOTHING
            flange.s = s
            forceElement1 = s._internal.within
            forceElement  = forceElement1
        end
        if typeof(v) != NOTHING
            flange.v = v
            forceElement2 = v._internal.within
            ((typeof(forceElement)==NOTHING) ? (forceElement=forceElement2) : ( (typeof(forceElement)!=typeof(forceElement2)) ? (error("from Modia3D.AdaptorForceElementToFlange: all arguments should be of the same @forceElement.")) : () ) )
        end
        if typeof(a) != NOTHING
            flange.a = a
            forceElement3 = a._internal.within
            ((typeof(forceElement)==NOTHING) ? (forceElement=forceElement3) : ( (typeof(forceElement)!=typeof(forceElement3)) ? (error("from Modia3D.AdaptorForceElementToFlange: all arguments should be of the same @forceElement.")) : () ) )
        end
        if typeof(f) != NOTHING
            f.flow   = true
            flange.f = f
            forceElement4 = f._internal.within
            ((typeof(forceElement)==NOTHING) ? (forceElement=forceElement4) : ( (typeof(forceElement)!=typeof(forceElement4)) ? (error("from Modia3D.AdaptorForceElementToFlange: all arguments should be of the same @forceElement.")) : () ) )
        end
        if typeof(forceElement) != NOTHING
            new(ModiaMath.ComponentInternal(),forceElement,flange)
        else
            error("from Modia3D.SignalToFlangeTorque: There is no forceElement to convert.")
        end
    end
end

#=
mutable struct TransDyn
  filter_T::Float64
  signal::AbstractSignal
  flange::Flange
  function TransDyn(signal::AbstractSignal, filter_T = 50)
     new(signal, Flange()
  end
end
=#


text:
include("../coin-or-common.jl")

sources = [
    GitSource("https://github.com/coin-or/CHiPPS-BiCePS.git", BiCePS_gitsha),
]

script = raw"""
export CPPFLAGS="${CPPFLAGS} -I${includedir} -I${includedir}/coin"
if [[ "${target}" == *mingw* ]]; then
    export LDFLAGS="-L${bindir}"
elif [[ "${target}" == *linux* ]]; then
    export LDFLAGS="-ldl -lrt"
fi

cd $WORKSPACE/srcdir/CHiPPS-BiCePS
rm -f ${prefix}/lib/*.la
update_configure_scripts
sed -i s/elf64ppc/elf64lppc/ configure
mkdir build
cd build
../configure \
    --prefix=${prefix} \
    --build=${MACHTYPE} \
    --host=${target} \
    --with-pic \
    --disable-pkg-config \
    --disable-debug \
    --disable-dependency-tracking \
    --enable-shared \
    lt_cv_deplibs_check_method=pass_all \
    --with-coinutils-lib="-lCoinUtils" \
    --with-osi-lib="-lOsi" \
    --with-clp-lib="-lClp -lOsiClp" \
    --with-cgl-lib="-lCgl" \
    --with-alps-lib="-lAlps -lCoinUtils" \
    --with-coindepend-lib="-lCgl -lClp -lOsi -lCoinUtils"
make -j${nproc}
make install
"""

products = [
    LibraryProduct("libBcps", :libbcps),
]

dependencies = [
    Dependency("CoinUtils_jll", CoinUtils_version),
    Dependency("Osi_jll", Osi_version),
    Dependency("Clp_jll", Clp_version),
    Dependency("Cgl_jll", Cgl_version),
    Dependency("ALPS_jll"),  #, ALPS_version),
    Dependency("CompilerSupportLibraries_jll"),
]

build_tarballs(
    ARGS,
    "BiCePS",
    BiCePS_version,
    sources,
    script,
    platforms,
    products,
    dependencies;
    preferred_gcc_version = gcc_version,
    julia_compat = "1.6",
)

max_stars_repo_name: plut/Yggdrasil

max_issues_repo_name: plut/Yggdrasil

max_forks_repo_name: plut/Yggdrasil


text:
using Rayuela
using HDF5

# === Saving functions to keep track of experimental results ===
function save_results_pq_query_base(
  bpath::String, trial::Integer, C::Vector{Matrix{Float32}}, B, train_error, recall)
  for i = 1:length(C)
    h5write(bpath, "$(trial)/C_$i", C[i])
  end
  h5write(bpath, "$(trial)/B", convert(Matrix{UInt8}, B.-1))
  h5write(bpath, "$(trial)/train_error", train_error)
  h5write(bpath, "$(trial)/recall", recall)
end

function save_results_pq(
  bpath::String, trial::Integer, C::Vector{Matrix{Float32}}, B, train_error, B_base, recall)
  h5write(bpath, "$(trial)/B_base", convert(Matrix{UInt8}, B_base.-1))
  save_results_pq_query_base(bpath, trial, C, B, train_error, recall)
end

function save_results_opq_query_base(
  bpath::String, trial::Integer, C::Vector{Matrix{Float32}}, B, R::Matrix{Float32}, train_error, recall)
  h5write(bpath, "$(trial)/R", R)
  save_results_pq_query_base(bpath, trial, C, B, train_error, recall)
end

function save_results_opq(
  bpath::String, trial::Integer, C::Vector{Matrix{Float32}}, B, R::Matrix{Float32}, train_error, B_base, recall)
  h5write(bpath, "$(trial)/B_base", convert(Matrix{UInt8}, B_base.-1))
  save_results_opq_query_base(bpath, trial, C, B, R, train_error, recall)
end

function save_results_lsq_query_base(
  bpath::String, trial::Integer, C::Vector{Matrix{Float32}}, B, R::Matrix{Float32}, train_error, opq_error, recall)
  h5write(bpath, "$(trial)/opq_base", opq_error)
  save_results_opq_query_base(bpath, trial, C, B, R, train_error, recall)
end

function save_results_lsq(
  bpath::String, trial::Integer, C::Vector{Matrix{Float32}}, B, R::Matrix{Float32}, train_error, opq_error, B_base, recall)
  h5write(bpath, "$(trial)/B_base", convert(Matrix{UInt8}, B_base.-1))
  save_results_lsq_query_base(bpath, trial, C, B, R, train_error, opq_error, recall)
end

function load_chainq(fname::String, m::Integer, trial::Integer)
  B = h5read(fname, "$trial/B"); B = convert(Matrix{Int16}, B); B.+=1
  R = h5read(fname, "$trial/R")
  chainq_error = h5read(fname, "$trial/train_error")
  C = Vector{Matrix{Float32}}(undef, m)
  for i=1:(m); C[i] = h5read(fname, "$trial/C_$i"); end
  return C, B, R, chainq_error
end

function load_rvq(fname::String, m::Integer, trial::Integer)
  B = h5read(fname, "$trial/B"); B = convert(Matrix{Int16}, B); B.+=1
  rvq_error = h5read(fname, "$trial/train_error")
  C = Vector{Matrix{Float32}}(undef, m)
  for i=1:(m); C[i] = h5read(fname, "$trial/C_$i"); end
  return C, B, rvq_error
end

# === Data loading function ===
function load_experiment_data(
  dataset_name::String,
  ntrain::Integer, nbase::Integer, nquery::Integer, V::Bool=false)

  # Load training, base, queries and ground truth
  Xt = Rayuela.read_dataset(dataset_name, ntrain, V)
  Xb = Rayuela.read_dataset(dataset_name * "_base", nbase, V)
  Xq = Rayuela.read_dataset(dataset_name * "_query", nquery, V)[:,1:nquery]
  gt = Rayuela.read_dataset(dataset_name * "_groundtruth", nquery, V)

  # SIFT1M and GIST1M have zero-based indexing for their ground truth
  if dataset_name == "SIFT1M" || dataset_name == "GIST1M"
    gt = gt .+ 1
  end

  # Keep only the top neighbour in the ground truth
  if dataset_name != "Deep1M"
    gt = convert( Vector{UInt32}, gt[1,1:nquery] )
  else
    gt = convert( Vector{UInt32}, gt[1:nquery] )
  end

  return Xt, Xb, Xq, gt
end


text:
resODEfixed = Dict{Symbol,Dict}()
const S = Solvers

for (n,tc) in totest
    res = Dict{Solver,Any}()
    tstepss = [linspace(tc.tspan[1], tc.tspan[2], n) for n in ntsteps]
    for (solverfn,solver) in S.ODEsolvers
        if isapplicable(solver, tc) && !isadaptive(solver)
            if name(tc)==:bruss1d
                # 10^5 steps take more than 10 min to run, skip:
                suite = TestSuite(tc, solver, tstepss[ntsteps.<50_000])
            else
                suite = TestSuite(tc, solver, tstepss)
            end
            res[solver] = run_ode_testsuite(suite)
        end
    end
    resODEfixed[n] = res
end


text:
padjust(pValues::AbstractArray, method::BonferroniMethod) = bonferroni(pValues)
padjust(pValues::AbstractArray, method::BenjaminiHochbergMethod) = benjaminiHochberg(pValues)
padjust(pValues::AbstractArray, method::BenjaminiYekutieliMethod) = benjaminiYekutieli(pValues)
padjust(pValues::AbstractArray, method::HochbergMethod) = hochberg(pValues)
padjust(pValues::AbstractArray, method::HolmMethod) = holm(pValues)

function padjust(pValues::AbstractArray)
  @check_pValues pValues
  pValues
end


text:
@testset "multiclass" begin
    y = [1, 2, 3, 1, 1, 2, 3]
    l = LogisticSoftMaxLikelihood(3)
    AGP.create_mapping!(l, y)
    @test sort(l.class_mapping) == [1, 2, 3]
    @test l.ind_mapping == Dict(1 => 1, 2 => 2, 3 => 3)
    AGP.create_one_hot!(l, y[1:3])
    @test l.Y == [BitArray([1, 0, 0]), BitArray([0, 1, 0]), BitArray([0, 0, 1])]
    @test l.y_class == [1, 2, 3]

    l = LogisticSoftMaxLikelihood(2)
    @test_throws ErrorException AGP.create_mapping!(l, y)

    y = [1, 2, 1, 1]
    l = LogisticSoftMaxLikelihood(3)
    AGP.create_mapping!(l, y)
    @test l.class_mapping == [1, 2, 3]
    @test l.ind_mapping == Dict(1 => 1, 2 => 2, 3 => 3)
    AGP.create_one_hot!(l, y)
    @test l.Y == [
        BitArray([1, 0, 1, 1]),
        BitArray([0, 1, 0, 0]),
        BitArray([0, 0, 0, 0]),
    ]
    @test l.y_class == [1, 2, 1, 1]
    @test AGP.num_latent(l) == 3

    y = ["b", "a", "c", "a", "a"]
    l = LogisticSoftMaxLikelihood(3)
    AGP.create_mapping!(l, y)
    @test l.class_mapping == ["b", "a", "c"]
    @test l.ind_mapping == Dict("b" => 1, "a" => 2, "c" => 3)
    AGP.create_one_hot!(l, y)
    @test l.Y == [
        BitArray([1, 0, 0, 0, 0]),
        BitArray([0, 1, 0, 1, 1]),
        BitArray([0, 0, 1, 0, 0]),
    ]
    @test l.y_class == [1, 2, 3, 2, 2]

    l = LogisticSoftMaxLikelihood(["a", "b", "c"])
    @test l.ind_mapping == Dict("a" => 1, "b" => 2, "c" => 3)
    AGP.create_one_hot!(l, y)
    @test l.Y == [
        BitArray([0, 1, 0, 1, 1]),
        BitArray([1, 0, 0, 0, 0]),
        BitArray([0, 0, 1, 0, 0]),
    ]
    @test l.y_class == [2, 1, 3, 1, 1]

    l = LogisticSoftMaxLikelihood(3)
    AGP.treat_labels!(y, l)
    @test l.class_mapping == ["b", "a", "c"]
    @test l.ind_mapping == Dict("b" => 1, "a" => 2, "c" => 3)
    @test l.Y == [
        BitArray([1, 0, 0, 0, 0]),
        BitArray([0, 1, 0, 1, 1]),
        BitArray([0, 0, 1, 0, 0]),
    ]
    @test l.y_class == [1, 2, 3, 2, 2]
end


text:
using MathOptInterface
const MOI = MathOptInterface
const MOIB = MOI.Bridges
const MOIT = MOI.Test
const MOIU = MOI.Utilities

MOIU.@model(ModelData,
            (),
            (MOI.EqualTo, MOI.GreaterThan, MOI.LessThan, MOI.Interval),
            (MOI.SecondOrderCone,),
            (MOI.SOS1, MOI.SOS2),
            (),
            (MOI.ScalarAffineFunction, MOI.ScalarQuadraticFunction),
            (MOI.VectorOfVariables,),
            (MOI.VectorAffineFunction,))
const CACHE = MOIU.UniversalFallback(ModelData{Float64}())
const CACHED = MOIU.CachingOptimizer(CACHE, SCIP.Optimizer(display_verblevel=0))
const BRIDGED2 = MOIB.full_bridge_optimizer(CACHED, Float64)

const CONFIG_CACHED = MOIT.Config(
    atol=1e-5, rtol=1e-5,
    exclude=Any[
        MOI.ConstraintDual, MOI.ConstraintName, MOI.DualObjectiveValue, MOI.VariableBasisStatus, MOI.ConstraintBasisStatus,
    ],
)

@testset "MOI Modification tests" begin
    exclude_list = copy(MOI_BASE_EXCLUDED)
    append!(
        exclude_list,
        [
            # SCIP needs non-negative variable on right-hand side of second-order cone constraint, have lower bound: -1.0e20
            "test_conic_GeometricMeanCone_VectorAffineFunction",
            "test_conic_GeometricMeanCone_VectorOfVariables",
            "test_conic_RotatedSecondOrderCone_INFEASIBLE",
            "test_conic_RotatedSecondOrderCone_VectorAffineFunction",
            "test_conic_RotatedSecondOrderCone_VectorOfVariables",
            "test_conic_RotatedSecondOrderCone_out_of_order",
            "test_conic_RootDetConeTriangle_VectorOfVariables",
            "test_conic_SecondOrderCone_INFEASIBLE",
            "test_conic_SecondOrderCone_Nonnegatives",
            "test_conic_SecondOrderCone_Nonpositives",
            "test_conic_SecondOrderCone_VectorAffineFunction",
            "test_conic_SecondOrderCone_VectorOfVariables",
            "test_conic_SecondOrderCone_negative_initial_bound",
            "test_conic_SecondOrderCone_negative_post_bound",
            "test_conic_SecondOrderCone_no_initial_bound",
            "test_conic_SecondOrderCone_out_of_order",
            # Can not delete variable while model contains constraints
            "test_linear_integration",
            "test_quadratic_duplicate_terms",
            "test_quadratic_nonhomogeneous",
        ]
    )
    MOIT.runtests(BRIDGED2, CONFIG_CACHED, exclude = exclude_list)
end


text:
addIntegratorMedium_! =
Dict{String,Function}(
    "FTCS"=>addIntegratorMediumFTCS_!,
    "Lax"=>addIntegratorMediumFTCS_!,
    "Leapfrog"=>addIntegratorMediumFTCS_!,
)

δMedium_(i1,i2) = if i1==i2 1. else 0. end


text:
# Test discretization functions

arr = rand(100)

# Test with 1 values array
@test size(discretize_values(arr)) == (10, 1)
println("Discretize values with 1 array passed.")

# Test with 2 values arrays
@test size(discretize_values(arr, arr)) == (10, 10)
println("Discretize values with 2 arrays passed.")

# Test with 3 values arrays
@test size(discretize_values(arr, arr, arr)) == (10, 10, 10)
println("Discretize values with 3 arrays passed.")

# Test with 4 values arrays
@test size(discretize_values(arr, arr, arr, arr)) == (10, 10, 10, 10)
println("Discretize values with >3 arrays passed.")

# Test with uniform_width
@test size(discretize_values(arr, mode = "uniform_width")) == (10, 1)
println("Discretize values with uniform width passed.")

# Test with uniform_count
@test size(discretize_values(arr, mode = "uniform_count")) == (10, 1)
println("Discretize values with uniform count passed.")

# Test with bayesian_blocks
# @test size(discretize_values(arr, mode = "bayesian_blocks")) == (10, 1)
# println("Discretize values with Bayesian blocks passed.")

# Test with number_of_bins
@test size(discretize_values(arr, number_of_bins = 5)) == (5, 1)
println("Discretize values with number of bins passed.")

# Test with get_number_of_bins
@test size(discretize_values(arr, get_number_of_bins = function(values) return 2 end)) == (2, 1)
println("Discretize values with get number of bins passed.")


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

mutable struct VpnPacketCaptureStartParameters <: SwaggerModel
    filterData::Any # spec type: Union{ Nothing, String } # spec name: filterData

    function VpnPacketCaptureStartParameters(;filterData=nothing)
        o = new()
        validate_property(VpnPacketCaptureStartParameters, Symbol("filterData"), filterData)
        setfield!(o, Symbol("filterData"), filterData)
        o
    end
end # type VpnPacketCaptureStartParameters

const _property_map_VpnPacketCaptureStartParameters = Dict{Symbol,Symbol}(Symbol("filterData")=>Symbol("filterData"))
const _property_types_VpnPacketCaptureStartParameters = Dict{Symbol,String}(Symbol("filterData")=>"String")
Base.propertynames(::Type{ VpnPacketCaptureStartParameters }) = collect(keys(_property_map_VpnPacketCaptureStartParameters))
Swagger.property_type(::Type{ VpnPacketCaptureStartParameters }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_VpnPacketCaptureStartParameters[name]))}
Swagger.field_name(::Type{ VpnPacketCaptureStartParameters }, property_name::Symbol) =  _property_map_VpnPacketCaptureStartParameters[property_name]

function check_required(o::VpnPacketCaptureStartParameters)
    true
end

function validate_property(::Type{ VpnPacketCaptureStartParameters }, name::Symbol, val)
end


text:
using Indicators
using PyPlot
using Dates
using Random

# Generate some toy sample data
Random.seed!(1)
n = 250
Open = 100.0 .+ cumsum(randn(n))
High = Open .+ rand(n)
Low = Open .- rand(n)
Close = 100.0 .+ cumsum(randn(n))
for i = 1:n
	if Close[i] > High[i]
		Close[i] = High[i]
	elseif Close[i] < Low[i]
		Close[i] = Low[i]
	end
end
OHLC = [Open High Low Close]
HLC = [High Low Close]
HL = [High Low]
t = collect(today():Day(1):today()+Day(n-1))

# Overlays
subplot(411)
plot(t, Close, lw=2, c="k", label="Random Walk")
grid(ls="-", c=[0.8,0.8,0.8])
plot(t, sma(Close,n=40), c=[1,0.5,0], label="SMA (40)")
plot(t, ema(Close,n=10), c=[0,1,1], label="EMA (10)")
plot(t, wma(Close,n=20), c=[1,0,1], label="WMA (20)")
plot(t, psar(HL),   "bo", label="Parabolic SAR")
legend(loc="best", frameon=false)

# MACD
subplot(412)
plot(t, macd(Close)[:,1], label="MACD", c=[1,0.5,1])
plot(t, macd(Close)[:,2], label="Signal", c=[0.5,0.25,0.5])
bar(t, macd(Close)[:,3], align="center", label="Histogram", color=[0,0.5,0.5], alpha=0.25)
plot([t[1],t[end]], [0,0], ls="--", c=[0.5,0.5,0.5])
grid(ls="-", c=[0.8,0.8,0.8])
legend(loc="best", frameon=false)

# RSI
subplot(413)
plot(t, rsi(Close), c=[0.5,0.5,0], label="RSI")
grid(ls="-", c=[0.8,0.8,0.8])
plot([t[1],t[end]], [30,30], c="g")
plot([t[1],t[end]], [70,70], c="r")
legend(loc="best", frameon=false)

# ADX
subplot(414)
plot(t, adx(HLC)[:,1], "g-", label="DI+")
plot(t, adx(HLC)[:,2], "r-", label="DI-")
plot(t, adx(HLC)[:,3], c=[0,0,1], lw=2, label="ADX")
grid(ls="-", c=[0.8,0.8,0.8])
legend(loc="best", frameon=false)

tight_layout()


text: abstract type AbstractSolver end


text:
module TestFundamentalValues
using AlphaVantage
using Test

TEST_SLEEP_TIME =  parse(Float64, get(ENV, "TEST_SLEEP_TIME", "15"))
MAX_TESTS = parse(Int64, get(ENV, "MAX_TESTS", "1"))

@testset "Fundamental Values" begin

vals = rand([AlphaVantage.INCOME_STATEMENT_KEYS;
             AlphaVantage.CASH_FLOW_KEYS;
             AlphaVantage.BALANCE_SHEET_KEYS;
             AlphaVantage.EARNINGS_KEYS_Q;
             AlphaVantage.EARNINGS_KEYS_A], MAX_TESTS)

for val in vals
    @testset "$val" begin
        @testset "Annual" begin
            fnameA = Symbol(val * "_" * "annuals")
            @eval begin
                aRes = $(fnameA)("AAPL", datatype="json")
                @test length(aRes) == 2
            end
        end
        sleep(TEST_SLEEP_TIME + 2*rand())
        @testset "Quarterly" begin
            fnameQ = Symbol(val * "_" * "quarterlys")
            @eval begin
                qRes = $(fnameQ)("AAPL", datatype="json")
                @test length(qRes) == 2
            end
        end
    end
    sleep(TEST_SLEEP_TIME + 2*rand()) #as to not overload the API
end

end

end # module


text:
module Env

export State, newstate, onestep, reward

# この実験における定数
const g = 9.80665   # 重力加速度
const M = 1.0       # カートの質量
const m = 0.1       # ポールの質量
const l = 0.5       # ポールの半分の長さ
const fps = 50      # frames per second
const tau = 1 / fps # 制御周期

const State = Vector{Float64}

# 最初の状態
# [x, theta, xdot, thetadot]
const initstate = [0.0, -pi, 0.0, 0.0]

# あとの計算で使う
const ml = m * l
const mass = M + m

function newstate()
    copy(initstate)
end

function onestep(s, a)
    rungekuttasolve(s, a, tau)
end

function reward(s, a)
    x, θ, xdot, θdot = s
    if abs(x) > 2.0
        return -2.0
    end
    -abs(θ) + pi / 2
end

# 状態 s で力 u を加えたときの微分
function differential(s, u)
    x, θ, xdot, θdot = s
    sinθ = sin(θ)
    cosθ = cos(θ)

    xddot = (4u / 3 + 4ml * θdot^2 * sinθ / 3 - m * g * sin(2θ) / 2) / (4mass - m * cosθ^2)
    θddot = (mass * g * sinθ - ml * θdot^2 * sinθ * cosθ - u * cosθ) /
        (4mass * l / 3 - ml * cosθ^2)

    [xdot, θdot, xddot, θddot]
end

# オイラー法を用いて微分方程式を解く
function eulersolve(s, sdot, dt)
    s + sdot * dt
end

# ルンゲクッタ法を用いて微分方程式を解く
function rungekuttasolve(s, u, dt)
    k1 = differential(s, u)
    s1 = eulersolve(s, k1, dt / 2)
    k2 = differential(s1, u)
    s2 = eulersolve(s, k2, dt / 2)
    k3 = differential(s2, u)
    s3 = eulersolve(s, k3, dt)
    k4 = differential(s3, u)

    snext = s + (k1 + 2k2 + 2k3 + k4) * dt / 6
    snext[2] = mod2pi(snext[2] + pi) - pi
    snext
end

end

max_stars_repo_name: high-moctane/anylang-rl

max_issues_repo_name: high-moctane/anylang-rl

max_forks_repo_name: high-moctane/anylang-rl


text:
function clear_c3(c3,num)

    ctx = Gtk.getgc(c3)

    set_source_rgb(ctx,0.0,0.0,0.0)
    paint(ctx)

    nothing
end

function c3_press_win(widget::Ptr,param_tuple,user_data::Tuple{Single_Channel})

    sc, = user_data
    event = unsafe_load(param_tuple)

    if event.button == 1 #left click captures window
        check_c3_click(sc,event.x,event.y)
    elseif event.button == 3 #right click refreshes window
    end
    nothing
end

function check_c3_click(sc::Single_Channel,x,y)

    ctx=Gtk.getgc(sc.c3)
    mywidth=width(ctx)

    total_clus = max(sc.total_clus+1,5)

    xbounds=linspace(0.0,mywidth,total_clus+1)

    count=1
    inmulti=false
    if y<130
        for j=2:length(xbounds)
            if (x<xbounds[j])
                inmulti=true
                break
            end
            count+=1
        end
    end
    if (inmulti)&(count<sc.total_clus+1)
        selmodel=Gtk.GAccessor.selection(sc.sort_tv)
        Gtk.select!(selmodel, Gtk.iter_from_index(sc.sort_list,count+1))
        select_unit(sc)
    end
    nothing
end