text:
ROOT = pwd()
include(joinpath(ROOT, "src_PowSysMod", "PowSysMod_body.jl"))

# folder = "Phase_0_IEEE14"
# folder = "Phase_0_Feas179"
# folder = "Phase_0_RTS96"
folder = "Phase_0_IEEE14_1Scenario"
scenario = "scenario_1"
filenames = [folder, scenario]
filenames_path = joinpath("data_GOC", folder, scenario)
instance_path = filenames_path

## Build global pb
OPFpbs = load_OPFproblems(GOCInput, instance_path)
introduce_Sgenvariables!(OPFpbs)
pb_global = build_globalpb(OPFpbs)

## Build solution
global_point = solution_point(instance_path)

## Add binary variables value
# bin_point = create_bin_point(OPFpbs, global_point)

println("minslack of GOC global solution: $(get_minslack(pb_global, global_point))")

# evaluate(pb.constraints["Scen1_3_Gen1_CC_Supper"].p, global_point)
# evaluate(pb.constraints["Scen1_3_Gen1_CC_Slower"].p, global_point)

get_minslack(pb_global, global_point)

pb_sansCC = Problem()
pb_sansCC.variables = copy(pb_global.variables)
pb_sansCC.objective = copy(pb_global.objective)
for (cstrname, cstr) in pb_global.constraints
    if !ismatch(r"Pgen|Qgen", cstrname)
        add_constraint!(pb_sansCC, cstrname, cstr)
    end
end
println("minslack of GOC solution without coupling constraints: $(get_minslack(pb_sansCC, global_point))")

## Export problem
amplexportpath = joinpath("knitro_runs", "$(folder[9:end])_$(scenario)_move")

pb_global_real = pb_cplx2real(pb_global)
global_point_real = cplx2real(global_point)

export_to_dat(pb_global_real, amplexportpath, global_point)

## Knitro call and solution import
run_knitro(amplexportpath, joinpath(pwd(), "src_ampl"))
pt_knitro, pt_GOC = read_Knitro_output(amplexportpath, pb_global_real)

length(global_point_real)
length(pt_knitro)

println("Minslack for GOC point : $(get_minslack(pb_global_real, pt_GOC))")
println("Minslack for Knitro point : $(get_minslack(pb_global_real, pt_knitro))")

println("Objective for GOC point :    $(get_objective(pb_global_real, pt_GOC))")
println("Objective for Knitro point : $(get_objective(pb_global_real, pt_knitro))")

println("||pt_GOC - global_point||_2 = ", norm(pt_GOC - global_point, 2))
println("||pt_GOC - global_point||_Inf = ", norm(pt_GOC - global_point, Inf))

# slacks = sort(collect(get_slacks(pb_global_real, pt_GOC)), by=x->real(x[2]))
# violated_cstrs = collect(filter(x->real(x[2])<-1e-4, slacks))
# println("GOC 1e-4 Violated_constraints    : $(length(violated_cstrs))")
#
# slacks = sort(collect(get_slacks(pb_global_real, pt_knitro)), by=x->real(x[2]))
# violated_cstrs = collect(filter(x->real(x[2])<-1e-4, slacks))
# println("Knitro 1e-4 Violated_constraints : $(length(violated_cstrs))")

# bc_volt_vars, bc_bin_vars, bc_prod_vars = get_splitted_Cpt(pt_knitro, "BaseCase")
# sc_volt_vars, sc_bin_vars, sc_prod_vars = get_splitted_Cpt(pt_knitro, "Scen1")
# sc_delta_var = get_delta_var(pt_knitro, "Scen1")
# haskey(pt_knitro, Variable("BaseCase_3_Gen1_Sgen", Complex))
#
#
# using Plots
#
# plot_Volt_vars(pt_knitro, keys(OPFpbs))
# # plot_Sgen_vars(pt_knitro, ["BaseCase"])
# plot_Sgen_vars(pt_knitro, keys(OPFpbs))
#
# plot_ViVj_vars(pt_knitro, ["BaseCase"])
# plot_ViVj_vars(pt_knitro, keys(OPFpbs))

# scatter!(real(ptsVbc), imag(ptsVbc), linealpha=0.1, marker=:circle, series_annotations=[text(matchall(r"", x[1])[1]) for (x,y) in bc_volt_vars])

max_stars_repo_name: Gimaju/GOC

max_issues_repo_name: Gimaju/GOC

max_forks_repo_name: Gimaju/GOC


text:
################################################################################
#
#	ABSTRACT TYPE
#
#   Lattice{S,B,U}
#   --> S is the site type (<: AbstractSite{LS,D})
#       --> D is the dimension of embedding space
#       --> LS is the label type of sites
#   --> B is the bond type (<: AbstractBond{LB,N})
#       --> N is the dimension of the Bravais lattice that the bond is located in
#       --> LB is the label type of bonds
#   --> U is the unitcell type (<: AbstractUnitcell{SU,BU})
#       --> SU is the site type of the unitcell (<: AbstractSite{LUS,DU})
#           --> DU is the dimension of embedding space (of the UC)
#           --> LUS is the label type of sites (of the UC)
#       --> BU is the bond type of the unitcell (<: AbstractBond{LUB,NU})
#           --> NU is the dimension of the Bravais lattice that the bond is located in (of the UC)
#           --> LUB is the label type of bonds (of the UC)
#
#   FILE CONTAINS
#       - abstract type definition
#       - interface definition
#       - TODO interface testing
#
################################################################################

################################################################################
#
#   ABSTRACT TYPE DEFINITION
#
################################################################################
abstract type AbstractLattice{
        S <: AbstractSite{LS,D} where {LS,D},
        B <: AbstractBond{LB,N} where {LB,N},
        U <: AbstractUnitcell{SU,BU} where {
            SU <: AbstractSite{LUS,DU} where {LUS,DU},
            BU <: AbstractBond{LUB,NU} where {LUB,NU},
        }
    } end

# export the type
export AbstractLattice

# DOCSTRING
"""
    abstract type AbstractLattice{S,B,U}

The abstract unitcell type that describes all unitcell implementations.
It is parametric in three types,
- `S` the type of sites within lattice (subtype of `AbstractSite{LS,D}`)
- `B` the type of bonds within lattice (subtype of `AbstractBond{LB,N}`)
- `U` the type of unitcell within lattice (subtype of `AbstractUnitcell{S,B}`). Note that the site and bond types of the unitcell can be different from that of the lattice.
Note that the spatial dimension or the number of Bravais lattice vectors is already
encoded in the site and bond types respectively, as e.g. `N` describes the
number of Bravais lattice vectors.

The abstract type is equipped with interface functions which are listed in the following.
These interface functions have to be implemented by concrete subtypes / structs for the
concrete type to be usable in all pre-implemented functions.
- `newLattice` to create a new lattice object of a passed concrete lattice type
- `latticeVectors` and `latticeVectors!` to access the Bravais lattice vectors
- `sites` and `sites!` to access the site list of the lattice
- `bonds` and `bonds!` to access the bond list of the lattice
- `unitcell` and `unitcell!` to access the unitcell of the lattice

The interface functions throw adequate errors when called but not implemented for
concrete types. See specific documentation for the individual functions.

Furthermore, there are certain convinience functions which do not have to be implemented for every
concrete type. These are
- `numSites` to get the number of sites (i.e. length of site list)
- `numBonds` to get the number of bonds (i.e. length of bond list)
- `site` and `bond` to explicitly access individual sites and bonds
- `organizedBondsFrom` and `organizedBondsTo` to get a reorganized form of the bond list
- `a1`, `a2` and `a3` to access individual Bravais lattice vectors directly

# Examples

`AbstractLattice{Site{Int64,3}, Bond{Int64,2}, Unitcell{Site{Int64,3}, Bond{Symbol,2}}}`
is the supertype of a lattice in `3` spatial dimensions with `2` Bravais lattice vectors with
`Int64` site labels and `Int64` bond labels and a unitcell in `3` spatial dimensions with `2`
Bravais lattice vectors with `Int64` site labels and `Symbol` bond labels.

"""
AbstractLattice

"""
Number of spatial dimensions the lattice is embedded in.
"""
Base.ndims(l::AbstractLattice{S}) where S<:AbstractSite = ndims(S)

################################################################################
#
#	INTERFACING / ACCESSING LATTICES
#	(functions have to be overwritten by concrete types)
#
################################################################################

# default constructor interface
# used for creation of new lattices
"""
    function newLattice(
            ::Type{L},
            lattice_vectors :: Vector{<:Vector{<:Real}},
            sites           :: Vector{S},
            bonds           :: Vector{B},
            unitcell        :: U
        ) :: L where{...}

Interface function for creation of new `AbstractLattice` object of a passed type `L` from a passed
set of `lattice_vectors`, `sites`, `bonds` and a `unitcell`. Returns a new lattice object of type `L`.
Note that `sites` have to be `AbstractSite` objects and `bonds` have to be `AbstractBond` objects so that
from their types one can infere information on the lattice. Furthermore, the lattice type has to be specified
to agree with the types of `S`, `B` and `U`.

This function has to be overwritten by a concrete type,
otherwise it will throw an error when used in further functions.

NOTE that this constructor function is most commonly used in further lattice constructing
functions that build on abstract interfaces. This way, any lattice type can be chosen
as a type for the constructed lattice and the functions don't have to know the details
of the specific types.

# Examples

```julia-REPL
julia> lt = newLattice(
                Lattice{Site{String,2}, Bond{Int64,2}, Unitcell{Site{String,2}, Bond{Int64,2}}},
                lattice_vectors,
                sites,
                bonds,
                unitcell
            )
...
```
"""
function newLattice(
            ::Type{L},
            lattice_vectors :: Vector{<:Vector{<:Real}},
            sites           :: Vector{S},
            bonds           :: Vector{B},
            unitcell        :: U
        ) :: L where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'newLattice' for concrete lattice type " *
            string(L) * " with bond type " * string(B) *
            " and site type " * string(S)   )
end

# export the newLattice interface
export newLattice

# accessing a list of lattice vectors
"""
    function latticeVectors(
            lattice :: AbstractLattice{S,B,U}
        ) :: Vector{Vector{Float64}} where {...}

Interface function for obtaining the Bravais lattice vectors of a passed `AbstractLattice` object `lattice`.
Returns a list of Bravais lattice vectors as an object of type `Vector{Vector{Float64}}`.

This function has to be overwritten by a concrete type,
otherwise it will throw an error when used in further functions.

# Examples

```julia-REPL
julia> latticeVectors(lattice)
2-element Array{Array{Float64,1},1}:
 [1.0, 0.0]
 [0.0, 1.0]
```
"""
function latticeVectors(
            lattice :: L
        ) :: Vector{Vector{Float64}} where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'latticeVectors' for concrete lattice type " * string(L) )
end
# setting a list of lattice vectors
"""
    function latticeVectors!(
            lattice         :: AbstractLattice{S,B,U},
            lattice_vectors :: Vector{<:Vector{<:Real}}
        ) where {...}

Interface function for setting the Bravais lattice vectors of a passed `AbstractLattice` object `lattice` to a new value.
Returns nothing.

This function has to be overwritten by a concrete type,
otherwise it will throw an error when used in further functions.

# Examples

```julia-REPL
julia> latticeVectors!(lattice, [[2,0], [0,2]])

julia> latticeVectors(lattice)
2-element Array{Array{Float64,1},1}:
 [2.0, 0.0]
 [0.0, 2.0]
```
"""
function latticeVectors!(
            lattice         :: L,
            lattice_vectors :: Vector{<:Vector{<:Real}}
        ) where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'latticeVectors!' for concrete lattice type " * string(L) )
end

# export the latticeVectors interface
export latticeVectors, latticeVectors!

# accessing a list of sites
"""
    function sites(
            lattice :: AbstractLattice{S,B,U}
        ) :: Vector{S} where {...}

Interface function for obtaining the list of sites of a passed `AbstractLattice` object `lattice`.
Returns a list of `AbstractSite` objects of type `S` as an object of type `Vector{S}`.

This function has to be overwritten by a concrete type,
otherwise it will throw an error when used in further functions.

# Examples

```julia-REPL
julia> sites(lattice)
20-element Array{Site{String,2},1}:
 Site{Int64,2} @[0.0, 0.0]: "site1"
 Site{Int64,2} @[0.57735, 0.0]: "site2"
 ...
```
"""
function sites(
            lattice :: L
        ) :: Vector{S} where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'sites' for concrete lattice type " *
            string(L) * " with site type " * string(S)   )
end
# setting a list of sites
"""
    function sites!(
            lattice :: AbstractLattice{S,B,U},
            sites   :: Vector{S}
        ) where {...}

Interface function for setting the sites of a passed `AbstractLattice` object `lattice` to a new value.
Returns nothing.

This function has to be overwritten by a concrete type,
otherwise it will throw an error when used in further functions.

# Examples

```julia-REPL
julia> sites!(lattice, new_site_list)

julia> sites(lattice)
10-element Array{Site{String,2},1}:
 Site{Int64,2} @[0.0, 1.0]: "site1_new"
 Site{Int64,2} @[0.1, 0.0]: "site2_new"
 ...
```
"""
function sites!(
            lattice :: L,
            sites   :: Vector{S}
        ) where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'sites!' for concrete lattice type " *
            string(L) * " with site type " * string(S)   )
end

# export the sites interface
export sites, sites!

# accessing a list of bonds
"""
    function bonds(
            lattice :: AbstractLattice{S,B,U}
        ) :: Vector{B} where {...}

Interface function for obtaining the list of bonds of a passed `AbstractLattice` object `lattice`.
Returns a list of `AbstractBond` objects of type `B` as an object of type `Vector{B}`.

This function has to be overwritten by a concrete type,
otherwise it will throw an error when used in further functions.

# Examples

```julia-REPL
julia> bonds(lattice)
60-element Array{Bond{Int64,2},1}:
 Bond{Int64,2} 1-->2 @(0, 0): 1
 Bond{Int64,2} 2-->1 @(0, 0): 1
 ...
```
"""
function bonds(
            lattice :: L
        ) :: Vector{B} where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'bonds' for concrete lattice type " *
            string(L) * " with bond type " * string(B)   )
end
# setting a list of bonds
"""
    function bonds!(
            lattice :: AbstractLattice{S,B,U},
            bonds   :: Vector{B}
        ) where {...}

Interface function for setting the bonds of a passed `AbstractLattice` object `lattice` to a new value.
Returns nothing.

NOTE that bonds are always directed and require a returning counterpart to work as expected.

This function has to be overwritten by a concrete type,
otherwise it will throw an error when used in further functions.

# Examples

```julia-REPL
julia> bonds!(lattice, bond_list_new)

julia> bonds(uc)
20-element Array{Bond{Int64,2},1}:
 Bond{Int64,2} 1-->2 @(0, 1): 42
 Bond{Int64,2} 2-->1 @(0, -1): 42
 ...
```
"""
function bonds!(
            lattice :: L,
            bonds   :: Vector{B}
        ) where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'bonds!' for concrete lattice type " *
            string(L) * " with bond type " * string(B)   )
end

# export the bonds interface
export bonds, bonds!

# accessing the unitcell
"""
    function unitcell(
            lattice :: AbstractLattice{S,B,U}
        ) :: U where {...}

Interface function for obtaining the unitcell of a passed `AbstractLattice` object `lattice`.
Returns an object of type `U`.

This function has to be overwritten by a concrete type,
otherwise it will throw an error when used in further functions.

# Examples

```julia-REPL
julia> unitcell(lattice)
...
```
"""
function unitcell(
            lattice :: L
        ) :: U where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'unitcell' for concrete lattice type " *
            string(L) * " with unitcell type " * string(U)   )
end
# setting the unitcell
"""
    function unitcell(
            lattice  :: AbstractLattice{S,B,U},
            unitcell :: U
        ) :: U where {...}

Interface function for setting the unitcell of a passed `AbstractLattice` object `lattice`
to a new `AbstractUnitcell` object `unitcell` of type `U`.
Returns nothing.

This function has to be overwritten by a concrete type,
otherwise it will throw an error when used in further functions.

# Examples

```julia-REPL
julia> unitcell!(lattice, uc)
...
```
"""
function unitcell!(
            lattice  :: L,
            unitcell :: U
        ) where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'unitcell!' for concrete lattice type " *
            string(L) * " with unitcell type " * string(U)   )
end

# export the unitcell interface
export unitcell, unitcell!

function saveLattice(
        lt :: L,
        fn :: AbstractString,
        group :: AbstractString = "lattice"
        ;
        append :: Bool = false
    ) where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'saveLattice' for concrete lattice type " *
            string(L) * " with unitcell type " * string(U)   )
end

function loadLattice(
        ::Type{L},
        fn :: AbstractString,
        group :: AbstractString = "lattice"
    ) :: L where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # print an error because implementation for concrete type is missing
    error(  "not implemented function 'loadLattice' for concrete lattice type " *
            string(L) * " with unitcell type " * string(U)   )
end

export saveLattice, loadLattice

# SIMILAR FUNCTION (can be overwritten but does not have to be overwritten)

# without new parameters
function similar(
            l :: L
        ) where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # return a new lattice object
    return newLattice(
        L,
        deepcopy(latticeVectors(l)),
        deepcopy(sites(l)),
        deepcopy(bonds(l)),
        deepcopy(unitcell(l))
    )
end
# with new parameters
function similar(
            l :: L,
            lattice_vectors :: Vector{<:Vector{<:Real}},
            sites           :: Vector{S},
            bonds           :: Vector{B},
            unitcell        :: U
        ) where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # create a new lattice object
    l_new = similar(l)
    # set parameters
    latticeVectors!(l_new, lattice_vectors)
    sites!(l_new, sites)
    bonds!(l_new, bonds)
    unitcell!(l_new, unitcell)
    # return the new object
    return l_new
end

# export the similar interface
export similar

# some more beauty interface
# builds on interface defined above but can also be overwritten

# number of sites
"""
    function numSites(
            lattice  :: AbstractLattice{S,B,U}
        ) :: Int64 where {...}

Function for obtaining the number of sites of a passed `AbstractLattice` object `lattice`.
Returns the number as an `Int64`.

This function does not have to be overwritten by a concrete type as it is implemented
per default as the length of the site list obtained by `sites(lattice)`.

# Examples

```julia-REPL
julia> numSites(lattice)
20
```
"""
function numSites(
            lattice :: L
        ) :: Int64 where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # return length of the site array that the lattice type implements
    return length(sites(lattice))
end

# number of bonds
"""
    function numBonds(
            lattice  :: AbstractLattice{S,B,U}
        ) :: Int64 where {...}

Function for obtaining the number of bonds of a passed `AbstractLattice` object `lattice`.
Returns the number as an `Int64`.

This function does not have to be overwritten by a concrete type as it is implemented
per default as the length of the bond list obtained by `bonds(lattice)`.

# Examples

```julia-REPL
julia> numBonds(lattice)
60
```
"""
function numBonds(
            lattice :: L
        ) :: Int64 where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # return length of the bond array that the lattice type implements
    return length(bonds(lattice))
end

# export the number interfaces
export numSites, numBonds

# access a specific site or bond

# site
"""
    function site(
            lattice :: AbstractLattice{S,B,U},
            index   :: Integer
        ) :: S where {...}

Function for obtaining the `AbstractSite` object of type `S` that corresponds to the site with index `index`
of a passed `AbstractLattice` object `lattice`. Returns an object of type `S`.

This function does not have to be overwritten by a concrete type as it is implemented
per default as explicit call from the site list obtained by `sites(lattice)`.

# Examples

```julia-REPL
julia> site(lattice,1)
Site{Int64,2} @[0.0, 0.0]: "site1"
```
"""
function site(
            lattice :: L,
            index   :: Int64
        ) :: S where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # return the respective site
    return sites(lattice)[index]
end

# bond
"""
    function bond(
            lattice :: AbstractLattice{S,B,U},
            index   :: Integer
        ) :: B where {...}

Function for obtaining the `AbstractBond` object of type `B` that corresponds to the bond with index `index`
of a passed `AbstractLattice` object `lattice`. Returns an object of type `B`.

This function does not have to be overwritten by a concrete type as it is implemented
per default as explicit call from the bond list obtained by `bonds(lattice)`.

# Examples

```julia-REPL
julia> bond(lattice,1)
Bond{Int64,2} 1-->2 @(0, 0): 1
```
"""
function bond(
            lattice :: L,
            index   :: Int64
        ) :: B where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # return the respective bond
    return bonds(lattice)[index]
end

# export the specific site and bond interfaces
export site, bond

# get an organized bond list (organized by 'from')
"""
    function organizedBondsFrom(
            lattice :: AbstractLattice{S,B,U}
        ) :: Vector{Vector{B}} where {...}

Function for obtaining an organized version of the list of bonds of a passed `AbstractLattice` object `lattice`.
Returns a nested list of `AbstractBond` objects of type `B` as an object of type `Vector{Vector{B}}`,
in which the element `i` is a list of all bonds emerging from site `i`.

This function does not have to be overwritten by a concrete type as it is implemented
on the level of abstract types and interface functions.

# Examples

```julia-REPL
julia> organizedBondsFrom(lattice)
20-element Array{Array{Bond{Int64,2},1},1}:
 [Bond{Int64,2} 1-->2 @(0, 0): 1, Bond{Int64,2} 1-->2 @(-1, 0): 1, Bond{Int64,2} 1-->2 @(0, -1): 1]
 [Bond{Int64,2} 2-->1 @(0, 0): 1, Bond{Int64,2} 2-->1 @(1, 0): 1, Bond{Int64,2} 2-->1 @(0, 1): 1]
 ...
```
"""
function organizedBondsFrom(
            lattice :: L
        ) :: Vector{Vector{B}} where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # temporary fix for dispatch behavior: name all types explicitly
    D,N,LS,LB,U,S,B,L
    # construct a list of indices
    indices  = zeros(Int64, numBonds(lattice))
    list_len = zeros(Int64, numSites(lattice))
    # give each bond an index
    for b in 1:numBonds(lattice)
        list_len[from(bond(lattice,b))] += 1
        indices[b] = list_len[from(bond(lattice,b))]
    end
    # create all lists
    organized_bonds = Vector{Vector{B}}(undef, numSites(lattice))
    for s in 1:numSites(lattice)
        organized_bonds[s] = Vector{B}(undef, list_len[s])
    end
    # insert all bonds
    for b in 1:numBonds(lattice)
        organized_bonds[from(bond(lattice,b))][indices[b]] = bond(lattice,b)
    end
    # return the list
    return organized_bonds
end
# get an organized bond list (organized by 'to')
"""
    function organizedBondsTo(
            lattice :: AbstractLattice{S,B,U}
        ) :: Vector{Vector{B}} where {...}

Function for obtaining an organized version of the list of bonds of a passed `AbstractLattice` object `lattice`.
Returns a nested list of `AbstractBond` objects of type `B` as an object of type `Vector{Vector{B}}`,
in which the element `i` is a list of all bonds pointing to site `i`.

This function does not have to be overwritten by a concrete type as it is implemented
on the level of abstract types and interface functions.

# Examples

```julia-REPL
julia> organizedBondsTo(lattice)
2-element Array{Array{Bond{Int64,2},1},1}:
 [Bond{Int64,2} 2-->1 @(0, 0): 1, Bond{Int64,2} 2-->1 @(1, 0): 1, Bond{Int64,2} 2-->1 @(0, 1): 1]
 [Bond{Int64,2} 1-->2 @(0, 0): 1, Bond{Int64,2} 1-->2 @(-1, 0): 1, Bond{Int64,2} 1-->2 @(0, -1): 1]
 ...
```
"""
function organizedBondsTo(
            lattice :: L
        ) :: Vector{Vector{B}} where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # temporary fix for dispatch behavior: name all types explicitly
    D,N,LS,LB,U,S,B,L
    # construct a list of indices
    indices  = zeros(Int64, numBonds(lattice))
    list_len = zeros(Int64, numSites(lattice))
    # give each bond an index
    for b in 1:numBonds(lattice)
        list_len[to(bond(lattice,b))] += 1
        indices[b] = list_len[to(bond(lattice,b))]
    end
    # create all lists
    organized_bonds = Vector{Vector{B}}(undef, numSites(lattice))
    for s in 1:numSites(lattice)
        organized_bonds[s] = Vector{B}(undef, list_len[s])
    end
    # insert all bonds
    for b in 1:numBonds(lattice)
        organized_bonds[to(bond(lattice,b))][indices[b]] = bond(lattice,b)
    end
    # return the list
    return organized_bonds
end

# export organized bond function
export organizedBondsFrom, organizedBondsTo

# specific Bravais lattices

# a1
"""
    function a1(lattice ::AbstractLattice{S,B,U}) ::Vector{Float64} where {...}

Function for directly obtaining the first Bravais lattice vector of a passed `AbstractLattice` object `lattice`.
Returns the vector as an object of type `Vector{Float64}`.

This function does not have to be overwritten by a concrete type as it is implemented
as a simple wrapper around `latticeVectors(lattice)`.

# Examples

```julia-REPL
julia> a1(lattice)
[1,0,0]
```
"""
function a1(
            lattice :: L
        ) :: Vector{Float64} where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # return the first entry in the lattice vectors list
    return latticeVectors(lattice)[1]
end

# a2
"""
    function a2(lattice ::AbstractLattice{S,B,U}) ::Vector{Float64} where {...}

Function for directly obtaining the second Bravais lattice vector of a passed `AbstractLattice` object `lattice`.
Returns the vector as an object of type `Vector{Float64}`.

This function does not have to be overwritten by a concrete type as it is implemented
as a simple wrapper around `latticeVectors(lattice)`.

# Examples

```julia-REPL
julia> a2(lattice)
[0,1,0]
```
"""
function a2(
            lattice :: L
        ) :: Vector{Float64} where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # return the second entry in the lattice vectors list
    return latticeVectors(lattice)[2]
end

# a3
"""
    function a3(lattice ::AbstractLattice{S,B,U}) ::Vector{Float64} where {...}

Function for directly obtaining the third Bravais lattice vector of a passed `AbstractLattice` object `lattice`.
Returns the vector as an object of type `Vector{Float64}`.

This function does not have to be overwritten by a concrete type as it is implemented
as a simple wrapper around `latticeVectors(lattice)`.

# Examples

```julia-REPL
julia> a3(lattice)
[0,0,1]
```
"""
function a3(
            lattice :: L
        ) :: Vector{Float64} where {D,N,LS,LB,U,S<:AbstractSite{LS,D},B<:AbstractBond{LB,N},L<:AbstractLattice{S,B,U}}

    # return the third entry in the lattice vectors list
    return latticeVectors(lattice)[3]
end

# export the Bravais lattice interfaces
export a1, a2, a3

# Syntax for directly obtaining a connecting vector

# Fallback (error) for non-fitting pairs & DOCTSTRING
"""
    function vector(b::AbstractBond, l::AbstractLattice) ::Vector{Float64} where {...}

Function for directly obtaining the vector that describes the bond `b` in real space.
Lattice object `l` is necessary to pass since it contains site and lattice vector information.

# Examples

```julia-REPL
julia> vector(newBond(Bond{String,3}, 1,1, "mybond", (1,0,0)), mylattice)
[1.0, 0.0, 0.0]
```
"""
function vector(
            bond    :: B,
            lattice :: LA
        ) :: Vector{Float64} where {N,L,B<:AbstractBond{L,N}, SU,BU,U<:AbstractUnitcell{SU,BU}, SL,LL,NL,BL<:AbstractBond{LL,NL},LA<:AbstractLattice{SL,BL,U}}

    # throw an error
    @error "unitcell and bond are not fitting"
end

# 0d
function vector(
            bond    :: B,
            lattice :: LA
        ) :: Vector{Float64} where {L,B<:AbstractBond{L,0}, SU,BU,U<:AbstractUnitcell{SU,BU}, SL,LL,BL<:AbstractBond{LL,0},LA<:AbstractLattice{SL,BL,U}}

    # return the offset vector
    return (
        point(site(lattice,to(bond))) .- point(site(lattice,from(bond)))
    )
end

# 1d
function vector(
            bond    :: B,
            lattice :: LA
        ) :: Vector{Float64} where {L,B<:AbstractBond{L,1}, SU,BU,U<:AbstractUnitcell{SU,BU}, SL,LL,BL<:AbstractBond{LL,1},LA<:AbstractLattice{SL,BL,U}}

    # return the offset vector
    return (
        point(site(lattice,to(bond))) .- point(site(lattice,from(bond))) .+
        wrap(bond)[1].*a1(lattice)
    )
end

# 2d
function vector(
            bond    :: B,
            lattice :: LA
        ) :: Vector{Float64} where {L,B<:AbstractBond{L,2}, SU,BU,U<:AbstractUnitcell{SU,BU}, SL,LL,BL<:AbstractBond{LL,2},LA<:AbstractLattice{SL,BL,U}}

    # return the offset vector
    return (
        point(site(lattice,to(bond))) .- point(site(lattice,from(bond))) .+
        wrap(bond)[1].*a1(lattice) .+ wrap(bond)[2].*a2(lattice)
    )
end

# 3d
function vector(
            bond    :: B,
            lattice :: LA
        ) :: Vector{Float64} where {L,B<:AbstractBond{L,3}, SU,BU,U<:AbstractUnitcell{SU,BU}, SL,LL,BL<:AbstractBond{LL,3},LA<:AbstractLattice{SL,BL,U}}

    # return the offset vector
    return (
        point(site(lattice,to(bond))) .- point(site(lattice,from(bond))) .+
        wrap(bond)[1].*a1(lattice) .+ wrap(bond)[2].*a2(lattice) .+ wrap(bond)[3].*a3(lattice)
    )
end

# Nd
function vector(
            bond    :: B,
            lattice :: LA
        ) :: Vector{Float64} where {N,L,B<:AbstractBond{L,N}, SU,BU,U<:AbstractUnitcell{SU,BU}, SL,LL,BL<:AbstractBond{LL,N},LA<:AbstractLattice{SL,BL,U}}

    # build the offset vector
    v = point(site(lattice,to(bond))) .- point(site(lattice,from(bond)))
    for i in 1:N
        v .+= wrap(bond)[i].*latticeVectors(lattice)[i]
    end
    # return the offset vector
    return v
end

# export the function
export vector

ext: jl


text:
@testset "Default continuous post-operator" begin
    prob, dt = motor_homog()
    sol = solve(prob, tspan=dt);
    @test sol.alg isa GLGM06
    @test sol.alg.static == Val{false}()
    @test setrep(sol) == Zonotope{Float64,Array{Float64,1},Array{Float64,2}}

    # static case
    sol = solve(prob, tspan=dt, static=true);
    @test sol.alg isa GLGM06
    @test sol.alg.static == Val{true}()
    @test setrep(sol) == Zonotope{Float64,SArray{Tuple{8},Float64,1,8},SArray{Tuple{8,8},Float64,2,64}}

    # if the static kwarg is passed outside the algorithm => it is ignored
    sol = solve(prob, tspan=dt, alg=GLGM06(δ=1e-2), static=true);
    @test setrep(sol) == Zonotope{Float64,Array{Float64,1},Array{Float64,2}}
end

@testset "Flowpipe interface" begin
    p = @ivp(x' = -x, x(0) ∈ 0..1)
    δ = 0.1
    sol = solve(p, tspan=(0.0, 1.0), GLGM06(δ=δ))
    F = flowpipe(sol)

    # iteration
    @test set(F, 1) == set(F[1])
    @test set(F, length(F)) == set(F[end])

    # time span methods
    @test _isapprox(tspan(sol), 0.0 .. 1.0)
    @test tstart(F) == 0.0
    @test tend(F) ≈ 1.0
    @test tstart(F[1]) == 0.0
    @test tend(F[1]) ≈ 0.1
    @test tstart(F[end]) ≈ 0.9
    @test tend(F[end]) ≈ 1.0

    # time span for flowpipe slices
    @test tstart(F[1:3]) ≈ 0.0
    @test tend(F[1:3]) ≈ 3δ
    @test tspan(F[1:3]) ≈ 0.0 .. 3δ

    @test tstart(F, 1:3) ≈ 0.0  # same, more efficient
    @test tend(F, 1:3) ≈ 3δ
    @test tspan(F, 1:3) ≈ 0.0 .. 3δ

    @test tstart(sol[1:3]) ≈ 0.0
    @test tend(sol[1:3]) ≈ 3δ
    @test tspan(sol[1:3]) ≈ 0.0 .. 3δ

    # set representation
    @test setrep(F) <: Zonotope
    N = Float64
    ZT = Zonotope{N, Vector{N}, Matrix{N}}
    @test setrep(F) == ZT
    @test rsetrep(F) == ReachSet{N, ZT}

    # callable behavior
    @test F(0..1) == F[1:end]
    @test F(0.05) == F[1]
    @test F(1.0) == F[end]
    @test F(0.05 .. 0.15) == F[1:2]

    # time interval *not* strictly contained in flowpipe returns a subset
    @test tspan(F(0.05 .. 1.05)) == tspan(F)

    # time interval totally outside the flowpipe returns an error
    @test_throws ArgumentError F(2 .. 3)

    # test that in the border of the time transition we get two reachsets
    F = flowpipe(sol)
    @test F(0.1) == F[1:2]

    # dimension
    @test dim(F) == 1

    # different ways to input the time span or the time horizon
    sol = solve(p, tspan=(0.0, 1.0))
    sol = solve(p, (0.0, 1.0))
    sol = solve(p, tspan=[0.0, 1.0])
    sol = solve(p, [0.0, 1.0])
    sol = solve(p, T=1.0)
    sol = solve(p, 1.0)
end

@testset "Solution interface: initial states" begin
    # interval initial condition
    p = @ivp(x' = -x, x(0) ∈ 0..1)
    solve(p, T=1.0)

    # interval initial condition
    p = @ivp(x' = -x, x(0) ∈ Interval(0, 1))
    solve(p, T=1.0)

    # deterministic initial condition, scalar for one-dimensional matrix (TODO)
    p = InitialValueProblem(@system(x' = -x), 0.5)
    solve(p, T=1.0)

    # deterministic initial condition, vector
    p = InitialValueProblem(@system(x' = -x), [0.5])
    solve(p, T=1.0)
end

@testset "Solution interface: time span" begin
    p = @ivp(x' = -x, x(0) ∈ 0..1)
    Δt = 0.0 .. 2.0

    # only time horizon given
    sol = solve(p, T=2.0)
    @test _isapprox(tspan(sol), Δt)

    # both time horizon and time span given => error
    @test_throws ArgumentError solve(p, T=1.0, tspan=(0.0, 2.0))

    # time span given as a tuple
    sol = solve(p, tspan=(0.0, 2.0))
    @test _isapprox(tspan(sol), Δt)

    # time span given as an interval
    sol = solve(p, tspan=0.0 .. 2.0)
    @test _isapprox(tspan(sol), Δt)

    # time span given as a LazySets interval
    sol = solve(p, tspan=Interval(0.0, 2.0))
    @test _isapprox(tspan(sol), Δt)

    # time span given as a vector
    sol = solve(p, tspan=[0.0, 2.0])
    @test _isapprox(tspan(sol), Δt)
end

@testset "Concrete projection" begin
    prob, tspan = motor_homog()
    sol = solve(prob, tspan=tspan, GLGM06(δ=0.01), static=false)

    project(sol, (1, 3))
    project(sol, [1, 3])
    project(sol, vars=[1, 3])
    project(sol, vars=(1, 3))

    F = flowpipe(sol)
    project(F, (1, 3))
    project(F, [1, 3])
    project(F, vars=[1, 3])
    project(F, vars=(1, 3))

    R = sol[end]
    project(R, (1, 3))
    project(R, [1, 3])
    project(R, vars=(1, 3))
    project(R, vars=[1, 3])

    # TODO concrete projection of sets with static array fields
end

# TODO:
# eachindex(F)

#=
TESTS

using LazySets, Revise, ReachabilityAnalysis
N = Float64
X = Hyperrectangle(N[0, 0], N[1, 1])
R = ReachSet(X, 0 .. 1)
set(R) ==
tstart(R) == 0.0
tend(R) == 1.0
tspan(R) == 1.0
dim(R) == 2
overapproximate(project(X, [1]), Interval) == Interval(-1, 1)
=#


text:
using Grisu

max_double = v = 1.7976931348623157e308
function perf(n,v=max_double)
    tic()
    for i = 1:n
        l,p,b,s = Grisu.grisu(v,Grisu.SHORTEST,0)
    end
    a = toq()
    tic()
    for i = 1:n
        l,b,s = Base.Grisu.grisu(v,Base.Grisu.SHORTEST,0)
    end
    b = toq()
    println("Shortest:\n  Native Julia: $a\n  Base.Grisu: $b")
end

perf(1000000,1.0)


text:
module GMHPhotoReceptor

import Compat: view
import Distributions
import JLD
import GeneralizedMetropolisHastings

import Base:
    show

import GeneralizedMetropolisHastings:
    AbstractModel,
    trait,traitvalue,traittype,_trait,_traitname,_policy,
    noise,numvalues,datavalues,dataindex,
    parameters,_parameters,_model,evaluate!,
    noisemodel,measurements

export
    photonsequence,lightinducedcurrent

include("models/util.jl")
include("models/datafunctions.jl")
include("models/PhotoReceptor.jl")
include("models/PhotoReceptorPolicy.jl")
include("models/PhotoReceptorModel.jl")
include("models/lightinducedcurrent.jl")

end


text:
# use Julia's libopenblas instead of system's liblapack and libblas?
const JULIA_LAPACK = false
const suffix       = JULIA_LAPACK ? ".64" : ""
const version      = "6.1.1"
const libname      = "libcsdp$suffix.$(Libdl.dlext)"
const csdpversion  = "Csdp-$version"
const download_url =
    "http://www.coin-or.org/download/source/Csdp/Csdp-$version.tgz"

patchf      = Pkg.dir("CSDP", "deps", "src$suffix", "debug-mat.c")
srcdir      = Pkg.dir("CSDP", "deps", "src$suffix", csdpversion, "lib")
prefix      = Pkg.dir("CSDP", "deps", "usr")
builddir    = Pkg.dir("CSDP", "deps", "build$suffix")
cflags      = ["-I$srcdir/../include",  "-DNOSHORTS", "-g"]
libdir      = joinpath(prefix, @static is_windows() ? "bin" : "lib/")
dlpath      = joinpath(libdir, libname)
Makefile    = joinpath(srcdir, "Makefile")
CC          = get(ENV, "CCOMPILER", "gcc")

"""Name of the current Git branch"""
git_branch() = chomp(readstring(`git rev-parse --abbrev-ref HEAD`))


text:
# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder

name = "cryptopp"
version = v"8.2"

# Collection of sources required to build CFITSIO
sources = [
    "https://github.com/weidai11/cryptopp.git" =>
    "9dcc26c58213abb8351fbb1b2a7a1d2c667366e4",
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/cryptopp
make -j${nproc} dynamic
make -j${nproc} install PREFIX=${prefix}
"""

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
platforms = supported_platforms()

# ARM hits internal compiler errors
platforms = filter(p -> arch(p) != :armv7l, platforms)

# The products that we will ensure are always built
products(prefix) = [
    LibraryProduct(prefix, "libcryptopp", :libcryptopp)
]

# Dependencies that must be installed before this package can be built
dependencies = [
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies)


text:
#Visualization

#Colormap
#using Color
#cm = Uint32[Color.convert(Color.RGB24,c) for c in flipud(Color.colormap("RdBu"))]
#cm = Uint32[Color.convert(Color.RGB24,c) for c in Color.colormap("RdBu")]

#Visualize common matrix
function visualize_M(data::AbstractMatrix,
                     x, y;
                     g=1,
                     title="",
                     dmin=0.0,
                     dmax=:find)

    ny, nx = size(data)
    xs = g +1
    xe = nx - g + 1
    ye = ny - g + 1

    xmin = x[xs]
    xmax = x[xe]
    ymin =  y[xs]
    ymax =  y[ye]

    hdata = data[xs:ye, xs:xe]
    xs = [string("x",i) for i = xe]
    ys = [string("y",i) for i = ye]
    #p = FramedPlot()

#    #look or set min and max values
#    if dmin == :find
#        hmin = minimum(hdata)
#    elseif isa(dmin, Real)
#        hmin = dmin
#    end
#
#    if dmax == :find
#        hmax = maximum(hdata)
#    elseif isa(dmax, Real)
#        hmax = dmax
#    end
#
#    clims = (minimum(hdata), maximum(hdata))

    #make image
		#cm = Winston.colormap("jet", 10)
    #img = Winston.data2rgb(hdata, clims, cm)
	  #img = Winston.imagesc(hdata)
    #add(p, Image((xmin, xmax), (ymin, ymax), img;))
    #setattr(p, xrange=(xmin, xmax))
    #setattr(p, yrange=(ymin, ymax))
    #setattr(p, title=title)
		p = heatmap(hdata)

    return p
end

function visualize(hyd::data2d)

    #density
    p1 = visualize_M(hyd.rho,
                     hyd.x, hyd.y,
                     g=3,
                     title="density \\rho",
                     dmin = :find,
                     dmax = :find)

    #pressure
    p2 = visualize_M(hyd.press,
                     hyd.x, hyd.y,
                     g=3,
                     title="pressure p",
                     dmin = 0.0,
                     dmax = :find)

    #velocity
    hdata = sqrt.(hyd.velx.^2.0 .+ hyd.vely.^2.0)
    #hdata = hyd.velx[xs:ye, xs:xe]

    p3 = visualize_M(hdata,
                     hyd.x, hyd.y,
                     g=3,
                     title="velocity (u^2 + v^2)^{1/2}",
                     dmin = :find,
                     dmax = :find)

    #internal energy
    p4 = visualize_M(hyd.press,
                     hyd.x, hyd.y,
                     g=3,
                     title="internal energy ε",
                     dmin = 0.0,
                     dmax = :find)

    ######
    #additional window for 1-dim figs

    #diagonal slice
    xy = Float64[sqrt(hyd.x[i]^2+hyd.y[i]^2.0) for i = 1:hyd.nx]
    rhoxy = Float64[hyd.rho[hyd.nx-i+1,i] for i = hyd.nx:-1:1]
    velxy = Float64[sqrt(hyd.velx[hyd.nx-i+1,i]^2.0 + hyd.velx[hyd.nx-i+1,i]^2.0) for i = hyd.nx:-1:1]

    velxxy = Float64[hyd.velx[hyd.nx-i+1,i] for i = hyd.nx:-1:1]
    velyxy = Float64[hyd.vely[hyd.nx-i+1,i] for i = hyd.nx:-1:1]

    pressxy = Float64[hyd.press[hyd.nx-i+1,i] for i = hyd.nx:-1:1]
    epsxy = Float64[hyd.eps[hyd.nx-i+1,i] for i = hyd.nx:-1:1]

    p11 = plot(xy, rhoxy, linecolor=:red,title="diagonal slice", label="rho")
    p11 = plot!(xy, abs.(velxxy), linecolor=:blue, label="velx")
    p11 = plot!(xy, abs.(velyxy), linecolor=:black, label="vely")
    p11 = plot!(xy, pressxy, linecolor=:green, label="pres")
    #p11 = oplot(hyd.y, epsxy, "k")

    #middle slice
    mid = Int(hyd.nx/2)
    p12 = plot(hyd.y, hyd.rho[:,mid], linecolor=:red,title="middle slice")
    p12 = plot!(hyd.y, hyd.vely[:,mid], linecolor=:blue)
    p12 = plot!(hyd.y, hyd.press[:,mid], linecolor=:green)
    #p12 = oplot(hyd.y, hyd.eps[:,mid], "k")

    #t = Table(2,3)
    #t[1,1] = p1
    #t[1,2] = p2
    #t[2,1] = p3
    #t[2,2] = p4
    #
    #t[1,3] = p11
    #t[2,3] = p12

    #display(p11)
    savefig(p1,"p1.png")
    savefig(p2,"p2.png")
    savefig(p3,"p3.png")
    savefig(p4,"p4.png")
    savefig(p11,"p11.png")
    savefig(p12,"p12.png")

end

max_stars_repo_name: gzahl/hydro

max_issues_repo_name: gzahl/hydro

max_forks_repo_name: gzahl/hydro


text:
# # ControlSystems using MonteCarloMeasurements
# In this example, we will create a transfer function with uncretain coefficients, and use it to calculate bode diagrams and simulate the system.
using ControlSystems, MonteCarloMeasurements, StatsPlots
using Test, LinearAlgebra, Statistics
import MonteCarloMeasurements: ±,⊗
unsafe_comparisons(true, verbose=false) # This file requires mean comparisons for displaying transfer functions in text form as well as for discretizing a LTIsystem
default(size=(2000,1200))

p = 1 ± 0.1
ζ = 0.3 ± 0.05
ω = 1 ± 0.1;
# Alternative definitions of the uncertain parameters are given by

# `p,ζ,ω = outer_product([Normal(1,0.1),Normal(0.3,0.05),Normal(1,0.1)], 2_000)`

# `p,ζ,ω = [1,0.3,1] ⊗ [0.1, 0.05, 0.1] # Defaults to N≈100_000`
G = tf([p*ω], [1, 2ζ*ω, ω^2])

dc = dcgain(G)[]
density(dc)
#
w = exp10.(LinRange(-0.7,0.7,100))
@time mag, phase = bode(G,w) .|> vec;

# ## Bode plot
scales = (yscale=:log10, xscale=:log10)
errorbarplot(w,mag,0.00; scales..., layout=3, subplot=1, lab="q=$(0.00)")
errorbarplot!(w,mag,0.01, subplot=1, lab="q=$(0.01)")
errorbarplot!(w,mag,0.1, subplot=1, lab="q=$(0.1)", legend=:bottomleft, linewidth=3)
mcplot!(w,mag; scales..., alpha=0.2, subplot=2, c=:black)
ribbonplot!(w,mag, 2; yscale=:log10, xscale=:log10, alpha=0.2, subplot=3)
# A ribbonplot is not always suitable for plots with logarithmic scales.

# ## Nyquist plot
# We can visualize the uncertainty in the Nyquist plot in a number of different ways, here are two examples
reny,imny,wny = nyquist(G,w) .|> vec
plot(reny, imny, 0.005, lab="Nyquist curve 99%")
plot!(reny, imny, 0.025, lab="Nyquist curve 95%", ylims=(-4,0.2), xlims=(-2,2), legend=:bottomright)
vline!([-1], l=(:dash, :red), primary=false)
vline!([0], l=(:dash, :black), primary=false)
hline!([0], l=(:dash, :black), primary=false)
#
plot(reny, imny, lab="Nyquist curve 95%", ylims=(-4,0.2), xlims=(-2,2), legend=:bottomright, points=true)
vline!([-1], l=(:dash, :red), primary=false)
vline!([0], l=(:dash, :black), primary=false)
hline!([0], l=(:dash, :black), primary=false)
#

# ## Time Simulations
# We start by sampling the system to obtain a discrete-time model.
@unsafe Pd = c2d(G, 0.1)
# We then simulate an plot the results
y,t,x = step(Pd, 20)
errorbarplot(t,y[:], 0.00, layout=3, subplot=1, alpha=0.5)
errorbarplot!(t,y[:], 0.05, subplot=1, alpha=0.5)
errorbarplot!(t,y[:], 0.1, subplot=1, alpha=0.5)
mcplot!(t,y[:], subplot=2, l=(:black, 0.02))
ribbonplot!(t,y[:], subplot=3)

# # System identification
using MonteCarloMeasurements, ControlSystemIdentification, ControlSystems
using Random, LinearAlgebra
# We start by creating a system to use as the subject of identification and some data to use for identification
N  = 500      # Number of time steps
t  = 1:N
Δt = 1        # Sample time
u  = randn(N) # A random control input
G  = tf(0.8, [1,-0.9], 1) # An interesting system
y  = lsim(G,u,t)[1][:]
yn = y + randn(size(y));

# Validation data
uv  = randn(N)
yv  = lsim(G,uv,t)[1][:]
ynv = yv + randn(size(yv));
# Identification parameters
na,nb,nc = 2,1,1

Gls,Σls     = arx(Δt,yn,u,na,nb) # Regular least-squares estimation
Gtls,Σtls   = arx(Δt,yn,u,na,nb, estimator=tls) # Total least-squares estimation
Gwtls,Σwtls = arx(Δt,yn,u,na,nb, estimator=wtls_estimator(y,na,nb)) # Weighted Total least-squares estimation

# Next, we create transfer functions with uncertainty, the first argument is the particle type we want to use
Gls = TransferFunction(Particles, Gls, Σls)
Gtls = TransferFunction(Particles, Gtls, Σtls)
Gwtls = TransferFunction(Particles, Gwtls, Σwtls)

# We now calculate and plot the Bode diagrams for the uncertain transfer functions
scales = (yscale=:log10, xscale=:log10)
w = exp10.(LinRange(-3,log10(π),30))
magG = bode(G,w)[1][:]
mag = bode(Gls,w)[1][:]
errorbarplot(w,mag,0.01; scales..., layout=3, subplot=1, lab="ls")
# plot(w,mag; scales..., layout=3, subplot=1, lab="ls") # src
plot!(w,magG, subplot=1)
mag = bode(Gtls,w)[1][:]
errorbarplot!(w,mag,0.01; scales..., subplot=2, lab="qtls")
# plot!(w,mag; scales..., subplot=2, lab="qtls") # src
plot!(w,magG, subplot=2)
mag = bode(Gwtls,w)[1][:]
errorbarplot!(w,mag,0.01; scales..., subplot=3, lab="wtls")
# plot!(w,mag; scales..., subplot=3, lab="wtls") # src
plot!(w,magG, subplot=3)

## bode benchmark =========================================
using BenchmarkTools, Printf
using MonteCarloMeasurements: ∓
p = 1 ± 0.1
ζ = 0.3 ± 0.1
ω = 1 ± 0.1
G = tf([p*ω], [1, 2ζ*ω, ω^2])
t1 = @belapsed bode($G,$w)
p = 1
ζ = 0.3
ω = 1
G = tf([p*ω], [1, 2ζ*ω, ω^2])
t2 = @belapsed bode($G,$w)
using Measurements
p = Measurements.:(±)(1, 0.1)
ζ = Measurements.:(±)(0.3, 0.1)
ω = Measurements.:(±)(1, 0.1)
G = tf([p*ω], [1, 2ζ*ω, ω^2])
t3 = @belapsed bode($G,$w)

p = 1 ∓ 0.1
ζ = 0.3 ∓ 0.1
ω = 1 ∓ 0.1
G = tf([p*ω], [1, 2ζ*ω, ω^2])
t4 = @belapsed bode($G,$w)

p,ζ,ω = StaticParticles(sigmapoints([1, 0.3, 1], 0.1^2))
G = tf([p*ω], [1, 2ζ*ω, ω^2])
t5 = @belapsed bode($G,$w)
##
@printf("
| Benchmark | Result |
|-----------|--------|
| Time with 500 particles | %16.4fms |
| Time with regular floating point | %7.4fms |
| Time with Measurements | %17.4fms |
| Time with 100 static part. | %13.4fms |
| Time with static sigmapoints. | %10.4fms |
| 500×floating point time | %16.4fms |
| Speedup factor vs. Manual | %11.1fx |
| Slowdown factor vs. Measurements | %4.1fx |
| Slowdown static vs. Measurements | %4.1fx |
| Slowdown sigma vs. Measurements | %5.1fx|\n",
1000*t1, 1000*t2, 1000*t3, 1000*t4, 1000*t5, 1000*500t2, 500t2/t1, t1/t3, t4/t3, t5/t3) #src


text:
"""
	sparsegrid( D::Int, k::Int, f::Function=gausshermite; sym::Bool=true )

Computation of sparse grid nodes and the associated weights

- `D` : Dimension of integrant
- `k` : Order of quadrature rule
- `f` : Function generating 1D nodes and weights -- in that order -- for an integer input
- `sym` : Boolean variable determining if the nodes should be symmetrized

If the nodes are supposed to be symmetric (as those in the Gauss-Hermite rule),
they should be so in order to correctly identify multiply occuring nodes in the
union of sparse sets
"""
function sparsegrid(D::Integer, order::Integer, f::Function=gausshermite; sym::Bool=true)
	# Final nodes and weights in D dimensions
	nodes = Array{Float64}(undef, D, 0)
	weights = Array{Float64}(undef, 0)

	# Compute univariate nodes and weights
	nodes1D = Vector{Vector{Float64}}(undef, order)
	weights1D = similar(nodes1D)

	for k in 1:order
		nodes1D[k], weights1D[k] = f(k)

		if sym
			symmetrize!(nodes1D[k])
		end
	end

	nodes, weights = sparsegrid(D, nodes1D, weights1D)

	return nodes, weights
end

# Computation of sparse grid nodes and the associated weights
# from collection of one-dimensional nodes and weights

function sparsegrid(D::Integer, nodes1D::Vector{Vector{Float64}}, weights1D::Vector{Vector{Float64}})
	order = length(nodes1D)

	mink = max(0, order - D)
	maxk = order - 1
	all_alpha_lists = [listNdq(D, D + k) for k in mink:maxk]

	number_of_nodes = map(x -> sum(prod.(x)), all_alpha_lists) |> sum

	# Final nodes and weights in D dimensions
	nodes = Vector{Vector{Float64}}(undef, 0)
	sizehint!(nodes, number_of_nodes)

	weights = Array{Float64}(undef, 0)
	sizehint!(weights, number_of_nodes)

	for (alpha_idx, k) in enumerate(mink:maxk)
		this_alpha_list = all_alpha_lists[alpha_idx]

		for alpha in this_alpha_list
			# The nodes and weights for this alpha mixture
			N = [nodes1D[index] for index in alpha]
			W = [weights1D[index] for index in alpha]

			# Compute all the possible combinations of D-dimensional nodes
			combN = combvec(N)

			# Compute the associated weights
			cw = combvec(W)
			combW = (-1)^(maxk - k) * binomial(D - 1, D + k - order) * map(prod, cw)

			append!(nodes, combN)
			append!(weights, combW)
		end
	end

	unique_nodes, combined_weights = uniquenodes(nodes, weights)
	return unique_nodes, combined_weights
end

"""
To correctly reduce "overlapping" nodes the middle node in an uneven number must be exactly zero
"""
function symmetrize!(nodes::Vector{Float64})
	N = length(nodes)

	if isodd(N)
		midpoint = div(N - 1, 2)
		nodes[midpoint + 1] = 0.0
	else
		midpoint = div(N, 2)
	end

	for n in 1:midpoint
		nodes[n] = -nodes[N + 1 - n]
	end
end

# ------------------------------------------------------------
# N^D_q = \{ i \in N^D : sum(i) = q \}

"""
	listNdq(D::Int, q::Int)

Find elements in the set
```math
N_q^D = {i in N^D : sum(i) = q}
```

The algorithm and the formula for computing the number of elements in this set is found in the thesis mentioned in the README
"""
function listNdq(D::Integer, q::Integer)
	if q < D
		error("q must be larger than D")
	end

	M = binomial(q - 1, D - 1)
	L = [ones(Int, D) for _ in 1:M]

	k = ones(Int, D)
	maxk = q - D + 1
	khat = maxk*ones(Int, D)

	p = 1
	count = 0

	while k[D] < maxk
		k[p] += 1

		if k[p] > khat[p]
			k[p] = 1
			p += 1
		else
			for i in 1:p - 1
				khat[i] = khat[p] - k[p] + 1
			end

			k[1] = khat[1]
			p = 1

			count += 1
			copy!(L[count], k)
		end
	end

	return L
end

"""
	combvec(vecs)

Counterpart of Matlab's combvec:
Creates all combinations of vectors in `vecs`, an array of vectors.
"""
function combvec(vecs::Vector{Vector{T}}) where T
	# Construct all Cartesian combinations of elements in vecs
	P = Iterators.product(vecs...)
	y = collect.(vec(collect(P)))
	return y
end

"""
	uniquenodes(nodes, weights)

Find unique nodes and sum the weights of identical nodes
"""
function uniquenodes(nodes, weights)
	# Sort nodes and weights according to nodes
	perm = sortperm(nodes)
	sorted_nodes = nodes[perm]
	perm_weights = weights[perm]

	unique_nodes = similar(nodes, 0)
	N = length(nodes)

	indices_to_keep = [1]
	sizehint!(indices_to_keep, N)
	last_index_to_keep = 1

	for n in 2:N
		if sorted_nodes[last_index_to_keep] == sorted_nodes[n]
			perm_weights[last_index_to_keep] += perm_weights[n]
		else
			last_index_to_keep = n
			push!(indices_to_keep, n)
		end
	end

	unique_nodes = sorted_nodes[indices_to_keep]
	collected_weights = perm_weights[indices_to_keep]

	return unique_nodes, collected_weights
end

# ------------------------------------------------------------
# Compute tensor product grid

"""
	tensorgrid( N::Vector, W::Vector, D::Int )

	Compute tensor grid of `N` nodes and corresponding weights `W` for `D` dimensions.
"""
function tensorgrid(N::Vector, W::Vector, D::Integer)
	NN = repeat([N], outer=[D; 1])
	WW = repeat([W], outer=[D; 1])

	tensorN = combvec(NN[:])
	tensorW = vec(prod(combvec(WW[:]), 1))

	return tensorN, tensorW
end

function tensorgrid(D::Integer, order::Integer, f::Function=gausshermite)
	N, W = f(order)

	tensorN, tensorW = tensorgrid(N, W, D)

	return tensorN, tensorW
end


text:
export genplots, getexamples, runplotgen

""" results = runplotgen()
Run full generation of the plots needed for the tests in ControlSystems.jl
"""
function runplotgen()
  funcs, refs, eps = getexamples()
  genplots(funcs, refs, eps=eps)
end

""" results = genplots(funcs, refs; eps, kwargs...)
Generate the plots needed for the tests in ControlSystems.jl
"""
function genplots(funcs, refs; eps=0.01*ones(length(refs)), kwargs...)
    ENV["MPLBACKEND"] = "Agg"
    results = Array{VisualRegressionTests.VisualTestResult,1}(undef, length(refs))
    #Run/generate tests
    for (i,ref) in enumerate(refs)
        testf(fn) = png(funcs[i](), fn)
        results[i] = test_images(VisualTest(testf, ref); tol=eps[i], kwargs...)
    end
    results
end

"""funcs, refs, eps = getexamples()
Get the example functions and locations of reference plots needed for the tests in ControlSystems.jl
"""
function getexamples()
    tf1 = tf([1],[1,1])
    tf2 = tf([1/5,2],[1,1,1])
    sys = [tf1 tf2]
    sysss = ss([-1 2; 0 1], [1 0; 1 1], [1 0; 0 1], [0.1 0; 0 -0.2])

    ws = 10.0 .^range(-2,stop=2,length=200)
    ts = 0:0.01:5
    bodegen() = begin
      setPlotScale("dB")
      bodeplot(sys,ws)
    end
    nyquistgen() = nyquistplot(sysss,ws)
    sigmagen() = sigmaplot(sysss,ws)
    #Only siso for now
    nicholsgen() = nicholsplot(tf1,ws)

    stepgen() = stepplot(sys, ts[end], ts[2]-ts[1], l=(:dash, 4))
    impulsegen() = impulseplot(sys, ts[end], ts[2]-ts[1], l=:blue)
    L = lqr(sysss.A, sysss.B, [1 0; 0 1], [1 0; 0 1])
    lsimgen() = lsimplot(sysss, (x,i)->-L*x, ts, [1;2])

    margingen() = marginplot([tf1, tf2], ws)
    gangoffourgen() = begin
      setPlotScale("log10");
      gangoffourplot(tf1, [tf(1), tf(5)])
    end
    pzmapgen() = pzmap(tf2, xlims=(-15,5))
    rlocusgen() = rlocusplot(tf2)

    plotsdir = joinpath(dirname(pathof(ControlExamplePlots)), "..", "src", "figures")
    refs = ["bode.png", "nyquist.png", "sigma.png", "nichols.png", "step.png",
            "impulse.png", "lsim.png", "margin.png", "gangoffour.png", "pzmap.png", "rlocus.png"]
    funcs = [bodegen, nyquistgen, sigmagen, nicholsgen, stepgen,
             impulsegen, lsimgen, margingen, gangoffourgen, pzmapgen, rlocusgen]
    eps = 0.001*ones(length(refs));
    funcs, map(s -> joinpath(plotsdir,s), refs), eps
end


text:
function Base.show(io::IO, mime::MIME"text/plain", ep::EndPoint; extra_spaces::Bool = false)
  spaces = extra_spaces ? "    " : ""

  println(io, ":$(ep.direction) Endpoint with status :$(ep.status)")
  println(io, spaces*"  value: $(ep.value)")
  println(io, spaces*"  profilePoints count: $(length(ep.profilePoints))")
  println(io, spaces*"  status: :$(ep.status)")
  println(io, spaces*"  direction: :$(ep.direction)")
  println(io, spaces*"  counter: $(ep.counter)")
  println(io, spaces*"  supreme: $(ep.supreme)")
end

function Base.show(io::IO, mime::MIME"text/plain", pe::ParamInterval)
  left_interval_point = if pe.result[1].status === :BORDER_FOUND_BY_SCAN_TOL || pe.result[1].status === :BORDER_FOUND_BY_LOSS_TOL
    round(pe.result[1].value, sigdigits=4)
  elseif pe.result[1].status === :SCAN_BOUND_REACHED
    bound_1 = pe.input.options[:scan_bounds][1]
    "<$(round(bound_1, sigdigits=4))"
  else
    pe.result[1].value
  end
  right_interval_point = if pe.result[2].status === :BORDER_FOUND_BY_SCAN_TOL || pe.result[2].status === :BORDER_FOUND_BY_LOSS_TOL
    round(pe.result[2].value, sigdigits=4)
  elseif pe.result[2].status === :SCAN_BOUND_REACHED
    bound_2 = pe.input.options[:scan_bounds][2]
    ">$(round(bound_2, sigdigits=4))"
  else
    pe.result[2].value
  end

  println(io, "ParamInterval [$left_interval_point, $right_interval_point] by :$(pe.method)")
  #println(io, "  input: $(pe.input)")
  println(io, "  loss_init: $(pe.loss_init)")
  println(io, "  method: :$(pe.method)")
  println(io, "  result:")
  print(io, "    1: ")
  show(io, mime, pe.result[1], extra_spaces = true)
  print(io, "    2: ")
  show(io, mime, pe.result[2], extra_spaces = true)
end


text:
module CompositeOperations

export CompositeOperation,
       CompositeClear,
       CompositeCopy,
       CompositeDestination,
       CompositeSourceOver,
       CompositeDestinationOver,
       CompositeSourceIn,
       CompositeDestinationIn,
       CompositeSourceOut,
       CompositeDestinationOut,
       CompositeSourceAtop,
       CompositeDestinationAtop,
       CompositeXor,
       CompositeLighter

"""
    CompositeOperation{op}

A type used for specifying the Porter-Duff operator, or the mode of generalized
alpha compositing. The `op` should be a symbol.
"""
struct CompositeOperation{op} end

"""
    CompositeClear

A basic Porter-Duff operator with the fractional terms `Fa = 0; Fb = 0`.
The composite result is completely transparent.
"""
const CompositeClear = CompositeOperation{:clear}()

"""
    CompositeCopy

A basic Porter-Duff operator with the fractional terms `Fa = 1; Fb = 0`.
The composite result is the copy of source.

!!! note
    Even if the source alpha is zero, the color components are not cleared.
"""
const CompositeCopy = CompositeOperation{:copy}()

"""
    CompositeDestination

A basic Porter-Duff operator with the fractional terms `Fa = 0; Fb = 1`.
The composite result is the copy of destination (backdrop).

!!! note
    Even if the destination alpha is zero, the color components are not cleared.
"""
const CompositeDestination = CompositeOperation{:destination}()

"""
    CompositeSourceOver

A basic Porter-Duff operator with the fractional terms `Fa = 1; Fb = 1 - αsrc`.
This means the simple alpha compositing.
"""
const CompositeSourceOver = CompositeOperation{Symbol("source-over")}()

"""
    CompositeDestinationOver

A basic Porter-Duff operator with the fractional terms `Fa = 1 - αb; Fb = 1`.
"""
const CompositeDestinationOver = CompositeOperation{Symbol("destination-over")}()

"""
    CompositeSourceIn

A basic Porter-Duff operator with the fractional terms `Fa = αb; Fb = 0`.
"""
const CompositeSourceIn = CompositeOperation{Symbol("source-in")}()

"""
    CompositeDestinationIn

A basic Porter-Duff operator with the fractional terms `Fa = 0; Fb = αsrc`.
"""
const CompositeDestinationIn = CompositeOperation{Symbol("destination-in")}()

"""
    CompositeSourceOut

A basic Porter-Duff operator with the fractional terms `Fa = 1 - αb; Fb = 0`.
"""
const CompositeSourceOut = CompositeOperation{Symbol("source-out")}()

"""
    CompositeDestinationOut

A basic Porter-Duff operator with the fractional terms `Fa = 0; Fb = 1 - αsrc`.
"""
const CompositeDestinationOut = CompositeOperation{Symbol("destination-out")}()

"""
    CompositeSourceAtop

A basic Porter-Duff operator with the fractional terms `Fa = αb; Fb = 1 - αsrc`.
"""
const CompositeSourceAtop = CompositeOperation{Symbol("source-atop")}()

"""
    CompositeDestinationAtop

A basic Porter-Duff operator with the fractional terms `Fa = 1 - αsrc; Fb = αb`.
"""
const CompositeDestinationAtop = CompositeOperation{Symbol("destination-atop")}()

"""
    CompositeXor

A basic Porter-Duff operator with the fractional terms `Fa = 1 - αb; Fb = 1 - αsrc`.
"""
const CompositeXor = CompositeOperation{:xor}()

"""
    CompositeLighter

A basic Porter-Duff operator with the fractional terms `Fa = 1; Fb = 1`.
"""
const CompositeLighter = CompositeOperation{:lighter}()

end # module


text:
# plot/z-test.jl

using Test: @testset

list = [
"jim.jl"
#"setup.jl"
]

for file in list
	@testset "$file" begin
		include(file)
	end
end


text:
module AlpaoInstall

using Libdl

path = get(ENV, "ALPAO_SDK_DLL", "libasdk."*dlext)
sym = :asdkInit
ptr1 = dlopen_e(path)
ptr2 = (ptr1 == C_NULL ? C_NULL : dlsym_e(ptr1, sym))
if ptr2 == C_NULL
    error("\n\n", (ptr1 == C_NULL ? "Unable to load" :
                   "Symbol `$sym` not found in"),
          " dynamic library:\n\n    $path\n\n",
          "Please (re)install Alpao SDK and re-run ",
          "\`Pkg.build(\"Alpao\")\`.  You may set the\nenvironment ",
          "variable ALPAO_SDK_DLL with the path of Alpao SDK dynamic ",
          "library\nbefore re-building.\n")
end

open(joinpath(@__DIR__, "deps.jl"), "w") do io
    write(io, "# This is an auto-generated file; do not edit.\n\n")
    write(io, "const libasdk = \"$path\"\n")
end

end # module


text:
# Module for The King is Dead bot
# This houses all of the types

struct Faction
    name::String
end

mutable struct Region
    name::String
    followers::Dict{String, Int64}
    size::Int8
    resolved::Bool
    controller::Union{String, Nothing}
    adjacent::Array{String}
end

mutable struct Player
    name::String
    court::Dict{String, Int64}
    court_size::Int8
end

mutable struct Board
    regions::Array{Region}
    unresolved_regions::Array{Region}
    resolved_regions::Array{Region}
    supply::Dict{String, Int64}
    invasions::Int8
    players::Array{Player}
    turn::Int8
end

struct Card
    name::String
    type::String
    adjacent::Union{String, Bool}
    place::Union{Dict{String, Int64}, Nothing}
    swap::Union{Dict{String, Int64}, Nothing}
end

function Board(regions, players)
    supply = Dict{String, Int64}()
    for (f_name, _) in faction_names
        supply[f_name] = 18
    end
    Board(regions, shuffle(regions), Array{Region}(undef, 0), supply, 0, players, 1)
end

function Region(name, followers::Dict{String, Int64}, size::Int, adjacent::Array{String})
    Region(name, followers, size, false, nothing, adjacent)
end

function Player(name)
    Player(name, Dict(k=>0 for k in keys(faction_names)), 0)
end

function Card(name, card)
    for (k,v) in card
        if v == "nothing"
            card[k] = nothing
        elseif typeof(v) == Dict{String, Any}
            try
                card[k] = convert(Dict{String, Int}, v)
            catch
            end
        end
    end
    Card(name, card["type"], card["adjacent"], card["place"], card["swap"])
end

max_stars_repo_name: danielpicone/the-king-is-dead

max_issues_repo_name: danielpicone/the-king-is-dead

max_forks_repo_name: danielpicone/the-king-is-dead


text:
module Noteworthy

include("replmod.jl")
include("noteworthy.jl")
include("noteworthy_repl.jl")

NOTES_FNAME = joinpath(Pkg.dir("Noteworthy"), "notes.json")
NOTES_PROMPT = "notes> "
NEW_NOTES_PROMPT = "new note> "
NOTES_KEY = '/'
PROMPT_COLOR = Base.text_colors[:cyan]
TEXT_COLOR = Base.text_colors[:normal]

###### Maintain State ######
verify_notes_file(NOTES_FNAME)
NOTES_DICT, TAGS_DICT = create_dicts(NOTES_FNAME)
NOTES_LATEST_ID = isempty(NOTES_DICT) ? 0 : maximum(keys(NOTES_DICT))
increment_id() = global NOTES_LATEST_ID += 1

###### Create easy functions ######
add_note(note::Note) = add_note(note, NOTES_DICT, TAGS_DICT, writeback=true, fname=NOTES_FNAME)
get_notes(tags) = get_notes(tags, TAGS_DICT, NOTES_DICT)

###### Set up REPL mode ######
function init_repl_mode(repl)
    global main_mode = repl.interface.modes[1]

    global NOTES_MODE = create_mode(
        NOTES_PROMPT,
        :notes,
        prefix_color=PROMPT_COLOR,
        suffix_color=TEXT_COLOR,
        on_done = create_on_done_fn(increment_id),
        on_enter = create_on_complete_fn(NEW_NOTES_PROMPT, NOTES_PROMPT)
        )

    add_mode_to_repl(NOTES_KEY, NOTES_MODE)
end

if isdefined(Base, :active_repl)
    repl = Base.active_repl
    init_repl_mode(repl)
else
    atreplinit() do repl
        repl.interface = Base.REPL.setup_interface(repl)
        init_repl_mode(repl)
    end
end

end # module


text:
# This file is a part of Julia. License is MIT: http://julialang.org/license

# Floating point numbers - basic tests
@test 4.00000000000001 ≈ 4.0
@test 5.0 ≈ 4.999999999999993
@test 4.000000002 ≉ 4.00300002

# Other tolerance levels
@test 4.32 ≈ 4.3 rtol=0.1 atol=0.01
@test 1.001 ≈ 1.002 rtol=0.001 atol=0.0001
@test 4.5 ≉ 4.9 rtol=0.001 atol=0.001

# Complex numbers
@test 1.0 + 1.0im ≈ 1.0 + 1.00000000000001im
@test 0.9999999999999 + 1.0im ≈ 1.0 + 1.000000000000001im
@test 0.9999 + 1.0im ≈ 1.0 + 1.1im rtol=0.0001 atol=1.1

# Complex <-> reals
@test 1.0 + 0im ≈ 1.0000000000001
@test 0.9999999999999 ≈ 1.0 + 0im
@test 1.0+1im ≉ 1.000000000000001

# Comparing NaNs
@test 4.0 ≉ NaN
@test NaN ≉ 4.0
@test complex(2.3,NaN) ≉ complex(NaN,2.3)
@test NaN ≉ NaN
@test complex(NaN,NaN) ≉ complex(NaN,NaN)
@test complex(NaN,2.3) ≉ complex(NaN,2.3)
@test complex(2.3,NaN) ≉ complex(2.3,NaN)

# Comparing Infs
@test Inf ≈ Inf
@test Inf ≉ 1
@test Inf ≉ -Inf
@test complex(0.0,Inf) ≈ complex(0.0,Inf)
@test complex(0.0,Inf) ≉ complex(0.0,-Inf)

# Tests for integers and rationals
@test 4 ≈ 4
@test 4 ≈ 5 atol=1
@test 4 ≉ 6 atol=1
@test 4 ≉ 5

@test 1//2+3im ≈ 1//2+3im
@test 1//3 ≈ 0.33333333333333333
@test 1//3 ≈ 0.3333 rtol=0.0001 atol=0.0001
@test 1+1im ≈ 1im+1

# Notably missing from this test suite at the moment
# * Tests for other magnitudes of numbers - very small, very big, and combinations of small and big
# * Tests for various odd combinations of types, e.g. x::Integer ≈ y::Rational

# issue #12375:
@test 1e17 ≉ 1

# Tests for arrays:
@test [1,2,3] ≈ [1,2,3+1e-9]
@test [0,1] ≈ [1e-9, 1]
@test [0,Inf] ≈ [0,Inf]
@test [0,Inf] ≉ [0,-Inf]

# issue #19936
for elty in (Float16,Float32,Float64)
    nan  = elty(NaN)
    half = elty(0.5)
    @test nan ≉ nan
    @test nan ≈ nan nans=true
    @test [half, nan, half] ≉ [half, nan, half]
    @test [half, nan, half] ≈ [half, nan, half] nans=true
end


text:
## REMEMBER TO UPDATE TESTS FOR BOTH THE N-GMRES and the O-ACCEL TEST SETS

@testset "N-GMRES" begin
    method = NGMRES
    solver = method()

    skip = ("Trigonometric", )
    run_optim_tests(solver; skip = skip,
                    iteration_exceptions = (("Penalty Function I", 10000), ),
                    show_name = debug_printing)

    # Specialized tests
    prob = MVP.UnconstrainedProblems.examples["Rosenbrock"]
    df = OnceDifferentiable(MVP.objective(prob),
                            MVP.gradient(prob),
                            prob.initial_x)

    @test solver.nlpreconopts.iterations == 1
    @test solver.nlpreconopts.allow_f_increases == true

    defopts = Optim.default_options(solver)
    @test defopts == Dict(:allow_f_increases => true)

    state = Optim.initial_state(solver, Optim.Options(;defopts...), df,
                                prob.initial_x)
    @test state.x          === state.nlpreconstate.x
    @test state.x_previous === state.nlpreconstate.x_previous
    @test size(state.X)    == (length(state.x), solver.wmax)
    @test size(state.R)    == (length(state.x), solver.wmax)
    @test size(state.Q)    == (solver.wmax, solver.wmax)
    @test size(state.ξ)    == (solver.wmax,)
    @test state.curw       == 1
    @test size(state.A)    == (solver.wmax, solver.wmax)
    @test length(state.b)  == solver.wmax
    @test length(state.xA) == length(state.x)

    # Test that tracing doesn't throw errors
    res = optimize(df, prob.initial_x, solver,
                   Optim.Options(extended_trace=true, store_trace=true;
                                 defopts...))

    @test Optim.converged(res)
    # The bounds are due to different systems behaving differently
    # TODO: is it a bad idea to hardcode these?
    @test 64 < Optim.iterations(res) < 84
    @test 234 < Optim.f_calls(res) <  286
    @test 234 < Optim.g_calls(res) < 286
    @test Optim.minimum(res) < 1e-10

    @test_throws AssertionError method(manifold=Optim.Sphere(), nlprecon = GradientDescent())

    for nlprec in (LBFGS, BFGS)
        solver = method(nlprecon=nlprec())
        clear!(df)
        res = optimize(df, prob.initial_x, solver)

        if !Optim.converged(res)
            display(res)
        end
        @test Optim.converged(res)
        @test Optim.minimum(res) < 1e-10
    end

    # O-ACCEL handles the InitialConstantChange functionality in a special way,
    # so we should test that it works well.
    for nlprec in (GradientDescent(),
                   GradientDescent(alphaguess = LineSearches.InitialConstantChange()))
        solver = method(nlprecon = nlprec,
                        alphaguess = LineSearches.InitialConstantChange())
        clear!(df)

        res = optimize(df, prob.initial_x, solver)

        if !Optim.converged(res)
            display(res)
        end
        @test Optim.converged(res)
        @test Optim.minimum(res) < 1e-10
    end
end

@testset "O-ACCEL" begin
    method = OACCEL
    solver = method()
    skip = ("Trigonometric", )
    run_optim_tests(solver; skip = skip,
                    iteration_exceptions = (("Penalty Function I", 10000), ),
                    show_name = debug_printing)

    prob = MVP.UnconstrainedProblems.examples["Rosenbrock"]
    df = OnceDifferentiable(MVP.objective(prob),
                            MVP.gradient(prob),
                            prob.initial_x)
    @test solver.nlpreconopts.iterations == 1
    @test solver.nlpreconopts.allow_f_increases == true

    defopts = Optim.default_options(solver)
    @test defopts == Dict(:allow_f_increases => true)

    state = Optim.initial_state(solver, Optim.Options(;defopts...), df,
                                prob.initial_x)
    @test state.x          === state.nlpreconstate.x
    @test state.x_previous === state.nlpreconstate.x_previous
    @test size(state.X)    == (length(state.x), solver.wmax)
    @test size(state.R)    == (length(state.x), solver.wmax)
    @test size(state.Q)    == (solver.wmax, solver.wmax)
    @test size(state.ξ)    == (solver.wmax, 2)
    @test state.curw       == 1
    @test size(state.A)    == (solver.wmax, solver.wmax)
    @test length(state.b)  == solver.wmax
    @test length(state.xA) == length(state.x)

    # Test that tracing doesn't throw errors
    res = optimize(df, prob.initial_x, solver,
                   Optim.Options(extended_trace=true, store_trace=true;
                                 defopts...))
    @test Optim.converged(res)
    # The bounds are due to different systems behaving differently
    # TODO: is it a bad idea to hardcode these?
    @test 72 < Optim.iterations(res) < 88
    @test 245 < Optim.f_calls(res) <  292
    @test 245 < Optim.g_calls(res) <  292

    @test Optim.minimum(res) < 1e-10

    @test_throws AssertionError method(manifold=Optim.Sphere(), nlprecon = GradientDescent())

    for nlprec in (LBFGS, BFGS)
        solver = method(nlprecon=nlprec())
        clear!(df)
        res = optimize(df, prob.initial_x, solver)

        if !Optim.converged(res)
            display(res)
        end
        @test Optim.converged(res)
        @test Optim.minimum(res) < 1e-10
    end

    # O-ACCEL handles the InitialConstantChange functionality in a special way,
    # so we should test that it works well.
    for nlprec in (GradientDescent(),
                   GradientDescent(alphaguess = LineSearches.InitialConstantChange()))
        solver = method(nlprecon = nlprec,
                        alphaguess = LineSearches.InitialConstantChange())
        clear!(df)

        res = optimize(df, prob.initial_x, solver)

        if !Optim.converged(res)
            display(res)
        end
        @test Optim.converged(res)
        @test Optim.minimum(res) < 1e-10
    end
end


text:
A = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

function zad43(A,key)
    m = Int(floor(length(A)/2))
    if A[m]<key
        return "Element se nalazi u prvoj polovini"
    elseif A[m] == key
        return "Element se nalazi na sredini niza"
    else
        return "Element se nalazi u drugoj polovini"
    end
end

function zad43A(A,key)
    m = Int(floor(length(A)/2))
    if A[m] == key
        return "Element se nalazi na sredini niza"
    end
    k = length(A)
    i = 1
    while(i<m && k > m)
        if A[i] == key
            return "Element nalazi se u prvoj polovini"
        elseif A[k] == key
            return "Element se nalazi u drugoj polovini"
        end
        i+=1
        k-=1
    end

    return "Element se ne nalazi u nizu"
end


text:
include("7.5.1 u (a+b arcsech(c x))^n.jl")
include("7.5.2 Miscellaneous inverse hyperbolic secant.jl")

max_stars_repo_path: src/rules/7 Inverse hyperbolic functions/7.5 Inverse hyperbolic secant/.jl


text:
# Test ArbFloats.jl

using Base.Test
using ArbFloats

function package_directory(pkgName::String)
    pkgdir = Base.find_in_path(pkgName)
    nothing == pkgdir && throw(ErrorException(string("Package $pkgName not found.")))
    return abspath(joinpath(split(pkgdir, pkgName)[1], pkgName))
end

d = joinpath(package_directory("ArbFloats"),"test")
test_files = [
                joinpath(d,"TestAsType.jl"),
                joinpath(d,"TestAsNumber.jl"),
                joinpath(d,"TestAsInterval.jl")
              ]

#= prepare to test =#

# include(joinpath(d,"test_prep.jl"))

#= begin tests =#

# println("Linting ...")
# using Lint
# @test isempty(lintpkg( "MyPackage", returnMsgs=true))
# println("Done.")

#println("Testing ...")
for f in test_files
#    println(f)
    include(f)
end
#println("Done testing.")

# end testing ArbFloats


text:
fatalerrors = length(ARGS) > 0 && ARGS[1] == "-f"
anyerrors = false

using Base.Test
using Roxygen

my_tests = ["components.jl", "roxygenize.jl"]

println("Running tests:")

mkdir(Pkg.dir("Roxygen", "output"))

for my_test in my_tests
    try
        include(Pkg.dir("Roxygen", "test", my_test))
        println("\t\033[1m\033[32mPASSED\033[0m: $(my_test)")
    catch
        anyerrors = true
        println("\t\033[1m\033[31mFAILED\033[0m: $(my_test)")
        if fatalerrors
            rethrow()
        end
    end
end

rm(Pkg.dir("Roxygen", "output", "example.md"))
rmdir(Pkg.dir("Roxygen", "output"))

if anyerrors
    throw("Tests failed")
end


text:
using DrWatson
@quickactivate "Medical segmentation evaluation"
using Test

module CUDAGpuUtilsTest

s = SubArray( a, (1:3,))

A = [1 2 3;
     3 4 5 ;
     6 7 8 ];

B = ones(3,3,3)
B[1,:,:] = A
B[2,:,:] = A.*10
B[3,:,:] = A.*100
B

V = view(B, :, :,1)
Base.iscontiguous(V)


text:
module GeodesicBase

import Parameters: @with_kw
import SciMLBase

include("metric-params.jl")
include("physical-quantities.jl")
include("geodesic-solutions.jl")

export AbstractMetricParams, metric_params, metric

end # module


text:
# Some Simple Tests
using Test
using InteractiveUtils
using BenchmarkTools
BenchmarkTools.DEFAULT_PARAMETERS.samples=1
BenchmarkTools.DEFAULT_PARAMETERS.evals=1

macro testset_include(filename)
    @assert filename isa AbstractString
    quote
        @testset $filename begin
            @info $filename
            include($filename)
        end;
    end
end

macro inferred_with_info(expr)
    rexpr = quote
        try
            $expr
            @show $(expr.args[1])
            @inferred $expr
            true
        catch e
            if typeof(e) == ErrorException && occursin("does not match inferred return type", e.msg)
                @info "Type inference failed. Here is the result of @code_warntype\n"
                InteractiveUtils.@code_warntype $expr
                false
            else
                rethrow(e)
            end
        end
    end
    return esc(rexpr)
end # macro

@testset "all" begin
    @testset_include "test_control_system.jl"
    @testset_include "test_linear_system.jl"
    @testset_include "test_product_system.jl"
    @testset_include "test_system_trajectory.jl"
    @testset_include "test_solve_lq_game.jl"
    @testset_include "test_ilq_solver.jl"
    @testset_include "test_nplayer_navigation.jl"
    @testset_include "test_flat.jl"
end;


text:
@doc raw"""
    dex_func"..."
    dex_func"..."c

Compiles a string of dex code which defines a function.
That function can be anonymous, or named.
If named it can either be a lambda that is assigned to a variable, or defined using `def`.

Flags:
 - `c`: for a named function declares it as const

!!! warning
    If the code in the string does anything other than define a single function then the
    behavour of the `dex_func` string macro is undefined. It will probably eventually error.

# Examples
###Long form:
```julia
julia> dex_func\"\"\"
              def myTranspose (n: Int) ?-> (m: Int) ?->
                              (x : (Fin n)=>(Fin m)=>Float) : (Fin m)=>(Fin n)=>Float =
                  for i j. x.j.i
              \"\"\"
(::NativeFunction{Matrix{Float32}}) (generic function with 1 method)

julia> myTranspose([1f0 2f0 3f0; 4f0 5f0 6f0])
3×2 Matrix{Float32}:
 1.0  4.0
 2.0  5.0
 3.0  6.0
```

### Short form
julia> dex_func"inc = \a:Int. a + 1"
(::NativeFunction{Int32}) (generic function with 1 method)

julia> inc(Int32(9))
10
```

### Anonymous
```julia
julia> map(dex_func"\x:Float. pow 2.0 x", [1f0, 2f0,  3f0])
3-element Vector{Float32}:
 2.0
 4.0
 8.0
```
"""
macro dex_func_str(str, flags="")
    # Check if it is named function. Note that we don't need to check if the name is a
    # valid Dex/Julia identifier, the parser of each would/will error if it isn't.
    m = something(
        match(r"^def\s+(.+?)\b", str),  # `def foo`
        match(r"^(.+?)\b\s*=\s*[\\]", str),  # `foo = \x`
        Some(nothing)  # not found by either, so still give nothing.
    )
    if m === nothing  # then this must be an anon function
        NativeFunction(evaluate(str))
    else  # named function
        name = Symbol(only(m.captures))
        mod = DexModule(str)
        atom = getproperty(mod, name)
        native_func = NativeFunction(atom)

        assigment = :($(esc(name)) = $(native_func))
        if 'c' in flags
            assigment = Expr(:const, assigment)
        end
        return assigment
    end
end

"holds information on how to map an argument argment in a signature into a julia type"
struct Binder
    name::Symbol
    type  # Intentionally left unrestricted for now. No restriction seems useful, it is either one of half a dozen scalar types or an ArrayBuilder
    implicit::Bool
end

"Creates an `Array{T,N}``, if all elements of size are present then that array is initialized to hold `size`"
struct ArrayBuilder{T,N}
    size::Vector{Union{Symbol,Int}}
end
ArrayBuilder{T}(size) where T = ArrayBuilder{T,length(size)}(size)

"""
    NativeFunction{R}

Callable Julia wrapper of some native Dex function.
Return type from calling it is is `R`.

Usually constructed using [`@dex_func_str`](@ref),
or via `NativeFunction(atom)` on some [`DexCall.Atom`](@ref).
"""
struct NativeFunction{R} <: Function
    c_func_ptr::Ptr{Nothing}
    argument_signature::Vector{Binder}
    result_signature::Vector{Binder}
end

NativeFunction(atom::Atom, jit=JIT) = NativeFunction(atom.ptr, atom.ctx, jit)
function NativeFunction(atom::Ptr{HsAtom}, ctx=PRELUDE, jit=JIT)
    c_func_ptr = compile(ctx, atom, jit)
    sig_ptr = get_function_signature(c_func_ptr, jit)
    sig_ptr == C_NULL && error("Failed to retrieve the function signature")

    try
        signature = NativeFunctionSignatureJL(sig_ptr)
        result_signature = parse_sig(signature.res)
        R = result_type(result_signature)
        f = NativeFunction{R}(
            c_func_ptr,
            parse_sig(signature.arg),
            result_signature
        )

        # We are attaching this to f.result_signature because only mutable types can have finalizers
        finalizer(f.result_signature) do _
            unload(c_func_ptr, jit)
        end
        return f
    catch
        unload(c_func_ptr, jit)
        rethrow()
    finally
        free_function_signature(sig_ptr)
    end
end

function (f::NativeFunction{R})(args...)::R where R
    named_sizes = Dict{Symbol, Int}()
    num_explict = 0
    c_args = map(f.argument_signature) do binder
        if binder.implicit
            -one(binder.type)  # we will do implicts in a second pass, once named_sizes is filled out
            # Note: because scoping rules are left-to-right if we reversed the list we could do this in a single pass
        else
            num_explict += 1
            to_ctype!(named_sizes, binder.type, args[num_explict])
        end
    end
    num_explict == length(args) || throw(ArgumentError("Wrong number of arguments, expected $num_explict"))

    for (i, binder) in enumerate(f.argument_signature)
        # second pass, filling in implicits from the `named_sizes`
        binder.implicit || continue
        # Make sure it is the right type, just in case dex ever allows e.g Int32 implicts
        c_args[i] = convert(binder.type, named_sizes[binder.name])
    end

    results_ptrs_and_thunks = map(f.result_signature) do builder
        create(builder.type, named_sizes)
    end

    result_ptrs = first.(results_ptrs_and_thunks)
    result_thunks = Tuple(last.(results_ptrs_and_thunks))

    # No return value, that we care about because it write's its return into  the results_ptrs
    _ccall_dex_func(f.c_func_ptr, c_args..., result_ptrs...)

    if length(result_thunks) === 1
        only(result_thunks)()
    else
        map(t->t(), result_thunks)
    end
end

"""
    _ccall_dex_func(f_ptr, args...)

Use `ccall` to call the dex native function pointed to by `f_ptr`, passing in the given `args`.
The `args` must already be in a C compatible type etc.

!!! warning
    Noone should be expected to follow what this code does.
    Like even people who have been using julia for years shouldn't.
    It's pretty gross.

The sensible version of this code is:
```julia
ccall(f_ptr, Int64, typeof.(args), args...)
```

However, we can not do that directly because `ccall` is not a function but rather a built-in
language intrinsic that is largely resolved at compile time, and that needs the type
information given to it as literals.
`typeof.(args)` is not a literal which is a problem -- even though it can actually be
resolved at compile-time -- the information exists.

So we use a generated function in order to get at the information.
Docs on those are at https://docs.julialang.org/en/v1/manual/metaprogramming/#Generated-functions
The short version though is that they take in arguments at compile time and they only get their types,
then they return a AST which is what is run at runtime.
So what we are doing is building the AST that is for the ccall, which has the types all present as literals.

See: https://github.com/JuliaLang/julia/issues/41991
"""
@generated function _ccall_dex_func(f_ptr, args...)
    arg_types = Expr(:tuple, args...)
    return :(ccall(f_ptr, Int64, $arg_types, $(Any[:(args[$i]) for i in 1:length(args)]...)))
end

"""
    to_ctype!(named_sizes::Dict{Symbol, Int}, builder, actual)

Returns a object suitable for passing into Dex's C API, that represents `actual`.
Checks the consistency of `actual` with the `builder`, and with `named_sizes`.
Sizes referred to by name for the first time are added to `named_sizes`, with the `actual` size.
"""
to_ctype!(named_sizes, builder::ArrayBuilder, actual) = to_ctype(named_sizes, builder, collect(actual))
to_ctype!(::Any, ::ArrayBuilder{T}, ::Array{S}) where {S,T} = throw(ArgumentError("Expected eltype $T, got $S."))
to_ctype!(::Any, ::ArrayBuilder{T,N}, ::Array{T,M}) where {T,N,M} = throw(DimensionMismatch("Expected $B, got $M dims."))

function to_ctype!(named_sizes::Dict{Symbol, Int}, builder::ArrayBuilder{T, N}, actual::Array{T, N}) where {T, N}
    combined_size = Tuple(map(builder.size, size(actual)) do size_or_name, actual_size
        # replace all the `nothings` (being the sizes specified not as literals) with the actual size.
        if size_or_name isa Symbol
            #Either record the size, or return the size that is already recorded
            get!(named_sizes, size_or_name, actual_size)
        else
            @assert size_or_name isa Int
            size_or_name
        end
    end)
    size(actual) == combined_size || throw(DimensionMismatch("Expected $(combined_size), got $(actual_size)"))
    return pointer(flip_array_order(actual))  # flip array order to C
end

# scalar types:
to_ctype!(::Any, ::Type{T}, actual::T) where T = actual
to_ctype!(::Any, ::Type{T}, ::S) where {T,S} = throw(ArgumentError("expected $T got $S"))

"Makes for writing into. Returns a pointer, and a thunk that when run gives the instance."
function create(builder::ArrayBuilder{T, N}, named_sizes::Dict{Symbol,Int}) where {T,N}
    size::NTuple{N,Int} = Tuple(size_or_name isa Symbol ? named_sizes[size_or_name] : size_or_name
            for size_or_name in builder.size)

    result = Array{T, N}(undef, reverse(size)...)  # reverse size because dex wants C ordered
    return pointer(result), ()->flip_array_order(result)  # flip order back to Fortran
end

# scalar types
function create(::Type{T}, ::Any) where T
    ref = Ref{T}()
    pointer_from_objref(ref), ()->ref[]
end

"converts between C and Fortran order"
flip_array_order(x::Vector) = x
flip_array_order(x::Array) = permutedims(x, ndims(x):-1:1)

"Mirror of NativeFunctionSignature that using julia Strings, rather than CStrings"
struct NativeFunctionSignatureJL
    arg::String
    res::String
    _ccall::String
end
function NativeFunctionSignatureJL(x::NativeFunctionSignature)
    return NativeFunctionSignatureJL(unsafe_string.((x.arg, x.res, x._ccall))...)
end
function NativeFunctionSignatureJL(ptr::Ptr{NativeFunctionSignature})
    return NativeFunctionSignatureJL(unsafe_load(ptr))
end

"given a Binder for a result_signature returns the julia type that will be returned by the funcion"
result_type(x::Binder) = result_type(x.type)
function result_type(x::Vector{Binder})
    @assert !isempty(x)
    if length(x) == 1
        return result_type(only(x))
    else
        Tuple{result_type.(x)...}  # multiple returns, represented as a Tuple
    end
end
result_type(x::Type) = x
result_type(::ArrayBuilder{T,N}) where {T,N} = Array{T,N}

# CombinedParsers.jl based parser:
function parse_sig(sig)
    @with_names begin
        name = map(Symbol, !re"arg\d+")
        scalar_type = Either{Any}(
            parser("f32"=>Float32),
            parser("f64"=>Float64),
            parser("i32"=>Int32),
            parser("i64"=>Int64),
            parser("i8"=>Int8),
        )
        size_ele = NumericParser(Int) | name
        sizes = join(Repeat(size_ele),",")
        array_type = map(scalar_type * "[" * sizes * "]") do (T, _, sz, _)
            ArrayBuilder{T}(sz)
        end
        type = array_type | scalar_type
        implicit = parser("?"=>true) | false
        arg_sig = map(implicit * name * ":" * type) do (i, n, _ , t)
            Binder(n, t, i)
        end
        arg_sigs = join(Repeat(arg_sig),",")
    end
    return parse(arg_sigs, sig)
end

max_stars_repo_name: justinchiu/dex-lang

max_issues_repo_name: justinchiu/dex-lang

max_forks_repo_name: justinchiu/dex-lang


text:
using Pkg

# Activate test environment on older Julia versions
if VERSION < v"1.2"
    Pkg.activate(@__DIR__)
    Pkg.develop(PackageSpec(path=dirname(@__DIR__)))
    Pkg.instantiate()
end

using MCMCChains
using Documenter

using Test
using Random

# set seed for all testsets
Random.seed!(0)

@testset "MCMCChains" begin
    # MLJXGBoostInterface requires Julia >= 1.3
    # XGBoost errors on 32bit systems: https://github.com/dmlc/XGBoost.jl/issues/92
    if VERSION >= v"1.3" && Sys.WORD_SIZE == 64
        # run tests related to rstar statistic
        println("Rstar")
        Pkg.add("MLJModels")
        Pkg.add("MLJXGBoostInterface")
        @time include("rstar_tests.jl")

        DocMeta.setdocmeta!(
            MCMCChains,
            :DocTestSetup,
            :(using MCMCChains);
            recursive=true
        )

        doctest(
            MCMCChains;
            # https://github.com/JuliaLang/julia/pull/37085#issuecomment-683356098
            doctestfilters = [
                r"{([a-zA-Z0-9]+,\s?)+[a-zA-Z0-9]+}",
                r"(Array{[a-zA-Z0-9]+,\s?1}|Vector{[a-zA-Z0-9]+})",
                r"(Array{[a-zA-Z0-9]+,\s?2}|Matrix{[a-zA-Z0-9]+})",
            ],
        )
    end

    # run tests for effective sample size
    println("ESS")
    @time include("ess_tests.jl")

    # run plotting tests
    println("Plotting")
    @time include("plot_test.jl")

    # run function tests
    println("Diagnostics")
    @time include("diagnostic_tests.jl")

    # run tests for missing values
    println("Missing values")
    @time include("missing_tests.jl")

    # run tests for describing sections
    println("Sections")
    @time include("sections_tests.jl")

    # run tests for accessing parameters
    println("Accessing parameters")
    @time include("get_tests.jl")

    # run tests for serialization
    println("Serialization")
    @time include("serialization_tests.jl")

    # run tests for sampling api
    println("Sampling")
    @time include("sampling_tests.jl")

    # run tests for array constructor
    println("Array")
    @time include("arrayconstructor_tests.jl")

    # run tests for tables interfaces
    println("Tables interfaces")
    @time include("tables_tests.jl")

    # run tests for dataframe summary
    println("Summary")
    @time include("summarize_tests.jl")

    # run tests for posterior stats
    println("Model statistics")
    @time include("modelstats_test.jl")

    # run tests for concatenation
    println("Concatenation")
    @time include("concatenation_tests.jl")

end


text:
# All code in this file was copied from https://github.com/JuliaTesting/TestReports.jl/blob/cc146819be746274c286e544ff3ab540bd1226e6/src/runner.jl

using Pkg
import Pkg: PackageSpec, Types
import Pkg.Types: Context, EnvCache, ensure_resolved, is_project_uuid
import Pkg.Operations: project_resolve!, project_deps_resolve!, manifest_resolve!, manifest_info, project_rel_path

# Version specific imports
@static if VERSION >= v"1.4.0"
    import Pkg.Operations: gen_target_project
else
    import Pkg.Operations: with_dependencies_loadable_at_toplevel
end
@static if VERSION >= v"1.2.0"
    import Pkg.Operations: update_package_test!, source_path, sandbox
else
    import Pkg.Operations: find_installed
    import Pkg.Types: SHA1
end

"""
    gettestfilepath(ctx::Context, pkgspec::Types.PackageSpec)
Gets the testfile path of the package. Code for each Julia version mirrors that found
in `Pkg/src/Operations.jl`.
"""
function gettestfilepath(ctx::Context, pkgspec::Types.PackageSpec)
    @static if VERSION >= v"1.4.0"
        if is_project_uuid(ctx, pkgspec.uuid)
            pkgspec.path = dirname(ctx.env.project_file)
            pkgspec.version = ctx.env.pkg.version
        else
            update_package_test!(pkgspec, manifest_info(ctx, pkgspec.uuid))
            pkgspec.path = project_rel_path(ctx, source_path(ctx, pkgspec))
        end
        pkgfilepath = source_path(ctx, pkgspec)
    elseif VERSION >= v"1.2.0"
        pkgspec.special_action = Pkg.Types.PKGSPEC_TESTED
        if is_project_uuid(ctx.env, pkgspec.uuid)
            pkgspec.path = dirname(ctx.env.project_file)
            pkgspec.version = ctx.env.pkg.version
        else
            update_package_test!(pkgspec, manifest_info(ctx.env, pkgspec.uuid))
            pkgspec.path = joinpath(project_rel_path(ctx, source_path(pkgspec)))
        end
        pkgfilepath = project_rel_path(ctx, source_path(pkgspec))
    elseif VERSION >= v"1.1.0"
        pkgspec.special_action = Pkg.Types.PKGSPEC_TESTED
        if is_project_uuid(ctx.env, pkgspec.uuid)
            pkgspec.version = ctx.env.pkg.version
            pkgfilepath = dirname(ctx.env.project_file)
        else
            entry = manifest_info(ctx.env, pkg.uuid)
            if entry.repo.tree_sha !== nothing
                pkgfilepath = find_installed(pkgspec.name, pkgspec.uuid, entry.repo.tree_sha)
            elseif entry.path !== nothing
                pkgfilepath =  project_rel_path(ctx, entry.path)
            elseif pkgspec.uuid in keys(ctx.stdlibs)
                pkgfilepath = Types.stdlib_path(pkgspec.name)
            else
                throw(PkgTestError("Could not find either `git-tree-sha1` or `path` for package $(pkgspec.name)"))
            end
        end
    else
        pkgspec.special_action = Pkg.Types.PKGSPEC_TESTED
        if is_project_uuid(ctx.env, pkgspec.uuid)
            pkgspec.version = ctx.env.pkg.version
            pkgfilepath = dirname(ctx.env.project_file)
        else
            info = manifest_info(ctx.env, pkgspec.uuid)
            if haskey(info, "git-tree-sha1")
                pkgfilepath = find_installed(pkgspec.name, pkgspec.uuid, SHA1(info["git-tree-sha1"]))
            elseif haskey(info, "path")
                pkgfilepath =  project_rel_path(ctx, info["path"])
            elseif pkgspec.uuid in keys(ctx.stdlibs)
                pkgfilepath = Types.stdlib_path(pkgspec.name)
            else
                throw(PkgTestError("Could not find either `git-tree-sha1` or `path` for package $(pkgspec.name)"))
            end
        end
    end
    testfilepath = joinpath(pkgfilepath, "test", "runtests.jl")
    return testfilepath
end

"""
    isinstalled!(ctx::Union{Context, EnvCache}, pkgspec::Types.PackageSpec)
Checks if the package is installed by using `ensure_resolved` from `Pkg/src/Types.jl`.
This function fails if the package is not installed, but here we wrap it in a
try-catch as we may want to test another package after the one that isn't installed.
For Julia versions V1.4 and later, the first arguments of the Pkg functions used
is of type `Pkg.Types.Context`. For earlier versions, they are of type
`Pkg.Types.EnvCache`.
"""
function isinstalled!(ctx::Context, pkgspec::Types.PackageSpec)
    @static if VERSION >= v"1.4.0"
        var = ctx
    else
        var = ctx.env
    end
    project_resolve!(var, [pkgspec])
    project_deps_resolve!(var, [pkgspec])
    manifest_resolve!(var, [pkgspec])
    try
        ensure_resolved(var, [pkgspec])
    catch
        return false
    end
    return true
end

max_stars_repo_name: novitk/julia-vscode

max_issues_repo_name: novitk/julia-vscode

max_forks_repo_name: novitk/julia-vscode