text:
# syntax: proto3
using ProtoBuf
import ProtoBuf.meta

mutable struct SavedUserObject <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedUserObject(; kwargs...)
        obj = new(meta(SavedUserObject), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedUserObject
const __meta_SavedUserObject = Ref{ProtoMeta}()
function meta(::Type{SavedUserObject})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedUserObject)
            __meta_SavedUserObject[] = target = ProtoMeta(SavedUserObject)
            allflds = Pair{Symbol,Union{Type,String}}[:identifier => AbstractString, :version => VersionDef, :metadata => AbstractString]
            meta(target, SavedUserObject, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedUserObject[]
    end
end
function Base.getproperty(obj::SavedUserObject, name::Symbol)
    if name === :identifier
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    elseif name === :version
        return (obj.__protobuf_jl_internal_values[name])::VersionDef
    elseif name === :metadata
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    else
        getfield(obj, name)
    end
end

mutable struct SavedAsset <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedAsset(; kwargs...)
        obj = new(meta(SavedAsset), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedAsset
const __meta_SavedAsset = Ref{ProtoMeta}()
function meta(::Type{SavedAsset})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedAsset)
            __meta_SavedAsset[] = target = ProtoMeta(SavedAsset)
            allflds = Pair{Symbol,Union{Type,String}}[:asset_file_def_index => Int32]
            meta(target, SavedAsset, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedAsset[]
    end
end
function Base.getproperty(obj::SavedAsset, name::Symbol)
    if name === :asset_file_def_index
        return (obj.__protobuf_jl_internal_values[name])::Int32
    else
        getfield(obj, name)
    end
end

mutable struct SavedConcreteFunction <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedConcreteFunction(; kwargs...)
        obj = new(meta(SavedConcreteFunction), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedConcreteFunction
const __meta_SavedConcreteFunction = Ref{ProtoMeta}()
function meta(::Type{SavedConcreteFunction})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedConcreteFunction)
            __meta_SavedConcreteFunction[] = target = ProtoMeta(SavedConcreteFunction)
            fnum = Int[2,3,4]
            pack = Symbol[:bound_inputs]
            allflds = Pair{Symbol,Union{Type,String}}[:bound_inputs => Base.Vector{Int32}, :canonicalized_input_signature => StructuredValue, :output_signature => StructuredValue]
            meta(target, SavedConcreteFunction, allflds, ProtoBuf.DEF_REQ, fnum, ProtoBuf.DEF_VAL, pack, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedConcreteFunction[]
    end
end
function Base.getproperty(obj::SavedConcreteFunction, name::Symbol)
    if name === :bound_inputs
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{Int32}
    elseif name === :canonicalized_input_signature
        return (obj.__protobuf_jl_internal_values[name])::StructuredValue
    elseif name === :output_signature
        return (obj.__protobuf_jl_internal_values[name])::StructuredValue
    else
        getfield(obj, name)
    end
end

mutable struct SavedObjectGraph_ConcreteFunctionsEntry <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedObjectGraph_ConcreteFunctionsEntry(; kwargs...)
        obj = new(meta(SavedObjectGraph_ConcreteFunctionsEntry), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedObjectGraph_ConcreteFunctionsEntry (mapentry)
const __meta_SavedObjectGraph_ConcreteFunctionsEntry = Ref{ProtoMeta}()
function meta(::Type{SavedObjectGraph_ConcreteFunctionsEntry})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedObjectGraph_ConcreteFunctionsEntry)
            __meta_SavedObjectGraph_ConcreteFunctionsEntry[] = target = ProtoMeta(SavedObjectGraph_ConcreteFunctionsEntry)
            allflds = Pair{Symbol,Union{Type,String}}[:key => AbstractString, :value => SavedConcreteFunction]
            meta(target, SavedObjectGraph_ConcreteFunctionsEntry, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedObjectGraph_ConcreteFunctionsEntry[]
    end
end
function Base.getproperty(obj::SavedObjectGraph_ConcreteFunctionsEntry, name::Symbol)
    if name === :key
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    elseif name === :value
        return (obj.__protobuf_jl_internal_values[name])::SavedConcreteFunction
    else
        getfield(obj, name)
    end
end

mutable struct SavedConstant <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedConstant(; kwargs...)
        obj = new(meta(SavedConstant), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedConstant
const __meta_SavedConstant = Ref{ProtoMeta}()
function meta(::Type{SavedConstant})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedConstant)
            __meta_SavedConstant[] = target = ProtoMeta(SavedConstant)
            allflds = Pair{Symbol,Union{Type,String}}[:operation => AbstractString]
            meta(target, SavedConstant, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedConstant[]
    end
end
function Base.getproperty(obj::SavedConstant, name::Symbol)
    if name === :operation
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    else
        getfield(obj, name)
    end
end

mutable struct SavedVariable <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedVariable(; kwargs...)
        obj = new(meta(SavedVariable), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedVariable
const __meta_SavedVariable = Ref{ProtoMeta}()
function meta(::Type{SavedVariable})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedVariable)
            __meta_SavedVariable[] = target = ProtoMeta(SavedVariable)
            allflds = Pair{Symbol,Union{Type,String}}[:dtype => Int32, :shape => TensorShapeProto, :trainable => Bool, :synchronization => Int32, :aggregation => Int32, :name => AbstractString, :device => AbstractString, :experimental_distributed_variable_components => Base.Vector{SavedVariable}]
            meta(target, SavedVariable, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedVariable[]
    end
end
function Base.getproperty(obj::SavedVariable, name::Symbol)
    if name === :dtype
        return (obj.__protobuf_jl_internal_values[name])::Int32
    elseif name === :shape
        return (obj.__protobuf_jl_internal_values[name])::TensorShapeProto
    elseif name === :trainable
        return (obj.__protobuf_jl_internal_values[name])::Bool
    elseif name === :synchronization
        return (obj.__protobuf_jl_internal_values[name])::Int32
    elseif name === :aggregation
        return (obj.__protobuf_jl_internal_values[name])::Int32
    elseif name === :name
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    elseif name === :device
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    elseif name === :experimental_distributed_variable_components
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{SavedVariable}
    else
        getfield(obj, name)
    end
end

const FunctionSpec_ExperimentalCompile = (;[
    Symbol("DEFAULT") => Int32(0),
    Symbol("ON") => Int32(1),
    Symbol("OFF") => Int32(2),
]...)

mutable struct FunctionSpec <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function FunctionSpec(; kwargs...)
        obj = new(meta(FunctionSpec), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct FunctionSpec
const __meta_FunctionSpec = Ref{ProtoMeta}()
function meta(::Type{FunctionSpec})
    ProtoBuf.metalock() do
        if !isassigned(__meta_FunctionSpec)
            __meta_FunctionSpec[] = target = ProtoMeta(FunctionSpec)
            fnum = Int[1,2,5,6]
            allflds = Pair{Symbol,Union{Type,String}}[:fullargspec => StructuredValue, :is_method => Bool, :input_signature => StructuredValue, :experimental_compile => Int32]
            meta(target, FunctionSpec, allflds, ProtoBuf.DEF_REQ, fnum, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_FunctionSpec[]
    end
end
function Base.getproperty(obj::FunctionSpec, name::Symbol)
    if name === :fullargspec
        return (obj.__protobuf_jl_internal_values[name])::StructuredValue
    elseif name === :is_method
        return (obj.__protobuf_jl_internal_values[name])::Bool
    elseif name === :input_signature
        return (obj.__protobuf_jl_internal_values[name])::StructuredValue
    elseif name === :experimental_compile
        return (obj.__protobuf_jl_internal_values[name])::Int32
    else
        getfield(obj, name)
    end
end

mutable struct SavedFunction <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedFunction(; kwargs...)
        obj = new(meta(SavedFunction), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedFunction
const __meta_SavedFunction = Ref{ProtoMeta}()
function meta(::Type{SavedFunction})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedFunction)
            __meta_SavedFunction[] = target = ProtoMeta(SavedFunction)
            allflds = Pair{Symbol,Union{Type,String}}[:concrete_functions => Base.Vector{AbstractString}, :function_spec => FunctionSpec]
            meta(target, SavedFunction, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedFunction[]
    end
end
function Base.getproperty(obj::SavedFunction, name::Symbol)
    if name === :concrete_functions
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{AbstractString}
    elseif name === :function_spec
        return (obj.__protobuf_jl_internal_values[name])::FunctionSpec
    else
        getfield(obj, name)
    end
end

mutable struct SavedBareConcreteFunction <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedBareConcreteFunction(; kwargs...)
        obj = new(meta(SavedBareConcreteFunction), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedBareConcreteFunction
const __meta_SavedBareConcreteFunction = Ref{ProtoMeta}()
function meta(::Type{SavedBareConcreteFunction})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedBareConcreteFunction)
            __meta_SavedBareConcreteFunction[] = target = ProtoMeta(SavedBareConcreteFunction)
            allflds = Pair{Symbol,Union{Type,String}}[:concrete_function_name => AbstractString, :argument_keywords => Base.Vector{AbstractString}, :allowed_positional_arguments => Int64, :function_spec => FunctionSpec]
            meta(target, SavedBareConcreteFunction, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedBareConcreteFunction[]
    end
end
function Base.getproperty(obj::SavedBareConcreteFunction, name::Symbol)
    if name === :concrete_function_name
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    elseif name === :argument_keywords
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{AbstractString}
    elseif name === :allowed_positional_arguments
        return (obj.__protobuf_jl_internal_values[name])::Int64
    elseif name === :function_spec
        return (obj.__protobuf_jl_internal_values[name])::FunctionSpec
    else
        getfield(obj, name)
    end
end

mutable struct SavedResource <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedResource(; kwargs...)
        obj = new(meta(SavedResource), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedResource
const __meta_SavedResource = Ref{ProtoMeta}()
function meta(::Type{SavedResource})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedResource)
            __meta_SavedResource[] = target = ProtoMeta(SavedResource)
            allflds = Pair{Symbol,Union{Type,String}}[:device => AbstractString]
            meta(target, SavedResource, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedResource[]
    end
end
function Base.getproperty(obj::SavedResource, name::Symbol)
    if name === :device
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    else
        getfield(obj, name)
    end
end

mutable struct SaveableObject <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SaveableObject(; kwargs...)
        obj = new(meta(SaveableObject), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SaveableObject
const __meta_SaveableObject = Ref{ProtoMeta}()
function meta(::Type{SaveableObject})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SaveableObject)
            __meta_SaveableObject[] = target = ProtoMeta(SaveableObject)
            fnum = Int[2,3]
            allflds = Pair{Symbol,Union{Type,String}}[:save_function => Int32, :restore_function => Int32]
            meta(target, SaveableObject, allflds, ProtoBuf.DEF_REQ, fnum, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SaveableObject[]
    end
end
function Base.getproperty(obj::SaveableObject, name::Symbol)
    if name === :save_function
        return (obj.__protobuf_jl_internal_values[name])::Int32
    elseif name === :restore_function
        return (obj.__protobuf_jl_internal_values[name])::Int32
    else
        getfield(obj, name)
    end
end

mutable struct SavedObject_SaveableObjectsEntry <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedObject_SaveableObjectsEntry(; kwargs...)
        obj = new(meta(SavedObject_SaveableObjectsEntry), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedObject_SaveableObjectsEntry (mapentry)
const __meta_SavedObject_SaveableObjectsEntry = Ref{ProtoMeta}()
function meta(::Type{SavedObject_SaveableObjectsEntry})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedObject_SaveableObjectsEntry)
            __meta_SavedObject_SaveableObjectsEntry[] = target = ProtoMeta(SavedObject_SaveableObjectsEntry)
            allflds = Pair{Symbol,Union{Type,String}}[:key => AbstractString, :value => SaveableObject]
            meta(target, SavedObject_SaveableObjectsEntry, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedObject_SaveableObjectsEntry[]
    end
end
function Base.getproperty(obj::SavedObject_SaveableObjectsEntry, name::Symbol)
    if name === :key
        return (obj.__protobuf_jl_internal_values[name])::AbstractString
    elseif name === :value
        return (obj.__protobuf_jl_internal_values[name])::SaveableObject
    else
        getfield(obj, name)
    end
end

mutable struct SavedObject <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedObject(; kwargs...)
        obj = new(meta(SavedObject), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedObject
const __meta_SavedObject = Ref{ProtoMeta}()
function meta(::Type{SavedObject})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedObject)
            __meta_SavedObject[] = target = ProtoMeta(SavedObject)
            fnum = Int[1,3,4,5,6,7,8,9,10,11]
            allflds = Pair{Symbol,Union{Type,String}}[:children => Base.Vector{TrackableObjectGraph_TrackableObject_ObjectReference}, :slot_variables => Base.Vector{TrackableObjectGraph_TrackableObject_SlotVariableReference}, :user_object => SavedUserObject, :asset => SavedAsset, :_function => SavedFunction, :variable => SavedVariable, :bare_concrete_function => SavedBareConcreteFunction, :constant => SavedConstant, :resource => SavedResource, :saveable_objects => Base.Dict{AbstractString,SaveableObject}]
            oneofs = Int[0,0,1,1,1,1,1,1,1,0]
            oneof_names = Symbol[Symbol("kind")]
            meta(target, SavedObject, allflds, ProtoBuf.DEF_REQ, fnum, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, oneofs, oneof_names)
        end
        __meta_SavedObject[]
    end
end
function Base.getproperty(obj::SavedObject, name::Symbol)
    if name === :children
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{TrackableObjectGraph_TrackableObject_ObjectReference}
    elseif name === :slot_variables
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{TrackableObjectGraph_TrackableObject_SlotVariableReference}
    elseif name === :user_object
        return (obj.__protobuf_jl_internal_values[name])::SavedUserObject
    elseif name === :asset
        return (obj.__protobuf_jl_internal_values[name])::SavedAsset
    elseif name === :_function
        return (obj.__protobuf_jl_internal_values[name])::SavedFunction
    elseif name === :variable
        return (obj.__protobuf_jl_internal_values[name])::SavedVariable
    elseif name === :bare_concrete_function
        return (obj.__protobuf_jl_internal_values[name])::SavedBareConcreteFunction
    elseif name === :constant
        return (obj.__protobuf_jl_internal_values[name])::SavedConstant
    elseif name === :resource
        return (obj.__protobuf_jl_internal_values[name])::SavedResource
    elseif name === :saveable_objects
        return (obj.__protobuf_jl_internal_values[name])::Base.Dict{AbstractString,SaveableObject}
    else
        getfield(obj, name)
    end
end

mutable struct SavedObjectGraph <: ProtoType
    __protobuf_jl_internal_meta::ProtoMeta
    __protobuf_jl_internal_values::Dict{Symbol,Any}
    __protobuf_jl_internal_defaultset::Set{Symbol}

    function SavedObjectGraph(; kwargs...)
        obj = new(meta(SavedObjectGraph), Dict{Symbol,Any}(), Set{Symbol}())
        values = obj.__protobuf_jl_internal_values
        symdict = obj.__protobuf_jl_internal_meta.symdict
        for nv in kwargs
            fldname, fldval = nv
            fldtype = symdict[fldname].jtyp
            (fldname in keys(symdict)) || error(string(typeof(obj), " has no field with name ", fldname))
            values[fldname] = isa(fldval, fldtype) ? fldval : convert(fldtype, fldval)
        end
        obj
    end
end # mutable struct SavedObjectGraph
const __meta_SavedObjectGraph = Ref{ProtoMeta}()
function meta(::Type{SavedObjectGraph})
    ProtoBuf.metalock() do
        if !isassigned(__meta_SavedObjectGraph)
            __meta_SavedObjectGraph[] = target = ProtoMeta(SavedObjectGraph)
            allflds = Pair{Symbol,Union{Type,String}}[:nodes => Base.Vector{SavedObject}, :concrete_functions => Base.Dict{AbstractString,SavedConcreteFunction}]
            meta(target, SavedObjectGraph, allflds, ProtoBuf.DEF_REQ, ProtoBuf.DEF_FNUM, ProtoBuf.DEF_VAL, ProtoBuf.DEF_PACK, ProtoBuf.DEF_WTYPES, ProtoBuf.DEF_ONEOFS, ProtoBuf.DEF_ONEOF_NAMES)
        end
        __meta_SavedObjectGraph[]
    end
end
function Base.getproperty(obj::SavedObjectGraph, name::Symbol)
    if name === :nodes
        return (obj.__protobuf_jl_internal_values[name])::Base.Vector{SavedObject}
    elseif name === :concrete_functions
        return (obj.__protobuf_jl_internal_values[name])::Base.Dict{AbstractString,SavedConcreteFunction}
    else
        getfield(obj, name)
    end
end

export SavedObjectGraph_ConcreteFunctionsEntry, SavedObjectGraph, SavedObject_SaveableObjectsEntry, SavedObject, SavedUserObject, SavedAsset, SavedFunction, SavedConcreteFunction, SavedBareConcreteFunction, SavedConstant, SavedVariable, FunctionSpec_ExperimentalCompile, FunctionSpec, SavedResource, SaveableObject
# mapentries: "SavedObject_SaveableObjectsEntry" => ("AbstractString", "SaveableObject"), "SavedObjectGraph_ConcreteFunctionsEntry" => ("AbstractString", "SavedConcreteFunction")


text:
"""
```
uconvert{T,U}(a::Units, x::Quantity{T,U})
```

Convert a [`Unitful.Quantity`](@ref) to different units. The conversion will
fail if the target units `a` have a different dimension than the dimension of
the quantity `x`. You can use this method to switch between equivalent
representations of the same unit, like `N m` and `J`.

Example:

```jldoctest
julia> uconvert(u"hr",3602u"s")
1801//1800 hr
julia> uconvert(u"J",1.0u"N*m")
1.0 J
```
"""
function uconvert{T,D,U}(a::Units, x::Quantity{T,D,U})
    if typeof(a) == U
        Quantity(x.val, a)    # preserves numeric type if convfact is 1
    else
        Quantity(x.val * convfact(a, U()), a)
    end
end

"""
```
uconvert{T,U}(a::Units, x::Quantity{T,Dimensions{(Dimension{:Temperature}(1),)},U})
```

In this method, we are special-casing temperature conversion to respect scale
offsets, if they do not appear in combination with other dimensions.
"""
@generated function uconvert{T,D,U}(a::Units,
        x::Quantity{T,D,Units{U,Dimensions{(Dimension{:Temperature}(1),)}}})
    if a == U
        :(Quantity(x.val, a))
    else
        xunits = x.parameters[3]
        aData = a()
        xData = xunits()
        conv = convfact(aData, xData)

        xtup = xunits.parameters[1]
        atup = a.parameters[1]
        t0 = offsettemp(xtup[1])
        t1 = offsettemp(atup[1])
        quote
            v = ((x.val + $t0) * $conv) - $t1
            Quantity(v, a)
        end
    end
end

function uconvert(a::Units, x::Number)
    if dimension(a) == NoDims
        Quantity(x * convfact(a, NoUnits), a)
    else
        throw(DimensionError())
    end
end

"""
```
convfact(s::Units, t::Units)
```

Find the conversion factor from unit `t` to unit `s`, e.g. `convfact(m,cm) = 0.01`.
"""
@generated function convfact(s::Units, t::Units)
    sunits = s.parameters[1]
    tunits = t.parameters[1]

    # Check if conversion is possible in principle
    sdim = dimension(s())
    tdim = dimension(t())
    sdim != tdim && throw(DimensionError())

    # first convert to base SI units.
    # fact1 is what would need to be multiplied to get to base SI units
    # fact2 is what would be multiplied to get from the result to base SI units

    inex1, ex1 = basefactor(t())
    inex2, ex2 = basefactor(s())

    a = inex1 / inex2
    ex = ex1 // ex2     # do overflow checking?

    tens1 = mapreduce(tensfactor, +, 0, tunits)
    tens2 = mapreduce(tensfactor, +, 0, sunits)

    pow = tens1-tens2

    fpow = 10.0^pow
    if fpow > typemax(Int) || 1/(fpow) > typemax(Int)
        a *= fpow
    else
        comp = (pow > 0 ? fpow * num(ex) : 1/fpow * den(ex))
        if comp > typemax(Int)
            a *= fpow
        else
            ex *= (10//1)^pow
        end
    end

    a ≈ 1.0 ? (inex = 1) : (inex = a)
    y = inex * ex
    :($y)
end

"""
```
convfact{S}(s::Units{S}, t::Units{S})
```

Returns 1. (Avoids effort when unnecessary.)
"""
convfact{S}(s::Units{S}, t::Units{S}) = 1

"""
```
convert{T,D,U}(::Type{Quantity{T,D,U}}, x::Number)
```

Direct type conversion using `convert` is permissible provided conversion
is between two quantities of the same dimension.
"""
function convert{T,D,U}(::Type{Quantity{T,D,U}}, x::Number)
    if dimension(x) == D()
        Quantity(T(uconvert(U(),x).val), U())
    else
        throw(DimensionError())
    end
end

"""
```
convert{D}(::Type{DimensionedQuantity{D}}, x::Quantity)
```

Convert `x` to a [`Unitful.DimensionedQuantity`](@ref) type.
If `x` is already of the specified dimensions, this is a no-op; if it is not, an
`ErrorException` is thrown.
"""
function convert{D}(::Type{DimensionedQuantity{D}}, x::Quantity)
    if dimension(x) == D()
        return x
    else
        throw(DimensionError())
    end
end

"""
```
convert{T,U}(::Type{DimensionlessQuantity{T,U}}, x::Number)
```

Convert `x` to a [`Unitful.DimensionlessQuantity`](@ref) type.
"""
convert{T,U}(::Type{DimensionlessQuantity{T,U}}, x::Number) =
    uconvert(U(), convert(T,x))

"""
```
convert{T,U}(::Type{DimensionlessQuantity{T,U}}, x::Quantity)
```

Convert `x` to a [`Unitful.DimensionlessQuantity`](@ref) type.
If `x` is already dimensionless, this is a no-op; if it is not, an
`ErrorException` is thrown.
"""
function convert{T,U}(::Type{DimensionlessQuantity{T,U}}, x::Quantity)
    if dimension(x) == NoDims
        Quantity(T(x.val), U())
    else
        throw(DimensionError())
    end
end

convert(::Type{Number}, y::Quantity) = y
convert{T<:Real}(::Type{T}, y::Quantity) =
    T(uconvert(NoUnits, y))
convert{T<:Complex}(::Type{T}, y::Quantity) =
    T(uconvert(NoUnits, y))

ext: jl


text:
@testset "Normalized innovation squared" begin
    num_samples = 20000

    unbiased_innos_scalar = randn(num_samples) .* sqrt(2)
    unbiased_variance_scalar = ones(num_samples) .* 2
    nis_over_time_us = map((x, σ²) -> calc_nis(x, σ²), unbiased_innos_scalar, unbiased_variance_scalar)
    @test nis_test(nis_over_time_us, num_samples) == true

    biased_innos_scalar = randn(num_samples) .* sqrt(2) .+ 1
    biased_variance_scalar = ones(num_samples) .* 2
    nis_over_time_bs = map((x, σ²) -> calc_nis(x, σ²), biased_innos_scalar, biased_variance_scalar)
    @test nis_test(nis_over_time_bs, num_samples) == false

    unbiased_innos = [randn(2) .* sqrt(2) for i = 1:num_samples]
    unbiased_variance = fill(Matrix{Float64}(I, 2, 2) .* 2, num_samples)
    nis_over_time_uv = map((x, σ²) -> calc_nis(x, σ²), unbiased_innos, unbiased_variance)
    dof_uv = num_samples * 2
    @test nis_test(nis_over_time_uv, dof_uv) == true

    biased_innos = [randn(2) .* sqrt(2) .+ 1 for i = 1:num_samples]
    biased_variance = fill(Matrix{Float64}(I, 2, 2) .* 2, num_samples)
    nis_over_time_bv = map((x, σ²) -> calc_nis(x, σ²), biased_innos, biased_variance)
    dof_bv = num_samples * 2
    @test nis_test(nis_over_time_bv, dof_bv) == false

    A = randn(4,4)
    P = A'A
    P_chol = cholesky(P)
    x = randn(4)
    @test calc_nis(x, P) ≈ calc_nis(x, P_chol)
end

@testset "σ bound test" begin
    num_samples = 20000

    unbiased_innos_scalar = randn(num_samples) .* sqrt(2)
    unbiased_variance_scalar = ones(num_samples) .* 2
    @test sigma_bound_test(unbiased_innos_scalar, unbiased_variance_scalar) == true
    @test two_sigma_bound_test(unbiased_innos_scalar, unbiased_variance_scalar) == true

    biased_innos_scalar = randn(num_samples) .* sqrt(2) .+ 1
    biased_variance_scalar = ones(num_samples) .* 2
    @test sigma_bound_test(biased_innos_scalar, biased_variance_scalar) == false
    @test two_sigma_bound_test(biased_innos_scalar, biased_variance_scalar) == false

    unbiased_innos = [randn(2) .* sqrt(2) for i = 1:num_samples]
    unbiased_variance = fill(Matrix{Float64}(I, 2, 2) .* 2, num_samples)
    @test sigma_bound_test(unbiased_innos, unbiased_variance) == [true; true]
    @test two_sigma_bound_test(unbiased_innos, unbiased_variance) == [true; true]

    biased_innos = [randn(2) .* sqrt(2) .+ 1 for i = 1:num_samples]
    biased_variance = fill(Matrix{Float64}(I, 2, 2) .* 2, num_samples)
    @test sigma_bound_test(biased_innos, biased_variance) == [false; false]
    @test two_sigma_bound_test(biased_innos, biased_variance) == [false; false]
end


text:
__precompile__()

module DataCubes

import Formatting: sprintf1

# including files.
include("common.jl")
include("datatypes/ldict.jl")
include("datatypes/abstract_types.jl")
include("datatypes/dict_array.jl")
include("datatypes/labeled_array.jl")
include("datatypes/enumeration_array.jl")
include("na/na.jl")
include("na/naarray_operators.jl")
include("util/select.jl")
include("util/join.jl")
include("util/sort.jl")
include("util/ungroup.jl")
include("util/array_util.jl")
include("util/mapslices_base.jl")
include("util/unique.jl")
include("util/union.jl")
include("util/intersect.jl")
include("util/setdiff.jl")
include("util/array_helper_functions.jl")
include("interface/dataframe_interface.jl")

export LDict, DictArray, LabeledArray, EnumerationArray
export @select,
       @update,
       @darr,
       @larr,
       @nalift,
       @rap,
       @enumeration,
       enumeration,
       nalift,
       peel,
       pick,
       pickaxis,
       delete,
       selct,
       update,
       larr,
       darr,
       igna,
       ignabool,
       isna,
       ungroup,
       flds2axis,
       axis2flds,
       replace_axes,
       collapse_axes,
       dropna,
       mapna,
       mapvalues,
       leftjoin,
       innerjoin,
       reorder,
       rename,
       tensorprod,
       extract,
       discard,
       providenames,
       withdrawnames,
       msum, # moving sum
       mprod, # moving product
       mmean, # moving average
       mmedian, # moving median
       mminimum, # moving minimum
       mmaximum, # moving maximum
       mmiddle, # moving middle
       mquantile, # moving quantile
       nafill, # fill forward/backword na's.
       describe,
       shift,
       namerge

export dcube

module Tools
  using DataCubes
  items = [:AbstractArrayWrapper, :FloatNAArray, :simplify_array, :wrap_array, :type_array,
           :getindexpair,
           :getindexvalue,
           :gtake, :gdrop,
           :create_dict, :setna!,
           :dropnaiter, :enum_dropnaiter, :zip_dropnaiter,
           # some display setting functions.
           :set_showalongrow!, :set_showsize!, :set_showheight!, :set_showwidth!, :set_default_showsize!,
           :set_dispalongrow!, :set_dispsize!, :set_dispheight!, :set_dispwidth!, :set_default_dispsize!,
           :set_format_string!]
  for item in items
    @eval begin
      $item = DataCubes.$item
      export $item
    end
  end
end

dcube = DataCubes.Tools

end


text:
function bitmask_type(spec::SpecBitmask)
    @match spec.width begin
        8 => :UInt8
        16 => :UInt16
        32 => :UInt32
        64 => :UInt64
        _ => error("Failed to generate bitmask type with width $(spec.width) from $spec")
    end
end

bitmask_value(spec::SpecBit) = 2^(spec.position)
bitmask_value(spec::SpecBitCombination) = spec.value

function BitmaskDefinition(spec::SpecBitmask)
    name = bitmask_flag_type(spec)
    p = Dict(
        :category => :enum,
        :macro => Symbol("@bitmask_flag"),
        :values => map(x -> :($(remove_vk_prefix(x.name)) = $(bitmask_value(x))), [collect(spec.bits); collect(spec.combinations)]),
        :decl => :($name::$(bitmask_type(spec))),
    )
    BitmaskDefinition(spec, p)
end

max_stars_repo_name: JuliaGPU/VulkanAbstraction

max_issues_repo_name: JuliaGPU/VulkanAbstraction

max_forks_repo_name: JuliaGPU/VulkanAbstraction


text:
include("../src/PyEnum_test.jl")
using .PyEnum

@pyenum Colors::String begin
	RED="RED"
	GREEN="GREEN"
	BLUE="BLUE"
end

@pyenum Cor begin
	NOT_RED=1
	NOT_GREEN=2
	NOT_BLUE=3
end

# For comparison
@enum WorkingColors begin
	TRUE_RED
	TRUE_GREEN
	TRUE_BLUE
end

function show()
	color_map = Dict(Colors.RED => "1", Colors.GREEN => "2", Colors.BLUE => "3")
	a = Colors.GREEN
	if a == Colors.GREEN
		println(join(["green"], " "));
	else
		println(join(["Not green"], " "));
	end
	println(join([length(color_map)], " "));
end

function main()
	show();
end

main()

max_stars_repo_name: MiguelMarcelino/PyEnum

max_issues_repo_name: MiguelMarcelino/PyEnum

max_forks_repo_name: MiguelMarcelino/PyEnum


text:
function fractional_covering_number(graph::AbstractGraph)

    model = Model(GLPK.Optimizer)
    V = vertices(graph)
    @variable(model, x[V]>=0)
    for e = edges(graph)
        @constraint(model, x[src(e)]+x[dst(e)] >=1)
    end
    @objective(model, Min, sum(x))

    optimize!(model)

    return (value.(x),objective_value(model))
end

function fractional_matching_number(graph::AbstractGraph)

    model = Model(GLPK.Optimizer)
    E = edges(graph)
    @variable(model, x[E]>=0)
    for v = vertices(graph)
        Ev = edges_of(graph, v)
        @constraint(model, sum(x[i] for i in Ev) <= 1)
    end

    @objective(model, Max, sum(x))

    optimize!(model)

    return (value.(x),objective_value(model))
end

function fractional_coloring_number(graph::AbstractGraph)

    model = Model(GLPK.Optimizer)
    independent_sets = maximal_cliques(unweighted_complement(graph))

    @variable(model, x[independent_sets] >= 0)

    for v = vertices(graph)
        independent_v = [i for i in independent_sets if v in i]
        @constraint(model, sum(x[i] for i in independent_v) >= 1)
    end

    @objective(model, Min, sum(x))

    optimize!(model)

    return (value.(x),objective_value(model))
end


text:
println("Loading packages and data, this may take some time...")
using MAT
cd(dirname(Base.source_path()))
include("../src/utils.jl")
include("../src/2d/cpab2dIntegration.jl")
include("../src/2d/imageWarp.jl")
include("../src/2d/2dInference.jl")

file = matopen("tri_R2toR2_MINS_0_0_MAXS_512_512_nc_4_4_Xbdr_0_0_ext_0.mat")
As = read(file, "As")
@broadcast :As As
pts_src = read(file, "pts_src")
@broadcast :pts_src pts_src
pts_fwd = read(file, "pts_fwd")
@broadcast :pts_fwd pts_fwd
tw_args = read(file, "tw_args")
@broadcast :tw_args tw_args
@everywhere nCols = tw_args["nCols"]
@everywhere nRows = tw_args["nRows"]
B = read(file, "B")
@broadcast :B B
θ = vec(read(file, "theta"))
@broadcast :θ θ
priorCov = read(file, "covariance_of_the_prior")
@broadcast :priorCov priorCov
close(file)

@everywhere nC1 = 4
@everywhere nC2 = 4
@everywhere incX = nCols/nC1
@everywhere incY = nRows/nC2
@everywhere nPts = size(pts_src,1)
@everywhere t=0.001
@everywhere nSteps = 100
@everywhere Nsteps = 10
@everywhere Δt = t/Nsteps
@everywhere ΔtAs = Δt*As

@everywhere function decreaseNumPts(A)
  reshape(reshape(A,512,512,2)[16:32:end,16:32:end,:],256,2)
end
@everywhere pts_src1 = decreaseNumPts(pts_src)
@everywhere pts_fwd1 = decreaseNumPts(pts_fwd)
@everywhere solutionSingleThread1 = zeros(size(pts_src1,1), 2)
@everywhere expT = Array(Float64, size(As,1), 3, 3)
@everywhere Avees = Array(Float64, size(θ,1))

@everywhere function leastSquaresTransformation(θ)
  computeAndEvaluateTransformationSingleThread(B,θ,As,pts_src1,pts_fwd1,solutionSingleThread1,t,nCols,nRows,incX,incY,Nsteps,Δt,nSteps,ΔtAs,expT,Avees)
end

iterations = 200
using PyPlot
println("Running Particle Filter, this may take some time...")
@time optimizedθ, llTrace, lpTrace, lpllTrace = particleFilterParallel(leastSquaresTransformation, rand(size(θ,1)), 1000, iterations, 10.0, priorCov, 0.005*priorCov, false, true)
println("Done!")
optimizedθArray = convert(Array, optimizedθ)

PyPlot.figure("Particle Filter",figsize=(18,6))
PyPlot.subplot(2,6,1)
PyPlot.title("Original Points")
xOriginal, yOriginal = separateAxis2D(pts_src1)
PyPlot.axis([0.0,512.0,0.0,512.0])
PyPlot.scatter(xOriginal, yOriginal, label="Original Points", color="blue")

PyPlot.subplot(2,6,2)
PyPlot.title("Destination Points")
PyPlot.axis([0.0,512.0,0.0,512.0])
xDst, yDst = separateAxis2D(pts_fwd1)
PyPlot.scatter(xDst, yDst, label="Destination Points", color="blue")

PyPlot.subplot(2,6,3)
PyPlot.title("Transformed Points")
PyPlot.axis([0.0,512.0,0.0,512.0])
leastSquaresTransformation(optimizedθArray)
xInferred, yInferred = separateAxis2D(solutionSingleThread1)
PyPlot.scatter(xDst, yDst, label="Destination Points", color="blue")
PyPlot.scatter(xInferred, yInferred, label="Transformed Points", color="red")

PyPlot.subplot(2,6,7)
PyPlot.title("Original Image")
img = load("lena.jpg")
imr = reinterpret(UInt8, separate(img))
PyPlot.imshow(imr.data)

PyPlot.subplot(2,6,8)
PyPlot.title("Destination Image")
newimg1 = reinterpret(UInt8, separate(imwarp(pts_fwd, img, nCols, nRows)))
PyPlot.imshow(newimg1.data)

PyPlot.subplot(2,6,9)
PyPlot.title("Transformed Image")
transformedAs = similar(As)
solutionSingleThread = similar(pts_src)
computeAs(B,optimizedθArray,transformedAs)
solver2d(pts_src,solutionSingleThread,t,transformedAs,nCols,nRows,incX,incY,Nsteps,Δt,nSteps,ΔtAs)
newimg2 = reinterpret(UInt8, separate(imwarp(solutionSingleThread, img, nCols, nRows)))
PyPlot.imshow(newimg2.data)

PyPlot.subplot(1,2,2)
PyPlot.title("Log Probability vs Iterations")
PyPlot.plot(1:iterations, llTrace,label="log likelihood", color="blue")
PyPlot.plot(1:iterations, lpTrace,label="log prior", color="red")
PyPlot.plot(1:iterations, lpllTrace,label="log likelihood + log prior", color="green")
PyPlot.xlabel("Iterations")
PyPlot.ylabel("Log Probability")
PyPlot.legend(loc="lower right",fancybox="true")


text:
# 10,1,10,"Samples per record"
# 10,2,10,"Seconds per record"
# 10,3,30,"Records per packet"
# 10,4,200,"Trial size"
# 11,1,21,"Eggs reporting"
# 11,2,1627776000,"Start time",2021-08-01 00:00:00
# 11,3,1627776600,"End time",2021-08-01 00:10:00
# 11,4,601,"Seconds of data"

function getheader(str, spl)
  headerstr = str[1:spl[1] - 5]

  header = Header()
  i = 1

  for line in eachline(IOBuffer(headerstr))
    val = readdlm(IOBuffer(line), ',')[:3]

    if i == 1
      header.samples_per_record =  val
    elseif i == 2
      header.seconds_per_record = val
    elseif i == 3
      header.records_per_packet = val
    elseif i == 4
      header.trial_size = val
    elseif i == 5
      header.eggs_reporting = val
    elseif i == 6
      header.start_time = Dates.unix2datetime(val)
    elseif i == 7
      header.end_time =  Dates.unix2datetime(val)
    elseif i == 8
      header.seconds_of_data = val
    end

    i = i + 1
  end

  return header
end

# 12,"gmtime",,1,37,112,226,228,231,1070,1237,2028,2083,2178,2220,2232,2250,3002,3060,3101,3104,3106,4002,4234
# 13,1625097600,,105,106,93,98,106,95,94,,106,90,98,92,90,98,,104,106,94,101,110,110
# 13,1625097601,,94,111,103,97,97,104,99,,104,103,102,103,103,94,,95,109,106,104,113,91
# 13,1625097602,,101,114,102,108,101,97,97,,93,89,95,97,102,99,,102,117,100,102,103,112
# 13,1625097603,,94,112,94,95,106,103,107,,106,94,108,106,102,105,,114,101,106,101,84,98

function getdataframe(str, spl)
  datastr = str[spl[1] - 1:length(str)]
  df = CSV.File(IOBuffer(datastr), silencewarnings=true) |> DataFrame
  coalesce.(df, 0)

  for col in names(df)
      df[col] = Missings.coalesce.(df[col], 0)
  end

  return df
end

function splitheader(str)
  spl = findfirst("gmtime", str)
  return spl
end


text:
# Thanks to Mason Protter for this benchmark

module SUFib
using SymbolicUtils
using SymbolicUtils.Rewriters

@syms fib(x::Int)::Int

const rset = [
    @rule fib(0) => 0
    @rule fib(1) => 1
    @rule fib(~n) => fib(~n - 1) + fib(~n - 2)
] |> Chain |> Postwalk |> Fixpoint

compute_fib(n) = rset(fib(n))

end

module MTFib

using Metatheory
using Metatheory.EGraphs

@metatheory_init ()

const fibo = @theory begin
    x::Int + y::Int |> x+y
    fib(n::Int) |> (n < 2 ? n : :(fib($(n-1)) + fib($(n-2))))
end;

function compute_fib(n)
    params = SaturationParams(timeout = 7000,
        scheduler=Schedulers.SimpleScheduler)
    g = EGraph(:(fib($n)))
    saturate!(g, fibo, params)
    extract!(g, astsize)
end

end

using BenchmarkTools

ns = 1:2:22

SU_ts = map(ns) do n
    println(n)
    @assert SUFib.compute_fib(n) isa Number
    b = @benchmarkable SUFib.compute_fib($n) seconds=0.2
    mean(run(b)).time / 1e9
end

MT_ts = map(ns) do n
    println(n)
    @assert MTFib.compute_fib(n) isa Number
    b = @benchmarkable MTFib.compute_fib($n) seconds=0.2
    mean(run(b)).time / 1e9
end

using Plots
pyplot()

font = "DejaVu Math TeX Gyre"
# default(titlefont=font, legendfont=font, fontfamily=font)
default(fontfamily=font, markerstrokewidth=0)

plot(ns, SU_ts, label="SymbolicUtils.jl", title="fib(n)", ylabel="Time (s)", xlabel="n",
    color = :black, legend = :topleft, line=:dot,  # m=(:cross, :blue),
    size=(320,220), legendfontsize = 9, titlefontsize=12)
plot!(ns, MT_ts, label="Metatheory.jl", color = :black) # m = (:circle, :orange) )
savefig("benchmarks/figures/fib.pdf")


text:
module I18n

export locale

LOCALE = nothing
CALLBACKS = Function[]

function locale()
    if LOCALE === nothing
        # XXX:TBD return default locale
        return ""
    end
    LOCALE
end

function locale(s::ByteString)
    global LOCALE = s
    # XXX:TBD call setlocale
    for cb in CALLBACKS
        cb()
    end
end

end # module

max_stars_repo_name: jakebolewski/julia

max_issues_repo_name: jakebolewski/julia

max_forks_repo_name: jakebolewski/julia


text:
module CommunalHelperConnectedDreamBlock
using ..Ahorn, Maple

@mapdef Entity "CommunalHelper/ConnectedDreamBlock" ConnectedDreamBlock( x::Integer, y::Integer,
	width::Integer=Maple.defaultBlockWidth, height::Integer=Maple.defaultBlockHeight,
	featherMode::Bool = false, oneUse::Bool = false, doubleRefill::Bool=false)

const placements = Ahorn.PlacementDict(
    "Connected Dream Block (Normal) (Communal Helper)" => Ahorn.EntityPlacement(
        ConnectedDreamBlock,
		"rectangle"
    ),
	"Connected Dream Block (Feather Mode) (Communal Helper)" => Ahorn.EntityPlacement(
        ConnectedDreamBlock,
		"rectangle",
        Dict{String, Any}(
            "featherMode" => true
        )
    ),
	"Connected Dream Block (Normal, One Use) (Communal Helper)" => Ahorn.EntityPlacement(
        ConnectedDreamBlock,
		"rectangle",
        Dict{String, Any}(
            "oneUse" => true
        )
    ),
	"Connected Dream Block (Feather Mode, One Use) (Communal Helper)" => Ahorn.EntityPlacement(
        ConnectedDreamBlock,
		"rectangle",
        Dict{String, Any}(
            "featherMode" => true,
			"oneUse" => true
        )
    )
)

Ahorn.minimumSize(entity::ConnectedDreamBlock) = 8, 8
Ahorn.resizable(entity::ConnectedDreamBlock) = true, true

function Ahorn.selection(entity::ConnectedDreamBlock)
    x, y = Ahorn.position(entity)

    width = Int(get(entity.data, "width", 8))
    height = Int(get(entity.data, "height", 8))

    return Ahorn.Rectangle(x, y, width, height)
end

function Ahorn.render(ctx::Ahorn.Cairo.CairoContext, entity::ConnectedDreamBlock)
    x = Int(get(entity.data, "x", 0))
    y = Int(get(entity.data, "y", 0))

    width = Int(get(entity.data, "width", 32))
    height = Int(get(entity.data, "height", 32))

	 Ahorn.Cairo.save(ctx)

    Ahorn.set_antialias(ctx, 1)
    Ahorn.set_line_width(ctx, 1)

    fillColor = get(entity.data, "featherMode", false) ? (0.31, 0.69, 1.0, 0.4) : (0.0, 0.0, 0.0, 0.4)
	 lineColor = get(entity.data, "oneUse", false) ? (1.0, 0.0, 0.0, 1.0) : (1.0, 1.0, 1.0, 1.0)
    Ahorn.drawRectangle(ctx, 0, 0, width, height, fillColor, lineColor)

    Ahorn.restore(ctx)
end

end

max_stars_repo_name: FlynnSC/CommunalHelper

max_issues_repo_name: FlynnSC/CommunalHelper

max_forks_repo_name: FlynnSC/CommunalHelper


text:
#	MIT License
#
#  Copyright © 2020 Michael J Simms. All rights reserved.
#
#	Permission is hereby granted, free of charge, to any person obtaining a copy
#	of this software and associated documentation files (the "Software"), to deal
#	in the Software without restriction, including without limitation the rights
#	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#	copies of the Software, and to permit persons to whom the Software is
#	furnished to do so, subject to the following conditions:
#
#	The above copyright notice and this permission notice shall be included in all
#	copies or substantial portions of the Software.
#
#	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#	SOFTWARE.

module IsolationForest

# Tree node, used internally.
mutable struct Node
    featureName::String
    splitValue::Float64
    left::Any
    right::Any
end

# This struct represents a sample. Each sample has a name and list of features.
mutable struct Sample
    name::String
    features::Dict{String,Float64}
end

# Isolation Forest.
mutable struct Forest
    numTrees::UInt64
    subSamplingSize::UInt64
    featureValues::Dict{String,Array} # Dictionary that maps feature names to a sorted array of feature values
    trees::Array
end

# Adds the features to the specified sample.
function add_features_to_sample(sample::Sample, features::Dict{String,Float64})
    merge!(sample.features, features)
end

# Adds each of the sample's features to the list of known features with the corresponding set of unique values.
function add_sample_to_forest(forest::Forest, sample::Sample)

    # We don't store the sample directly, just the features.
    for feature_name in keys(sample.features)
        feature_value = sample.features[feature_name] # Value to insert

        try
            existing_feature_values = forest.featureValues[feature_name]
            push!(existing_feature_values, feature_value)
            sort(existing_feature_values)
            forest.featureValues[feature_name] = existing_feature_values
        catch error
            if isa(error, KeyError)
                existing_feature_values = []
                push!(existing_feature_values, feature_value)
                forest.featureValues[feature_name] = existing_feature_values
            end
        end
    end
end

# Creates and returns a single tree. As this is a recursive function, depth indicates the current depth of the recursion.
function create_tree(forest::Forest, feature_values::Dict{String,Array}, depth::UInt64)

    # Sanity check
    feature_values_len = length(feature_values)
    if feature_values_len <= 1
        return Nothing
    end

    # If we've exceeded the maximum desired depth, then stop.
    if (forest.subSamplingSize > 0) && (depth >= forest.subSamplingSize)
        return Nothing
    end

    # Randomly select a feature.
    selected_feature_index = rand(1:feature_values_len)
    all_feature_names = collect(keys(feature_values))
    selected_feature_name = all_feature_names[selected_feature_index]

    # Randomly select a split value.
    feature_value_set = feature_values[selected_feature_name]
    feature_value_set_len = length(feature_value_set)
    if feature_value_set_len <= 1
        return Nothing
    end
    split_value_index = rand(1:feature_value_set_len)
    split_value = feature_value_set[split_value_index]

    # Create a tree node to hold the split value.
    tree = Node(selected_feature_name, split_value, Nothing, Nothing)

    # Create two versions of the feature value set that we just used,
    # one for the left side of the tree and one for the right.
    temp_feature_values = feature_values

    # Create the left subtree.
    left_features = feature_value_set[1:split_value_index]
    temp_feature_values[selected_feature_name] = left_features
    tree.left = IsolationForest.create_tree(forest, temp_feature_values, depth + 1)

    # Create the right subtree.
    if split_value_index + 1 < feature_value_set_len
        right_features = feature_value_set[split_value_index + 1:feature_value_set_len]
        temp_feature_values[selected_feature_name] = right_features
        tree.right = IsolationForest.create_tree(forest, temp_feature_values, depth + 1)
    end

    return tree
end

# Creates a forest containing the number of trees specified to the constructor.
function create_forest(forest::Forest)
    for i = 1:forest.numTrees
        temp_feature_values = deepcopy(forest.featureValues)
        tree = create_tree(forest, temp_feature_values, UInt64(0))
        if tree != Nothing
            push!(forest.trees, tree)
        end
    end
end

# Scores the sample against the specified tree.
function score_sample_against_tree(tree::Node, sample::Sample)
    depth = 0.0
    current_node = tree

    while current_node != Nothing
        found_feature = false

        # Find the next feature in the sample.
        for current_feature in sample.features
            current_feature_name = current_feature.first

            # If the current node has the feature in question.
            if current_feature_name == current_node.featureName
                current_feature_value = current_feature.second
                if current_feature_value < current_node.splitValue
                    current_node = current_node.left
                else
                    current_node = current_node.right
                end

                depth = depth + 1.0
                found_feature = true
                break
            end
        end

        # If the tree contained a feature not in the sample then take
        # both sides of the tree and average the scores together.
        if found_feature == false
            left_depth = depth + score_sample_against_tree(sample, current_node.left)
            right_depth = depth + score_sample_against_tree(sample, current_node.right)
            return (left_depth + right_depth) / 2.0
        end
    end

    return depth
end

# Scores the sample against the entire forest of trees. Result is the average path length.
function score_sample_against_forest(forest::Forest, sample::Sample)
    num_trees = 0
    avg_path_len = 0.0

    for tree in forest.trees
        path_len = score_sample_against_tree(tree, sample)
        if path_len > 0
            avg_path_len = avg_path_len + path_len
            num_trees = num_trees + 1
        end
    end

    if num_trees > 0
        avg_path_len = avg_path_len / num_trees
    end

    return avg_path_len
end

# Scores the sample against the entire forest of trees. Result is normalized so that values
# close to 1 indicate anomalies and values close to zero indicate normal values.
function H(i)
    return log(i) + 0.5772156649
end
function C(n)
    return 2 * H(n - 1) - (2 * (n - 1) / n)
end
function score_sample_against_forest_normalized(forest::Forest, sample::Sample)

    # Compute the average path length for all valid trees.
    num_trees = 0
    avg_path_len = 0.0

    for tree in forest.trees
        path_len = score_sample_against_tree(tree, sample)
        if path_len > 0
            avg_path_len = avg_path_len + path_len
            num_trees = num_trees + 1
        end
    end

    if num_trees > 0
        avg_path_len = avg_path_len / num_trees
    end

    # Normalize, per the original paper.
    score = 0.0
    if num_trees > 1.0
        exponent = -1.0 * (avg_path_len / C(num_trees))
        score = 2 ^ exponent
    end

    return score
end

# Destroys a single tree.
function destroy_tree(tree::Node)
end

# Destroys the entire forest of trees.
function destroy()
    for tree in self.trees
        self.destroy_tree(tree)
    end
end

# Returns the specified node as a dictionary object.
function dump_node(node::Node)
    data = Dict()
    if node != Nothing
        data["Feature Name"] = node.featureName
        data["Split Value"] = node.splitValue
        if node.left == Nothing
            data["Left"] = Dict()
        else
            data["Left"] = dump_node(node.left)
        end
        if node.right == Nothing
            data["Right"] = Dict()
        else
            data["Right"] = dump_node(node.right)
        end
    end
    return data
end

# Loads/creates a node from a JSON object.
function load_node(data::Dict)
    try
        node = Node(data["Feature Name"], data["Split Value"])
        node.left = load_node(data["Left"])
        node.right = load_node(data["Right"])
        return node
    catch error
    end

    return Nothing
end

# Returns the specified tree as a dictionary object.
function dump_tree(tree::Node)
    data = dump_node(tree)
    return data
end

# Loads/creates a tree from a dictionary object.
function load_tree(forest::Forest, data::Dict)
    tree = load_node(data)
    if tree != Nothing
        push!(forest.trees, tree)
    end
end

# Returns the forest as a JSON object.
function dump(forest::Forest)
    data = Dict()
    data["Sub Sampling Size"] = forest.subSamplingSize
    data["Feature Values"] = forest.featureValues
    tree_data = []
    for tree in forest.trees
        push!(tree_data, dump_tree(tree))
    end
    data["Trees"] = tree_data
    return data
end

# Loads the forest from a JSON object.
function load(data::Dict)
    forest = Forest(0, 0, Dict(), [])
    forest.subSamplingSize = data["Sub Sampling Size"]
    forest.featureValues = data["Feature Values"]
    for tree_data in data["Trees"]
        load_tree(forest, tree_data)
    end
    forest.numTrees = length(forest.trees)
    return forest
end

end

max_stars_repo_name: msimms/LibIsolationForest

max_issues_repo_name: msimms/LibIsolationForest

max_forks_repo_name: msimms/LibIsolationForest


text:
include("../aimajulia.jl");

using Test;

using Main.aimajulia;

#The following logic tests are from the aima-python doctests

x = Expression("x");

y = Expression("y");

z = Expression("z");

@test variables(expr("F(x, x) & G(x, y) & H(y, z) & R(A, z, z)")) == Set([x, y, z]);

@test variables(expr("F(x, A, y)")) == Set([x, y]);

@test variables(expr("F(G(x), z)")) == Set([x, z]);

@test show(expr("P & Q ==> Q")) == "((P & Q) ==> Q)";

@test show(expr("P ==> Q(1)")) == "(P ==> Q(1))";

@test show(expr("P & Q | ~R(x, F(x))")) == "((P & Q) | ~(R(x, F(x))))";

@test show(expr("P & Q ==> R & S")) == "(((P & Q) ==> R) & S)";

@test tt_entails(expr("P & Q"), expr("Q")) == true;

@test tt_entails(expr("P | Q"), expr("Q")) == false;

@test tt_entails(expr("A & (B | C) & E & F & ~(P | Q)"), expr("A & E & F & ~P & ~Q")) == true;

@test proposition_symbols(expr("x & y & z | A")) == [Expression("A")];

@test proposition_symbols(expr("(x & B(z)) ==> Farmer(y) | A")) == [Expression("A"), expr("Farmer(y)"), expr("B(z)")];

@test tt_true("(P ==> Q) <=> (~P | Q)") == true;

@test typeof(pl_true(Expression("P"))) <: Nothing;

@test typeof(pl_true(expr("P | P"))) <: Nothing;

@test pl_true(expr("P | Q"), model=Dict([Pair(Expression("P"), true)])) == true;

@test pl_true(expr("(A | B) & (C | D)"),
                model=Dict([Pair(Expression("A"), false),
                            Pair(Expression("B"), true),
                            Pair(Expression("C"), true)])) == true;

@test pl_true(expr("(A & B) & (C | D)"),
                model=Dict([Pair(Expression("A"), false),
                            Pair(Expression("B"), true),
                            Pair(Expression("C"), true)])) == false;

@test pl_true(expr("(A & B) | (A & C)"),
                model=Dict([Pair(Expression("A"), false),
                            Pair(Expression("B"), true),
                            Pair(Expression("C"), true)])) == false;

@test typeof(pl_true(expr("(A | B) & (C | D)"),
                model=Dict([Pair(Expression("A"), true),
                            Pair(Expression("D"), false)]))) <: Nothing;

@test pl_true(Expression("P"), model=Dict([Pair(Expression("P"), false)])) == false;

@test typeof(pl_true(expr("P | ~P"))) <: Nothing;

@test eliminate_implications(expr("A ==> (~B <== C)")) == expr("(~B | ~C) | ~A");

@test eliminate_implications(expr("A ^ B")) == expr("(A & ~B) | (~A & B)");

@test move_not_inwards(expr("~(A | B)")) == expr("~A & ~B");

@test move_not_inwards(expr("~(A & B)")) == expr("~A | ~B");

@test move_not_inwards(expr("~(~(A | ~B) | ~(~C))")) == expr("(A | ~B) & ~C");

@test distribute_and_over_or(expr("(A & B) | C")) == expr("(A | C) & (B | C)");

@test associate("&", (expr("A & B"), expr("B | C"), expr("B & C"))) == expr("&(A, B, (B | C), B, C)");

@test associate("|", (expr("A | (B | (C | (A & B)))"),)) == expr("|(A, B, C, (A & B))");

@test conjuncts(expr("A & B")) == [Expression("A"), Expression("B")];

@test conjuncts(expr("A | B")) == [expr("A | B")];

@test disjuncts(expr("A | B")) == [Expression("A"), Expression("B")];

@test disjuncts(expr("A & B")) == [expr("A & B")];

@test repr(to_conjunctive_normal_form(Expression("&",
                                                aimajulia.wumpus_world_inference,
                                                Expression("~", expr("~P12"))))) ==
                                                "((~(P12) | B11) & (~(P21) | B11) & (P12 | P21 | ~(B11)) & ~(B11) & P12)";

@test to_conjunctive_normal_form(expr("~(B | C)")) == expr("~B & ~C");

@test repr(to_conjunctive_normal_form(expr("~(B | C)"))) == "(~(B) & ~(C))";

@test to_conjunctive_normal_form(expr("(P & Q) | (~P & ~Q)")) == expr("&((~P | P), (~Q | P), (~P | Q), (~Q | Q))");

@test repr(to_conjunctive_normal_form(expr("(P & Q) | (~P & ~Q)"))) == "((~(P) | P) & (~(Q) | P) & (~(P) | Q) & (~(Q) | Q))";

@test to_conjunctive_normal_form(expr("B <=> (P1 | P2)")) == expr("&((~P1 | B), (~P2 | B), |(P1, P2, ~B))");

@test repr(to_conjunctive_normal_form(expr("B <=> (P1 | P2)"))) == "((~(P1) | B) & (~(P2) | B) & (P1 | P2 | ~(B)))";

@test to_conjunctive_normal_form(expr("a | (b & c) | d")) == expr("|(b, a, d) & |(c, a, d)");

@test repr(to_conjunctive_normal_form(expr("a | (b & c) | d"))) == "((b | a | d) & (c | a | d))";

@test to_conjunctive_normal_form(expr("A & (B | (D & E))")) == expr("&(A, (D | B), (E | B))");

@test repr(to_conjunctive_normal_form(expr("A & (B | (D & E))"))) == "(A & (D | B) & (E | B))";

@test to_conjunctive_normal_form(expr("A | (B | (C | (D & E)))")) == expr("|(D, A, B, C) & |(E, A, B, C)");

@test repr(to_conjunctive_normal_form(expr("A | (B | (C | (D & E)))"))) == "((D | A | B | C) & (E | A | B | C))";

prop_kb = PropositionalKnowledgeBase();

@test count((function(item)
                if (typeof(item) <: Bool)
                    return item;
                else
                    return true;
                end
            end), collect(ask(prop_kb, e) for e in map(expr, ["A", "C", "D", "E", "Q"]))) == 0;

tell(prop_kb, expr("A & E"));

@test ask(prop_kb, expr("A")) == Dict([]);

@test ask(prop_kb, expr("E")) == Dict([]);

tell(prop_kb, expr("E ==> C"));

@test ask(prop_kb, expr("C")) == Dict([]);

retract(prop_kb, expr("E"));

@test ask(prop_kb, expr("E")) == false;

@test ask(prop_kb, expr("C")) == false;

plr_results = pl_resolve(to_conjunctive_normal_form(expr("A | B | C")),
                        to_conjunctive_normal_form(expr("~B | ~C | F")));

@test pretty_set(Set{Expression}(disjuncts(plr_results[1]))) == "Set(Expression[A, C, F, ~(C)])";

@test pretty_set(Set{Expression}(disjuncts(plr_results[2]))) == "Set(Expression[A, B, F, ~(B)])";

# Use PropositionalKnowledgeBase to represent the Wumpus World (Fig. 7.4)

kb_wumpus = PropositionalKnowledgeBase();
tell(kb_wumpus, expr("~P11"));
tell(kb_wumpus, expr("B11 <=> (P12 | P21)"));
tell(kb_wumpus, expr("B21 <=> (P11 | P22 | P31)"));
tell(kb_wumpus, expr("~B11"));
tell(kb_wumpus, expr("B21"));

# Can't find a pit at location (1, 1).
@test ask(kb_wumpus, expr("~P11")) == Dict([]);

# Can't find a pit at location (1, 2).
@test ask(kb_wumpus, expr("~P12")) == Dict([]);

# Found pit at location (2, 2).
@test ask(kb_wumpus, expr("P22")) == false;

# Found pit at location (3, 1).
@test ask(kb_wumpus, expr("P31")) == false;

# Locations (1, 2) and (2, 1) do not contain pits.
@test ask(kb_wumpus, expr("~P12 & ~P21")) == Dict([]);

# Found a pit in either (3, 1) or (2,2).
@test ask(kb_wumpus, expr("P22 | P31")) == Dict([]);

@test pl_fc_entails(aimajulia.horn_clauses_kb, Expression("Q")) == true;

@test pl_fc_entails(aimajulia.horn_clauses_kb, Expression("SomethingSilly")) == false;

@test inspect_literal(Expression("P")) == (Expression("P"), true);

@test inspect_literal(Expression("~", Expression("P"))) == (Expression("P"), false);

@test unit_clause_assign(expr("A | B | C"), Dict([Pair(Expression("A"), true)])) == (nothing, nothing);

@test unit_clause_assign(expr("B | ~C"), Dict([Pair(Expression("A"), true)])) == (nothing, nothing);

@test unit_clause_assign(expr("B | C"), Dict([Pair(Expression("A"), true)])) == (nothing, nothing);

@test unit_clause_assign(expr("~A | ~B"), Dict([Pair(Expression("A"), true)])) == (Expression("B"), false);

@test unit_clause_assign(expr("B | ~A"), Dict([Pair(Expression("A"), true)])) == (Expression("B"), true);

@test find_unit_clause(map(expr, ["A | B | C", "B | ~C", "~A | ~B"]), Dict([Pair(Expression("A"), true)])) == (Expression("B"), false);

@test find_pure_symbol(map(expr, ["A", "B", "C"]), map(expr, ["A | ~B", "~B | ~C", "C | A"])) == (Expression("A"), true);

@test find_pure_symbol(map(expr, ["A", "B", "C"]), map(expr, ["~A | ~B", "~B | ~C", "C | A"])) == (Expression("B"), false);

@test find_pure_symbol(map(expr, ["A", "B", "C"]), map(expr, ["~A | B", "~B | ~C", "C | A"])) == (nothing, nothing);

@test dpll_satisfiable(expr("A & ~B")) == Dict([Pair(Expression("A"), true),
                                                Pair(Expression("B"), false),]);

@test dpll_satisfiable(expr("P & ~P")) == false;

@test (dpll_satisfiable(expr("A & ~B & C & (A | ~D) & (~E | ~D) & (C | ~D) & (~A | ~F) & (E | ~F) & (~D | ~F) & (B | ~C | D) & (A | ~E | F) & (~A | E | D)"))
        == Dict([Pair(Expression("A"), true),
                Pair(Expression("B"), false),
                Pair(Expression("C"), true),
                Pair(Expression("D"), true),
                Pair(Expression("E"), false),
                Pair(Expression("F"), false),]));

function walksat_test(clauses::Array{Expression, 1}; solutions::Dict=Dict())
    local sln = walksat(clauses);
    if (!(typeof(sln) <: Nothing)) #found a satisfiable solution
        @test all(collect(pl_true(clause, model=sln) for clause in clauses));
        if (length(solutions) != 0)
            @test all(collect(pl_true(clause, model=solutions) for clause in clauses));
            @test sln == solutions;
        end
    end
    nothing;
end

walksat_test(map(expr, ["A & B", "A & C"]));

walksat_test(map(expr, ["A | B", "P & Q", "P & B"]));

walksat_test(map(expr, ["A & B", "C | D", "~(D | P)"]), solutions=Dict([Pair(Expression("A"), true),
                                                            Pair(Expression("B"), true),
                                                            Pair(Expression("C"), true),
                                                            Pair(Expression("D"), false),
                                                            Pair(Expression("P"), false),]));

@test (typeof(walksat(map(expr, ["A & ~A"]), p=0.5, max_flips=100)) <: Nothing);

@test (typeof(walksat(map(expr, ["A | B", "~A", "~(B | C)", "C | D", "P | Q"]), p=0.5, max_flips=100)) <: Nothing);

@test (typeof(walksat(map(expr, ["A | B", "B & C", "C | D", "D & A", "P", "~P"]), p=0.5, max_flips=100)) <: Nothing);

transition = Dict([Pair("A", Dict([Pair("Left", "A"), Pair("Right", "B")])),
                    Pair("B", Dict([Pair("Left", "A"), Pair("Right", "C")])),
                    Pair("C", Dict([Pair("Left", "B"), Pair("Right", "C")]))]);

@test (typeof(sat_plan("A", transition,"C", 2)) <: Nothing);

@test sat_plan("A", transition, "B", 3) == ["Right"];

@test sat_plan("C", transition, "A", 3) == ["Left", "Left"];

transition = Dict([Pair((0, 0), Dict([Pair("Right", (0, 1)), Pair("Down", (1, 0))])),
                    Pair((0, 1), Dict([Pair("Left", (1, 0)), Pair("Down", (1, 1))])),
                    Pair((1, 0), Dict([Pair("Right", (1, 0)), Pair("Up", (1, 0)), Pair("Left", (1, 0)), Pair("Down", (1, 0))])),
                    Pair((1, 1), Dict([Pair("Left", (1, 0)), Pair("Up", (0, 1))]))]);

@test sat_plan((0, 0), transition, (1, 1), 4) == ["Right", "Down"];

@test unify(expr("x + y"), expr("y + C"), Dict([])) == Dict([Pair(Expression("x"), Expression("y")),
                                                            Pair(Expression("y"), Expression("C"))]);

@test unify(expr("x"), expr("3"), Dict([])) == Dict([Pair(Expression("x"), Expression("3"))]);

@test unify(expr("x"), expr("x"), Dict([])) == Dict([]);

@test extend(Dict([Pair(Expression("x"), 1)]), Expression("y"), 2) == Dict([Pair(Expression("x"), 1),
                                                                            Pair(Expression("y"), 2)]);

@test repr(substitute(Dict([Pair(Expression("x"), Expression("42")),
                            Pair(Expression("y"), Expression("0"))]),
                    expr("F(x) + y"))) == "(F(42) + 0)";

function fol_bc_ask_query(q::Expression; kb::Union{Nothing, AbstractKnowledgeBase}=nothing)
    local answers::Tuple;
    if (typeof(kb) <: Nothing)
        answers = fol_bc_ask(aimajulia.test_fol_kb, q);
    else
        answers = fol_bc_ask(kb, q);
    end
    local test_vars = variables(q);
    return sort(collect(Dict(collect(Pair(k, v) for (k, v) in answer if (k in test_vars))) for answer in answers),
            lt=(function(d1::Dict, d2::Dict)
                    return isless(repr(d1), repr(d2));
                end));
end

@test fol_bc_ask_query(expr("Farmer(x)")) == [Dict([Pair(Expression("x"), Expression("Mac"))])];

@test fol_bc_ask_query(expr("Human(x)")) == [Dict([Pair(Expression("x"), Expression("Mac"))]),
                                            Dict([Pair(Expression("x"), Expression("MrsMac"))])];

@test fol_bc_ask_query(expr("Rabbit(x)")) == [Dict([Pair(Expression("x"), Expression("MrsRabbit"))]),
                                            Dict([Pair(Expression("x"), Expression("Pete"))])];

@test fol_bc_ask_query(expr("Criminal(x)"), kb=aimajulia.crime_kb) == [Dict([Pair(Expression("x"), Expression("West"))])];

@test differentiate(expr("x * x"), expr("x")) == expr("(x * 1) + (x * 1)");

@test differentiate_simplify(expr("x * x"), expr("x")) == expr("2 * x");

@test (constant_symbols(expr("x & y & z | A")) == Set([expr("A")]));

@test (constant_symbols(expr("(x & B(z)) & Father(John) ==> Farmer(y) | A")) == Set(map(expr, ["A", "John"])));

@test (predicate_symbols(expr("x & y & z | A")) == Set());

@test (predicate_symbols(expr("(x & B(z)) & Father(John) ==> Farmer(y) | A")) == Set([("B", 1), ("Father", 1), ("Farmer", 1)]));

@test (predicate_symbols(expr("(x & B(x, y, z)) & F(G(x, y), x) ==> P(Q(R(x, y)), x, y, z)")) == Set([("G", 2), ("P", 4), ("R", 2), ("B", 3), ("Q", 1), ("F", 2)]));

max_stars_repo_name: mikhail-j/aima-julia-aimacode-fork

max_issues_repo_name: mikhail-j/aima-julia-aimacode-fork

max_forks_repo_name: mikhail-j/aima-julia-aimacode-fork


text:
export get_pha!

"""
    T = get_pha(Δ::Float64, z::Float64)

Command-line interface to IRIS online travel time calculator, which calls TauP [1-2].
Returns a matrix of strings.

Specify Δ in decimal degrees, z in km treating down as +.

Standard keywords: pha, to, v

Additional keywords:
* model: velocity model ("iasp91")

### References
[1] TauP manual: http://www.seis.sc.edu/downloads/TauP/taup.pdf
[2] Crotwell, H. P., Owens, T. J., & Ritsema, J. (1999). The TauP Toolkit:
Flexible seismic travel-time and ray-path utilities, SRL 70(2), 154-160.
"""
function get_pha!(Ev::SeisEvent;
                  pha::String   = KW.pha,
                  model::String = "iasp91",
                  to::Int64     = KW.to,
                  v::Int64      = KW.v
                  )

  # Check that distaz has been done
  TD = getfield(Ev, :data)
  N = getfield(TD, :n)
  z = zeros(Float64, N)
  if (TD.az == z) && (TD.baz == z) && (TD.dist == z)
    v > 0 && println(stdout, "az, baz, and dist are unset; calling distaz!...")
    distaz!(Ev)
  end

  # Generate URL and do web query
  src_dep = getfield(getfield(getfield(Ev, :hdr), :loc), :dep)
  if isempty(pha) || pha == "all"
    pq = "&phases=ttall"
  else
    pq = string("&phases=", pha)
  end
  url_tail = string("&evdepth=", src_dep, pq, "&model=", model, "&mintimeonly=true&noheader=true")

  # Loop begins
  dist = getfield(TD, :dist)
  PC = getfield(TD, :pha)
  for i = 1:N
    Δ = getindex(dist, i)
    pcat = getindex(PC, i)

    url = string("http://service.iris.edu/irisws/traveltime/1/query?", "distdeg=", Δ, url_tail)
    v > 1 && println(stdout, "url = ", url)

    req_info_str = string("\nIRIS travel time request:\nΔ = ", Δ, "\nDepth = ", z, "\nPhases = ", pq, "\nmodel = ", model)
    (R, parsable) = get_http_req(url, req_info_str, to)

    # Parse results
    if parsable
      req = String(take!(copy(IOBuffer(R))))
      pdat = split(req, '\n')
      deleteat!(pdat, findall(isempty, pdat))   # can have trailing blank line
      npha = length(pdat)
      for j = 1:npha
        pha = split(pdat[j], keepempty=false)
        pcat[pha[10]] = SeisPha(0.0,                              # a
                                parse(Float64, pha[8]),           # d
                                parse(Float64, pha[7]),           # ia
                                0.0,                              # res
                                parse(Float64, pha[5]),           # rp
                                parse(Float64, pha[6]),           # ta
                                parse(Float64, pha[4]),           # tt
                                0.0,                              # unc
                                ' ',                              # pol
                                ' ',                              # qual
                                )
      end
    end
  end
  return nothing
end
# "Model: iasp91"
# "Distance   Depth   Phase        Travel    Ray Param  Takeoff  Incident  Purist    Purist    "
# "  (deg)     (km)   Name         Time (s)  p (s/deg)   (deg)    (deg)   Distance   Name      "
# "--------------------------------------------------------------------------------------------"
# "   66.83    19.7   P             650.37     6.375     19.49    19.42    66.83   = P"
# "   66.83    19.7   pP            656.77     6.385    160.48    19.45    66.83   = pP"
# "   66.83    19.7   sP            659.32     6.383    168.84    19.45    66.83   = sP"
# "   66.83    19.7   PcP           678.82     4.167     12.59    12.55    66.83   = PcP"
# "   66.83    19.7   PP            797.49     8.699     27.08    26.98    66.83   = PP"
# "   66.83    19.7   PKiKP        1038.70     1.352      4.06     4.04    66.83   = PKiKP"
# "   66.83    19.7   pPKiKP       1045.47     1.352    175.94     4.04    66.83   = pPKiKP"
# "   66.83    19.7   sPKiKP       1047.95     1.352    177.65     4.04    66.83   = sPKiKP"
# "   66.83    19.7   S            1182.56    12.085     21.49    21.42    66.83   = S"
# "   66.83    19.7   pS           1190.65    12.109    140.68    21.46    66.83   = pS"
# "   66.83    19.7   sS           1193.48    12.101    158.48    21.45    66.83   = sS"
# "   66.83    19.7   SP           1201.90    13.645     24.43    45.38    66.83   = SP"
# "   66.83    19.7   PS           1204.86    13.644     45.55    24.35    66.83   = PS"
# "   66.83    19.7   SKS          1246.03     7.572     13.27    13.23    66.83   = SKS"
# "   66.83    19.7   SKKS         1246.05     7.585     13.29    13.25    66.83   = SKKS"
# "   66.83    19.7   ScS          1246.40     7.761     13.61    13.56    66.83   = ScS"
# "   66.83    19.7   SKiKP        1250.70     1.408      2.45     4.21    66.83   = SKiKP"
# "   66.83    19.7   pSKS         1254.86     7.573    156.66    13.23    66.83   = pSKS"
# "   66.83    19.7   sSKS         1257.44     7.573    166.73    13.23    66.83   = sSKS"
# "   66.83    19.7   SS           1441.81    15.478     27.98    27.88    66.83   = SS"
# "   66.83    19.7   PKIKKIKP     1860.33     1.411      4.23     4.22   293.17   = PKIKKIKP"
# "   66.83    19.7   SKIKKIKP     2072.34     1.352      2.35     4.05   293.17   = SKIKKIKP"
# "   66.83    19.7   PKIKKIKS     2074.81     1.352      4.06     2.34   293.17   = PKIKKIKS"
# "   66.83    19.7   SKIKKIKS     2286.62     1.297      2.25     2.25   293.17   = SKIKKIKS"
# "   66.83    19.7   PKIKPPKIKP   2359.03     1.666      5.00     4.98   293.17   = PKIKPPKIKP"
# "   66.83    19.7   PKPPKP       2361.68     2.976      8.96     8.93   293.17   = PKPPKP"
# "   66.83    19.7   PKPPKP       2364.24     3.928     11.86    11.82   293.17   = PKPPKP"
# "   66.83    19.7   SKIKSSKIKS   3216.94     1.426      2.48     2.47   293.17   = SKIKSSKIKS"


text:
# Exports
export build_automaton

function build_automaton(lambda::T) where {T <: Constraint}

    # Find constraint with maximum K value
    # Extract necessary parameters
    k = lambda.k
    n = _get_nbr_cons_hits(lambda)

    # Decide IntType
    IntType = _word_type(lambda, k)

    # IF we are not allowed to miss a single deadline, return a one vertex automaton
    if !is_satisfied(lambda, consword(IntType(k)) << IntType(1))

        # Initialise Automaton
        initvertex              = WordVertex{Int8}(Int8(Hit))
        automaton               = Automaton{Int8}(initvertex)
        initvertex.hit          = initvertex
        automaton[Int8(Hit)]    = initvertex
        return automaton

    # ELSE IF we are allowed to miss infinite number of misses, return another one vertex automaton
    elseif _allmissespermitted(lambda)
        # Initialise Automaton
        initvertex              = WordVertex{Int8}(Int8(Hit))
        automaton               = Automaton{Int8}(initvertex)
        initvertex.hit          = initvertex
        initvertex.miss         = initvertex
        automaton[Int8(Hit)]    = initvertex
        return automaton

    # ELSE add next vertex to transitions and continue
    else

        # Initialise automaton
        initvertex = WordVertex{IntType}(consword(IntType(n)))
        automaton = Automaton{IntType}(initvertex)
        sizehint!(automaton.data, _minimal_size(lambda))

        # If we have a rowhit constraint, change building method
        if typeof(lambda) == RowHitConstraint
            z = _get_nbr_cons_misses(lambda)
            return _build_automaton_rh!(lambda,
                                        automaton,
                                        initvertex,
                                        IntType(z),
                                        IntType(n),
                                        IntType(k))
        end # if

        # Else
        return _build_automaton!(lambda,
                                 automaton,
                                 initvertex)
    end
end # function

##################################
### Auxiliary Functions for RH ###
##################################

function _initiate_vertex_rh!(lambda::T,
                              automaton::Automaton{S},
                              list::_UninitializedList{S},
                              miss_list::Vector{WordVertex{S}},
                              vertex::WordVertex{S},
                              initword::S,
                              k::S) where {T <: Constraint, S <: Integer}
    (wm, wh) = _children_rh(vertex, initword)
    _extend_automaton_rh!(lambda, automaton, list, miss_list, vertex, wm, wh, k)
end # function

#= Extend automaton with the children (nm, nh) if they satisfy lambda =#
function _extend_automaton_rh!(lambda::T,
                               automaton::Automaton{S},
                               list::_UninitializedList{S},
                               miss_list::Vector{WordVertex{S}},
                               vertex::WordVertex{S},
                               wm::S,
                               wh::S,
                               k::S) where {T <: Constraint, S <: Integer}
    vertexH = nothing

    # Check if miss word satisfies constraints and whether it is initialized
    if is_satisfied(lambda, wm)
        vertex.miss = miss_list[_nbr_misses_permitted(lambda, vertex.w, k)]
    end

    # Check how many consecutive misses we are permitted,
    #   If it is more than 0: add to the automata (unless already present)
    if _nbr_misses_permitted(lambda, wh, k) > 0
        # check if hit word is initialised
        if !haskey(automaton, wh)
            vertexH         = WordVertex{S}(wh)
            automaton[wh]   = vertexH
            _push!(list, vertexH)
        else
            vertexH = automaton[wh]
        end
    else
        vertexH = automaton[consword(S(trailing_ones(wh)))]
    end

    # Add hit path to vertex
    vertex.hit = vertexH
end

#= Return the children of vertex, disregarding satisfiability =#
function _children_rh(vertex::WordVertex{T}, initword::T) where {T <: Integer}
    wm = shift_rowhit(vertex.w, Miss, initword)
    wh = shift_rowhit(vertex.w, Hit, initword)
    return (wm, wh)
end

# Returns how many consecutive misses we permit following w
function _nbr_misses_permitted(lambda::T, w::S, k::S) where {T <: Constraint, S <: Integer}
    for z in S(1):k
        if !is_satisfied(lambda, (w << (z+S(1))) | S(1))
            return z-S(1)
        end
    end
    return k
end # function

#= Add first nodes to the automaton by adding the maximum consecutive miss path to it. =#
function _add_miss_path_rh!(lambda::T,
                            automaton::Automaton{S},
                            list::_UninitializedList{S},
                            vertex::WordVertex{S},
                            z::S,
                            n::S,
                            k::S) where {T <: Constraint, S <: Integer}
    # Add "hit path" to automaton
    v = vertex
    for n_ in n-S(1):S(-1):S(1)
        w               = consword(n_)
        v_prior         = WordVertex{S}(w)
        v_prior.hit     = v
        automaton[w]    = v_prior
        v               = v_prior
    end # for

    # A list where each index "i" corresponds to the vertex with "i" more deadlines tolerated
    aux_list = Vector{WordVertex{S}}(undef, z+1)

    # Add "miss path" to automaton
    v       = vertex
    vertexM = nothing
    for z_ in z+S(1):S(-1):S(1)
        aux_list[z_]    = v
        (wm, wh)        = _children_rh(v, consword(n))

        # Check if miss word satisfies constraints and whether it is initialized
        if is_satisfied(lambda, wm)
            vertexM         = WordVertex{S}(wm)
            automaton[wm]   = vertexM

            # Add miss path to vertex
            v.miss         = vertexM
        end

        # check if hit word is initialised
        if _nbr_misses_permitted(lambda, wh, k) > 0
            if !haskey(automaton, wh)
                vertexH         = WordVertex{S}(wh)
                automaton[wh]   = vertexH
                _push!(list, vertexH)
            else
                vertexH = automaton[wh]
            end
        else
            vertexH = automaton[consword(S(trailing_ones(wh)))]
        end

        # Add hit path to vertex
        v.hit = vertexH

        v = vertexM
    end # for

    return aux_list

end # function

#= Build the automaton =#
function _build_automaton_rh!(lambda::T,
                              automaton::Automaton{S},
                              initvertex::WordVertex{S},
                              z::S,
                              n::S,
                              k::S) where {T <: Constraint, S <: Integer}
    # First initialize the necessary miss path in the graph
    list                    = _UninitializedList{S}()
    automaton[initvertex.w] = initvertex
    miss_list = _add_miss_path_rh!(lambda, automaton, list, initvertex, z, n, k)

    # Add the remaining vertices to the while loop
    while !isnothing(list.head) # while we have elements to iterate
        # Extract first element to iterate
        vertex = _pop!(list)

        # Add new feasible vertices to structures and lists
        _initiate_vertex_rh!(lambda, automaton, list, miss_list, vertex, consword(n), k)
    end #while

    return automaton
end # function

##########################################
### Auxiliary Functions for RM, AM, AH ###
##########################################

function _initiate_vertex!(lambda::T,
                           automaton::Automaton{S},
                           list::_UninitializedList{S},
                           vertex::WordVertex{S}) where {T <: Constraint, S <: Integer}
    (wm, wh) = _children(vertex)
    _extend_automaton!(lambda, automaton, list, vertex, wm, wh)
end # function

#= Extend automaton with the children (nm, nh) if they satisfy lambda =#
function _extend_automaton!(lambda::T,
                            automaton::Automaton{S},
                            list::_UninitializedList{S},
                            vertex::WordVertex{S},
                            wm::S,
                            wh::S) where {T <: Constraint, S <: Integer}
    vertexM = nothing
    vertexH = nothing

    # Check if miss word satisfies constraints and whether it is initialized
    if is_satisfied(lambda, wm)
        if !haskey(automaton, wm)
            vertexM         = WordVertex{S}(wm)
            automaton[wm]   = vertexM
            _push!(list, vertexM)
        else
            vertexM         = automaton[wm]
        end

        # Add miss path to vertex
        vertex.miss         = vertexM
    end

    # check if hit word is initialised
    if !haskey(automaton, wh)
        vertexH         = WordVertex{S}(wh)
        automaton[wh]   = vertexH
        _push!(list, vertexH)
    else
        vertexH         = automaton[wh]
    end

    # Add hit path to vertex
    vertex.hit = vertexH
end

#= Return the children of vertex, disregarding satisfiability =#
function _children(vertex::WordVertex{T}) where {T <: Integer}
    wm = shift(vertex.w, Miss)
    wh = shift(vertex.w, Hit)
    return (wm, wh)
end

#= Building the automaton =#
function _build_automaton!(lambda::T,
                           automaton::Automaton{S},
                           initvertex::WordVertex{S}) where {T <: Constraint, S <: Integer}
    # First initialize the necessary miss path in the graph
    list                    = _UninitializedList{S}()
    automaton[initvertex.w] = initvertex
    _push!(list, initvertex)

    # Add the remaining vertices to the while loop
    while !isnothing(list.head) # while we have elements to iterate
        # Extract first element to iterate
        vertex = _pop!(list)

        # Add new feasible vertices to structures and lists
        _initiate_vertex!(lambda, automaton, list, vertex)
    end #while

    return automaton
end # function


text:
"""
    SuperPixel(pixels, pos)
    SuperPixel(img, pos)

A super pixel is a collection of pixels with their position information.

# Fields

* `color::AbstractArray{<:Colorant}` stores its pixel/color information.
* `position::CartesianIndices` stores its position information.

Relative order in `color` and `position` is important; `color[idx]` is the
image pixel at position `position[idx]`.

!!! tip

    There's a helper for each field. For example, `color(sp)` is equivalent to
    `sp.color`. This is useful to enable broadcasting such as `position.(img)`
    where `img` is a `SuperPixel` array.

# Examples

There're various ways to generate a superpixel at `img[1:2, 3:4]`:

```julia
img = rand(Gray, 4, 4)

SuperPixel(img, (1:2, 3:4))

pos = CartesianIndices(1:2, 3:4)
SuperPixel(img[pos], pos)
```

!!! note

    Each pixel in a superpixel is a `Colorant`; `Number` is promoted to `Gray`
    when constructing a `SuperPixel` object.

An array of `SuperPixel`s can be treated as an image, you can use [`synthesize`](@ref)
to generate the potential image contents.

```julia
img = rand(Gray, 4, 4)

img_sp = [SuperPixel(img, (1:2, 1:2)),
          SuperPixel(img, (1:2, 3:4)),
          SuperPixel(img, (3:4, 1:2)),
          SuperPixel(img, (3:4, 3:4))]

segments = [(1:2, 1:2), (1:2, 3:4), (3:4, 1:2), (3:4, 3:4)]
img_sp = [SuperPixel(img, pos) for pos in segments]

synthesize(img_sp) # composite superpixels into a complete image
synthesize(img_sp, Average()) # each superpixel is averaged first
```
"""
struct SuperPixel{T<:Colorant, N, AT<:AbstractArray{T}}
    color::AT
    position
end

function SuperPixel(
    color::AbstractArray{T},
    position::AbstractArray{CartesianIndex{N}}) where {T<:Colorant, N}

    color = length(color) == length(position) ? color : color[position]
    SuperPixel{T, N, typeof(color)}(color, position)
end

SuperPixel(color::AbstractArray{<:Colorant}, pos::Tuple) =
    SuperPixel(color, CartesianIndices(pos))

SuperPixel(pixels::AbstractArray{<:Number}, pos) =
    SuperPixel(Gray.(pixels), pos)

color(sp::SuperPixel) = sp.color
position(sp::SuperPixel) = sp.position

# support usage such as RGB.(img_sp)
function Base.convert(::Type{C}, sp::SuperPixel) where {C<:Colorant}
    CT = ccolor(C, eltype(sp.color))
    src = sp.color
    dest = similar(src, CT)
    @inbounds for idx in CartesianIndices(src)
        dest[idx] = ColorTypes.cconvert(ccolor(C, CT), src[idx])
    end
    return SuperPixel(dest, sp.position)
end

Base.isempty(sp::SuperPixel) = isempty(color(sp))
Base.:(==)(x::SuperPixel, y::SuperPixel) = x.position == y.position && x.color == y.color

color_type(sp::SuperPixel{CT}) where CT <: Colorant = CT
color_type(img::AbstractArray{<:SuperPixel}) = color_type(eltype(img))
color_type(::Type{<:SuperPixel{CT}}) where CT <: Colorant = CT

"""
    imsize(img)

Returns the size of potential image represented by [`SuperPixel`](@ref).
"""
imsize(img::AbstractArray{<:SuperPixel}) = _size(Iterators.flatten(position.(img)))
imsize(img::SuperPixel) = _size(position(img))
imsize(img::AbstractArray) = size(img)
function _size(R)
    I_first, I_last = extrema(R)
    return I_last.I .- I_first.I .+ (1, 1)
end


text:
module Neuron

using CuArrays

include("lif.jl")
include("srm0.jl")

end


text:
using TopicModels

exdir = Pkg.dir("TopicModels", "examples")

testDocuments = readDocuments(open(joinpath(exdir, "cora.documents")))
testLexicon = readLexicon(open(joinpath(exdir, "cora.lexicon")))

corpus = Corpus(testDocuments)

model = Model(fill(0.1, 10), 0.01, length(testLexicon), corpus)

@time trainModel(model, 30)

topWords = topTopicWords(model, testLexicon, 21)


text:
@testset "Synthetic satellite" begin
    system = GPSL1()
    sat = ConstantDopplerSatellite(
        system,
        1,
        carrier_doppler = 1000.0Hz,
        carrier_phase = π / 2,
        code_phase = 100.0,
        cn0 = 45dBHz
    )
    synthetic_sat = SyntheticSatellite(sat)

    @test @inferred(get_carrier_phase(synthetic_sat)) == π / 2
    @test @inferred(get_code_phase(synthetic_sat)) == 100.0

    rng = MersenneTwister(1234)
    signal = @inferred GNSSSimulator.gen_signal!(
        synthetic_sat,
        2.5e6Hz,
        10.0Hz,
        1/Hz,
        2500,
        rng
    )

    code_doppler = 1000.0 * 1023e3 / 1.57542e9
    reference_signal = get_code.(
        system,
        (0:2499) .* (1023e3 .+ code_doppler) ./ 2.5e6 .+ 100,
        1
    ) .* cis.(2π .* (0:2499) .* (1000.0 + 10.0) ./ 2.5e6 .+ π / 2) .*
        sqrt(10^(45 / 10))
    @test sqrt(sum(abs2.(signal .- reference_signal)) / 2500) < 1e-2 * sqrt(10^(45 / 10))

    next_synthetic_sat = @inferred GNSSSimulator.propagate(
        synthetic_sat,
        1,
        100.0Hz,
        2e6Hz,
        1.0/Hz,
        Random.GLOBAL_RNG
    )
    @test @inferred(get_carrier_doppler(next_synthetic_sat)) == 1000Hz
    @test @inferred(get_code_doppler(next_synthetic_sat)) ≈ 1000Hz / 1540
    @test @inferred(get_carrier_phase(next_synthetic_sat)) ≈ π / 2 + 2π * 1100Hz / 2e6Hz
    @test @inferred(get_code_phase(next_synthetic_sat)) ≈ 100 + (1023e3Hz + 1000Hz / 1540) / 2e6Hz
    @test @inferred(get_existence(next_synthetic_sat)) == true
    @test @inferred(get_carrier_to_noise_density_ratio(next_synthetic_sat)) ≈ 45dBHz
    @test @inferred(get_prn(next_synthetic_sat)) == 1
    @test @inferred(get_gnss_system(next_synthetic_sat)) == system

    manifold = IdealManifold(
        1575420e3,
        0.1904 / 4 * SVector(SVector(1, 1, 0), SVector(-1, 1, 0)),
    )
    @test get_steer_vec(manifold, synthetic_sat, RotXYZ(0.0,0.0,0.0)) == [1.0, 1.0]

    synthetic_sat_with_steer_vec = SyntheticSatellite(sat, SVector(1.0, 1.0im))
    @test get_steer_vec(manifold, synthetic_sat_with_steer_vec, RotXYZ(0.0,0.0,0.0)) == [1.0, 1.0im]

end


text:
module TestValue
using Test
using CategoricalArrays
using CategoricalArrays: DefaultRefType, level,  reftype, leveltype

@testset "leveltype on non CategoricalValue types" begin
    @test leveltype("abc") === String
    @test leveltype(String) === String
    @test leveltype(1.0) === Float64
    @test leveltype(Float64) === Float64
end

@testset "CategoricalValue on DefaultRefType pool in sorted order" begin
    pool = CategoricalPool(
        Dict(
            "a" => DefaultRefType(1),
            "b" => DefaultRefType(2),
            "c" => DefaultRefType(3),
        )
    )

    for i in 1:3
        x = CategoricalValue(i, pool)

        @test leveltype(x) === String
        @test leveltype(typeof(x)) === String
        @test reftype(x) === DefaultRefType
        @test reftype(typeof(x)) === DefaultRefType
        @test x isa CategoricalValue{String, DefaultRefType}

        @test level(x) === DefaultRefType(i)
        @test CategoricalArrays.pool(x) === pool

        @test typeof(x)(x) === x
        @test CategoricalValue(UInt8(i), pool) == x
    end
end

@testset "CategoricalValue on UInt8 pool in custom order" begin
    pool = CategoricalPool(
        Dict(
            "a" => UInt8(3),
            "b" => UInt8(2),
            "c" => UInt8(1),
        )
    )

    for i in 1:3
        x = CategoricalValue(i, pool)

        @test leveltype(x) === String
        @test leveltype(typeof(x)) === String
        @test reftype(x) === UInt8
        @test reftype(typeof(x)) === UInt8
        @test x isa CategoricalValue{String, UInt8}

        @test level(x) === UInt8(i)
        @test CategoricalArrays.pool(x) === pool

        @test typeof(x)(x) === x
        @test CategoricalValue(UInt32(i), pool) == x
    end
end

end