text:
using Seaborn
using Pandas
using PyPlot
using PyCall

@pyimport numpy

#for some strange reason loading doesn't work the first time
tips = nothing
try
    tips = load_dataset("tips");
catch
    tips = load_dataset("tips");
end

head(tips)

g = regplot(x="total_bill", y="tip", data=tips)
title("Total Bill vs. Tip") #current active figure PyPlot
# alternatively
# g[:figure][:axes][1][:set_title]("Total Bill vs. Tip")

f, (ax1, ax2,ax3)  = subplots(1, 3, sharey=true)
regplot(x="size", y="tip", data=tips, ax=ax1);
regplot(x="size", y="tip", data=tips, x_jitter=.05, ax=ax2);
regplot(x="size", y="tip", data=tips, x_estimator=numpy.mean, ax=ax3);

anscombe = load_dataset("anscombe");
head(anscombe)

lmplot(x="x", y="y", data=query(anscombe, "dataset == 'II'"),
           ci=nothing, scatter_kws=Dict("s"=> 80));

lmplot(x="x", y="y", data=query(anscombe, "dataset == 'II'"),
           ci=nothing, scatter_kws=Dict("s"=> 80), order =2);

jointplot(x="total_bill", y="tip", data=tips, kind="reg")
savefig("./test.svg")

lmplot(x="total_bill", y="tip", hue="smoker", data=tips);

lmplot(x="total_bill", y="tip", col="day", data=tips,
           aspect=.5);


text:
using Test

# Helper function for numerical tests
check_numerical(chain, symbols::Vector{Symbol}, exact_vals::Vector;
                eps=0.2) = begin
  for (sym, val) in zip(symbols, exact_vals)
    E = mean(chain[sym])
    print("  $sym = $E ≈ $val (eps = $eps) ?")
    cmp = abs.(sum(mean(chain[sym]) - val)) <= eps
    if cmp
      printstyled("./\n", color = :green)
      printstyled("    $sym = $E, diff = $(abs.(E - val))\n", color = :green)
    else
      printstyled(" X\n", color = :red)
      printstyled("    $sym = $E, diff = $(abs.(E - val))\n", color = :red)
    end
  end
end

"""
  getteststoskip(filepath)

Returns a list of files (tests) to skip within a test group.
"""
function getteststoskip(filepath)
  if isfile(filepath)
    lines = readlines(filepath)
    lines = filter(line -> endswith(line, ".jl"), lines)
    lines = filter(line -> !startswith(line, "#"), lines)
    lines = filter(line -> length(split(line)) == 1, lines)
    lines = map(line -> strip(line), lines)
    return Set{String}(lines)
  else
    return Set{String}()
  end
end

"""
  runtests(; tests = ["all"])

Run specified Turing tests. By default this function runs all Turing tests.
The user can specify a list of test sets that she wants to run if necessary.

Example:
```julia
runtests(tests = ["util.jl", "trace.jl"])
```
"""
function runtests(; tests = ["all"])

  # test groups
  CORE_TESTS = ["ad.jl", "compiler.jl", "container.jl", "varinfo.jl",
                # "io.jl",
                "util.jl"]
  DISTR_TESTS = ["transform.jl"]
  SAMPLER_TESTS = ["resample.jl", "adapt.jl", "vectorisation.jl", "gibbs.jl", "nuts.jl",
                   "hmcda.jl", "hmc_core.jl", "hmc.jl", "sghmc.jl", "sgld.jl", "is.jl",
                   "mh.jl",
                   # "pmmh.jl", "ipmcmc.jl", "pgibbs.jl", "smc.jl"
                  ]
  TRACE_TESTS = ["tarray.jl", "taskcopy.jl", "trace.jl"]
  ALL = union(CORE_TESTS, DISTR_TESTS, SAMPLER_TESTS, TRACE_TESTS)

  # test groups that should be executed
  TEST_GROUPS = "all" ∈ tests ? ALL : tests

  # Run tests
  tr = @testset "Turing tests" begin
    for test_group in TEST_GROUPS
      teststoskip = getteststoskip(joinpath(test_group, "skip_tests"))
      @testset "$(test_group)" begin
        for test in filter(f -> endswith(f, ".jl") && !(f ∈ teststoskip), readdir(test_group))
          @testset "$(test)" begin
            include(joinpath(test_group, test))
          end
        end
      end
    end
  end

  println()
  Test.print_test_results(tr)
end

ext: jl


text:
include("test_scalar_ref.jl")
include("test_scalar_ewise.jl")
include("test_scalar_special.jl")
include("test_scalar_reduc.jl")
include("test_scalar_hybrid.jl")


text:
"""
$(README)

$(EXPORTS)
"""
module VoronoiFVM

using Printf
using DocStringExtensions
using LinearAlgebra
using SparseArrays
using SuiteSparse

using ForwardDiff
using DiffResults
using IterativeSolvers
using JLD2
using StaticArrays
using SparseDiffTools
using SparsityDetection
using RecursiveArrayTools

using ExtendableSparse
using ExtendableGrids

include("vfvm_physics.jl")
include("vfvm_functions.jl")
export fbernoulli
export fbernoulli_pm

include("vfvm_densesolution.jl")
include("vfvm_sparsesolution.jl")
export num_dof
export dof
export getdof
export setdof!

include("vfvm_transientsolution.jl")
export transient_solution,TransientSolution

include("vfvm_xgrid.jl")
export cartesian!, circular_symmetric!, spherical_symmmetric!
export coordinates

include("vfvm_system.jl")
export unknowns
export enable_species!
export enable_boundary_species!
export enable_discontinuous_species!
export update_grid!
export boundary_dirichlet!
export boundary_neumann!
export boundary_robin!
export value
export check_allocs!
export physics!

include("vfvm_geometryitems.jl")
include("vfvm_formfactors.jl")
export meas,project
export unknown_indices
export edgevelocities,bfacevelocities

include("vfvm_newtoncontrol.jl")
export fixed_timesteps!,NewtonControl
export edgelength
export viewK,viewL,data

include("vfvm_solver.jl")
include("vfvm_diffeq_interface.jl")
export evolve!
export embed!
export solve!,solve

include("vfvm_postprocess.jl")
export nodeflux
include("vfvm_testfunctions.jl")
export integrate
export testfunction

include("vfvm_quantities.jl")
export ContinuousQuantity
export DiscontinuousQuantity
export InterfaceQuantity

include("vfvm_impedance.jl")
export impedance,freqdomain_impedance
export measurement_derivative

end


text:
# https://www.hackerrank.com/challenges/30-dictionaries-and-maps/problem

function rec_phone_book(n::Int)
    phone_book = Dict{String,String}()
    for _ in 1:n
        person, number = map(string, split(readline()))
        phone_book[person] = number
    end
    return phone_book
end

function rec_name(n::Int)
    name_list = String[]
    for _ in 1:n
        append!(name_list, readlines())
    end
    return name_list
end

function get_number(book::Dict{String,String}, name_rec::Array{String})
    names_in_book = keys(book)
    for name in name_rec
        if name in names_in_book
            phone = book[name]
            println("$name=$phone")
        else
            println("Not found")
        end
    end
end

n = parse(Int, readline())
phone_book = rec_phone_book(n)
name_list = rec_name(n)
get_number(phone_book, name_list)

max_stars_repo_path: Practice/Tutorials/30 Days of Code/Day 08 Dictionaries and Maps.jl

max_stars_repo_name: mtaufanr/hackerrank-code-julia

max_issues_repo_name: mtaufanr/hackerrank-code-julia

max_forks_repo_name: mtaufanr/hackerrank-code-julia


text:
using VLOptionsModeling

# Changed this function to private -
# generate the index array for N -
# number_of_levels = 4
# crr_index_array = compute_crr_index_array(number_of_levels)


text:
#=
  Assignment problems in Julia ConstraintSolver.jl

  Different assignments problem, both minimization and maximization.
  See the sources of the problem below.

  Compare to the following MiniZinc models, from which these problems
  are taken:
  * http://www.hakank.org/minizinc/assignment.mzn
  * http://www.hakank.org/minizinc/assignment2.mzn
  * http://www.hakank.org/minizinc/assignment2_2.mzn
  * http://www.hakank.org/minizinc/assignment3.mzn
  * http://www.hakank.org/minizinc/assignment5.mzn
  * http://www.hakank.org/minizinc/assignment6.mzn

  Model created by Hakan Kjellerstrand, hakank@gmail.com
  See also my Julia page: http://www.hakank.org/julia/

=#
using ConstraintSolver, JuMP
using Cbc, GLPK
const CS = ConstraintSolver
include("constraints_utils.jl")
include("assignment_instances.jl")

function assignment(data)

    cbc_optimizer = optimizer_with_attributes(Cbc.Optimizer, "logLevel" => 0)
    glpk_optimizer = optimizer_with_attributes(GLPK.Optimizer)

    model = Model(optimizer_with_attributes(CS.Optimizer,   # "all_solutions"=> true,
                                                            "all_optimal_solutions"=>true,
                                                            "logging"=>[],

                                                            # "traverse_strategy"=>:BFS,
                                                            # "traverse_strategy"=>:DFS, # <-
                                                            # "traverse_strategy"=>:DBFS,

                                                            # "branch_split"=>:Smallest,
                                                            # "branch_split"=>:Biggest,
                                                            # "branch_split"=>:InHalf, # <-

                                                            # "simplify"=>false,
                                                            # "simplify"=>true, # default

                                                            "time_limit"=>16,

                                                            # "lp_optimizer" => cbc_optimizer,
                                                            "lp_optimizer" => glpk_optimizer,
                                        ))

    op = data[:op]
    cost  = resize_matrix(data[:m])
    rows, cols = size(cost)

    @variable(model, x[1:rows,1:cols], Bin)
    @variable(model, 0 <= total_cost <= sum(cost), Int)

    # exacly one assignment per row, all rows must be assigned
    for i in 1:rows
        @constraint(model,sum([x[i,j] for j in 1:cols]) == 1 )
    end

    # zero or one assignments per column
    for j in 1:cols
        @constraint(model,sum([x[i,j] for i in 1:rows]) <= 1)
    end

    # calculate TotalCost

    @constraint(model,total_cost == sum(x.*cost))

    # optimization mode
    if op == :minimize
       @objective(model,Min,total_cost)
    else
        @objective(model,Max,total_cost)
    end

    # Solve the problem
    optimize!(model)

    status = JuMP.termination_status(model)
    # println("status:$status")
    if status == MOI.OPTIMAL
        num_sols = MOI.get(model, MOI.ResultCount())
        println("num_sols:$num_sols\n")
        if print_solutions
            for sol in 1:num_sols
                println("solution #$sol")
                xx = convert.(Integer,JuMP.value.(x; result=sol))
                total_costx = convert.(Integer,JuMP.value.(total_cost; result=sol))
                println("total_cost:$total_costx")
                assignments = [j for i in 1:rows for j in 1:cols if xx[i,j] == 1]
                println("Assignments: $assignments")
                #=
                for row in eachrow(xx)
                    println(row)
                end
                =#
            end
        end
    else
        println("status:$status")
    end

    return status
end

for instance in sort(collect(keys(assignment_instances)))
    println("\ninstance: $instance")
    @time assignment(assignment_instances[instance])
end

max_stars_repo_name: Wikunia/hakank

max_issues_repo_name: Wikunia/hakank

max_forks_repo_name: Wikunia/hakank


text:
# Unit tests for implementations/nbodysimulator/nbodysimulator_simulator.jl

@testset "nbodysimulator_simulator.jl" begin
    simulator1 = NBSimulator(400, 10, thermostat=NBodySimulator.AndersenThermostat(100, 2e-4))
    simulator2 = NBSimulator(400, 10, t₀=1000)
    simulator3 = NBSimulator(400u"ns", 10, simulator=DPRKN6())
    simulator4 = NBSimulator(400u"ns", 10, t₀=1000u"ns")

    @test simulator1 isa NBSimulator{NBodySimulator.VelocityVerlet,typeof(1u"ħ_au / hartree"),<:NBodySimulator.AndersenThermostat}
    @test simulator1.Δt == 400.0u"ħ_au / hartree"
    @test simulator1.steps == 10
    @test simulator1.t₀ == 0.0u"ħ_au / hartree"
    @test simulator1.thermostat == NBodySimulator.AndersenThermostat(100, 2e-4)
    @test simulator1.simulator == NBodySimulator.VelocityVerlet()
    @test Atomistic.time_range(simulator1) == (0.0, 4000.0)

    @test simulator2 isa NBSimulator{NBodySimulator.VelocityVerlet,typeof(1u"ħ_au / hartree"),NBodySimulator.NullThermostat}
    @test simulator2.Δt == 400.0u"ħ_au / hartree"
    @test simulator2.steps == 10
    @test simulator2.t₀ == 1000.0u"ħ_au / hartree"
    @test simulator2.thermostat == NBodySimulator.NullThermostat()
    @test simulator2.simulator == NBodySimulator.VelocityVerlet()
    @test Atomistic.time_range(simulator2) == (1000.0, 5000.0)

    @test simulator3 isa NBSimulator{DPRKN6,typeof(1u"ns"),NBodySimulator.NullThermostat}
    @test simulator3.Δt == 400.0u"ns"
    @test simulator3.steps == 10
    @test simulator3.t₀ == 0.0u"ns"
    @test simulator3.thermostat == NBodySimulator.NullThermostat()
    @test simulator3.simulator == DPRKN6()
    @test all(Atomistic.time_range(simulator3) .≈ (0.0, 10austrip(400.0u"ns")))

    @test simulator4 isa NBSimulator{NBodySimulator.VelocityVerlet,typeof(1u"ns"),NBodySimulator.NullThermostat}
    @test simulator4.Δt == 400.0u"ns"
    @test simulator4.steps == 10
    @test simulator4.t₀ == 1000.0u"ns"
    @test simulator4.thermostat == NBodySimulator.NullThermostat()
    @test simulator4.simulator == NBodySimulator.VelocityVerlet()
    @test all(Atomistic.time_range(simulator4) .≈ (austrip(1000.0u"ns"), austrip(1000.0u"ns") + 10austrip(400.0u"ns")))

    particles = [
        AtomsBase.Atom(:Ar, (@SVector [7, 7, 7])u"bohr", 6e-5(@SVector randn(3))u"bohr * hartree / ħ_au"),
        AtomsBase.Atom(:Ar, (@SVector [7, 7, 21])u"bohr", 6e-5(@SVector randn(3))u"bohr * hartree / ħ_au"),
        AtomsBase.Atom(:Ar, (@SVector [7, 21, 7])u"bohr", 6e-5(@SVector randn(3))u"bohr * hartree / ħ_au"),
        AtomsBase.Atom(:Ar, (@SVector [7, 21, 21])u"bohr", 6e-5(@SVector randn(3))u"bohr * hartree / ħ_au"),
        AtomsBase.Atom(:Ar, (@SVector [21, 7, 7])u"bohr", 6e-5(@SVector randn(3))u"bohr * hartree / ħ_au"),
        AtomsBase.Atom(:Ar, (@SVector [21, 7, 21])u"bohr", 6e-5(@SVector randn(3))u"bohr * hartree / ħ_au"),
        AtomsBase.Atom(:Ar, (@SVector [21, 21, 7])u"bohr", 6e-5(@SVector randn(3))u"bohr * hartree / ħ_au"),
        AtomsBase.Atom(:Ar, (@SVector [21, 21, 21])u"bohr", 6e-5(@SVector randn(3))u"bohr * hartree / ħ_au")
    ]
    box = [[28.0, 0.0, 0.0], [0.0, 28.0, 0.0], [0.0, 0.0, 28.0]]u"bohr"
    system = periodic_system(particles, box)

    potential = InteratomicPotentials.LennardJones(1.657e-21u"J", 0.34u"nm", 0.765u"nm", [:Ar])

    result = simulate(system, simulator1, potential)

    @test result isa NBSResult
    @test length(result.energy_cache) == length(result.result.solution.t)
end


text:
module Pulses

# more coming soon, once I rewrite them
include("computational_funcs.jl")
include("pulse_defs.jl")

export propagator, full_propagator, fast_propagator, full_fast_propagator,
expectation_value, track_expectation_value,
pulse, pi_pulse, pi_half_pulse, delay, optimal_pulse, PulseSequence, nmr_pulse, array_pulse

end


text:
function labelelledtri()
    p1 = O + (10EM, 0)
    line(O, p1, :stroke)
    label(string(p1), :SE, p1)

    p2 = p1 + (0, 10EM)
    line(p1, p2, :stroke)
    label(string(p2), :SE, p2)

    setdash("longdashed")
    line(p2, O, :stroke)
    setdash("solid")
    label("longdashed", :NE, midpoint(p2, O))

    fontface("Calibri-bold")
    fontsize(FS * 1.2)
    label("Rotation " * string(round(getrotation()*180/π)) * "°", :N, midpoint(O, p1))
    fontsize(FS)
end


text:
abstract type Quadrature end

dimension(q::Q) where {Q <: Quadrature} = 2

"""
Get the index of the abscissae pointing in the opposite direction of the given index

Here we assume that the abscissae of a quadrature are ordered such that each abscissae
follows its opposite abscissae
"""
function opposite(q::Quadrature, idx::Int64)
    if idx == 1
        return 1
    end
    if (mod(idx, 2) == 0)
        return idx + 1
    end
    return idx - 1
end

# Specific velocity sets
include("quadratures/D2Q4.jl")
include("quadratures/D2Q5.jl")
include("quadratures/D2Q9.jl")
include("quadratures/D2Q13.jl")
include("quadratures/D2Q17.jl")
include("quadratures/D2Q21.jl")
include("quadratures/D2Q37.jl")

const Quadratures = (
    D2Q4 = D2Q4(),
    D2Q5 = D2Q5(),
    D2Q9 = D2Q9(),
    D2Q13 = D2Q13(),
    D2Q17 = D2Q17(),
    D2Q21 = D2Q21(),
    D2Q37 = D2Q37(),
)


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

@doc raw"""
    ObjsFileShares(;
        private=nothing,
        public=nothing,
    )

    - private::Any
    - public::Any
"""
mutable struct ObjsFileShares <: SwaggerModel
    private::Any # spec type: Union{ Nothing, Any } # spec name: private
    public::Any # spec type: Union{ Nothing, Any } # spec name: public

    function ObjsFileShares(;private=nothing, public=nothing)
        o = new()
        validate_property(ObjsFileShares, Symbol("private"), private)
        setfield!(o, Symbol("private"), private)
        validate_property(ObjsFileShares, Symbol("public"), public)
        setfield!(o, Symbol("public"), public)
        o
    end
end # type ObjsFileShares

const _property_map_ObjsFileShares = Dict{Symbol,Symbol}(Symbol("private")=>Symbol("private"), Symbol("public")=>Symbol("public"))
const _property_types_ObjsFileShares = Dict{Symbol,String}(Symbol("private")=>"Any", Symbol("public")=>"Any")
Base.propertynames(::Type{ ObjsFileShares }) = collect(keys(_property_map_ObjsFileShares))
Swagger.property_type(::Type{ ObjsFileShares }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_ObjsFileShares[name]))}
Swagger.field_name(::Type{ ObjsFileShares }, property_name::Symbol) =  _property_map_ObjsFileShares[property_name]

function check_required(o::ObjsFileShares)
    true
end

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


text:
"""
    peelNode!(model::SequencingModel, node::RelaxedSequencingNode, arcs::Vector{ExactArc};bestKnownValue::Union{T,Nothing}=nothing,rrbSetting::Union{RRBSetting,Nothing},rrbPacket)where{T<:Real}

Peels a node, like splitting a node, but the sorting of arcs is pre-determined
Returns peeledNode (RelaxedSequencingNode), the new node

# Arguments
- `model::SequencingModel`: The sequencing problem
- `node::RelaxedSequencingNode`: The node to peel
- `arcs::Vector{ExactArc}`: The set of 'in' arcs belonging to the new node
- `bestKnownValue::Union{T,Nothing}`: The value of the best known feasible solution
- `rrbSetting::Union{RRBSetting,Nothing}`: A rough relaxed bounding method, or lack thereof
- `rrbPacket`: Optional data to be passed to the rrbFunction

"""
function peelNode!(model::SequencingModel, node::RelaxedSequencingNode, arcs::Vector{ExactArc};bestKnownValue::Union{T,Nothing}=nothing,rrbSetting::Union{RRBSetting,Nothing},rrbPacket)where{T<:Real}
    peeledNode = RelaxedSequencingNode(
        node.length, #bestPath
        node.state, #current state
        copy(node.allUp), #allUp
        BitVector(), #allDown
        copy(node.someUp), #someUp
        BitVector(), #someDown
        node.lengthToRoot, #to root
        node.lengthToTerminal, #to terminal
        Vector{Int}(),
        node.exact, #exact
        Vector{ExactArc}(), #arcsin
        Vector{ExactArc}() #arcsout
    )

    #add new arcs out
    for arc in node.arcsOut
        newArc = ExactArc(peeledNode, arc.destination, arc.assignment, arc.value)
        push!(peeledNode.arcsOut, newArc)
        push!(arc.destination.arcsIn, newArc)
    end

    #fix the destination of the in arc for the new node
    for arc in arcs
        newArc = ExactArc(arc.origin, peeledNode, arc.assignment, arc.value)
        push!(peeledNode.arcsIn, newArc)
        push!(arc.origin.arcsOut, newArc)
    end

    #get rid of the extra incoming arcs
    deleteArcs!(arcs)

    updateNodeDownVariables!(peeledNode,model)
    filterArcs!(peeledNode.arcsOut,model,bestKnownValue=bestKnownValue, rrbSetting=rrbSetting, rrbPacket=rrbPacket)

    if isempty(node.arcsIn)
        deleteArcs!(node.arcsOut)
    elseif isempty(node.arcsOut) && length(node) != length(model)
        deleteArcs!(node.arcsIn)
    else
        updateNodeDownVariables!(node,model)
        filterArcs!(node.arcsOut,model,bestKnownValue=bestKnownValue, rrbSetting=rrbSetting, rrbPacket=rrbPacket)
    end

    return peeledNode
end

"""
peelDD!(
    model::SequencingModel,
    maxWidth::T,
    dd::Vector{Vector{RelaxedSequencingNode}},
    relaxedSolution::Vector{T},
    frontierNode::RelaxedSequencingNode,
    fNodeIndex::U,
    splitOrder::Vector{T},
    bestKnownValue::Union{U,Nothing},
    rrbSetting::Union{RRBSetting,Nothing},
    rrbPacket,
    loggingOn::Bool,
    debugOn::Bool
)where{T<:Int,U<:Real}

Peel a diagram given the node to start from, and the diagram
Returns (dd, bound, relaxedSol, ddExact), (newDD, peeledBound, peeledRelaxedSol, peeledExact), bestKnownSolution, bestKnownValue
(dd, bound, relaxedSol, ddExact): is a Tuple{Vector{Vector{RelaxedSequencingNode}}, Real, Vector{Int}, Bool} storing all the updated info for 'dd'
(newDD, peeledBound, peeledRelaxedSol, peeledExact): is also a Tuple{Vector{Vector{RelaxedSequencingNode}}, Real, Vector{Int}, Bool} storing all the info for the peeled dd
bestKnownSolution, bestKnownValue: are Vector{Int}, Real

# Arguments
- `model::SequencingModel`: The sequencing problem
- `maxWidth::Int`: The max width allowed in a decision diagram layer
- `dd::Vector{Vector{RelaxedSequencingNode}}`: The starting diagram
- `relaxedSolution::::Vector{T}`: The best path through 'dd'
- `frontierNode::RelaxedSequencingNode`: The node start from
- `fNodeIndex::U`: The index of the layer of 'dd' that 'frontierNode' is on
- `splitOrder::Vector{T}`: A heuristic ordering of nodes
- `bestKnownValue::Union{T,Nothing}`: The value of the best known feasible solution
- `rrbSetting::Union{RRBSetting,Nothing}`: A rough relaxed bounding method, or lack thereof
- `rrbPacket`: Optional data to be passed to the rrbFunction
- `loggingOn::Bool`: An optional parameter that can be used to turn off logging to the console and local file
- `debugOn::Bool`: An optional parameter that can be used to turn on debug statements in other functions

"""
function peelDD!(
    model::SequencingModel,
    maxWidth::T,
    dd::Vector{Vector{RelaxedSequencingNode}},
    relaxedSolution::Vector{T},
    frontierNode::RelaxedSequencingNode,
    fNodeIndex::U,
    splitOrder::Vector{T},
    bestKnownValue::Union{U,Nothing},
    rrbSetting::Union{RRBSetting,Nothing},
    rrbPacket,
    loggingOn::Bool,
    debugOn::Bool
)where{T<:Int,U<:Real}
    cleanRelaxedDD(dd) = relaxedSequencingDD(model, maxWidth,splitOrder, dd = dd, debugOn=debugOn,bestKnownSolution=bestKnownSolution, bestKnownValue=bestKnownValue, rrbSetting=rrbSetting, rrbPacket=rrbPacket)
    bestKnownSolution = Vector{Int}()
    filter!(x->x!=frontierNode, dd[fNodeIndex])
    deleteArcs!(frontierNode.arcsIn)
    newDD = Vector{Vector{RelaxedSequencingNode}}()
    push!(newDD, [frontierNode])
    for i in 1:length(relaxedSolution)-length(frontierNode)
        arcMap = Dict{RelaxedSequencingNode, Vector{ExactArc}}()
        #create a map of child nodes to the arcs that should go with them
        for node in newDD[i]
            for arc in node.arcsOut
                if haskey(arcMap, arc.destination)
                    push!(arcMap[arc.destination], arc)
                else
                    arcMap[arc.destination] = [arc]
                end
            end
        end
        #iterate over each child node of the current layer and peel it
        push!(newDD, Vector{RelaxedSequencingNode}())
        for key in keys(arcMap)
            newNode = peelNode!(model, key, arcMap[key],bestKnownValue=bestKnownValue, rrbSetting=rrbSetting, rrbPacket=rrbPacket)
            #check the peeled node to make sure it is worth adding
            if !isempty(newNode.arcsOut) || length(model)==length(newNode)
                push!(newDD[i+1], newNode)
            else #delete in arcs so parent nodes may be removed in subsequent passes
                deleteArcs!(newNode.arcsIn)
            end
            #check the old node to make sure it doesnt need to be removed
            if isempty(key.arcsOut) && (i+fNodeIndex)<length(dd)
                #delete in arcs so parent nodes may be removed in subsequent passes
                deleteArcs!(key.arcsIn)
                filter!(x->x!=key, dd[i+fNodeIndex])
            elseif isempty(key.arcsIn)
                #delete in arcs so parent nodes may be removed in subsequent passes
                deleteArcs!(key.arcsOut)
                filter!(x->x!=key, dd[i+fNodeIndex])
            end
        end

        for node in dd[i+fNodeIndex]
            if isempty(node.arcsIn)
                deleteArcs!(node.arcsOut)
            end
        end
        filter!(x->length(x.arcsIn)!=0, dd[i+fNodeIndex])
        for node in dd[i+fNodeIndex]
            updateNodeDownVariables!(node,model)
        end
    end#iterate through the layers
    #check and upddate the two DDs
    if !isempty(last(dd))
        bottomUpUpdate(model, dd,bestKnownValue)
        bound = last(dd)[1].lengthToRoot
        relaxedSol = last(dd)[1].bestSeq
        bestKnownSolution, bestKnownValue = checkFeasibleTerminalSolutions!(model, last(dd)[1],bestKnownValue=bestKnownValue,bestKnownSolution=bestKnownSolution)
        if !isnothing(bound) && isBetterSolutionValue(model, bound, bestKnownValue)
            ddExact = false
        else
            dd = nothing
            bound = bestKnownValue
            relaxedSol = nothing
            ddExact = true
        end
    else
        dd = nothing
        bound = bestKnownValue
        relaxedSol = nothing
        ddExact = true
    end
    if !isempty(last(newDD))
        bottomUpUpdate(model, newDD, bestKnownValue)
        peeledBound = last(newDD)[1].lengthToRoot
        peeledRelaxedSol = last(newDD)[1].bestSeq
        bestKnownSolution, bestKnownValue = checkFeasibleTerminalSolutions!(model, last(newDD)[1],bestKnownValue=bestKnownValue,bestKnownSolution=bestKnownSolution)
        if !isnothing(peeledBound) && isBetterSolutionValue(model, peeledBound, bestKnownValue)
            newDD, peeledBound, peeledRelaxedSol, bestKnownSolution, bestKnownValue, peeledExact = cleanRelaxedDD(newDD)
            if peeledExact
                newDD = Vector{Vector{RelaxedSequencingNode}}()
            end
        else
            newDD = nothing
            peeledBound = bestKnownValue
            peeledRelaxedSol = nothing
            peeledExact = true
        end
    else
        newDD = nothing
        peeledBound = bestKnownValue
        peeledRelaxedSol = nothing
        peeledExact = true
    end

    return (dd, bound, relaxedSol, ddExact), (newDD, peeledBound, peeledRelaxedSol, peeledExact), bestKnownSolution, bestKnownValue
end

"""
peelAndRemove!(
    model::SequencingModel,
    dd::Vector{Vector{RelaxedSequencingNode}},
    frontierNode::RelaxedSequencingNode,
    fNodeIndex::U,
    bestKnownValue::Union{U,Nothing},
    rrbSetting::Union{RRBSetting,Nothing},
    rrbPacket,
    loggingOn::Bool,
    debugOn::Bool
)where{T<:Int,U<:Real}

A version of the peel process that deletes the peeled dd as it is created
Returns (dd, bound, relaxedSol, ddExact), bestKnownSolution, bestKnownValue
(dd, bound, relaxedSol, ddExact): is a Tuple{Vector{Vector{RelaxedSequencingNode}}, Real, Vector{Int}, Bool} storing all the updated info for 'dd'
bestKnownSolution, bestKnownValue: are Vector{Int}, Real

# Arguments
- `model::SequencingModel`: The sequencing problem
- `dd::Vector{Vector{RelaxedSequencingNode}}`: The starting diagram
- `frontierNode::RelaxedSequencingNode`: The node start from
- `fNodeIndex::U`: The index of the layer of 'dd' that 'frontierNode' is on
- `bestKnownValue::Union{T,Nothing}`: The value of the best known feasible solution
- `rrbSetting::Union{RRBSetting,Nothing}`: A rough relaxed bounding method, or lack thereof
- `rrbPacket`: Optional data to be passed to the rrbFunction
- `loggingOn::Bool`: An optional parameter that can be used to turn off logging to the console and local file
- `debugOn::Bool`: An optional parameter that can be used to turn on debug statements in other functions

"""
function peelAndRemove!(
    model::SequencingModel,
    dd::Vector{Vector{RelaxedSequencingNode}},
    frontierNode::RelaxedSequencingNode,
    fNodeIndex::U,
    bestKnownValue::Union{U,Nothing},
    rrbSetting::Union{RRBSetting,Nothing},
    rrbPacket,
    loggingOn::Bool,
    debugOn::Bool
)where{T<:Int,U<:Real}
    bestKnownSolution = Vector{Int}()

    #remove the node from the dd
    deleteArcs!(frontierNode.arcsIn)
    deleteArcs!(frontierNode.arcsOut)

    filter!(x->x!=frontierNode, dd[fNodeIndex])

    #iterate downwards
    for i in (fNodeIndex+1):length(dd)
        for node in dd[i]
            if isempty(node.arcsIn)
                deleteArcs!(node.arcsOut)
            end
        end
        filter!(x->length(x.arcsIn)!=0, dd[i])
        for node in dd[i]
            updateNodeDownVariables!(node,model)
            filterArcs!(node.arcsOut,model;bestKnownValue=bestKnownValue, rrbSetting=rrbSetting, rrbPacket=rrbPacket)
        end
    end

    #update upwards values
    if !isempty(last(dd))
        bottomUpUpdate(model, dd,bestKnownValue)

        bound = last(dd)[1].lengthToRoot
        relaxedSol = last(dd)[1].bestSeq
        bestKnownSolution, bestKnownValue = checkFeasibleTerminalSolutions!(model, last(dd)[1],bestKnownValue=bestKnownValue,bestKnownSolution=bestKnownSolution)

        if !isnothing(bound) && isBetterSolutionValue(model, bound, bestKnownValue)
            ddExact = false
        else
            dd = nothing
            bound = bestKnownValue
            relaxedSol = nothing
            ddExact = true
        end
    else
        dd = nothing
        bound = bestKnownValue
        relaxedSol = nothing
        ddExact = true
    end

    return (dd, bound, relaxedSol, ddExact), bestKnownSolution, bestKnownValue
end

"""
    addDDToQueue!(queue::Vector{Tuple{T, U, Vector{V}, Bool}}, block::Tuple{T, U, Vector{V}, Bool}, model::SequencingModel) where{T<:Vector{Vector{RelaxedSequencingNode}}, U<:Real, V<:Int}

Adds a tuple containing a relaxed dd and related useful information to a sorted processing queue (at the correct index)

# Arguments
- `queue::Vector{Tuple{T, U, Vector{V}, Bool}}`: The queue
- `block::Tuple{T, U, Vector{V}, Bool}`: The block to add to the queue
- `model::SequencingModel`: The sequencing problem

"""
function addDDToQueue!(queue::Vector{Tuple{T, U, Vector{V}, Bool}}, block::Tuple{T, U, Vector{V}, Bool}, model::SequencingModel) where{T<:Vector{Vector{RelaxedSequencingNode}}, U<:Real, V<:Int}
    #put worst bound at back of queue
    if isempty(queue)
        push!(queue, block)
    else
        insert!(
            queue,
            searchsorted(queue, block, by = x -> x[2],rev= (model.objective!=minimization)).start,
            block
        )
    end
end

"""
    finishPeelAndBound(bestKnownSolution::Vector{Int}, bestKnownValue::T;startTime::Union{U,Nothing}=nothing, timeElapsed::V=0,fileName::Union{Nothing,String}=nothing)where{T<:Real, U<:Real, V<:Real}

Print the optimal solution

# Arguments
- `bestKnownSolution::Vector{Int}`: The solution as an ordered list of nodes
- `bestKnownValue::T`: The cost of the solution
- `startTime::U`: the time the program started (in seconds since the epoch)
- `additionalTimeElapsed::V`: additional time used (in seconds)
- `fileName::Union{Nothing,String}`: An optional file to write the log statement to
"""
function finishPeelAndBound(bestKnownSolution::Vector{Int}, bestKnownValue::T;startTime::Union{U,Nothing}=nothing, timeElapsed::V=0,fileName::Union{Nothing,String}=nothing)where{T<:Real, U<:Real, V<:Real}
    logSequencingSolution(bestKnownSolution, bestKnownValue,firstLine="Optimal Solution Found:", fileName=fileName)
    if !isnothing(startTime)
        logRuntime(startTime, timeElapsed, fileName=fileName)
    end
    println()
end


text:
module GenieWebApp

using Genie, Logging, LoggingExtras

function main()
  Base.eval(Main, :(const UserApp = GenieWebApp))

  Genie.genie(; context = @__MODULE__)

  Base.eval(Main, :(const Genie = GenieWebApp.Genie))
  Base.eval(Main, :(using Genie))
end

end

max_stars_repo_name: jaantollander/genie-webapp-db

max_issues_repo_name: jaantollander/genie-webapp-db

max_forks_repo_name: jaantollander/genie-webapp-db


text:
using DrWatson
@quickactivate "StatReth"

# %%
using Plots
using StatsPlots
using StatsBase
using Distributions
using Turing  # for MCMCChains

# %%
n = 1_000
p_grid = range(0, 1, length = n)
prior = ones(n)
likelihood = @. pdf(Binomial(9, p_grid), 6)
posterior = likelihood .* prior
posterior ./= sum(posterior)

plot(p_grid, posterior)

# %%
ns = 10_000
weights = pweights(posterior)
samples = sample(p_grid, weights, ns)

density(samples)
plot!(p_grid, posterior * n)

# %%
mean(samples) do s
    s < 0.2
end

mean(samples) do s
    s > 0.8
end

mean(samples) do s
    0.2 < s < 0.8
end

quantile(samples, (0.2, 0.8))

chn = Chains(samples, ["no_water"])
hpd(chn; alpha = 0.66)

quantile(samples, ((1-0.66)/2, 1 - (1-0.66)/2))

mix = MixtureModel(Binomial.(9, samples))
rand(mix, 10_000) |> histogram


text:
# +
import Revise
import GLRenderer as GL
import ThreeDP3 as T
import Images as I
import MiniGSG as S
import PoseComposition: Pose
using Gen

hypers = T.Hyperparams(slack_dir_conc=300.0, slack_offset_var=0.5, p_outlier=0.01,
    noise=0.2, resolution=0.5, parent_face_mixture_prob=0.99, floating_position_bounds=(-1000.0, 1000.0, -1000.0,1000.0,-1000.0,1000.0))

params = T.SceneModelParameters(
    boxes=[S.Box(1.0,1.0,1.0), S.Box(1.0,1.0,1.0), S.Box(1.0,1.0,1.0)],
    get_cloud_from_poses_and_idx=(x,y,z) -> rand(3,100),
    camera_pose=T.IDENTITY_POSE,
    hyperparams=hypers, N=1)

num_obj = length(params.boxes)
g = T.graph_with_edges(3, [3=>1])
constraints = Gen.choicemap((T.structure_addr()) => g)

constraints[T.obs_addr()] = rand(3,100)

trace, _ = generate(T.scene, (params,), constraints);
@show T.get_poses(trace)


text:
function takeSnapshot(
    ocn::Ocean,
    filename::AbstractString;
    missing_value::Float64=1e20
)

    println("Outputting file: ", filename)

    _createNCFile(ocn, filename, missing_value)

    Dataset(filename, "a") do ds

        ds.attrib["timestamp"] = Dates.format(now(), "yyyy-mm-dd HH:MM:SS sss")
        ds.attrib["gridinfo_file"] = ocn.gi_file

        for (varname, (var, dim) ) in getVariableList(ocn, :RECORD, :BACKGROUND, :COORDINATE)

            print("Taking snapshot of variable: ", varname, "... ")

            if var == nothing
                println("not exist, skip this one.")
            else

                if dim == :SCALAR
                    ds.attrib[varname] = getfield(ocn, var)
                else
                    _write2NCFile(ds, varname, dim, var, missing_value)
                end
                println("done.")

            end

        end

    end

end

function loadSnapshot(
    filename::AbstractString;
    gridinfo_file::AbstractString
)
    local ocn

    Dataset(filename, "r") do ds

        Ts_clim_relax_time = nothing
        Ss_clim_relax_time = nothing

        Ts_clim = nothing
        Ss_clim = nothing

        if haskey(ds, "Ts_clim")
            Ts_clim_relax_time = ds.attrib["Ts_clim_relax_time"]
            Ts_clim = toZXY(nomissing(ds["Ts_clim"][:], NaN), :xyz)
        end

        if haskey(ds, "Ss_clim")
            Ss_clim_relax_time = ds.attrib["Ss_clim_relax_time"]
            Ss_clim = toZXY(nomissing(ds["Ss_clim"][:], NaN), :xyz)
        end

        ocn = Ocean(
            id            = 0,
            gridinfo_file = gridinfo_file,
            Nx            = ds.dim["Nx"],
            Ny            = ds.dim["Ny"],
            zs_bone       = nomissing(ds["zs_bone"][:], NaN);
            Ts            = toZXY( nomissing(ds["Ts"][:], NaN), :xyz),
            Ss            = toZXY( nomissing(ds["Ss"][:], NaN), :xyz),
            K_v           = ds.attrib["K_v"],
            Dh_T          = ds.attrib["Dh_T"],
            Dv_T          = ds.attrib["Dv_T"],
            Dh_S          = ds.attrib["Dh_S"],
            Dv_S          = ds.attrib["Dv_S"],
            fs            = nomissing(ds["fs"][:], NaN),
            ϵs            = nomissing(ds["epsilons"][:], NaN),
            T_ML          = nomissing(ds["T_ML"][:], NaN),
            S_ML          = nomissing(ds["S_ML"][:], NaN),
            h_ML          = nomissing(ds["h_ML"][:], NaN),
            h_ML_min      = nomissing(ds["h_ML_min"][:], NaN),
            h_ML_max      = nomissing(ds["h_ML_max"][:], NaN),
            we_max        = ds.attrib["we_max"],
            R             = ds.attrib["R"],
            ζ             = ds.attrib["zeta"],
            Ts_clim_relax_time = Ts_clim_relax_time,
            Ss_clim_relax_time = Ss_clim_relax_time,
            Ts_clim       = Ts_clim,
            Ss_clim       = Ss_clim,
            topo          = nomissing(ds["topo"][:], NaN),
            in_flds       = nothing,
        )

        for (varname, (var, dim) ) in getVariableList(ocn, :RECORD)

            println("Restoring :RECORD variable: ", varname)

            if typeof(var) <: AbstractArray
                var .= nomissing(ds[varname][:])
            else
                throw(ErrorException("Non vector variable cannot be part of :RECORD variables"))
            end
        end

    end

    return ocn
end

function _createNCFile(
    ocn::Ocean,
    filename::AbstractString,
    missing_value::Float64,
)

    Dataset(filename, "c") do ds

        defDim(ds, "N_ocs", ocn.N_ocs)
        defDim(ds, "Nx", ocn.Nx)
        defDim(ds, "Ny", ocn.Ny)
        defDim(ds, "Nz_bone", ocn.Nz_bone)
        defDim(ds, "NP_zs_bone",   length(ocn.zs_bone))
        defDim(ds, "time",   Inf)

        ds.attrib["_FillValue"] = missing_value

    end

end

function _write2NCFile(
    ds            :: Dataset,
    varname       :: AbstractString,
    dim           :: Tuple,
    var_data      :: AbstractArray{T},
    missing_value :: G) where T where G

    #println("Write : ", varname)

    ds_var = defVar(ds, varname, eltype(var_data), dim)

    ds_var.attrib["_FillValue"] = missing_value
    for (k, v) in getVarDesc(varname)
        ds_var.attrib[k] = v
    end

    ds_var[:] = var_data

end

"""
    This function is meant to append field into an NC file
    along the time dimension
"""
function _write2NCFile_time(
    ds            :: Dataset,
    varname       :: String,
    dim           :: Tuple,
    time          :: Integer,
    var_data      :: AbstractArray{T};
    missing_value :: Union{T, Nothing} = nothing,
) where T where G

#    time        :: Union{Nothing, UnitRange, Integer} = nothing,
#    time_exists :: Bool = true,
#    missing_value :: Union{T, Nothing} = nothing,
#) where T <: float

    local ds_var

    # Create variable if it is not in the file yet
    if ! ( varname in keys(ds) )

        ds_var = defVar(ds, varname, T, (dim..., "time"))

        if missing_value != nothing
            ds_var.attrib["_FillValue"] = missing_value
        end
    else
        ds_var = ds[varname]
    end

    ds_var[repeat([:,], length(dim))..., time] = var_data

end

max_stars_repo_name: meteorologytoday/IOM

max_issues_repo_name: meteorologytoday/IOM

max_forks_repo_name: meteorologytoday/IOM


text:
include("test_setup.jl")

@testset "Rachford-Rice" begin
    test_rachford_rice()
end

flash_methods = [SSIFlash(), NewtonFlash(), SSINewtonFlash()]
@testset "Peng-Robinson" begin
    for m in flash_methods
        name = typeof(m)
        @testset "$name" begin
            test_flash_pr(m)
        end
    end
end
@testset "Soave-Redlich-Kwong" begin
    for m in flash_methods
        name = typeof(m)
        @testset "$name" begin
            test_flash_srk(m)
        end
    end
end
@testset "Redlich-Kwong" begin
    for m in flash_methods
        name = typeof(m)
        @testset "$name" begin
            test_flash_rk(m)
        end
    end
end
@testset "Zudkevitch-Joffe" begin
    for m in flash_methods
        name = typeof(m)
        @testset "$name" begin
            test_flash_zj(m)
        end
    end
end
@testset "Zero allocating flash" begin
    for m in flash_methods
        name = typeof(m)
        @testset "$name - Arrays" begin
            test_flash_inplace(m, static_size = true)
        end
        @testset "$name - StaticArrays" begin
            test_flash_inplace(m, static_size = true)
        end
    end
end

@testset "Partial derivatives" begin
    test_flash_partials()
end


text:
macro linklibrary_p2f(n, es)
  path = normpath(Pkg.dir("FastSigmoid"),"c-src","libfastposit.so")
  fnname = QuoteNode(Symbol(:p, n, :e, es, :_to_f))
  inputtype = Symbol(:UInt, n)
  outputtype = n == 32 ? Float64 : Float32

  esc(quote
    p2f = (v) -> ccall( ($fnname, $path), $outputtype, ($inputtype,), v)
  end)
end

#spot unit testing
@linklibrary_p2f(8, 0)
@test p2f(0x7F) == 64.0

@linklibrary_p2f(16, 0)
@test p2f(0x0000) == zero(Float32)
@test p2f(0x8000) == Inf32
@test p2f(0b1100_0000_0000_0000) == -1.0f0
@test p2f(0x4000) == 1.0f0
@test p2f(0b0110_0000_0000_0000) == 2.0f0
@test p2f(0b0101_0000_0000_0000) == 1.5f0

@linklibrary_p2f(16, 1)
@test p2f(0x0000) == zero(Float32)
@test p2f(0x8000) == Inf32
@test p2f(0b1100_0000_0000_0000) == -1.0f0
@test p2f(0x4000) == 1.0f0
@test p2f(0b0110_0000_0000_0000) == 4.0f0
@test p2f(0b0101_0000_0000_0000) == 2.0f0
@test p2f(0b0101_1000_0000_0000) == 3.0f0
@test p2f(0b0010_0000_0000_0000) == 0.25f0
@test p2f(0b0011_0000_0000_0000) == 0.50f0

@linklibrary_p2f(16, 2)
@test p2f(0b0100_0000_0000_0000) == 1.0f0
@test p2f(0b0110_0000_0000_0000) == 16.0f0
@test p2f(0b0100_1000_0000_0000) == 2.0f0
@test p2f(0b0101_0000_0000_0000) == 4.0f0
@test p2f(0b0101_1000_0000_0000) == 8.0f0

@linklibrary_p2f(32, 2)
@test p2f(0x4000_0000) == 1.0
@test p2f(0x4400_0000) == 1.5
@test p2f(0x4800_0000) == 2.0
@test p2f(0x5000_0000) == 4.0
@test p2f(0x5800_0000) == 8.0
@test p2f(0x6000_0000) == 16.0

#comprehensive testing on 8,0;8,1;8,2
@linklibrary_p2f(8,0)
for idx=0x00:0xFF
  @test (p2f(idx),idx) == (Float32(reinterpret(Posit{8,0},idx)),idx)
end
@linklibrary_p2f(8,1)
for idx=0x00:0xFF
  @test (p2f(idx),idx) == (Float32(reinterpret(Posit{8,1},idx)),idx)
end
@linklibrary_p2f(8,2)
for idx=0x00:0xFF
  @test (p2f(idx),idx) == (Float32(reinterpret(Posit{8,2},idx)),idx)
end

#comprehensive testing on 16,0; 16,1; 16,2
@linklibrary_p2f(16,0)
for idx=0x0000:0xFFFF
  @test (p2f(idx),idx) == (Float32(reinterpret(Posit{16,0},idx)),idx)
end
@linklibrary_p2f(16,1)
for idx=0x0000:0xFFFF
  @test (p2f(idx),idx) == (Float32(reinterpret(Posit{16,1},idx)),idx)
end
@linklibrary_p2f(16,2)
for idx=0x0000:0xFFFF
  @test (p2f(idx),idx) == (Float32(reinterpret(Posit{16,2},idx)),idx)
end

#randomized testing on 32,0; 32,1; 32,2; 32,3
@linklibrary_p2f(32,0)
for idx=1:5000
  v = rand(UInt32)
  @test (p2f(v),v) == (Float64(reinterpret(Posit{32,0},v)),v)
end
@linklibrary_p2f(32,1)
for idx=1:5000
  v = rand(UInt32)
  @test (p2f(v),v) == (Float64(reinterpret(Posit{32,1},v)),v)
end
@linklibrary_p2f(32,2)
for idx=1:5000
  v = rand(UInt32)
  @test (p2f(v),v) == (Float64(reinterpret(Posit{32,2},v)),v)
end


text:
using AtomicLevels

function print_block(fun::Function,out=stdout)
    io = IOBuffer()
    fun(io)
    data = split(String(take!(io)), "\n")
    if length(data) == 1
        println(out, "[ $(data[1])")
    elseif length(data) > 1
        for (p,dl) in zip(vcat("⎡", repeat(["⎢"], length(data)-2), "⎣"),data)
            println(out, "$(p) $(dl)")
        end
    end
end

function print_states(cfgs::Vector{<:Configuration})
    foreach(cfgs) do cfg
        print_block() do io
            println(io, cfg)
            foreach(states.(csfs(cfg))) do ss
                print_block(io) do io
                    println(io, last(first(first(ss)).level.csf.terms))
                    foreach(ss) do s
                        print_block(io) do io
                            println(io)
                            foreach(sss -> println(io, sss), s)
                        end
                    end
                end
            end
        end
    end
end
print_states(cfgs::Configuration...) = print_states([cfgs...])

export print_states


text:
#-------------------------------------------------------------------
#* EMSO Model Library (EML) Copyright (C) 2004 - 2007 ALSOC.
#*
#* This LIBRARY is free software; you can distribute it and/or modify
#* it under the therms of the ALSOC FREE LICENSE as available at
#* http://www.enq.ufrgs.br/alsoc.
#*
#* EMSO Copyright (C) 2004 - 2007 ALSOC, original code
#* from http://www.rps.eng.br Copyright (C) 2002-2004.
#* All rights reserved.
#*
#* EMSO is distributed under the therms of the ALSOC LICENSE as
#* available at http://www.enq.ufrgs.br/alsoc.
#*--------------------------------------------------------------------
#* Author: Gerson Balbueno Bicca
#* $Id$
#*------------------------------------------------------------------
type DoublePipe_LMTD
	DoublePipe_LMTD()=begin
		new(
			DoublePipe_Basic(),
			DanaSwitcher(Dict{Symbol,Any}(
				:Brief=>"Flow Direction",
				:Valid=>["counter","cocurrent"],
				:Default=>"cocurrent"
			)),
			LMTD_Basic(Dict{Symbol,Any}(
				:Brief=>"LMTD Method of Calculation",
				:Symbol=>" "
			)),
			[
				:(_base_1.Details.Q = _base_1.Details.Ud*_base_1.Geometry.Pi*_base_1.Geometry.DoInner*_base_1.Geometry.Lpipe*Method.LMTD),
				:(_base_1.Details.Q = _base_1.Qestimated),
				:(Method.Fc = 1),
				:(Method.DT0 = _base_1.InletOuter.T - _base_1.InletInner.T),
				:(Method.DTL = _base_1.OutletOuter.T - _base_1.OutletInner.T),
				:(Method.DT0 = _base_1.InletOuter.T - _base_1.OutletInner.T),
				:(Method.DTL = _base_1.OutletOuter.T - _base_1.InletInner.T),
				:(Method.DT0 = _base_1.InletInner.T - _base_1.InletOuter.T),
				:(Method.DTL = _base_1.OutletInner.T - _base_1.OutletOuter.T),
				:(Method.DT0 = _base_1.InletInner.T - _base_1.OutletOuter.T),
				:(Method.DTL = _base_1.OutletInner.T - _base_1.InletOuter.T),
			],
			[
				"Duty","Duty","LMTD Correction Factor - True counter ou cocurrent flow","Temperature Difference at Inlet - Cocurrent Flow","Temperature Difference at Outlet - Cocurrent Flow","Temperature Difference at Inlet - Counter Flow","Temperature Difference at Outlet - Counter Flow","Temperature Difference at Inlet - Cocurrent Flow","Temperature Difference at Outlet - Cocurrent Flow","Temperature Difference at Inlet - Counter Flow","Temperature Difference at Outlet - Counter Flow",
			],
			[:FlowDirection,],
			[:Method,]
		)
	end
	_base_1::DoublePipe_Basic
	FlowDirection::DanaSwitcher
	Method::LMTD_Basic
	equations::Array{Expr,1}
	equationNames::Array{String,1}
	parameters::Array{Symbol,1}
	variables::Array{Symbol,1}
	attributes::Dict{Symbol,Any}
end
export DoublePipe_LMTD
function setEquationFlow(in::DoublePipe_LMTD)
	let switch=CalculationApproach
		if switch=="Full"
			addEquation(1)
		elseif switch=="Simplified"
			addEquation(2)
		end
	end
	addEquation(3)
	let switch=HotSide
		if HotSide==InletInner.T > InletOuter.T
			set(switch,"inner")
		end
		if HotSide==InletInner.T < InletOuter.T
			set(switch,"outer")
		end
		if switch=="outer"
			let switch=FlowDirection
				if switch=="cocurrent"
					addEquation(4)
					addEquation(5)
				elseif switch=="counter"
					addEquation(6)
					addEquation(7)
				end
			end
		elseif switch=="inner"
			let switch=FlowDirection
				if switch=="cocurrent"
					addEquation(8)
					addEquation(9)
				elseif switch=="counter"
					addEquation(10)
					addEquation(11)
				end
			end
		end
	end
end
function atributes(in::DoublePipe_LMTD,_::Dict{Symbol,Any})
	fields::Dict{Symbol,Any}=Dict{Symbol,Any}()
	fields[:Icon]="icon/DoublePipe"
	fields[:Pallete]=true
	fields[:Brief]="Double Pipe Heat Exchanger - LMTD Method"
	fields[:Info]="Thermal analysis of double pipe heat exchanger using the LMTD Method.

== Specify ==
* The Inlet Inner stream
* The Inlet Outer stream
== Setting Parameters ==
* Flow Direction:
** counter flow
** cocurrent flow (Default)
* Heat Transfer Correlations:
** Laminar flow
*** Hausen (Default)
*** Schlunder
** Transition flow
*** Gnielinski (Default)
*** Hausen
** Turbulent flow
*** Petukhov (Default)
*** Sieder Tate
* Geometrical Parameters:
** DoInner 	- Outside Diameter of Inner Pipe
** DiInner	- Inside Diameter of Inner Pipe
** DiOuter	- Inside Diameter of Outer pipe
** Lpipe		- Effective Tube Length of one segment of Pipe
** Kwall		- Tube Wall Material Thermal Conductivity
* Fouling:
**Rfi	-	Inside Fouling Resistance
**Rfo	- 	Outside Fouling Resistance
"
	drive!(fields,_)
	return fields
end
DoublePipe_LMTD(_::Dict{Symbol,Any})=begin
	newModel=DoublePipe_LMTD()
	newModel.attributes=atributes(newModel,_)
	newModel
end


text:
using Test
using ReinforcementLearningBase
using ReinforcementLearningEnvironments
using ArcadeLearningEnvironment
using PyCall
using OpenSpiel
# using SnakeGames
using Random
using StableRNGs
using Statistics

@testset "ReinforcementLearningEnvironments" begin
    include("environments/environments.jl")
end


text:
"""
  pb = pb_cplx2real(pb_C::Problem)

Convert a complex Polynomial Optimization Problem into a real polynomial
problem in real variables.
"""
function pb_cplx2real(pb_C::Problem)
  pb = Problem()
  for (varName, varType) in get_variables(pb_C)
    if varType <: Complex
      varName_real, varName_imag = varname_cplx2real(varName)
      add_variable!(pb, Variable(varName_real, Real))
      add_variable!(pb, Variable(varName_imag, Real))
    else
      add_variable!(pb, Variable(varName, varType))
    end
  end

  realPart, imagPart = cplx2real(pb_C.objective)
  set_objective!(pb, realPart)

  for (cstrName, cstr) in get_constraints(pb_C)
    realPart, imagPart = cplx2real(cstr.p)
    cstrName_real, cstrName_imag = varname_cplx2real(cstrName)
    if length(realPart) != 0
      cstrreal = real(cstr.lb) << realPart << real(cstr.ub)
      cstr.precond != :none && (cstrreal.precond = cstr.precond)
      add_constraint!(pb, cstrName_real, cstrreal)
    end
    if length(imagPart) != 0
      cstrimag = imag(cstr.lb) << imagPart << imag(cstr.ub)
      cstr.precond != :none && (cstrimag.precond = cstr.precond)
      add_constraint!(pb, cstrName_imag, cstrimag)
    end
  end
  return pb
end

max_stars_repo_name: Gimaju/GOC

max_issues_repo_name: Gimaju/GOC

max_forks_repo_name: Gimaju/GOC


text:
# Random Fourier Features
# from: Rahimi,Recht, "Random Features for Large-Scale Kernel Machines", NIPS 2007
#
# Danny Perry (dperry@cs.utah.edu)
# Oct 2014
#
# compare to Gaussian kernel:

using PyPlot
using PyCall
@pyimport matplotlib.lines as mlines
using Debug
using MAT

using RandomFourierFeatures
using Kernel
using Sketch

macro nonzero(default, list)
	:([$list[find($list .> 0)],$default])
end

X = []
Labels = []

name = "gaussian"

d = 0
n = 0

@debug function showresults(fn,dataset)

	FDstyles = ["bo-","gs-","yD-","mv-","c<-","r+-"]

	rankkstyles = ["bs--","rs--","gs--","ms--","cs--","ys--"]
	Krankkstyles = ["b+:","r+:","g+:","m+:","c+:","y+:"]

	if dataset == "cpu"
		n = 3000
	end

	file = matopen(fn)
	errs_fro = read(file, "errs_fro")
	errs_l2 = read(file, "errs_l2")
	timings = read(file, "timings")
	timings_test = read(file, "timings_test")

	errs_FD_fro = read(file, "errs_FD_fro")
	errs_FD_l2 = read(file, "errs_FD_l2")
	timings_FD = read(file, "timings_FD")
	timings_test_FD = read(file, "timings_test_FD")
	errs_nystrom_fro = read(file, "errs_nystrom_fro")
	errs_nystrom_l2 = read(file, "errs_nystrom_l2")
	timings_nystrom = read(file, "timings_nystrom")
	#timings_test_nystrom = read(file, "timings_test_nystrom")
	errs_nystromwr_fro = read(file, "errs_nystromwr_fro")
	errs_nystromwr_l2 = read(file, "errs_nystromwr_l2")
	timings_nystromwr = read(file, "timings_nystromwr")
	timings_test_nystromwr = read(file, "timings_test_nystromwr")
	errs_rff_nystrom_fro = read(file, "errs_rff_nystrom_fro")
	errs_rff_nystrom_l2 = read(file, "errs_rff_nystrom_l2")
	timings_rff_nystrom = read(file, "timings_rff_nystrom")
	timings_test_rff_nystrom = read(file, "timings_test_rff_nystrom")
	dims = read(file, "dims")
	ells = read(file, "ells")
	epsilons = read(file, "epsilons")
	#sketch_size = read(file, "sketch_size")
  #sketch_size = 5
	#dims = [1:length(errs_fro)]
	dims = dims[1:length(errs_fro)]
	#epsilons = [1e1 1e0 1e-1 1e-2 1e-3]
	#ells = zeros(length(epsilons))
	#for i=1:length(epsilons)
	#	ells[i] = ceil(sketch_size + sketch_size/epsilons[i])
	#end
	close(file)

	marksize = 8
	fontsize = 25
	tickfontsize = 20
	linewidth = 2

	ellis = collect(1:length(ells))
	titlename = dataset
	addlim = 1

	figure()
	xmin=1e6
	xmax=-1e6
	ymin=1e6
	ymax=-1e6
	xmin = min(xmin, minimum(@nonzero(xmin,dims.^2)))
	xmax = max(xmax, maximum(@nonzero(xmax,dims.^2)))
	ymin = min(ymin, minimum(@nonzero(ymin,errs_fro)))
	ymax = max(ymax, maximum(@nonzero(ymax,errs_fro)))
	plot(dims.^2,errs_fro,color="r",marker="^",linewidth=linewidth,markersize=marksize)
	hold(:on)
	#plot(dims.^2,errs_nystrom_fro,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	ymin = min(ymin, minimum(@nonzero(ymin,errs_nystromwr_fro)))
	ymax = max(ymax, maximum(@nonzero(ymax,errs_nystromwr_fro)))
	plot(dims.^2,errs_nystromwr_fro,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	names = ["RNCA","Nystrom"]
	for li=ellis
		xmin = min(xmin, minimum(@nonzero(xmin,ells[li].*dims)))
		xmax = max(xmax, maximum(@nonzero(xmax,ells[li].*dims)))
		ymin = min(ymin, minimum(@nonzero(ymin,errs_FD_fro[li,1:length(dims)])))
		ymax = max(ymax, maximum(@nonzero(ymax,errs_FD_fro[li,1:length(dims)])))
  	plot(ells[li] .* dims, reshape(errs_FD_fro[li,1:length(dims)],length(dims)) ,color=@sprintf("%s",FDstyles[li][1]),marker=@sprintf("%s",FDstyles[li][2]),linewidth=linewidth,markersize=marksize)
		push!(names, @sprintf("SKPCA (%d)",ells[li]))
	end
	ylim(ymin*0.90,ymax*1.10)
	xlim(xmin*0.90,xmax*1.10)
	#legend(names, loc="upper right", frameon = false, numpoints = 1)
  yscale("log")
  xscale("log")
  #ylabel("Kernel Frobenius Error", fontsize = fontsize)
  xlabel("space", fontsize = fontsize)
	tick_params(axis="both", which="major", labelsize=tickfontsize)
	tick_params(axis="both", which="minor", labelsize=tickfontsize)
	#title(titlename)
	subplots_adjust(bottom=0.15)
	savefig(@sprintf("%s_space_error_fro.png",dataset),bbox_inches="tight")
	savefig(@sprintf("%s_space_error_fro.pdf",dataset),bbox_inches="tight")

	#figure()
	#l1 = mlines.Line2D([], [], color="r", marker="^", linewidth=linewidth, markersize=marksize, label=names[1], numpoints=1)
	##legend(handles=[l1])
	###legend(names, loc="upper right", frameon = false, numpoints = 1)
	#savefig(@sprintf("#legend.png",dataset),bbox_inches="tight")
	#savefig(@sprintf("#legend.pdf",dataset),bbox_inches="tight")

	figure()
	xmin=1e6
	xmax=-1e6
	ymin=1e6
	ymax=-1e6
	xmin = min(xmin, minimum(@nonzero(xmin,dims.^2)))
	xmax = max(xmax, maximum(@nonzero(xmax,dims.^2)))
	ymin = min(ymin, minimum(@nonzero(ymin,errs_l2)))
	ymax = max(ymax, maximum(@nonzero(ymax,errs_l2)))
	plot(dims.^2,errs_l2 ,color="r",marker="^",linewidth=linewidth,markersize=marksize)
	hold(:on)
	#plot(dims.^2,errs_nystrom_l2,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	ymin = min(ymin, minimum(@nonzero(ymin,errs_nystromwr_l2)))
	ymax = max(ymax, maximum(@nonzero(ymax,errs_nystromwr_l2)))
	plot(dims.^2,errs_nystromwr_l2 ,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	names = ["RNCA","Nystrom"]
	for li=ellis
		xmin = min(xmin, minimum(@nonzero(xmin,ells[li].*dims)))
		xmax = max(xmax, maximum(@nonzero(xmax,ells[li].*dims)))
		ymin = min(ymin, minimum(@nonzero(ymin,errs_FD_l2[li,1:length(dims)])))
		ymax = max(ymax, maximum(@nonzero(ymax,errs_FD_l2[li,1:length(dims)])))
  	plot(ells[li] .* dims, reshape(errs_FD_l2[li,1:length(dims)],length(dims)) ,color=@sprintf("%s",FDstyles[li][1]),marker=@sprintf("%s",FDstyles[li][2]),linewidth=linewidth,markersize=marksize)
		push!(names, @sprintf("SKPCA (%d)",ells[li]))
	end
	ylim(ymin*0.90,ymax*1.10)
	xlim(xmin*0.90,xmax*1.10)
	legend(names, loc="upper right", frameon = false, numpoints = 1)
  yscale("log")
  xscale("log")
	title(dataset)
  ylabel("Kernel Spectral Error", fontsize=fontsize)
  xlabel("space", fontsize=fontsize)
	tick_params(axis="both", which="major", labelsize=tickfontsize)
	tick_params(axis="both", which="minor", labelsize=tickfontsize)
	#ylim(ymin*.90,ymax*1.10)
	title(titlename)
	subplots_adjust(bottom=0.15)
	savefig(@sprintf("%s_space_error_l2.png",dataset),bbox_inches="tight")
	savefig(@sprintf("%s_space_error_l2.pdf",dataset),bbox_inches="tight")

	############ SAMPLE SIZE PLOTS

	figure()
	xmin=1e6
	xmax=-1e6
	ymin=1e6
	ymax=-1e6
	xmin = min(xmin, minimum(@nonzero(xmin,dims)))
	xmax = max(xmax, maximum(@nonzero(xmax,dims)))
	ymin = min(ymin, minimum(@nonzero(ymin,errs_fro)))
	ymax = max(ymax, maximum(@nonzero(ymax,errs_fro)))
	plot(dims,errs_fro ,color="r",marker="^",linewidth=linewidth,markersize=marksize)
	hold(:on)
	#plot(dims.^2,errs_nystrom_fro,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	ymin = min(ymin, minimum(@nonzero(ymin,errs_nystromwr_fro)))
	ymax = max(ymax, maximum(@nonzero(ymax,errs_nystromwr_fro)))
	plot(dims,errs_nystromwr_fro ,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	names = ["RNCA","Nystrom"]
	for li=ellis
		xmin = min(xmin, minimum(@nonzero(xmin,dims)))
		xmax = max(xmax, maximum(@nonzero(xmax,dims)))
		ymin = min(ymin, minimum(@nonzero(ymin,errs_FD_fro[li,1:length(dims)])))
		ymax = max(ymax, maximum(@nonzero(ymax,errs_FD_fro[li,1:length(dims)])))
  	plot(dims, reshape(errs_FD_fro[li,1:length(dims)],length(dims)) ,color=@sprintf("%s",FDstyles[li][1]),marker=@sprintf("%s",FDstyles[li][2]),linewidth=linewidth,markersize=marksize)
		push!(names, @sprintf("SKPCA (%d)",ells[li]))
	end
	ylim(ymin*0.90,ymax*1.10)
	xlim(xmin*0.90,xmax*1.01)
	legend(names, loc="upper right", frameon = false, numpoints = 1)
  yscale("log")
  xscale("log")
  ylabel("Kernel Frobenius Error", fontsize = fontsize)
  xlabel("sample size", fontsize = fontsize)
	tick_params(axis="both", which="major", labelsize=tickfontsize)
	tick_params(axis="both", which="minor", labelsize=tickfontsize)
	#ylim(ymin*.90,ymax*1.10)
	#ylim(1e0,1e2)
	title(titlename)
	subplots_adjust(bottom=0.15)
	savefig(@sprintf("%s_sample_error_fro.png",dataset),bbox_inches="tight")
	savefig(@sprintf("%s_sample_error_fro.pdf",dataset),bbox_inches="tight")

	figure()
	xmin=1e6
	xmax=-1e6
	ymin=1e6
	ymax=-1e6
	xmin = min(xmin, minimum(@nonzero(xmin,dims)))
	xmax = max(xmax, maximum(@nonzero(xmax,dims)))
	ymin = min(ymin, minimum(@nonzero(ymin,errs_l2)))
	ymax = max(ymax, maximum(@nonzero(ymax,errs_l2)))
	plot(dims,errs_l2 ,color="r",marker="^",linewidth=linewidth,markersize=marksize)
	hold(:on)
	ymin = min(ymin, minimum(@nonzero(ymin,errs_nystromwr_l2)))
	ymax = max(ymax, maximum(@nonzero(ymax,errs_nystromwr_l2)))
	#plot(dims.^2,errs_nystrom_l2,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	plot(dims,errs_nystromwr_l2 ,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	names = ["RNCA","Nystrom"]
	for li=ellis
		xmin = min(xmin, minimum(@nonzero(xmin,dims)))
		xmax = max(xmax, maximum(@nonzero(xmax,dims)))
		ymin = min(ymin, minimum(@nonzero(ymin,errs_FD_l2[li,1:length(dims)])))
		ymax = max(ymax, maximum(@nonzero(ymax,errs_FD_l2[li,1:length(dims)])))
  	plot(dims, reshape(errs_FD_l2[li,1:length(dims)],length(dims))  ,color=@sprintf("%s",FDstyles[li][1]),marker=@sprintf("%s",FDstyles[li][2]),linewidth=linewidth,markersize=marksize)
		push!(names, @sprintf("SKPCA (%d)",ells[li]))
	end
	ylim(ymin*0.90,ymax*1.10)
	xlim(xmin*0.90,xmax*1.01)
	legend(names, loc="upper right", frameon = false, numpoints = 1)
  yscale("log")
  xscale("log")
	title(dataset)
  ylabel("Kernel Spectral Error", fontsize=fontsize)
  xlabel("sample size", fontsize=fontsize)
	tick_params(axis="both", which="major", labelsize=tickfontsize)
	tick_params(axis="both", which="minor", labelsize=tickfontsize)
	title(titlename)
	subplots_adjust(bottom=0.15)
	savefig(@sprintf("%s_sample_error_l2.png",dataset),bbox_inches="tight")
	savefig(@sprintf("%s_sample_error_l2.pdf",dataset),bbox_inches="tight")

	############ RUNTIME PLOTS - training

	figure()
	xmin=1e6
	xmax=-1e6
	ymin=1e6
	ymax=-1e6
	xmin = min(xmin, minimum(@nonzero(xmin,dims)))
	xmax = max(xmax, maximum(@nonzero(xmax,dims)))
	ymin = min(ymin, minimum(@nonzero(ymin,timings)))
	ymax = max(ymax, maximum(@nonzero(ymax,timings)))
	plot(dims,timings ,color="r",marker="^",linewidth=linewidth,markersize=marksize)
	hold(:on)
	#plot(dims.^2,errs_nystrom_fro,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	ymin = min(ymin, minimum(@nonzero(ymin,timings_nystromwr)))
	ymax = max(ymax, maximum(@nonzero(ymax,timings_nystromwr)))
	plot(dims,timings_nystromwr, color="k",marker="*",linewidth=linewidth,markersize=marksize)
	names = ["RNCA","Nystrom"]
	for li=ellis
		xmin = min(xmin, minimum(@nonzero(xmin,dims)))
		xmax = max(xmax, maximum(@nonzero(xmax,dims)))
		ymin = min(ymin, minimum(@nonzero(ymin,timings_FD[li,1:length(dims)])))
		ymax = max(ymax, maximum(@nonzero(ymax,timings_FD[li,1:length(dims)])))
  	plot(dims, reshape(timings_FD[li,1:length(dims)],length(dims)) ,color=@sprintf("%s",FDstyles[li][1]),marker=@sprintf("%s",FDstyles[li][2]),linewidth=linewidth,markersize=marksize)
		push!(names, @sprintf("SKPCA (%d)",ells[li]))
	end
	ylim(ymin*0.90,ymax*1.10)
	xlim(xmin*0.90,xmax*1.01)
	legend(names, loc="upper right", frameon = false, numpoints = 1)
  yscale("log")
  xscale("log")
  ylabel("Runtime (sec)", fontsize = fontsize)
  xlabel("sample size", fontsize = fontsize)
	tick_params(axis="both", which="major", labelsize=tickfontsize)
	tick_params(axis="both", which="minor", labelsize=tickfontsize)
	#ylim(ymin*.90,ymax*1.10)
	#ylim(1e0,1e2)
	title(titlename)
	subplots_adjust(bottom=0.15)
	savefig(@sprintf("%s_timings_train.png",dataset),bbox_inches="tight")
	savefig(@sprintf("%s_timings_train.pdf",dataset),bbox_inches="tight")

	############ RUNTIME PLOTS - tests

	figure()
	xmin=1e6
	xmax=-1e6
	ymin=1e6
	ymax=-1e6
	xmin = min(xmin, minimum(@nonzero(xmin,dims)))
	xmax = max(xmax, maximum(@nonzero(xmax,dims)))
	ymin = min(ymin, minimum(@nonzero(ymin,timings_test)))
	ymax = max(ymax, maximum(@nonzero(ymax,timings_test)))
	plot(dims,timings_test ,color="r",marker="^",linewidth=linewidth,markersize=marksize)
	hold(:on)
	#plot(dims.^2,errs_nystrom_fro,color="k",marker="*",linewidth=linewidth,markersize=marksize)
	ymin = min(ymin, minimum(@nonzero(ymin,timings_test_nystromwr)))
	ymax = max(ymax, maximum(@nonzero(ymax,timings_test_nystromwr)))
	plot(dims,timings_test_nystromwr, color="k",marker="*",linewidth=linewidth,markersize=marksize)
	names = ["RNCA","Nystrom"]
	for li=ellis
		xmin = min(xmin, minimum(@nonzero(xmin,dims)))
		xmax = max(xmax, maximum(@nonzero(xmax,dims)))
		ymin = min(ymin, minimum(@nonzero(ymin,timings_test_FD[li,1:length(dims)])))
		ymax = max(ymax, maximum(@nonzero(ymax,timings_test_FD[li,1:length(dims)])))
  	plot(dims, reshape(timings_test_FD[li,1:length(dims)],length(dims)) ,color=@sprintf("%s",FDstyles[li][1]),marker=@sprintf("%s",FDstyles[li][2]),linewidth=linewidth,markersize=marksize)
		push!(names, @sprintf("SKPCA (%d)",ells[li]))
	end
	ylim(ymin*0.90,ymax*1.10)
	xlim(xmin*0.90,xmax*1.01)
	#legend(names, loc="upper center", frameon = false, numpoints = 1, ncol=length(names))
	legend(names, loc="upper center", frameon = false, numpoints = 1)
  yscale("log")
  #xscale("log")
  ylabel("Runtime (sec)", fontsize = fontsize)
  xlabel("sample size", fontsize = fontsize)
	tick_params(axis="both", which="major", labelsize=tickfontsize)
	tick_params(axis="both", which="minor", labelsize=tickfontsize)
	#ylim(ymin*.90,ymax*1.10)
	#ylim(1e0,1e2)
	title(titlename)
	subplots_adjust(bottom=0.15)
	savefig(@sprintf("%s_timings_test.png",dataset),bbox_inches="tight")
	savefig(@sprintf("%s_timings_test.pdf",dataset),bbox_inches="tight")

	PyPlot.plt[:show]()
end

showresults(ARGS[1],ARGS[2])


text:
function plot_3D(x)
    n = size(x)
    let
        vol = [x[ix,iy,iz] for ix in 1:n[1], iy in 1:n[2], iz in 1:n[3]]
        fig, ax, _ = volume(1:n[1], 1:n[2], 1:n[3], vol, colormap = :plasma, colorrange = (minimum(vol), maximum(vol)),
            figure = (; resolution = (800,800)),
            axis=(; type=Axis3, perspectiveness = 0.5,  azimuth = 7.19, elevation = 0.57,
                aspect = (1,1,1)))

        fig
    end
end

max_stars_repo_name: slimgroup/TwoPhaseSpeedTest

max_issues_repo_name: slimgroup/TwoPhaseSpeedTest

max_forks_repo_name: slimgroup/TwoPhaseSpeedTest


text:
# ----------------------------------------------------
# --- Radio Sim test file
# ----------------------------------------------------
# This file is dedicated to RadioSim backend

# ----------------------------------------------------
# --- Define test routines
# ----------------------------------------------------

"""
Test that the device can be open, configured and closed
"""
function check_open()
    # --- Main parameters
	carrierFreq		= 440e6;	# --- The carrier frequency
	samplingRate	= 8e6;         # --- Targeted bandwdith
    gain			= 0;         # --- Rx gain
	sdr				= :radiosim
    # --- Create the E310 device
   global sdr =openSDR(sdr,carrierFreq,samplingRate,gain);
   # Type is OK
   @test typeof(sdr) == RadioSim
   # SDR is not released yet
   @test sdr.rx.released == false
   # Configuration : Carrier Freq
   @test sdr.rx.carrierFreq == carrierFreq
   @test sdr.tx.carrierFreq == carrierFreq
   # Configuration : Badnwidth
   @test sdr.rx.samplingRate == samplingRate
   @test sdr.tx.samplingRate == samplingRate
   # --- We close the SDR
   close(sdr)
   @test isClosed(sdr) == true
end

"""
Check the carrier frequency update of the RadioSim device
"""
function check_carrierFreq()
    # --- Main parameters
	carrierFreq		= 440e6;	# --- The carrier frequency
	samplingRate	= 8e6;         # --- Targeted bandwdith
    gain			= 0;         # --- Rx gain
	sdr				= :radiosim
    # --- Create the E310 device
   global sdr =openSDR(sdr,carrierFreq,samplingRate,gain);
   #  Classic value, should work
   updateCarrierFreq!(sdr,800e6)
   @test sdr.rx.carrierFreq == 800e6
   @test sdr.tx.carrierFreq == 800e6
   # Targeting WiFi, should work
   updateCarrierFreq!(sdr,2400e6)
   @test sdr.rx.carrierFreq == 2400e6
   @test sdr.tx.carrierFreq == 2400e6
   close(sdr);
   @test isClosed(sdr) == true
end

"""
Check the sampling frequency update of the RadioSim device
"""
function check_samplingRate()
    # --- Main parameters
	carrierFreq		= 440e6;	# --- The carrier frequency
	samplingRate	= 8e6;         # --- Targeted bandwdith
    gain			= 0;         # --- Rx gain
	sdr				= :radiosim
    # --- Create the E310 device
   global sdr =openSDR(sdr,carrierFreq,samplingRate,gain);
   #  Classic value, should work
   updateSamplingRate!(sdr,8e6)
   @test sdr.rx.samplingRate == 8e6
   @test sdr.tx.samplingRate == 8e6
   # Targeting WiFi, should work
   updateSamplingRate!(sdr,15.36e6)
   @test sdr.rx.samplingRate == 15.36e6
   @test sdr.tx.samplingRate == 15.36e6
   close(sdr);
   @test isClosed(sdr) == true
end

"""
Check the gain update for RadioSim
"""
function check_gain()
    # --- Main parameters
	carrierFreq		= 440e6;	# --- The carrier frequency
	samplingRate	= 8e6;         # --- Targeted bandwdith
    gain			= 0;         # --- Rx gain
	sdr				= :radiosim
    # --- Create the E310 device
   global sdr =openSDR(sdr,carrierFreq,samplingRate,gain);
   #  Classic value, should work
   updateGain!(sdr,20)
   # @test sdr.rx.samplingRate == 8e6
   # @test sdr.tx.samplingRate == 8e6
   close(sdr);
   @test isClosed(sdr) == true
end

"""
Test that the device  can received data
"""
function check_recv()
    # --- Main parameters
	carrierFreq		= 440e6;	# --- The carrier frequency
	samplingRate	= 8e6;         # --- Targeted bandwdith
    gain			= 0;         # --- Rx gain
	sdr				= :radiosim
    # --- Create the E310 device
    global sdr =openSDR(sdr,carrierFreq,samplingRate,gain);
    sig = recv(sdr,1024)
    @test length(sig) == 1024
    @test eltype(sig) == Complex{Float32}
    close(sdr)
    @test isClosed(sdr) == true
end

"""
Test that radiosim device can feed desired data
"""
function check_recv_prealloc()
    # --- Main parameters
	carrierFreq		= 440e6;	# --- The carrier frequency
	samplingRate	= 100e6;         # --- Targeted bandwdith
    gain			= 0.0;         # --- Rx gain
	sdr				= :radiosim;
	nbSamples		= 1024;
    # ----------------------------------------------------
    # --- Buffer emulation
    # ----------------------------------------------------
    buffer = collect(1:4096);
    # --- Create the E310 device
    global sdr =openSDR(sdr,carrierFreq,samplingRate,gain;packetSize=512,buffer=buffer);
    sig = recv(sdr,1024)
    @test length(sig) == 1024
    @test eltype(sig) == Complex{Float32}
    # The first call should give the 1024 fist samples
    @test all(sig .== collect(1:1024))
    # --- Second call give second part
    sig = recv(sdr,1024)
    @test length(sig) == 1024
    @test eltype(sig) == Complex{Float32}
    @test all(sig .== collect(1025:2048))
    # --- Third call to have the end
    sig = recv(sdr,2048)
    @test length(sig) == 2048
    @test eltype(sig) == Complex{Float32}
    @test all(sig .== collect(2049:4096))
    # --- Another complete call with complete buffer
    sig = recv(sdr,4096)
    @test length(sig) == 4096
    @test eltype(sig) == Complex{Float32}
    @test all(sig .== buffer)
    # --- Close radio
    close(sdr)
    @test isClosed(sdr) == true
end

# ----------------------------------------------------
# --- Test calls
# ----------------------------------------------------
@testset "RadioSims Backend " begin
    @testset "Scanning and opening" begin
        check_open()
    end

    @testset "Radio configuration" begin
        check_carrierFreq()
        check_samplingRate()
        check_gain()
    end

    @testset "Checking data retrieval"  begin
        check_recv()
        check_recv_prealloc()
    end
end


text:
"""
```
normals{VT,FD,FT,FO}(vertices::Vector{Point{3, VT}},
                     faces::Vector{Face{FD,FT,FO}},
                     NT = Normal{3, VT})
```

Compute all vertex normals.
"""
function normals{VT,FD,FT,FO}(vertices::Vector{Point{3, VT}},
                                 faces::Vector{Face{FD,FT,FO}},
                                 NT = Normal{3, VT})
    normals_result = zeros(Point{3, VT}, length(vertices)) # initilize with same type as verts but with 0
    for face in faces
        v = vertices[face]
        # we can get away with two edges since faces are planar.
        a = v[2] - v[1]
        b = v[3] - v[1]
        n = cross(a,b)
        for i =1:FD
            fi = onebased(face, i)
            normals_result[fi] = normals_result[fi] + n
        end
    end
    map!(normalize, normals_result)
    map(NT, normals_result)
end


text:
# | Read a .2dm (SMS Aquaveo) mesh-file and construct a @Mesh@
function load(st::Stream{format"2DM"}, MeshType=GLNormalMesh)
    FT       = facetype(MeshType)
    VT       = vertextype(MeshType)
    faces    = FT[]
    vertices = VT[]
    io = stream(st)
    for line = readlines(io)
        if !isempty(line) && !iscntrl(line)
            line = chomp(line)
            w = split(line)
            if w[1] == "ND"
                push!(vertices, Point{3, Float32}(w[3:end]))
            elseif w[1] == "E3T"
                push!(faces, Face{3, Cuint, 0}(w[3:5]))
            elseif w[1] == "E4Q"
                push!(faces, decompose(FT, Face{4, Cuint, 0}(w[3:6]))...)
            else
                continue
            end
        end
    end
    MeshType(vertices, faces)
end

function render{T, O}(i::Int, f::Face{3, T, O})
    string("E3T $i ", join(Face{3, Cuint, 0}(f), " "))
end

function render{T, O}(i::Int, f::Face{4, T, O})
    string("E4Q $i ", join(Face{4, Cuint, 0}(f), " "))
end
# | Write @Mesh@ to an IOStream
function save(st::Stream{format"2DM"}, m::AbstractMesh)
    io = stream(st)
    println(io, "MESH2D")
    for (i, f) in enumerate(m.faces)
        println(io, render(i, f))
    end
    for (i, v) in enumerate(m.vertices)
        println(io, "ND $i ", join(v, " "))
    end
    nothing
end

@compat show(io::IO, ::MIME"model/2dm", mesh::AbstractMesh) = save(io, mesh)


text:
using CUDA
using Colors: RGB
using FastAI
using FilePathsBase
using FastAI.Datasets
using DLPipelines
using DataAugmentation
using DataAugmentation: getbounds
using Flux
using StaticArrays
using Test
using TestSetExtensions

ENV["DATADEPS_ALWAYS_ACCEPT"] = "true"
include("testdata.jl")

function test_gpu(f)
    if CUDA.functional()
        f()
    else
        @test_broken "No GPU"
    end
end


text:
@testset "Chain Rules" begin
    rng = MersenneTwister(123456)
    x = rand(rng, 5)
    y = rand(rng, 5)
    r = rand(rng, 5)
    Q = Matrix(Cholesky(rand(rng, 5, 5), 'U', 0))
    @assert isposdef(Q)

    compare_gradient(:Zygote, [x, y]) do xy
        Euclidean()(xy[1], xy[2])
    end
    compare_gradient(:Zygote, [x, y]) do xy
        SqEuclidean()(xy[1], xy[2])
    end
    compare_gradient(:Zygote, [x, y]) do xy
        KernelFunctions.DotProduct()(xy[1], xy[2])
    end
    compare_gradient(:Zygote, [x, y]) do xy
        KernelFunctions.Delta()(xy[1], xy[2])
    end
    compare_gradient(:Zygote, [x, y]) do xy
        KernelFunctions.Sinus(r)(xy[1], xy[2])
    end
    if VERSION < v"1.6"
        @test_broken "Chain rule of SqMahalanobis is broken in Julia pre-1.6"
    else
        compare_gradient(:Zygote, [Q, x, y]) do Qxy
            SqMahalanobis(Qxy[1])(Qxy[2], Qxy[3])
        end
    end
end


text:
# train DL and clac predictions

include(pwd()*"/dlmodel.jl")

Random.seed!(1234) # set random numbers

w = Any[ xavier(n_hidden_1,n_input), zeros(n_hidden_1,1),
         xavier(n_hidden_2,n_hidden_1), zeros(n_hidden_2,1),
         xavier(n_out,n_hidden_2), zeros(n_out,1)]

nbr_training_obs = length(y_train)
nbr_parameters = 0

for i in w
    global nbr_parameters = nbr_parameters + size(i,1)*size(i,2)
end

@printf "Nbr training obs %d, nbr parameters %d, obs/parameters %.2f\n" nbr_training_obs nbr_parameters nbr_training_obs/nbr_parameters

optim = optimizers(w, Adam)

# training
dropout_percentage = 0.
lambda = [0.1,0.1,0.1]
@time loss_train_vec, loss_val_vec = train(2000, dropout_percentage, lambda, w, optim)

# calc predictions
y_pred_train_proc = predict(w, x_train, 0)
y_pred_val_proc = predict(w, x_val, 0)
y_pred_proc = predict(w, x_test, 0)

y_pred_train = class_nll(y_pred_train_proc,[1,2])
y_pred_val = class_nll(y_pred_val_proc,[1,2])
y_pred_test = class_nll(y_pred_proc,[1,2])

# loss
loss_training = loss(w,x_train, y_train, 0, lambda)
loss_val = loss(w,x_val, y_val, 0, lambda)
loss_test = loss(w,x_test, y_test, 0, lambda)

# classification results
class_res_training = classification_results(y_pred_train, y_train, [1,2])
class_res_val = classification_results(y_pred_val, y_val, [1,2])
class_res_test = classification_results(y_pred_test, y_test, [1,2])

# loss as function of epoch
PyPlot.figure()
PyPlot.plot(loss_train_vec, "b")
PyPlot.ylabel("Loss")
PyPlot.xlabel("Epoch")

PyPlot.figure()
PyPlot.plot(loss_val_vec, "r")
PyPlot.ylabel("Loss")
PyPlot.xlabel("Epoch")

max_stars_repo_name: SamuelWiqvist/dl-compute-project

max_issues_repo_name: SamuelWiqvist/dl-compute-project

max_forks_repo_name: SamuelWiqvist/dl-compute-project


text:
Maybe{T} = Union{T, Nothing}

struct FindNTT{G<:Maybe{BigInt}, Q<:Maybe{BigInt}, N<:Maybe{Int}}
    g::G
    q::Q
    n::N
end

function (params::FindNTT{Nothing, Nothing, Int})()
    n = params.n
    for q in primes(n, 1000000n)
        for g in 2:min(q, 100)
            if mod(q - 1, n) == 0 && powermod(g, n, q) == 1 && !(1 in powermod.(g, 2:n - 1, q))
                println("(g, q, n) = ($g, $q, $n)")
            end
        end
    end
end

function (params::FindNTT{Nothing, BigInt, Nothing})()
    q = params.q
    for g in 2:q
        for n in 1:q
            if powermod(g, n, q) == 1
                println("(g, q, n) = ($g, $q, $n)")
                break
            end
        end
    end
end

function (params::FindNTT{BigInt, BigInt, Nothing})()
    (g, q) = (params.g, params.q)
    @assert g >= 0
    @assert g < q
    for n in 1:q
        if powermod(g, n, q) == 1
            println("(g, q, n) = ($g, $q, $n)")
            break
        end
    end
end

function (params::FindNTT{Nothing, BigInt, Int})()
    (q, n) = (params.q, params.n)
    for g in 2:q
        if powermod(g, n, q) == 1
            println("(g, q, n) = ($g, $q, $n)")
            break
        end
    end
end

function (params::FindNTT{BigInt, BigInt, Int})()
    g, q, n = params.g, params.q, params.n
    if mod(q - 1, n) == 0 && powermod(g, n, q) == 1 && !(1 in powermod.(g, 2:n - 1, q))
        println("(g, q, n) = ($g, $q, $n)")
    end
end


text:
function load_problem(path)
	p = splitpath(path)[end]
	name = replace(p, ".mps"=>"")

	id = Dict("id"=>name)
	model = read_from_file(path)
	MMKP_Prob(id, model)
end

function load_problems(; folder="MMKP/problems")
	map(load_problem, readdir(folder, join=true))
end

max_stars_repo_name: Dibillilia/JuliaOptHeuristics

max_issues_repo_name: Dibillilia/JuliaOptHeuristics

max_forks_repo_name: Dibillilia/JuliaOptHeuristics


text:
using Rubin
using Tests
using Elliptic
using HypergeometricFunctions
using Polylogarithms
using SpecialFunctions

@test integrate((e*x)^m*(a+b*x^n)^3*(A+B*x^n)*(c+d*x^n), x) == :(a*x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(B*a*(a*d+3*b*c)+3*A*b*(a*d+b*c))+b*x^(1+3n)*(e*x)^m*(1+m+3n)^-1*(A*b*(b*c+3*a*d)+3*B*a*(a*d+b*c))+a^2*x^(1+n)*(e*x)^m*(1+m+n)^-1*(A*a*d+B*a*c+3*A*b*c)+b^2*x^(1+4n)*(e*x)^m*(1+m+4n)^-1*(A*b*d+B*b*c+3*B*a*d)+A*c*a^3*e^-1*(e*x)^(1+m)*(1+m)^-1+B*d*b^3*x^(1+5n)*(e*x)^m*(1+m+5n)^-1)
@test integrate((e*x)^m*(a+b*x^n)^2*(A+B*x^n)*(c+d*x^n), x) == :(x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(A*b*(b*c+2*a*d)+B*a*(a*d+2*b*c))+a*x^(1+n)*(e*x)^m*(1+m+n)^-1*(A*a*d+B*a*c+2*A*b*c)+b*x^(1+3n)*(e*x)^m*(1+m+3n)^-1*(A*b*d+B*b*c+2*B*a*d)+A*c*a^2*e^-1*(e*x)^(1+m)*(1+m)^-1+B*d*b^2*x^(1+4n)*(e*x)^m*(1+m+4n)^-1)
@test integrate((e*x)^m*(A+B*x^n)*(a+b*x^n)*(c+d*x^n), x) == :(x^(1+n)*(e*x)^m*(1+m+n)^-1*(A*a*d+A*b*c+B*a*c)+x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(A*b*d+B*a*d+B*b*c)+A*a*c*e^-1*(e*x)^(1+m)*(1+m)^-1+B*b*d*x^(1+3n)*(e*x)^m*(1+m+3n)^-1)
@test integrate((e*x)^m*(A+B*x^n)*(c+d*x^n), x) == :(x^(1+n)*(e*x)^m*(1+m+n)^-1*(A*d+B*c)+A*c*e^-1*(e*x)^(1+m)*(1+m)^-1+B*d*x^(1+2n)*(e*x)^m*(1+m+2n)^-1)
@test integrate((e*x)^m*(a+b*x^n)^3*(c+d*x^n)^2*(A+B*x^n), x) == :(x^(1+3n)*(e*x)^m*(1+m+3n)^-1*(A*b*(b^2*c^2+3*a^2*d^2+6*a*b*c*d)+B*a*(a^2*d^2+3*b^2*c^2+6*a*b*c*d))+a*x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(A*(a^2*d^2+3*b^2*c^2+6*a*b*c*d)+B*a*c*(2*a*d+3*b*c))+b*x^(1+4n)*(e*x)^m*(1+m+4n)^-1*(c*b^2*(B*c+2*A*d)+3*B*a^2*d^2+3*a*b*d*(A*d+2*B*c))+A*a^3*c^2*e^-1*(e*x)^(1+m)*(1+m)^-1+B*b^3*d^2*x^(1+6n)*(e*x)^m*(1+m+6n)^-1+c*a^2*x^(1+n)*(e*x)^m*(1+m+n)^-1*(B*a*c+2*A*a*d+3*A*b*c)+d*b^2*x^(1+5n)*(e*x)^m*(1+m+5n)^-1*(A*b*d+2*B*b*c+3*B*a*d))
@test integrate((e*x)^m*(a+b*x^n)^2*(c+d*x^n)^2*(A+B*x^n), x) == :(x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(A*(a^2*d^2+b^2*c^2+4*a*b*c*d)+2*B*a*c*(a*d+b*c))+x^(1+3n)*(e*x)^m*(1+m+3n)^-1*(B*a^2*d^2+c*b^2*(B*c+2*A*d)+2*a*b*d*(A*d+2*B*c))+A*a^2*c^2*e^-1*(e*x)^(1+m)*(1+m)^-1+B*b^2*d^2*x^(1+5n)*(e*x)^m*(1+m+5n)^-1+a*c*x^(1+n)*(e*x)^m*(1+m+n)^-1*(2*A*(a*d+b*c)+B*a*c)+b*d*x^(1+4n)*(e*x)^m*(1+m+4n)^-1*(A*b*d+2*B*a*d+2*B*b*c))
@test integrate((e*x)^m*(c+d*x^n)^2*(A+B*x^n)*(a+b*x^n), x) == :(x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(a*d*(A*d+2*B*c)+b*c*(B*c+2*A*d))+c*x^(1+n)*(e*x)^m*(1+m+n)^-1*(A*b*c+B*a*c+2*A*a*d)+d*x^(1+3n)*(e*x)^m*(1+m+3n)^-1*(A*b*d+B*a*d+2*B*b*c)+A*a*c^2*e^-1*(e*x)^(1+m)*(1+m)^-1+B*b*d^2*x^(1+4n)*(e*x)^m*(1+m+4n)^-1)
@test integrate((e*x)^m*(c+d*x^n)^2*(A+B*x^n), x) == :(A*c^2*e^-1*(e*x)^(1+m)*(1+m)^-1+B*d^2*x^(1+3n)*(e*x)^m*(1+m+3n)^-1+c*x^(1+n)*(e*x)^m*(1+m+n)^-1*(B*c+2*A*d)+d*x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(A*d+2*B*c))
@test integrate((e*x)^m*(a+b*x^n)^3*(c+d*x^n)^3*(A+B*x^n), x) == :(x^(1+3n)*(e*x)^m*(1+m+3n)^-1*(A*(a^3*d^3+b^3*c^3+9*a*d*b^2*c^2+9*b*c*a^2*d^2)+3*B*a*c*(a^2*d^2+b^2*c^2+3*a*b*c*d))+x^(1+4n)*(e*x)^m*(1+m+4n)^-1*(B*a^3*d^3+b^3*c^2*(B*c+3*A*d)+3*b*a^2*d^2*(A*d+3*B*c)+9*a*c*d*b^2*(A*d+B*c))+A*a^3*c^3*e^-1*(e*x)^(1+m)*(1+m)^-1+B*b^3*d^3*x^(1+7n)*(e*x)^m*(1+m+7n)^-1+a^2*c^2*x^(1+n)*(e*x)^m*(1+m+n)^-1*(3*A*(a*d+b*c)+B*a*c)+b^2*d^2*x^(1+6n)*(e*x)^m*(1+m+6n)^-1*(A*b*d+3*B*a*d+3*B*b*c)+3*a*c*x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(A*(a^2*d^2+b^2*c^2+3*a*b*c*d)+B*a*c*(a*d+b*c))+3*b*d*x^(1+5n)*(e*x)^m*(1+m+5n)^-1*(B*a^2*d^2+c*b^2*(A*d+B*c)+a*b*d*(A*d+3*B*c)))
@test integrate((e*x)^m*(a+b*x^n)^2*(c+d*x^n)^3*(A+B*x^n), x) == :(x^(1+3n)*(e*x)^m*(1+m+3n)^-1*(a^2*d^2*(A*d+3*B*c)+b^2*c^2*(B*c+3*A*d)+6*a*b*c*d*(A*d+B*c))+c*x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(A*(b^2*c^2+3*a^2*d^2+6*a*b*c*d)+B*a*c*(2*b*c+3*a*d))+d*x^(1+4n)*(e*x)^m*(1+m+4n)^-1*(B*a^2*d^2+3*c*b^2*(A*d+B*c)+2*a*b*d*(A*d+3*B*c))+A*a^2*c^3*e^-1*(e*x)^(1+m)*(1+m)^-1+B*b^2*d^3*x^(1+6n)*(e*x)^m*(1+m+6n)^-1+a*c^2*x^(1+n)*(e*x)^m*(1+m+n)^-1*(B*a*c+2*A*b*c+3*A*a*d)+b*d^2*x^(1+5n)*(e*x)^m*(1+m+5n)^-1*(A*b*d+2*B*a*d+3*B*b*c))
@test integrate((e*x)^m*(c+d*x^n)^3*(A+B*x^n)*(a+b*x^n), x) == :(c*x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(b*c*(B*c+3*A*d)+3*a*d*(A*d+B*c))+d*x^(1+3n)*(e*x)^m*(1+m+3n)^-1*(a*d*(A*d+3*B*c)+3*b*c*(A*d+B*c))+c^2*x^(1+n)*(e*x)^m*(1+m+n)^-1*(A*b*c+B*a*c+3*A*a*d)+d^2*x^(1+4n)*(e*x)^m*(1+m+4n)^-1*(A*b*d+B*a*d+3*B*b*c)+A*a*c^3*e^-1*(e*x)^(1+m)*(1+m)^-1+B*b*d^3*x^(1+5n)*(e*x)^m*(1+m+5n)^-1)
@test integrate((e*x)^m*(c+d*x^n)^3*(A+B*x^n), x) == :(A*c^3*e^-1*(e*x)^(1+m)*(1+m)^-1+B*d^3*x^(1+4n)*(e*x)^m*(1+m+4n)^-1+c^2*x^(1+n)*(e*x)^m*(1+m+n)^-1*(B*c+3*A*d)+d^2*x^(1+3n)*(e*x)^m*(1+m+3n)^-1*(A*d+3*B*c)+3*c*d*x^(1+2n)*(e*x)^m*(1+m+2n)^-1*(A*d+B*c))

max_stars_repo_path: test/1 Algebraic functions/1.1 Binomial products/1.1.3 General/1.1.3.6 (g x)^m (a+b x^n)^p (c+d x^n)^q (e+f x^n)^r.jl


text:
import ElectricFields: Iaustrip

@testset "Field creation" begin
    @testset "Parametric field creation" begin
        #    Test parametric creation of fields, both from inside a function and
        #    from global scope.

        function test_parametric_fields(l)
            Is = range(0u"W/cm^2",stop=1e6u"W/cm^2", length=l)

            for (i,I₀) in enumerate(Is)
                @field(IR) do
                    λ = 800.0u"nm"
                    I₀ = I₀
                    τ = 6.2u"fs"
                    Tmax = 5
                end
                @test intensity(IR) == Iaustrip(I₀)
            end
        end
        test_parametric_fields(11)
        test_parametric_fields(8)

        Is = range(0u"W/cm^2",stop=1e6u"W/cm^2", length=11)

        for (i,I₀) in enumerate(Is)
            @field(IR) do
                λ = 800.0u"nm"
                I₀ = I₀
                τ = 6.2u"fs"
                Tmax = 5
            end
            @test intensity(IR) == Iaustrip(I₀)
        end

        @field(IR) do
            λ = 800.0u"nm"
            I₀ = 1e14u"W/cm^2"
            τ = 6.2u"fs"
            Tmax = 5
        end

        @test dimensions(IR) == 1

        @field(IR2) do
            λ = 800.0u"nm"
            I₀ = 1e14u"W/cm^2"
            τ = 6.2u"fs"
            Tmax = 5
            ξ = 0.4
        end

        @test dimensions(IR2) == 3
    end

    @test_throws ArgumentError @field(F) do
        I₀ = 1e14u"W/cm^2"
        λ = 800.0u"nm"
        kind = :there_is_no_such_field
    end

    @testset "Competing quantities" begin
        @field(A) do
            I₀ = 1e14u"W/cm^2"
            λ = 800.0u"nm"
            τ = 6.2u"fs"
            σmax = 4
        end

        @test period(A) |> u"fs" ≈ 2.6685127615852164u"fs"
        @test wavenumber(A) |> u"cm^-1" ≈ 12500.0u"cm^-1"
        @test frequency(A) |> u"THz" ≈ 374.7405725u"THz"
        @test photon_energy(A) ≈ 0.05695419066118882

        @test ponderomotive_potential(A) |> u"eV" ≈ 5.9758653162292505u"eV"
        @test intensity(A) ≈ 0.0028494532412131697
        @test amplitude(A) ≈ 0.05338026769639452
        @test vector_potential(A) ≈ 0.9372491659822719

        @field(B) do
            I₀ = 1e14u"W/cm^2"
            T = 2.6685127615852164u"fs"
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(C) do
            I₀ = 1e14u"W/cm^2"
            ν = 12500.0u"cm^-1"
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(D) do
            I₀ = 1e14u"W/cm^2"
            f = 374.7405725u"THz"
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(E) do
            I₀ = 1e14u"W/cm^2"
            ω = 2.354564459136067u"Prad/s"
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(E) do
            I₀ = 1e14u"W/cm^2"
            ħω = 0.05695419066118882
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(F) do
            I₀ = 0.0028494532412131697
            λ = 800.0u"nm"
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(G) do
            E₀ = 0.05338026769639452
            λ = 800.0u"nm"
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(H) do
            A₀ = 0.9372491659822719
            λ = 800.0u"nm"
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(I) do
            Uₚ = 5.9758653162292505u"eV"
            λ = 800.0u"nm"
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(J) do
            Uₚ = 0.21960899978361606
            λ = 800.0u"nm"
            τ = 6.2u"fs"
            σmax = 4
        end

        @field(K) do
            I₀ = 1e14u"W/cm^2"
            λ = 800.0u"nm"
            τ = 6.2u"fs"
            σmax = 4
            ξ = 1.0
        end

        @testset "$(fun)" for (fun,u) in [(wavelength, u"nm"),
                                          (period, u"fs"),
                                          (frequency, u"THz"),
                                          (photon_energy, NoUnits),
                                          (ponderomotive_potential, u"eV"),
                                          (intensity, NoUnits),
                                          (amplitude, NoUnits),
                                          (vector_potential, NoUnits)]
            @testset "i = $i" for (i,f) in enumerate([B,C,D,E,F,G,H,I,J,K])
                @test fun(f) |> u ≈ fun(A) |> u
            end
        end
    end
end


text:
import Elemental
const El = Elemental

using MPI

m = 500
n = 250
display = true
worldRank = MPI.Comm_rank(MPI.COMM_WORLD)

function rectang(height::Integer, width::Integer)
    A = El.DistMatrix()
    El.uniform!(A, height, width)
    return A
end

A = rectang(m, n)
b = El.DistMatrix()
El.gaussian!(b, m, 1)

# if display
    # El.Display(A, "A")
    # El.Display(b, "b")
# end

# ctrl = El.LPAffineCtrl_d()
# ctrl.mehrotraCtrl.progress = True

# timeLAV = @elapsed x = El.lav(A, b, ctrl)
timeLAV = @elapsed x = El.lav(A, b)
if MPI.Comm_rank(MPI.COMM_WORLD) == 0
    println("LAV time: $timeLAV seconds")
end

# if display
    # El.Display( x, "x" )

bTwoNorm = El.nrm2(b)
bInfNorm = El.maxNorm(b)

r = copy(b)
A_mul_B!(-1.0, A, x, 1., r)

# if display
    # El.Display(r, "r")
# end

rTwoNorm = El.nrm2(r)
rOneNorm = El.entrywiseNorm(r, 1.0)
if worldRank == 0
    println("|| b ||_2       = $bTwoNorm")
    println("|| b ||_oo      = $bInfNorm")
    println("|| A x - b ||_2 = $rTwoNorm")
    println("|| A x - b ||_1 = $rOneNorm")
end

timeLS = @elapsed xLS = El.leastSquares(A, b)

if worldRank == 0
    println("LS time: $timeLS seconds")
end
# if display
    # El.Display(xLS, "x_{LS}")
# end

rLS = copy(b)
A_mul_B!(-1.0, A, xLS, 1.0, rLS)

# if display:
    # El.Display(rLS, "A x_{LS} - b")
# end
rLSTwoNorm = El.nrm2(rLS)
rLSOneNorm = El.entrywiseNorm(rLS, 1.0)
if worldRank == 0
    println("|| A x_{LS} - b ||_2 = $rLSTwoNorm")
    println("|| A x_{LS} - b ||_1 = $rLSOneNorm")
end

# Require the user to press a button before the figures are closed
# commSize = El.mpi.Size( El.mpi.COMM_WORLD() )
El.Finalize()
# if commSize == 1:
#   raw_input('Press Enter to exit')


text:
module ExamplePlutoCI
    println("ExamplePlutoCI.jl - Some module functionality")
end

max_stars_repo_name: MattAmos/Example-Pluto-CI

max_issues_repo_name: MattAmos/Example-Pluto-CI

max_forks_repo_name: MattAmos/Example-Pluto-CI


text:
module pkgExample

export plusone

greet() = print("Hello World!")

plusone(x::Int) = x + 1

include("sumRand.jl")

end # module


text:
using Revise, Select, Test, FieldDefaults

import Select: selectable, @selectable, flattenable, @flattenable

@default_kw struct SubTest{X,Y}
    x::X | 1.0
    y::Y | :default
end

@selectable @flattenable @default_kw struct TestStruct{A,B,C,D}
    a::A | SubTest() | true  | Union{Nothing,SubTest}
    b::B | _         | true  | _
    c::C | SubTest() | true  | Union{Nothing,SubTest}
    d::D | SubTest() | false | _
end

t = TestStruct(1.0, 2, SubTest(8.0, 9.0), :nochange)
@test select(t) == ((Union{Nothing,SubTest}, Float64, :a), (Union{Nothing,SubTest}, SubTest, :c))

@test updateselected(t, (Nothing, Nothing,)) ==
    TestStruct{Nothing,Int64,Nothing,Symbol}(nothing, 2, nothing, :nochange)
@test updateselected(t, (Nothing, SubTest,)) ==
    TestStruct{Nothing,Int64,SubTest{Float64,Symbol},Symbol}(nothing, 2, SubTest(1.0, :default), :nochange)

t = TestStruct(SubTest(2,:update), 2, SubTest(2.0,:noupdate), :nochange)
@test updateselected(t, (SubTest, SubTest,)) ==
    TestStruct{SubTest{Float64,Symbol},Int64,SubTest{Float64,Symbol},Symbol}(SubTest(1.0, :default), 2, SubTest(2.0, :noupdate), :nochange)