text
stringlengths
5
1.02M
using Random, Plots, DataFrames, ColorSchemes import Plots: plot """ plot(𝐼::Individuals) Plot the initial and final positions as scatter plot in x,y plane. """ function plot(𝐼::Individuals) 🔴_by_t = groupby(𝐼.🔴, :t) if (sum(names(🔴_by_t).=="lon")==0) fig=scatter(🔴_by_t[1].x,🔴_by_t[1].y,c=:red,label="t0",marker = (:circle, stroke(0))) scatter!(🔴_by_t[end].x,🔴_by_t[end].y,c=:blue,label="t1",marker = (:circle, stroke(0))) else fig=scatter(🔴_by_t[1].lon,🔴_by_t[1].lat,c=:red,label="t0",marker = (:circle, stroke(0))) scatter!(🔴_by_t[end].lon,🔴_by_t[end].lat,c=:blue,label="t1",marker = (:circle, stroke(0))) end return fig end """ plot_paths(df::DataFrame,nn::Integer,dMax::Float64=0.) Plot random subset of size nn trajectories / paths. """ function plot_paths(df::DataFrame,nn::Integer,dMax::Float64=0.) IDs = randperm(maximum(df.ID)) COs=["w" "y" "g" "k"] plt=plot(leg=false) df_by_ID = groupby(df, :ID) ID_list=[df_by_ID[i][1,:ID] for i in 1:length(df_by_ID)] for ii=1:nn jj=findall(ID_list.==IDs[ii])[1] tmp=df_by_ID[jj] if dMax > 0. d=abs.(diff(tmp[!,:lon])) jj=findall(d .> dMax) tmp[jj,:lon].=NaN; tmp[jj,:lat].=NaN d=abs.(diff(tmp[!,:lat])) jj=findall(d .> dMax) tmp[jj,:lon].=NaN; tmp[jj,:lat].=NaN end CO=COs[mod(ii,4)+1] hasproperty(df,:z) ? plot!(tmp[!,:lon],tmp[!,:lat],tmp[!,:z],linewidth=0.3) : nothing !hasproperty(df,:z) ? plot!(tmp[!,:lon],tmp[!,:lat],linewidth=0.3) : nothing #plot!(tmp[!,:lon],tmp[!,:lat],tmp[!,:z],linewidth=0.3) end return plt end """ scatter_zcolor(df,zc; cam=(0, 90)) ``` df=groupby(𝐼.🔴, :t) scatter_zcolor(df[end],df[end].z) ``` """ function scatter_zcolor(df,zc; cam=(0, 90)) lo=extrema(df.lon); lo=round.(lo).+(-5.0,5.0) la=extrema(df.lat); la=round.(la).+(-5.0,5.0) de=extrema(zc); de=round.(de).+(-5.0,5.0) scatter(df.lon,df.lat,zc,zcolor = zc, markersize=2,markerstrokewidth=0.1,camera = cam, xlims=lo,ylims=la,zlims=de,clims=de,leg=false) end """ scatter_movie(𝐼; cam=(0, 90)) Animation using `scatter_zcolor() ``` 𝐼,Γ=example3("OCCA", lon_rng=(-165.0,-155.0),lat_rng=(25.0,35.0), z_init=5.5,) scatter_movie(𝐼,cam=(70, 70)) ``` """ function scatter_movie(𝐼; cam=(0, 90)) df=groupby(𝐼.🔴, :t) return @gif for t in 1:length(df) scatter_zcolor(df[t],df[t].z;cam=cam) end end """ phi_scatter(ϕ,df) ``` phi_scatter(ϕ,df) ``` """ function phi_scatter(ϕ,df) nx,ny=size(ϕ) contourf(-0.5 .+ (1:nx),-0.5 .+ (1:ny), transpose(ϕ),c = :blues,linewidth = 0.1) scatter!(df.x,df.y,markersize=4.0,c=:red,marker = (:circle, stroke(0)), xlims=(0,nx),ylims=(0,ny),leg=:none) end """ OceanDepthLog() Compute Ocean depth logarithm on regular grid. """ function OceanDepthLog(Γ) lon=[i for i=20.:2.0:380., j=-79.:2.0:89.] lat=[j for i=20.:2.0:380., j=-79.:2.0:89.] DL=interp_to_lonlat(Γ["Depth"],Γ,lon,lat) DL[findall(DL.<0)].=0 DL=transpose(log10.(DL)) DL[findall((!isfinite).(DL))].=NaN return (lon=lon[:,1],lat=lat[1,:],fld=DL,rng=(1.5,5)) end """ map(𝐼::Individuals,background::NamedTuple) Plot initial and final positions, superimposed on a map of ocean depth log. """ function map(𝐼::Individuals,𝐵::NamedTuple) xlims=extrema(𝐵.lon) ylims=extrema(𝐵.lat) plt=contourf(𝐵.lon,𝐵.lat,𝐵.fld,clims=𝐵.rng,c = :ice, colorbar=false, xlims=xlims,ylims=ylims) 🔴_by_t = groupby(𝐼.🔴, :t) lo=deepcopy(🔴_by_t[1].lon); lo[findall(lo.<xlims[1])]=lo[findall(lo.<xlims[1])].+360 scatter!(lo,🔴_by_t[1].lat,markersize=1.5,c=:red,leg=:none,marker = (:circle, stroke(0))) lo=deepcopy(🔴_by_t[end].lon); lo[findall(lo.<xlims[1])]=lo[findall(lo.<xlims[1])].+360 scatter!(lo,🔴_by_t[end].lat,markersize=1.5,c=:yellow,leg=:none,marker = (:dot, stroke(0))) return plt end
# Test Benders Algorithm for Mixed Integer Linear Programming # Edward J. Xu, edxu96@outlook.com # March 16th, 2019 # --------------------------------------------------------------------------- push!(LOAD_PATH, "$(homedir())/Desktop/OptiGas, DTU42136") cd("$(homedir())/Desktop/OptiGas, DTU42136") using BendersMilp_EDXU # --------------------------------------------------------------------------- # Test Example 1: mat_a and mat_b being column vector n_x = 1 n_y = 1 vec_max_y = hcat([10]) vec_c = hcat([5]) vec_f = hcat([-3]) vec_b = hcat([4; 0; -13]) mat_a = hcat([1; 2; 1]) mat_b = hcat([2; -1; -3]) BendersMilp(n_x = n_x, n_y = n_y, vec_max_y = vec_max_y, vec_c = vec_c, vec_f = vec_f, vec_b = vec_b, mat_a = mat_a, mat_b = mat_b, epsilon = 0, timesIterationMax = 5) # --------------------------------------------------------------------------- # Test Example 2: mat_a and mat_b being matrix n_x_2 = 2 n_y_2 = 2 vec_max_y_2 = hcat([10; 10]) vec_c_2 = hcat([5; 3]) vec_f_2 = hcat([-3; 1]) vec_b_2 = hcat([4; 0; -13]) mat_a_2 = [1 3; 2 1; 1 -5] mat_b_2 = [2 -4; -1 2; -3 1] BendersMilp(n_x = n_x_2, n_y = n_y_2, vec_max_y = vec_max_y_2, vec_c = vec_c_2, vec_f = vec_f_2, vec_b = vec_b_2, mat_a = mat_a_2, mat_b = mat_b_2, epsilon = 0.000001, timesIterationMax = 10) # --------------------------------------------------------------------------- # Test Example 3: sub and ray problem n_x_3 = 2 n_y_3 = 2 vec_max_y_3 = hcat([2; 2]) vec_c_3 = hcat([2; 6]) vec_f_3 = hcat([2; 3]) vec_b_3 = hcat([5; 4]) mat_a_3 = [-1 2; 1 -3] mat_b_3 = [3 -1; 2 2] BendersMilp(n_x = n_x_3, n_y = n_y_3, vec_max_y = vec_max_y_3, vec_c = vec_c_3, vec_f = vec_f_3, vec_b = vec_b_3, mat_a = mat_a_3, mat_b = mat_b_3, epsilon = 0.000001, timesIterationMax = 10) # --------------------------------------------------------------------------- # Test Example 4: what if when infeasibility in x n_x_4 = 2 n_y_4 = 2 vec_max_y_4 = hcat([2; 2]) vec_c_4 = hcat([2; 6]) vec_f_4 = hcat([2; 3]) vec_b_4 = hcat([5; 4; 1]) mat_a_4 = [-1 2; 1 -3; -1 -1] mat_b_4 = [3 -1; 2 2; 0 0] BendersMilp(n_x = n_x_4, n_y = n_y_4, vec_max_y = vec_max_y_4, vec_c = vec_c_4, vec_f = vec_f_4, vec_b = vec_b_4, mat_a = mat_a_4, mat_b = mat_b_4, epsilon = 0.000001, timesIterationMax = 10) # --------------------------------------------------------------------------- # Test Example 5: what if when infeasibility in y n_x_5 = 2 n_y_5 = 2 vec_max_y_5 = hcat([2; 2]) vec_c_5 = hcat([2; 6]) vec_f_5 = hcat([2; 3]) vec_b_5 = hcat([5; 4; 5]) mat_a_5 = [-1 2; 1 -3; 0 0] mat_b_5 = [3 -1; 2 2; 1 1] BendersMilp(n_x = n_x_5, n_y = n_y_5, vec_max_y = vec_max_y_5, vec_c = vec_c_5, vec_f = vec_f_5, vec_b = vec_b_5, mat_a = mat_a_5, mat_b = mat_b_5, epsilon = 0.000001, timesIterationMax = 10)
module CuDiff sqr(x) = (x*x) cube(x) = (x*x*x) inverse(x) = one(x) / x include("./dual.jl") # include("./single.jl") function derivative(f, x, p...) dual = f(Dual(x, one(x)), p...) return dual.u, dual.du end function evaluate(f, x, p...) res = f(Single(x), p...) return map(x -> isa(Dual) ? x.u : x, res) end export derivative, evaluate end # module
using LinearAlgebra using CompScienceMeshes using SauterSchwab3D using StaticArrays const pI = point(1,0,0) const pII = point(0,1,0) const pIII = point(0,0,0) const pIV = point(0,0,1) const qIV = point(0,0,-1) const P = simplex(pI,pII,pIV,pIII) const Q = simplex(pI,pIII,pII) const sing = SauterSchwab3D.singularity_detection(P,Q) Accuracy2 = 18 cf_ref = CommonFace5D(sing,SauterSchwab3D._legendre(Accuracy2,0.0,1.0)) function integrand(x,y) return ((x-pI)'*(y-pIV))*exp(-im*1*norm(x-y))/(4pi*norm(x-y)) end function INTEGRAND(u,v) j1 = volume(P) * factorial(dimension(P)) j2 = volume(Q) * factorial(dimension(Q)) x = barytocart(P,u) y = barytocart(Q,v) output = integrand(x,y)*j1*j2 return output end print("Ref: ") ref = sauterschwab_parameterized(INTEGRAND, cf_ref) println(ref) println() res_tp =[] res_sp =[] res_gm =[] n1 = [] n2 = [] n3 = [] for i in 2:1:15 Accuracy = i cf = CommonFace5D(sing,SauterSchwab3D._legendre(Accuracy,0.0,1.0)) int_tp = sauterschwab_parameterized(INTEGRAND, cf) num_pts = 9*length(cf.qps)^5 push!(n1,num_pts) push!(res_tp,int_tp) end for i in 2:1:7 Accuracy = i cf_s = CommonFace5D_S(sing,(SauterSchwab3D._legendre(Accuracy,0.0,1.0), SauterSchwab3D._shunnham2D(Accuracy), SauterSchwab3D._shunnham3D(Accuracy))) int_sp = sauterschwab_parameterized(INTEGRAND, cf_s) num_pts = length(cf_s.qps[1])*length(cf_s.qps[2])^2+8*length(cf_s.qps[2])*length(cf_s.qps[3]) push!(n2,num_pts) push!(res_sp,int_sp) end for i in 2:1:12 Accuracy = i cf_gm = CommonFace5D_S(sing,(SauterSchwab3D._legendre(Accuracy,0.0,1.0), SauterSchwab3D._grundmannMoeller2D(2*Accuracy-1), SauterSchwab3D._grundmannMoeller3D(2*Accuracy-1))) int_gm = sauterschwab_parameterized(INTEGRAND, cf_gm) num_pts = length(cf_gm.qps[1])*length(cf_gm.qps[2])^2+8*length(cf_gm.qps[2])*length(cf_gm.qps[3]) push!(n3,num_pts) push!(res_gm,int_gm) end err_tp = norm.(res_tp.-ref)/norm(ref) err_sp = norm.(res_sp.-ref)/norm(ref) err_gm = norm.(res_gm.-ref)/norm(ref) println(err_tp) println(err_sp) println(err_gm) using Plots plot( yaxis=:log, xaxis=:log, fontfamily="Times") plot!(n1,err_tp, label="Gauss Tensor-Product",markershape=:circle) plot!(n2,err_sp, label="Simplex Tensor-Product",markershape=:rect) #plot!(n3,err_gm, label="Simplex-Product GM",markershape=:x) plot!(xlims=(1e2,1e5),ylims=(1e-7,1)) plot!(xlabel="#Quad. pts/Func. evals", ylabel="Rel. Error.", title="Common Face 5D",legend=:bottomleft) using BenchmarkTools ref = -0.00463274359881397 + 0.002581200521272345im cf = CommonFace5D(sing,SauterSchwab3D._legendre(4,0.0,1.0)) int_tp = sauterschwab_parameterized(INTEGRAND, cf) num_pts = 9*length(cf.qps)^5 println("#Pts: ",num_pts) err_tp = norm.(int_tp.-ref)/norm(ref) println("Rel. Err: ",err_tp) @time for i in 1:100 sauterschwab_parameterized(INTEGRAND, cf) end cf_s = CommonFace5D_S(sing,(SauterSchwab3D._legendre(4,0.0,1.0), SauterSchwab3D._shunnham2D(4), SauterSchwab3D._shunnham3D(4))) int_sp = sauterschwab_parameterized(INTEGRAND, cf_s) num_pts = length(cf_s.qps[1])*length(cf_s.qps[2])^2+8*length(cf_s.qps[2])*length(cf_s.qps[3]) println("#Pts: ",num_pts) err_sp = norm.(int_sp.-ref)/norm(ref) println("Rel Err: ",err_sp) @time for i in 1:100 sauterschwab_parameterized(INTEGRAND, cf_s) end #= cf_gm = CommonFace5D_S((SauterSchwab3D._legendre(4,0.0,1.0), SauterSchwab3D._grundmannMoeller2D(2*4-1), SauterSchwab3D._grundmannMoeller3D(2*4-1))) int_gm = sauterschwab_parameterized(INTEGRAND, cf_gm) num_pts = length(cf_gm.qps[1])*length(cf_gm.qps[2])^2+8*length(cf_gm.qps[2])*length(cf_gm.qps[3]) println("#Pts: ",num_pts) err_gm = norm.(int_gm.-ref)/norm(ref) println("Rel Err: ",err_gm) =#
# This file is a part of SolidStateDetectors.jl, licensed under the MIT License (MIT). # Note: Most (if not all) of these types are temporary, to be replaced later # on by generic types from RadiationDetectorSignals.jl (when the latter is # mature enough). # Internal units should be SI units const internal_length_unit = ConstructiveSolidGeometry.internal_length_unit const internal_angle_unit = ConstructiveSolidGeometry.internal_angle_unit const internal_time_unit = u"s" const internal_voltage_unit = u"V" const internal_energy_unit = u"eV" const internal_efield_unit = internal_voltage_unit / internal_length_unit const internal_charge_unit = u"C" const external_charge_unit = u"e_au" # elementary charge - from UnitfulAtomic.jl to_internal_units(x::Quantity{<:Real, dimension(internal_time_unit)}) = ustrip(uconvert(internal_time_unit, x)) to_internal_units(x::Quantity{<:Real, dimension(internal_voltage_unit)}) = ustrip(uconvert(internal_voltage_unit, x)) to_internal_units(x::Quantity{<:Real, dimension(internal_efield_unit)}) = ustrip(uconvert(internal_efield_unit, x)) to_internal_units(x::Quantity{<:Real, dimension(internal_energy_unit)}) = ustrip(uconvert(internal_energy_unit, x)) to_internal_units(x::Quantity{<:Real, dimension(internal_charge_unit)}) = ustrip(uconvert(internal_charge_unit, x)) from_internal_units(x::Real, unit::Unitful.Units{<:Any, dimension(internal_time_unit)}) = uconvert(unit, x * internal_time_unit) from_internal_units(x::Real, unit::Unitful.Units{<:Any, dimension(internal_voltage_unit)}) = uconvert(unit, x * internal_voltage_unit) from_internal_units(x::Real, unit::Unitful.Units{<:Any, dimension(internal_efield_unit)}) = uconvert(unit, x * internal_efield_unit) from_internal_units(x::Real, unit::Unitful.Units{<:Any, dimension(internal_energy_unit)}) = uconvert(unit, x * internal_energy_unit) from_internal_units(x::Real, unit::Unitful.Units{<:Any, dimension(internal_charge_unit)}) = uconvert(unit, x * internal_charge_unit) # Internal function for now: We should also fano noise here (optionally) _convert_internal_energy_to_external_charge(material) = inv(to_internal_units(material.E_ionisation)) * external_charge_unit unit_conversion = Dict{String, Unitful.Units}( "nm" => u"nm", "um" => u"μm", "mm" => u"mm", "cm" => u"cm", "m" => u"m", #length "deg" => u"°","rad" => u"rad", #angle "V" => u"V", "kV" => u"kV", #potential "K" => u"K", "Kelvin" => u"K", "C" => u"°C", "Celsius" => u"°C", #temperature ) const UnitTuple = NamedTuple{(:length, :angle, :potential, :temperature), Tuple{ Unitful.FreeUnits{<:Any, Unitful.𝐋}, Unitful.FreeUnits{<:Any, NoDims}, Unitful.FreeUnits{<:Any, Unitful.𝐋^2 * Unitful.𝐌 * Unitful.𝐈^-1 * Unitful.𝐓^-3}, Unitful.FreeUnits{<:Any, Unitful.𝚯}}} function default_unit_tuple()::UnitTuple return ( length = u"m", angle = u"°", potential = u"V", temperature = u"K" ) end function construct_unit(ustring::String)::Unitful.Units try parsed_unit = uparse(ustring) @assert parsed_unit isa Unitful.Units return parsed_unit catch @assert ustring in keys(unit_conversion) "Unit string $(ustring) cannot be interpreted..." return unit_conversion[ustring] end end function construct_units(config_file_dict::AbstractDict)::UnitTuple dunits::NamedTuple = default_unit_tuple() if haskey(config_file_dict, "units") d = config_file_dict["units"] dunits = ( length = haskey(d, "length") ? construct_unit(d["length"]) : dunits.length, angle = haskey(d, "angle") ? construct_unit(d["angle"]) : dunits.angle, potential = haskey(d, "potential") ? construct_unit(d["potential"]) : dunits.potential, temperature = haskey(d, "temperature") ? construct_unit(d["temperature"]) : dunits.temperature ) end matching_units::Bool = dimension.(values(dunits)) == (Unitful.𝐋, Unitful.NoDims, Unitful.𝐋^2 * Unitful.𝐌 * Unitful.𝐈^-1 * Unitful.𝐓^-3, Unitful.𝚯) @assert matching_units "Some of the units are not given in the right format:"* (dimension(dunits.length) == Unitful.𝐋 ? "" : "\n - units.length ($(dunits.length)) does not describe a length.")* (dimension(dunits.angle) == Unitful.NoDims ? "" : "\n - units.angle ($(dunits.angle)) does not describe an angle.")* (dimension(dunits.potential) == Unitful.𝐋^2 * Unitful.𝐌 * Unitful.𝐈^-1 * Unitful.𝐓^-3 ? "" : "\n - units.potential ($(dunits.potential)) does not describe a potential.")* (dimension(dunits.temperature) == Unitful.𝚯 ? "" : "\n - units.temperature ($(dunits.temperature)) does not describe a temperature.") return UnitTuple(dunits) end const MaybeWithUnits{T} = Union{T, Quantity{<:T}} const RealQuantity = MaybeWithUnits{<:Real} DetectorHitEvents = TypedTables.Table{ <:NamedTuple{ (:evtno, :detno, :thit, :edep, :pos), <:Tuple{ Union{Integer, AbstractVector{<:Integer}}, Union{Integer, AbstractVector{<:Integer}}, AbstractVector{<:RealQuantity}, AbstractVector{<:RealQuantity}, AbstractVector{<:AbstractVector{<:RealQuantity}} } } }
module BumpOnTailSimulation using Plots, LaTeXStrings using ReducedBasisMethods using Particles using Particles.BumpOnTail using Random # parameters const dt = 1e-1 # timestep const T = 25 # final time const nt = Int(div(T, dt)) # nb. of timesteps const np = Int(5e3) # nb. of particles const nh = 16 # nb. of elements const p = 3 # spline degree const nₚ₁ = 10 const nₚ₂ = 1 const nₚ₃ = 1 const nₚ₄ = 1 const nₚ₅ = 1 const nparam = nₚ₁ * nₚ₂ * nₚ₃ * nₚ₄ * nₚ₅ const vmax = +10 const vmin = -10 # bump-on tail instability - reference values: κ, ε, a, v₀, σ params = (κ = 0.3, # spatial perturbation wave number ε = 0.03, # amplitude of spatial perturbation a = 0.1, # fast particle share v₀= 4.5, # velocity σ = 0.5, # temperature χ = 1.0) # sampling parameters κ = Parameter(:κ, 0.1, 0.5, nₚ₁) ε = Parameter(:ε, 0.03, 0.03, nₚ₂) a = Parameter(:a, 0.1, 0.1, nₚ₃) v₀= Parameter(:v₀, 4.5, 4.5, nₚ₄) σ = Parameter(:σ, 0.5, 0.5, nₚ₅) const pspace = ParameterSpace(κ, ε, a, v₀, σ) const L = 2π/params.κ # domain length # const h = L/nh # element width function run() # integrator parameters IP = VPIntegratorParameters(dt, nt, nt+1, nh, np) # integrator cache IC = VPIntegratorCache(IP) # B-spline Poisson solver poisson = PoissonSolverPBSplines(p, nh, L) # set random generator seed Random.seed!(1234) # initial data particles = BumpOnTail.draw_accept_reject(np, params) # particles = BumpOnTail.draw_importance_sampling(np, params) # training set TS = TrainingSet(nt+1, poisson, particles, pspace) # loop over parameter set for p in eachindex(pspace) # get parameter tuple lparams = merge(pspace(p), (χ = pspace[p].κ / params.κ,)) # integrate particles for parameter integrate_vp!(particles, poisson, lparams, IP, IC; save=true, given_phi=false) # copy solution TS.X[1,:,:,p] .= IC.X TS.V[1,:,:,p] .= IC.V TS.A[1,:,:,p] .= IC.A TS.Φ[1,:,:,p] .= IC.Φ # copy diagnostics TS.W[:,p] .= IC.W TS.K[:,p] .= IC.K TS.M[:,p] .= IC.M end # save results to HDF5 h5save("../runs/BoT_Np5e4_k_010_050_np_10_T25.h5", TS, IP, poisson, pspace, params) # plot plot(IP.t, TS.W, linewidth = 2, xlabel = L"$n_t$", yscale = :log10, legend = :none, grid = true, gridalpha = 0.5, minorgrid = true, minorgridalpha = 0.2) savefig("../runs/BoT_Np5e4_k_010_050_np_10_T25_plot1.pdf") # TODO: Change filename to something meaningful! # α, β = get_regression_αβ(IP.t, TS.W, 2) # Wₗᵢₙ = zero(TS.W) for i in axes(Wₗᵢₙ,2) Wₗᵢₙ[:,i] .= exp.(α[i] .+ β[i] .* IP.t) end # plot plot(xlabel = L"$n_t$", yscale = :log10, ylims = (1E-3,1E1), legend = :none, grid = true, gridalpha = 0.5, minorgrid = true, minorgridalpha = 0.2) plot!(IP.t, TS.W[:,1:5], linewidth = 2, alpha = 0.25) plot!(IP.t, Wₗᵢₙ[:,1:5], linewidth = 2, alpha = 0.5) savefig("../runs/BoT_Np5e4_k_010_050_np_10_T25_plot2.pdf") # TODO: Change filename to something meaningful! # plot plot(xlabel = L"$n_t$", yscale = :log10, ylims = (1E-3,1E1), legend = :none, grid = true, gridalpha = 0.5, minorgrid = true, minorgridalpha = 0.2) plot!(IP.t, TS.W[:,6:10], linewidth = 2, alpha = 0.25) plot!(IP.t, Wₗᵢₙ[:,6:10], linewidth = 2, alpha = 0.5) savefig("../runs/BoT_Np5e4_k_010_050_np_10_T25_plot3.pdf") # TODO: Change filename to something meaningful! end end using .BumpOnTailSimulation BumpOnTailSimulation.run()
const IterationResamplingTypes = Union{Holdout,Nothing,MLJBase.TrainTestPairs} ## TYPES AND CONSTRUCTOR mutable struct DeterministicIteratedModel{M<:Deterministic} <: MLJBase.Deterministic model::M controls resampling # resampling strategy measure weights::Union{Nothing,Vector{<:Real}} class_weights::Union{Nothing,Dict{Any,<:Real}} operation retrain::Bool check_measure::Bool iteration_parameter::Union{Nothing,Symbol,Expr} cache::Bool end mutable struct ProbabilisticIteratedModel{M<:Probabilistic} <: MLJBase.Probabilistic model::M controls resampling # resampling strategy measure weights::Union{Nothing,AbstractVector{<:Real}} class_weights::Union{Nothing,Dict{Any,<:Real}} operation retrain::Bool check_measure::Bool iteration_parameter::Union{Nothing,Symbol,Expr} cache::Bool end const ERR_MISSING_TRAINING_CONTROL = ArgumentError("At least one control must be a training control "* "(have type `$TrainingControl`) or be a "* "custom control that calls IterationControl.train!. ") const ERR_TOO_MANY_ARGUMENTS = ArgumentError("At most one non-keyword argument allowed. ") const EitherIteratedModel{M} = Union{DeterministicIteratedModel{M},ProbabilisticIteratedModel{M}} const ERR_NOT_SUPERVISED = ArgumentError("Only `Deterministic` and `Probabilistic` "* "model types supported.") const ERR_NEED_MEASURE = ArgumentError("Unable to deduce a default measure for specified model. "* "You must specify `measure=...`. ") const ERR_NEED_PARAMETER = ArgumentError("Unable to determine the name of your model's iteration "* "parameter. Please specify `iteration_parameter=...`. This "* "must be a `Symbol` or, in the case of a nested parameter, "* "an `Expr` (as in `booster.nrounds`). ") const ERR_MODEL_UNSPECIFIED = ArgumentError( "Expecting atomic model as argument, or as keyword argument `model=...`, "* "but neither detected. ") const WARN_POOR_RESAMPLING_CHOICE = "Training could be very slow unless "* "`resampling` is `Holdout(...)`, `nothing`, or "* "a vector of the form `[(train, test),]`, where `train` and `test` "* "are valid row indices for the data, as in "* "`resampling = [(1:100, 101:150),]`. " const WARN_POOR_CHOICE_OF_PAIRS = "Training could be very slow unless you limit the number of `(train, test)` pairs "* "to one, as in resampling = [(1:100, 101:150),]. Alternatively, "* "use a `Holdout` resampling strategy. " err_bad_iteration_parameter(p) = ArgumentError("Model to be iterated does not have :($p) as an iteration parameter. ") """ IteratedModel(model=nothing, controls=$CONTROLS_DEFAULT, retrain=false, resampling=Holdout(), measure=nothing, weights=nothing, class_weights=nothing, operation=predict, verbosity=1, check_measure=true, iteration_parameter=nothing, cache=true) Wrap the specified `model <: Supervised` in the specified iteration `controls`. Training a machine bound to the wrapper iterates a corresonding machine bound to `model`. Here `model` should support iteration. To list all controls, do `MLJIteration.CONTROLS`. Controls are summarized at [https://alan-turing-institute.github.io/MLJ.jl/dev/getting_started/](https://alan-turing-institute.github.io/MLJ.jl/dev/controlling_iterative_models/) but query individual doc-strings for details and advanced options. For creating your own controls, refer to the documentation just cited. To make out-of-sample losses available to the controls, the machine bound to `model` is only trained on part of the data, as iteration proceeds. See details on training below. Specify `retrain=true` to ensure the model is retrained on *all* available data, using the same number of iterations, once controlled iteration has stopped. Specify `resampling=nothing` if all data is to be used for controlled iteration, with each out-of-sample loss replaced by the most recent training loss, assuming this is made available by the model (`supports_training_losses(model) == true`). Otherwise, `resampling` must have type `Holdout` (eg, `Holdout(fraction_train=0.8, rng=123)`). Assuming `retrain=true` or `resampling=nothing`, `iterated_model` behaves exactly like the original `model` but with the iteration parameter automatically selected. If `retrain=false` (default) and `resampling` is not `nothing`, then `iterated_model` behaves like the original model trained on a subset of the provided data. Controlled iteration can be continued with new `fit!` calls (warm restart) by mutating a control, or by mutating the iteration parameter of `model`, which is otherwise ignored. ### Training Given an instance `iterated_model` of `IteratedModel`, calling `fit!(mach)` on a machine `mach = machine(iterated_model, data...)` performs the following actions: - Assuming `resampling !== nothing`, the `data` is split into *train* and *test* sets, according to the specified `resampling` strategy, which must have type `Holdout`. - A clone of the wrapped model, `iterated_model.model`, is bound to the train data in an internal machine, `train_mach`. If `resampling === nothing`, all data is used instead. This machine is the object to which controls are applied. For example, `Callback(fitted_params |> print)` will print the value of `fitted_params(train_mach)`. - The iteration parameter of the clone is set to `0`. - The specified `controls` are repeatedly applied to `train_mach` in sequence, until one of the controls triggers a stop. Loss-based controls (eg, `Patience()`, `GL()`, `Threshold(0.001)`) use an out-of-sample loss, obtained by applying `measure` to predictions and the test target values. (Specifically, these predictions are those returned by `operation(train_mach)`.) If `resampling === nothing` then the most recent training loss is used instead. Some controls require *both* out-of-sample and training losses (eg, `PQ()`). - Once a stop has been triggered, a clone of `model` is bound to all `data` in a machine called `mach_production` below, unless `retrain == false` or `resampling === nothing`, in which case `mach_production` coincides with `train_mach`. ### Prediction Calling `predict(mach, Xnew)` returns `predict(mach_production, Xnew)`. Similar similar statements hold for `predict_mean`, `predict_mode`, `predict_median`. ### Controls A control is permitted to mutate the fields (hyper-parameters) of `train_mach.model` (the clone of `model`). For example, to mutate a learning rate one might use the control Callback(mach -> mach.model.eta = 1.05*mach.model.eta) However, unless `model` supports warm restarts with respect to changes in that parameter, this will trigger retraining of `train_mach` from scratch, with a different training outcome, which is not recommended. ### Warm restarts If `iterated_model` is mutated and `fit!(mach)` is called again, then a warm restart is attempted if the only parameters to change are `model` or `controls` or both. Specifically, `train_mach.model` is mutated to match the current value of `iterated_model.model` and the iteration parameter of the latter is updated to the last value used in the preceding `fit!(mach)` call. Then repeated application of the (updated) controls begin anew. """ function IteratedModel(args...; model=nothing, control=CONTROLS_DEFAULT, controls=control, resampling=MLJBase.Holdout(), measures=nothing, measure=measures, weights=nothing, class_weights=nothing, operation=predict, retrain=false, check_measure=true, iteration_parameter=nothing, cache=true) length(args) < 2 || throw(ArgumentError("At most one non-keyword argument allowed. ")) if length(args) === 1 atom = first(args) model === nothing || @warn "Using `model=$atom`. Ignoring specification `model=$model`. " else model === nothing && throw(ERR_MODEL_UNSPECIFIED) atom = model end if atom isa Deterministic iterated_model = DeterministicIteratedModel(atom, controls, resampling, measure, weights, class_weights, operation, retrain, check_measure, iteration_parameter, cache) elseif atom isa Probabilistic iterated_model = ProbabilisticIteratedModel(atom, controls, resampling, measure, weights, class_weights, operation, retrain, check_measure, iteration_parameter, cache) else throw(ERR_NOT_SUPERVISED) end message = clean!(iterated_model) isempty(message) || @warn message return iterated_model end function MLJBase.clean!(iterated_model::EitherIteratedModel) message = "" measure = iterated_model.measure if measure === nothing && iterated_model.resampling !== nothing measure = MLJBase.default_measure(iterated_model.model) measure === nothing && throw(ERR_NEED_MEASURE) end iter = deepcopy(iterated_model.iteration_parameter) if iter === nothing iter = iteration_parameter(iterated_model.model) iter === nothing && throw(ERR_NEED_PARAMETER) end try MLJBase.recursive_getproperty(iterated_model.model, iter) catch throw(err_bad_iteration_parameter(iter)) end resampling = iterated_model.resampling if !(resampling isa IterationResamplingTypes) message *= WARN_POOR_RESAMPLING_CHOICE end if resampling isa MLJBase.TrainTestPairs && length(resampling) !== 1 message *= WARN_POOR_CHOICE_OF_PAIRS end training_control_candidates = filter(iterated_model.controls) do c c isa TrainingControl || !(c isa Control) end if isempty(training_control_candidates) throw(ERR_MISSING_TRAINING_CONTROL) end return message end
""" Simple container representing a task in a taskgraph. """ struct TaskgraphNode "The name of this task." name::String metadata::Dict{String,Any} # Constructor TaskgraphNode(name; metadata = emptymeta()) = new(name, metadata) end """ Simple container representing an edge in a taskgraph. """ struct TaskgraphEdge "Source task names." sources::Vector{String} "Sink task names." sinks::Vector{String} metadata::Dict{String,Any} function TaskgraphEdge(source, sink; metadata = Dict{String,Any}()) sources = wrap_vector(source) sinks = wrap_vector(sink) return new(sources, sinks, metadata) end end """ $(SIGNATURES) Return the names of sources of a `TaskgraphEdge`. """ getsources(taskgraph_edge::TaskgraphEdge) = taskgraph_edge.sources """ $(SIGNATURES) Return the names of sinks of a `TaskgraphEdge`. """ getsinks(taskgraph_edge::TaskgraphEdge) = taskgraph_edge.sinks """ Data structure encoding tasks and their relationships. """ struct Taskgraph "The name of the taskgraph" name::String "Nodes in the taskgraph. Type: [`Dict{String, TaskgraphNode}`](@ref TaskgraphNode)" nodes::Dict{String,TaskgraphNode} "Edges in the taskgraph. Type: [`Vector{TaskgraphEdge}`](@ref TaskgraphEdge)" edges::Vector{TaskgraphEdge} """ Outgoing adjacency list mapping node names to edge indices. Type: `Dict{String, Vector{Int64}}` """ node_edges_out::Dict{String,Vector{Int}} """ Incoming adjacency list mapping node names to edge indices. Type: `Dict{String, Vector{Int64}}` """ node_edges_in::Dict{String,Vector{Int}} function Taskgraph(name = "noname") return new( name, Dict{String,TaskgraphNode}(), TaskgraphEdge[], Dict{String,Vector{Int}}(), Dict{String,Vector{Int}}(), ) end function Taskgraph(name::String, nodes, edges) if eltype(nodes) != TaskgraphNode typer = TypeError( :Taskgraph, "Incorrect Node Element Type", TaskgraphNode, eltype(nodes) ) throw(typer) end if eltype(edges) != TaskgraphEdge typer = TypeError( :Taskgraph, "Incorrect Edge Element Type", TaskgraphEdge, eltype(edges) ) throw(typer) end # First - create the dictionary to store the nodes. Nodes can be # accessed via their name. nodes = Dict(n.name => n for n in nodes) # Initialize the adjacency lists with an entry for each node. Initialize # the values to empty arrays of edges so down-stream algortihms won't # have to check if an adjacency list exists for a node. edges = collect(edges) node_edges_out = Dict(name => Int[] for name in keys(nodes)) node_edges_in = Dict(name => Int[] for name in keys(nodes)) # Iterate through all edges - grow adjacency lists correctly. for (index, edge) in enumerate(edges) for source in edge.sources push!(node_edges_out[source], index) end for sink in edge.sinks push!(node_edges_in[sink], index) end end # Return the data structure return new(name, nodes, edges, node_edges_out, node_edges_in) end end # Allow construction without any name. Taskgraph(nodes, edges) = Taskgraph("noname", nodes, edges) ################################################################################ # METHODS FOR THE TASKGRAPH ################################################################################ # -- Some accessor methods. """ $(SIGNATURES) Return an iterator of [`TaskgraphNode`](@ref) yielding all nodes in `taskgraph`. """ getnodes(taskgraph::Taskgraph) = values(taskgraph.nodes) """ $(SIGNATURES) Return an iterator of [`TaskgraphEdge`](@ref) yielding all edges in `taskgraph`. """ getedges(taskgraph::Taskgraph) = taskgraph.edges """ $(SIGNATURES) Return the [`TaskgraphNode`](@ref) in `taskgraph` with `name`. """ getnode(taskgraph::Taskgraph, name::String) = taskgraph.nodes[name] """ $(SIGNATURES) Return the [`TaskgraphEdge`](@ref) in `taskgraph` with `index`. """ getedge(taskgraph::Taskgraph, index::Integer) = taskgraph.edges[index] # -- helpful query methods. """ $(SIGNATURES) Return an iterator yielding all names of nodes in `taskgraph`. """ nodenames(taskgraph::Taskgraph) = keys(taskgraph.nodes) """ $(SIGNATURES) Return the number of nodes in `taskgraph`. """ num_nodes(taskgraph::Taskgraph) = length(taskgraph.nodes) """ $(SIGNATURES) Return the number of edges in `taskgraph`. """ num_edges(taskgraph::Taskgraph) = length(taskgraph.edges) """ $(SIGNATURES) Return `Vector{TaskgraphNode}` of sources for `edge`. """ function getsources(taskgraph::Taskgraph, edge::TaskgraphEdge) return (taskgraph.nodes[n] for n in getsources(edge)) end """ $(SIGNATURES) Return `Vector{TaskgraphNode}` of sinks for `edge`. """ function getsinks(taskgraph::Taskgraph, edge::TaskgraphEdge) return (taskgraph.nodes[n] for n in getsinks(edge)) end """ $(SIGNATURES) Add a `node` to `taskgraph`. Error if node already exists. """ function add_node(taskgraph::Taskgraph, node::TaskgraphNode) if haskey(taskgraph.nodes, node.name) error("Task $(node.name) already exists in taskgraph.") end taskgraph.nodes[node.name] = node # Create adjacency list entries for the new nodes taskgraph.node_edges_out[node.name] = TaskgraphEdge[] taskgraph.node_edges_in[node.name] = TaskgraphEdge[] return nothing end """ $(SIGNATURES) Add a `edge` to `taskgraph`. """ function add_edge(taskgraph::Taskgraph, edge::TaskgraphEdge) # Update the edge array push!(taskgraph.edges, edge) index = length(taskgraph.edges) # Update the adjacency lists. for source in edge.sources push!(taskgraph.node_edges_out[source], index) end for sink in edge.sinks push!(taskgraph.node_edges_in[sink], index) end return nothing end # Methods for accessing the adjacency lists out_edges(t::Taskgraph, task::String) = [t.edges[i] for i in t.node_edges_out[task]] out_edges(t::Taskgraph, task::TaskgraphNode) = out_edges(t, task.name) out_edge_indices(t::Taskgraph, task::String) = t.node_edges_out[task] out_edge_indices(t::Taskgraph, task::TaskgraphNode) = out_edge_indices(t, task.name) in_edges(t::Taskgraph, task::String) = [t.edges[i] for i in t.node_edges_in[task]] in_edges(t::Taskgraph, task::TaskgraphNode) = in_edges(t, task.name) in_edge_indices(t::Taskgraph, task::String) = t.node_edges_in[task] in_edge_indices(t::Taskgraph, task::TaskgraphNode) = in_edge_indices(t, task.name) """ $(SIGNATURES) Return `true` if `taskgraph` has a task named `node`. """ hasnode(taskgraph::Taskgraph, node::String) = haskey(taskgraph.nodes, node) """ $(SIGNATURES) Return `Set{String}` of names of unique nodes that are the sink of an edges starting at `node`. """ function outnode_names(taskgraph::Taskgraph, node) edges = out_edges(taskgraph, node) node_names = Set{String}() for edge in edges union!(node_names, getsinks(edge)) end return node_names end """ $(SIGNATURES) Return [`Vector{TaskgraphNode}`](@ref TaskgraphNode) of unique nodes that are the sink of an edge starting at `node`. """ function outnodes(taskgraph::Taskgraph, node) names = outnode_names(taskgraph, node) return [getnode(taskgraph, name) for name in names] end """ $(SIGNATURES) Return `Set{String}` of names of unique nodes that are the source of an edges ending at `node`. """ function innode_names(taskgraph::Taskgraph, node) edges = in_edges(taskgraph, node) node_names = Set{String}() for edge in edges union!(node_names, getsources(edge)) end return node_names end """ $(SIGNATURES) Return [`Vector{TaskgraphNode}`](@ref TaskgraphNode) of unique nodes that are the source of an edge ending at `node`. """ function innodes(taskgraph::Taskgraph, node) names = innode_names(taskgraph, node) return [getnode(taskgraph, name) for name in names] end
using CartesianGP using Base.Test reload("Utilities.jl") @test output_mask(1) == convert(BitString,0b11) @test output_mask(2) == convert(BitString,0b1111) @test output_mask(3) == convert(BitString,0b11111111) @test output_mask(4) == convert(BitString,0b1111111111111111) @test std_input_context(1) == BitString[0b10] @test std_input_context(2) == BitString[0b1100,0b1010] @test std_input_context(3) == BitString[0b11110000,0b11001100,0b10101010] @test std_input_context(4) == BitString[0b1111111100000000,0b1111000011110000,0b1100110011001100,0b1010101010101010]
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/InterfaceMechanics.jl/blob/master/LICENSE using InterfaceMechanics, Test, StaticArrays parameters = CouloumbParameterState(mu=0.2, elastic_slip=0.001, c0 = 0.001, p0 = 100.0) h0 = -0.005 # Initial overclosure dh = 0.006 # Overclosure du = 1.0 drivers = CouloumbDriverState(displacements = SVector{3,Float64}([h0, 0.0, 0.0])) dtime = 1.0 ddrivers = CouloumbDriverState(time = dtime, displacements = SVector{3,Float64}([dh, 0.0, 0.0])) interface = Couloumb(parameters=parameters, drivers=drivers, ddrivers=ddrivers) @info("********* Starting simulation *********") # Step 1: Initialize contact @info "time = $(interface.drivers.time), traction = $(interface.variables.traction)" integrate_interface!(interface) update!(interface) @info "time = $(interface.drivers.time), traction = $(interface.variables.traction)" @test interface.variables.traction[1]>0 @test interface.variables.traction[2]==0 @test interface.variables.traction[3]==0 # Step 2: Tangential movement 1 ddrivers = CouloumbDriverState(time = dtime, displacements = SVector{3,Float64}([0.0, du, 0.0])) interface.ddrivers = ddrivers integrate_interface!(interface) update!(interface) @info "time = $(interface.drivers.time), traction = $(interface.variables.traction)" @test interface.variables.traction[1]>0 @test interface.variables.traction[2]>0 @test interface.variables.traction[3]==0 # Step 3: Tangential movement 2 ddrivers = CouloumbDriverState(time = dtime, displacements = SVector{3,Float64}([0.0, -du, 0.0])) interface.ddrivers = ddrivers integrate_interface!(interface) update!(interface) @info "time = $(interface.drivers.time), traction = $(interface.variables.traction)" @test interface.variables.traction[1]>0 @test interface.variables.traction[2]<0 @test interface.variables.traction[3]==0 # Step 3: Tangential movement 3 ddrivers = CouloumbDriverState(time = dtime, displacements = SVector{3,Float64}([0.0, du/sqrt(2), du/sqrt(2)])) interface.ddrivers = ddrivers integrate_interface!(interface) update!(interface) @info "time = $(interface.drivers.time), traction = $(interface.variables.traction)" @test interface.variables.traction[1]>0 @test interface.variables.traction[2]>0 @test interface.variables.traction[3]>0
# ********************************************************************************* # REopt, Copyright (c) 2019-2020, Alliance for Sustainable Energy, LLC. # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this list # of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, this # list of conditions and the following disclaimer in the documentation and/or other # materials provided with the distribution. # # Neither the name of the copyright holder nor the names of its contributors may be # used to endorse or promote products derived from this software without specific # prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. # ********************************************************************************* """ DomesticHotWaterLoad There are many ways in which a DomesticHotWaterLoad can be defined: 1. When using either `doe_reference_name` or `blended_doe_reference_names` in an `ElectricLoad` one only needs to provide the input key "DomesticHotWaterLoad" in the `Scenario` (JSON or Dict). In this case the values from DoE reference names from the `ElectricLoad` will be used to define the `DomesticHotWaterLoad`. 2. One can provide the `doe_reference_name` or `blended_doe_reference_names` directly in the `DomesticHotWaterLoad` key within the `Scenario`. These values can be combined with the `annual_mmbtu` or `monthly_mmbtu` inputs to scale the DoE reference profile(s). 3. One can provide the `fuel_loads_mmbtu_per_hour` value in the `DomesticHotWaterLoad` key within the `Scenario`. ```julia function DomesticHotWaterLoad(; doe_reference_name::String = "", city::String = "", blended_doe_reference_names::Array{String, 1} = String[], blended_doe_reference_percents::Array{<:Real,1} = Real[], annual_mmbtu::Union{Real, Nothing} = nothing, monthly_mmbtu::Array{<:Real,1} = Real[], fuel_loads_mmbtu_per_hour::Array{<:Real,1} = Real[], time_steps_per_hour::Int = 1, latitude::Real=0.0, longitude::Real=0.0 ) ``` """ struct DomesticHotWaterLoad loads_kw::Array{Real, 1} function DomesticHotWaterLoad(; doe_reference_name::String = "", city::String = "", blended_doe_reference_names::Array{String, 1} = String[], blended_doe_reference_percents::Array{<:Real,1} = Real[], annual_mmbtu::Union{Real, Nothing} = nothing, monthly_mmbtu::Array{<:Real,1} = Real[], # addressable_load_fraction, # TODO fuel_loads_mmbtu_per_hour::Array{<:Real,1} = Real[], # TODO shouldn't this be per_time_step? time_steps_per_hour::Int = 1, latitude::Real=0.0, longitude::Real=0.0 ) if length(fuel_loads_mmbtu_per_hour) > 0 if !(length(fuel_loads_mmbtu_per_hour) / time_steps_per_hour ≈ 8760) @error "Provided domestic hot water load does not match the time_steps_per_hour." end loads_kw = fuel_loads_mmbtu_per_hour .* (MMBTU_TO_KWH * EXISTING_BOILER_EFFICIENCY) elseif !isempty(doe_reference_name) loads_kw = BuiltInDomesticHotWaterLoad(city, doe_reference_name, latitude, longitude, 2017, annual_mmbtu, monthly_mmbtu) elseif length(blended_doe_reference_names) > 1 && length(blended_doe_reference_names) == length(blended_doe_reference_percents) loads_kw = blend_and_scale_doe_profiles(BuiltInDomesticHotWaterLoad, latitude, longitude, 2017, blended_doe_reference_names, blended_doe_reference_percents, city, annual_mmbtu, monthly_mmbtu) else error("Cannot construct DomesticHotWaterLoad. You must provide either [fuel_loads_mmbtu_per_hour], [doe_reference_name, city], or [blended_doe_reference_names, blended_doe_reference_percents, city].") end if length(loads_kw) < 8760*time_steps_per_hour loads_kw = repeat(loads_kw, inner=Int(time_steps_per_hour / (length(loads_kw)/8760))) @info "Repeating domestic hot water loads in each hour to match the time_steps_per_hour." end new( loads_kw ) end end """ SpaceHeatingLoad There are many ways in which a SpaceHeatingLoad can be defined: 1. When using either `doe_reference_name` or `blended_doe_reference_names` in an `ElectricLoad` one only needs to provide the input key "SpaceHeatingLoad" in the `Scenario` (JSON or Dict). In this case the values from DoE reference names from the `ElectricLoad` will be used to define the `SpaceHeatingLoad`. 2. One can provide the `doe_reference_name` or `blended_doe_reference_names` directly in the `SpaceHeatingLoad` key within the `Scenario`. These values can be combined with the `annual_mmbtu` or `monthly_mmbtu` inputs to scale the DoE reference profile(s). 3. One can provide the `fuel_loads_mmbtu_per_hour` value in the `SpaceHeatingLoad` key within the `Scenario`. ```julia function SpaceHeatingLoad(; doe_reference_name::String = "", city::String = "", blended_doe_reference_names::Array{String, 1} = String[], blended_doe_reference_percents::Array{<:Real,1} = Real[], annual_mmbtu::Union{Real, Nothing} = nothing, monthly_mmbtu::Array{<:Real,1} = Real[], fuel_loads_mmbtu_per_hour::Array{<:Real,1} = Real[], time_steps_per_hour::Int = 1, latitude::Real=0.0, longitude::Real=0.0 ) ``` """ struct SpaceHeatingLoad loads_kw::Array{Real, 1} function SpaceHeatingLoad(; doe_reference_name::String = "", city::String = "", blended_doe_reference_names::Array{String, 1} = String[], blended_doe_reference_percents::Array{<:Real,1} = Real[], annual_mmbtu::Union{Real, Nothing} = nothing, monthly_mmbtu::Array{<:Real,1} = Real[], # addressable_load_fraction, # TODO fuel_loads_mmbtu_per_hour::Array{<:Real,1} = Real[], time_steps_per_hour::Int = 1, latitude::Real=0.0, longitude::Real=0.0 ) if length(fuel_loads_mmbtu_per_hour) > 0 if !(length(fuel_loads_mmbtu_per_hour) / time_steps_per_hour ≈ 8760) @error "Provided space heating load does not match the time_steps_per_hour." end loads_kw = fuel_loads_mmbtu_per_hour .* (MMBTU_TO_KWH * EXISTING_BOILER_EFFICIENCY) elseif !isempty(doe_reference_name) loads_kw = BuiltInSpaceHeatingLoad(city, doe_reference_name, latitude, longitude, 2017, annual_mmbtu, monthly_mmbtu) elseif length(blended_doe_reference_names) > 1 && length(blended_doe_reference_names) == length(blended_doe_reference_percents) loads_kw = blend_and_scale_doe_profiles(BuiltInSpaceHeatingLoad, latitude, longitude, 2017, blended_doe_reference_names, blended_doe_reference_percents, city, annual_mmbtu, monthly_mmbtu) else error("Cannot construct BuiltInSpaceHeatingLoad. You must provide either [fuel_loads_mmbtu_per_hour], [doe_reference_name, city], or [blended_doe_reference_names, blended_doe_reference_percents, city].") end if length(loads_kw) < 8760*time_steps_per_hour loads_kw = repeat(loads_kw, inner=Int(time_steps_per_hour / (length(loads_kw)/8760))) @info "Repeating space heating loads in each hour to match the time_steps_per_hour." end new( loads_kw ) end end function BuiltInDomesticHotWaterLoad( city::String, buildingtype::String, latitude::Real, longitude::Real, year::Int, annual_mmbtu::Union{<:Real, Nothing}=nothing, monthly_mmbtu::Union{Vector{<:Real}, Nothing}=nothing ) dhw_annual_mmbtu = Dict( "Miami" => Dict( "FastFoodRest" => 53.47209411, "FullServiceRest" => 158.0518043, "Hospital" => 442.7295435, "LargeHotel" => 3713.248373, "LargeOffice" => 127.9412792, "MediumOffice" => 22.09603477, "MidriseApartment" => 158.0580017, "Outpatient" => 27.60091429, "PrimarySchool" => 105.3179165, "RetailStore" => 0.0, "SecondarySchool" => 250.1299246, "SmallHotel" => 242.232695, "SmallOffice" => 9.891779415, "StripMall" => 0.0, "Supermarket" => 17.94985187, "warehouse" => 0.0, "FlatLoad" => 333.0450133 ), "Houston" => Dict( "FastFoodRest" => 62.56835989, "FullServiceRest" => 188.292814, "Hospital" => 530.6352726, "LargeHotel" => 4685.666667, "LargeOffice" => 160.8917808, "MediumOffice" => 25.9266894, "MidriseApartment" => 199.2544784, "Outpatient" => 32.87691943, "PrimarySchool" => 128.0705362, "RetailStore" => 0.0, "SecondarySchool" => 314.7654465, "SmallHotel" => 290.6293673, "SmallOffice" => 10.27839347, "StripMall" => 0.0, "Supermarket" => 19.86608717, "warehouse" => 0.0, "FlatLoad" => 415.6076756 ), "Phoenix" => Dict( "FastFoodRest" => 57.34025418, "FullServiceRest" => 170.9086319, "Hospital" => 480.098265, "LargeHotel" => 4127.191046, "LargeOffice" => 141.8507451, "MediumOffice" => 23.71397275, "MidriseApartment" => 175.5949563, "Outpatient" => 29.83372212, "PrimarySchool" => 116.811664, "RetailStore" => 0.0, "SecondarySchool" => 285.2339344, "SmallHotel" => 262.8487714, "SmallOffice" => 10.05557471, "StripMall" => 0.0, "Supermarket" => 18.7637822, "warehouse" => 0.0, "FlatLoad" => 368.7653325 ), "Atlanta" => Dict( "FastFoodRest" => 71.33170579, "FullServiceRest" => 217.4332205, "Hospital" => 615.3498557, "LargeHotel" => 5622.340656, "LargeOffice" => 192.7164525, "MediumOffice" => 29.62182675, "MidriseApartment" => 238.9315749, "Outpatient" => 37.9759973, "PrimarySchool" => 148.8362119, "RetailStore" => 0.0, "SecondarySchool" => 372.2083434, "SmallHotel" => 337.2688069, "SmallOffice" => 10.65138846, "StripMall" => 0.0, "Supermarket" => 21.71038069, "warehouse" => 0.0, "FlatLoad" => 494.7735263 ), "LasVegas" => Dict( "FastFoodRest" => 63.63848459, "FullServiceRest" => 191.8494897, "Hospital" => 540.9697668, "LargeHotel" => 4800.331564, "LargeOffice" => 164.7154124, "MediumOffice" => 26.36796732, "MidriseApartment" => 204.1120165, "Outpatient" => 33.48190098, "PrimarySchool" => 131.9651451, "RetailStore" => 0.0, "SecondarySchool" => 327.441087, "SmallHotel" => 296.3578765, "SmallOffice" => 10.32392915, "StripMall" => 0.0, "Supermarket" => 20.08676069, "warehouse" => 0.0, "FlatLoad" => 425.7275876 ), "LosAngeles" => Dict( "FastFoodRest" => 69.63212501, "FullServiceRest" => 211.7827529, "Hospital" => 598.9350422, "LargeHotel" => 5440.174033, "LargeOffice" => 186.6199083, "MediumOffice" => 28.91483286, "MidriseApartment" => 231.215325, "Outpatient" => 37.00823296, "PrimarySchool" => 142.8059487, "RetailStore" => 0.0, "SecondarySchool" => 352.7467563, "SmallHotel" => 328.1935523, "SmallOffice" => 10.58011717, "StripMall" => 0.0, "Supermarket" => 21.35337379, "warehouse" => 0.0, "FlatLoad" => 478.7476251 ), "SanFrancisco" => Dict( "FastFoodRest" => 77.13092952, "FullServiceRest" => 236.7180594, "Hospital" => 671.40531, "LargeHotel" => 6241.842643, "LargeOffice" => 213.8445094, "MediumOffice" => 32.07909301, "MidriseApartment" => 265.1697301, "Outpatient" => 41.35500136, "PrimarySchool" => 160.4507431, "RetailStore" => 0.0, "SecondarySchool" => 401.395655, "SmallHotel" => 368.0979112, "SmallOffice" => 10.90004379, "StripMall" => 0.0, "Supermarket" => 22.9292287, "warehouse" => 0.0, "FlatLoad" => 546.4574286 ), "Baltimore" => Dict( "FastFoodRest" => 78.2191761, "FullServiceRest" => 240.338156, "Hospital" => 681.9322322, "LargeHotel" => 6358.710286, "LargeOffice" => 217.7306132, "MediumOffice" => 32.52815422, "MidriseApartment" => 270.1195541, "Outpatient" => 41.96148216, "PrimarySchool" => 165.3116185, "RetailStore" => 0.0, "SecondarySchool" => 417.9512972, "SmallHotel" => 373.906416, "SmallOffice" => 10.94554028, "StripMall" => 0.0, "Supermarket" => 23.15795696, "warehouse" => 0.0, "FlatLoad" => 557.0507802 ), "Albuquerque" => Dict( "FastFoodRest" => 76.9149868, "FullServiceRest" => 235.9992545, "Hospital" => 669.3128607, "LargeHotel" => 6219.08303, "LargeOffice" => 212.9944774, "MediumOffice" => 31.97726287, "MidriseApartment" => 264.2063457, "Outpatient" => 41.20639013, "PrimarySchool" => 162.1556119, "RetailStore" => 0.0, "SecondarySchool" => 409.1649863, "SmallHotel" => 366.9712928, "SmallOffice" => 10.88949351, "StripMall" => 0.0, "Supermarket" => 22.88525618, "warehouse" => 0.0, "FlatLoad" => 545.235078 ), "Seattle" => Dict( "FastFoodRest" => 81.80231236, "FullServiceRest" => 252.2609525, "Hospital" => 716.6111323, "LargeHotel" => 6741.736717, "LargeOffice" => 230.8057849, "MediumOffice" => 34.04746055, "MidriseApartment" => 286.3412104, "Outpatient" => 44.07342164, "PrimarySchool" => 172.0233322, "RetailStore" => 0.0, "SecondarySchool" => 434.0806311, "SmallHotel" => 392.968915, "SmallOffice" => 11.09863592, "StripMall" => 0.0, "Supermarket" => 23.91178737, "warehouse" => 0.0, "FlatLoad" => 588.8601433 ), "Chicago" => Dict( "FastFoodRest" => 84.2645196, "FullServiceRest" => 260.4454844, "Hospital" => 740.4172516, "LargeHotel" => 7005.083356, "LargeOffice" => 239.7065959, "MediumOffice" => 35.08184587, "MidriseApartment" => 297.4938584, "Outpatient" => 45.49600079, "PrimarySchool" => 179.4639347, "RetailStore" => 0.0, "SecondarySchool" => 456.8817409, "SmallHotel" => 406.0751832, "SmallOffice" => 11.2033023, "StripMall" => 0.0, "Supermarket" => 24.4292392, "warehouse" => 0.0, "FlatLoad" => 611.6276445 ), "Boulder" => Dict( "FastFoodRest" => 83.95201542, "FullServiceRest" => 259.3997752, "Hospital" => 737.372005, "LargeHotel" => 6971.32924, "LargeOffice" => 238.572519, "MediumOffice" => 34.9486709, "MidriseApartment" => 296.06471, "Outpatient" => 45.31437164, "PrimarySchool" => 178.3378526, "RetailStore" => 0.0, "SecondarySchool" => 453.228537, "SmallHotel" => 404.4154946, "SmallOffice" => 11.18970855, "StripMall" => 0.0, "Supermarket" => 24.36505320, "warehouse" => 0.0, "FlatLoad" => 608.6556221 ), "Minneapolis" => Dict( "FastFoodRest" => 89.48929949, "FullServiceRest" => 277.8184269, "Hospital" => 790.9262388, "LargeHotel" => 7563.607619, "LargeOffice" => 258.6874644, "MediumOffice" => 37.28641454, "MidriseApartment" => 321.1473562, "Outpatient" => 48.51884975, "PrimarySchool" => 191.9480118, "RetailStore" => 0.0, "SecondarySchool" => 491.5554097, "SmallHotel" => 433.8738637, "SmallOffice" => 11.42620649, "StripMall" => 0.0, "Supermarket" => 25.53218144, "warehouse" => 0.0, "FlatLoad" => 658.8635839 ), "Helena" => Dict( "FastFoodRest" => 90.44011877, "FullServiceRest" => 280.9757902, "Hospital" => 800.0940058, "LargeHotel" => 7665.023574, "LargeOffice" => 262.1461576, "MediumOffice" => 37.68905029, "MidriseApartment" => 325.4421541, "Outpatient" => 49.09222188, "PrimarySchool" => 193.4573283, "RetailStore" => 0.0, "SecondarySchool" => 494.7393735, "SmallHotel" => 438.9398731, "SmallOffice" => 11.46564268, "StripMall" => 0.0, "Supermarket" => 25.72866824, "warehouse" => 0.0, "FlatLoad" => 667.2021224 ), "Duluth" => Dict( "FastFoodRest" => 98.10641517, "FullServiceRest" => 306.4772907, "Hospital" => 874.2611723, "LargeHotel" => 8484.906093, "LargeOffice" => 290.0193773, "MediumOffice" => 40.92475821, "MidriseApartment" => 360.161261, "Outpatient" => 53.53681127, "PrimarySchool" => 211.2386551, "RetailStore" => 0.0, "SecondarySchool" => 543.3733772, "SmallHotel" => 479.7414481, "SmallOffice" => 11.79316054, "StripMall" => 0.0, "Supermarket" => 27.3451629, "warehouse" => 0.0, "FlatLoad" => 736.3678114 ), "Fairbanks" => Dict( "FastFoodRest" => 108.5335945, "FullServiceRest" => 341.1572799, "Hospital" => 975.1062178, "LargeHotel" => 9600.267161, "LargeOffice" => 327.8820873, "MediumOffice" => 45.32138512, "MidriseApartment" => 407.3910855, "Outpatient" => 59.6203514, "PrimarySchool" => 234.2595741, "RetailStore" => 0.0, "SecondarySchool" => 604.6838786, "SmallHotel" => 535.2525234, "SmallOffice" => 12.23744003, "StripMall" => 0.0, "Supermarket" => 29.53958045, "warehouse" => 0.0, "FlatLoad" => 830.07826 ) ) if isempty(city) city = find_ashrae_zone_city(latitude, longitude) end if !(buildingtype in default_buildings) error("buildingtype $(buildingtype) not in $(default_buildings).") end if isnothing(annual_mmbtu) annual_mmbtu = dhw_annual_mmbtu[city][buildingtype] end built_in_load("domestic_hot_water", city, buildingtype, year, annual_mmbtu, monthly_mmbtu) end function BuiltInSpaceHeatingLoad( city::String, buildingtype::String, latitude::Real, longitude::Real, year::Int, annual_mmbtu::Union{<:Real, Nothing}=nothing, monthly_mmbtu::Union{Vector{<:Real}, Nothing}=nothing, ) spaceheating_annual_mmbtu = Dict( "Miami" => Dict( "FastFoodRest" => 5.426780867, "FullServiceRest" => 12.03181471, "Hospital" => 6248.413294, "LargeHotel" => 198.0691407, "LargeOffice" => 168.9731637, "MediumOffice" => 0.036985655, "MidriseApartment" => 38.70606161, "Outpatient" => 2559.185872, "PrimarySchool" => 49.78021153, "RetailStore" => 12.12015432, "SecondarySchool" => 203.5185485, "SmallHotel" => 9.098564901, "SmallOffice" => 0.312524873, "StripMall" => 20.73216748, "Supermarket" => 101.2785324, "warehouse" => 56.0796017, "FlatLoad" => 605.2352137 ), "Houston" => Dict( "FastFoodRest" => 85.49111065, "FullServiceRest" => 199.7942842, "Hospital" => 8732.10385, "LargeHotel" => 1307.035548, "LargeOffice" => 2229.971744, "MediumOffice" => 16.25994314, "MidriseApartment" => 386.0269973, "Outpatient" => 2829.324307, "PrimarySchool" => 469.2532935, "RetailStore" => 289.0470815, "SecondarySchool" => 2011.1678969999998, "SmallHotel" => 108.9825885, "SmallOffice" => 19.55157672, "StripMall" => 292.23235389999996, "Supermarket" => 984.7374347000001, "warehouse" => 475.9377273, "FlatLoad" => 1277.307359 ), "Phoenix" => Dict( "FastFoodRest" => 57.89972381, "FullServiceRest" => 147.2569493, "Hospital" => 9382.021026, "LargeHotel" => 896.790817, "LargeOffice" => 1584.061452, "MediumOffice" => 1.922551528, "MidriseApartment" => 290.9887152, "Outpatient" => 3076.340876, "PrimarySchool" => 305.573525, "RetailStore" => 208.66330580000002, "SecondarySchool" => 1400.638544, "SmallHotel" => 83.98084516, "SmallOffice" => 9.988210938, "StripMall" => 230.16060699999997, "Supermarket" => 972.3008295, "warehouse" => 362.42249280000004, "FlatLoad" => 1188.188154 ), "Atlanta" => Dict( "FastFoodRest" => 168.8402371, "FullServiceRest" => 379.5865464, "Hospital" => 10467.659959999999, "LargeHotel" => 2427.6589879999997, "LargeOffice" => 3624.593975, "MediumOffice" => 49.00635733, "MidriseApartment" => 718.9316697, "Outpatient" => 3186.250588, "PrimarySchool" => 931.7212450999999, "RetailStore" => 627.2489826000001, "SecondarySchool" => 3968.4936420000004, "SmallHotel" => 202.26124219999997, "SmallOffice" => 42.74797302, "StripMall" => 615.2240506, "Supermarket" => 1880.5304489999999, "warehouse" => 930.9449202, "FlatLoad" => 1888.856302 ), "LasVegas" => Dict( "FastFoodRest" => 100.0877773, "FullServiceRest" => 247.21791319999997, "Hospital" => 9100.302056, "LargeHotel" => 1500.581408, "LargeOffice" => 2479.152321, "MediumOffice" => 5.220181581, "MidriseApartment" => 487.43122850000003, "Outpatient" => 2924.8220460000002, "PrimarySchool" => 499.6562223, "RetailStore" => 386.0185744, "SecondarySchool" => 2277.7410649999997, "SmallHotel" => 138.4427074, "SmallOffice" => 19.16330622, "StripMall" => 389.30494280000005, "Supermarket" => 1479.302604, "warehouse" => 579.7671637999999, "FlatLoad" => 1413.3882199999998 ), "LosAngeles" => Dict( "FastFoodRest" => 40.90390152, "FullServiceRest" => 97.94277036, "Hospital" => 10346.1713, "LargeHotel" => 707.848762, "LargeOffice" => 1458.148818, "MediumOffice" => 0.12342009699999999, "MidriseApartment" => 265.2851759, "Outpatient" => 3417.120585, "PrimarySchool" => 318.73600980000003, "RetailStore" => 175.104083, "SecondarySchool" => 1198.276619, "SmallHotel" => 72.42852638, "SmallOffice" => 5.898878347, "StripMall" => 193.18730269999998, "Supermarket" => 1040.273464, "warehouse" => 323.96697819999997, "FlatLoad" => 1228.8385369999999 ), "SanFrancisco" => Dict( "FastFoodRest" => 127.22328700000001, "FullServiceRest" => 362.48645889999995, "Hospital" => 11570.9155, "LargeHotel" => 1713.3629670000003, "LargeOffice" => 2690.1191, "MediumOffice" => 3.8159670660000002, "MidriseApartment" => 648.4472797999999, "Outpatient" => 3299.0539519999998, "PrimarySchool" => 818.2159102, "RetailStore" => 569.8081034, "SecondarySchool" => 3414.148347, "SmallHotel" => 189.0244446, "SmallOffice" => 27.53039453, "StripMall" => 526.2320428, "Supermarket" => 2301.616069, "warehouse" => 675.6758453, "FlatLoad" => 1808.604729 ), "Baltimore" => Dict( "FastFoodRest" => 305.2671204, "FullServiceRest" => 657.1337578, "Hospital" => 11253.61694, "LargeHotel" => 3731.0254619999996, "LargeOffice" => 5109.311943, "MediumOffice" => 116.8101842, "MidriseApartment" => 1132.964052, "Outpatient" => 3285.227941, "PrimarySchool" => 1428.239177, "RetailStore" => 1068.034778, "SecondarySchool" => 6557.634924, "SmallHotel" => 346.3683857, "SmallOffice" => 63.29818348, "StripMall" => 1075.39546, "Supermarket" => 2929.182261, "warehouse" => 1568.722061, "FlatLoad" => 2539.2645399999997 ), "Albuquerque" => Dict( "FastFoodRest" => 199.73581399999998, "FullServiceRest" => 398.5712205, "Hospital" => 8371.240776999999, "LargeHotel" => 2750.8382260000003, "LargeOffice" => 3562.0023950000004, "MediumOffice" => 47.49307973, "MidriseApartment" => 805.0965778, "Outpatient" => 2971.868562, "PrimarySchool" => 981.4176700999999, "RetailStore" => 755.4523907, "SecondarySchool" => 4338.227865999999, "SmallHotel" => 232.2194443, "SmallOffice" => 43.25360481, "StripMall" => 760.0982018, "Supermarket" => 2302.228741, "warehouse" => 1151.250885, "FlatLoad" => 1854.437216 ), "Seattle" => Dict( "FastFoodRest" => 255.5992711, "FullServiceRest" => 627.5634984000001, "Hospital" => 11935.157290000001, "LargeHotel" => 3343.683348, "LargeOffice" => 5266.970348, "MediumOffice" => 28.97979768, "MidriseApartment" => 1117.5465470000001, "Outpatient" => 3468.128914, "PrimarySchool" => 1263.541878, "RetailStore" => 952.2758742000001, "SecondarySchool" => 6367.850187, "SmallHotel" => 310.8087307, "SmallOffice" => 49.34878545, "StripMall" => 969.1074739000001, "Supermarket" => 3004.1844929999997, "warehouse" => 1137.398514, "FlatLoad" => 2506.1340600000003 ), "Chicago" => Dict( "FastFoodRest" => 441.93439000000006, "FullServiceRest" => 888.3312571, "Hospital" => 12329.57943, "LargeHotel" => 5104.848129, "LargeOffice" => 7706.028917000001, "MediumOffice" => 216.01411800000002, "MidriseApartment" => 1482.040156, "Outpatient" => 3506.5381090000005, "PrimarySchool" => 2006.0002120000001, "RetailStore" => 1472.8704380000001, "SecondarySchool" => 8962.172873, "SmallHotel" => 479.4653436000001, "SmallOffice" => 94.19308949, "StripMall" => 1497.556168, "Supermarket" => 3696.2112950000005, "warehouse" => 2256.477231, "FlatLoad" => 3258.766323 ), "Boulder" => Dict( "FastFoodRest" => 306.8980525, "FullServiceRest" => 642.8843574, "Hospital" => 9169.381845, "LargeHotel" => 3975.1080020000004, "LargeOffice" => 5027.882454, "MediumOffice" => 124.26913059999998, "MidriseApartment" => 1098.944993, "Outpatient" => 3087.969786, "PrimarySchool" => 1356.396807, "RetailStore" => 1086.9187570000001, "SecondarySchool" => 6268.036872, "SmallHotel" => 342.77800099999996, "SmallOffice" => 65.95714912, "StripMall" => 1093.093638, "Supermarket" => 2966.790122, "warehouse" => 1704.8648210000001, "FlatLoad" => 2394.8859239999997 ), "Minneapolis" => Dict( "FastFoodRest" => 588.8854722, "FullServiceRest" => 1121.229499, "Hospital" => 13031.2313, "LargeHotel" => 6359.946704, "LargeOffice" => 10199.279129999999, "MediumOffice" => 394.1525556, "MidriseApartment" => 1814.148381, "Outpatient" => 3661.1462229999997, "PrimarySchool" => 2600.964302, "RetailStore" => 1869.8106289999998, "SecondarySchool" => 11963.323859999999, "SmallHotel" => 618.0427338999999, "SmallOffice" => 128.12525349999999, "StripMall" => 1952.731917, "Supermarket" => 4529.776664, "warehouse" => 3231.223746, "FlatLoad" => 4004.001148 ), "Helena" => Dict( "FastFoodRest" => 468.8276835, "FullServiceRest" => 934.8994934, "Hospital" => 10760.57411, "LargeHotel" => 5554.910785, "LargeOffice" => 7373.056709, "MediumOffice" => 239.8330306, "MidriseApartment" => 1531.102079, "Outpatient" => 3390.42972, "PrimarySchool" => 2097.777112, "RetailStore" => 1494.85988, "SecondarySchool" => 9535.484059, "SmallHotel" => 499.85992930000003, "SmallOffice" => 98.85818175, "StripMall" => 1604.0043970000002, "Supermarket" => 3948.5338049999996, "warehouse" => 2504.784991, "FlatLoad" => 3252.362248 ), "Duluth" => Dict( "FastFoodRest" => 738.1353594999999, "FullServiceRest" => 1400.36692, "Hospital" => 14179.84149, "LargeHotel" => 7781.9012760000005, "LargeOffice" => 12504.64187, "MediumOffice" => 468.2112216, "MidriseApartment" => 2204.85149, "Outpatient" => 3774.3233130000003, "PrimarySchool" => 3160.1200719999997, "RetailStore" => 2298.8242920000002, "SecondarySchool" => 14468.64346, "SmallHotel" => 772.5386662000001, "SmallOffice" => 155.8350887, "StripMall" => 2411.847491, "Supermarket" => 5587.977185, "warehouse" => 3962.122014, "FlatLoad" => 4741.886326 ), "Fairbanks" => Dict( "FastFoodRest" => 1245.3608279999999, "FullServiceRest" => 2209.293209, "Hospital" => 20759.042680000002, "LargeHotel" => 12298.7791, "LargeOffice" => 23214.51532, "MediumOffice" => 949.8812392000001, "MidriseApartment" => 3398.039504, "Outpatient" => 4824.076322999999, "PrimarySchool" => 6341.861225, "RetailStore" => 3869.670979, "SecondarySchool" => 25619.149269999998, "SmallHotel" => 1264.41064, "SmallOffice" => 297.08593010000004, "StripMall" => 3934.89178, "Supermarket" => 8515.422039000001, "warehouse" => 6882.6512680000005, "FlatLoad" => 7851.508208 ) ) if isempty(city) city = find_ashrae_zone_city(latitude, longitude) end if !(buildingtype in default_buildings) error("buildingtype $(buildingtype) not in $(default_buildings).") end if isnothing(annual_mmbtu) annual_mmbtu = spaceheating_annual_mmbtu[city][buildingtype] end built_in_load("space_heating", city, buildingtype, year, annual_mmbtu, monthly_mmbtu) end
# Autogenerated wrapper script for Pixman_jll for aarch64-apple-darwin export libpixman JLLWrappers.@generate_wrapper_header("Pixman") JLLWrappers.@declare_library_product(libpixman, "@rpath/libpixman-1.0.dylib") function __init__() JLLWrappers.@generate_init_header() JLLWrappers.@init_library_product( libpixman, "lib/libpixman-1.0.40.0.dylib", RTLD_LAZY | RTLD_DEEPBIND, ) JLLWrappers.@generate_init_footer() end # __init__()
module GLSLBuildins # not in base, so inferable stump must be defined gl_FragCoord() = zero(Vec2f0) # replace rule for transpiler gl_FragCoord(backend::GL) = TGlobal("gl_FragCoord", Vec2f0) gl_InstanceID() = Int32(0) gl_InstanceID(backend::GL) = TGlobal("gl_InstanceID", Vec2f0) #Base.sin(x) already defined sin{T}(backend::GL, x::Type{T}) = TExpr("sin", T) EmitVertex() = nothing sin{T}(backend::GL) = TExpr("EmitVertex", T) end
# This file is a part of MGVI.jl, licensed under the MIT License (MIT). using MGVI using Distributions using LinearAlgebra using Random Test.@testset "test_normal_mvnormal_jac" begin epsilon = 1E-5 Random.seed!(145) true_params = randn(4) function _common_params(p) μ1 = p[1] - p[2] μ2 = p[2] * p[1] σ1 = p[3]^2 + 10. σ2 = (p[3] + p[4])^2 + 10. μ1, σ1, μ2, σ2 end function normal_model(p) μ1, σ1, μ2, σ2 = _common_params(p) n1 = Normal(μ1, σ1) n2 = Normal(μ2, σ2) Product([n1, n2]) end _flat_normal_model = MGVI.flat_params ∘ normal_model # NOTE: models are not the same. Σ[1, 1] = σ1^2, while here we assign σ1. # We do this because in this way it is easier to compare jacobians. # While in Normal, parameters are μ and σ, in MvNormal corresponding paramters # are μ and σ^2. function mvnormal_model(p) μ1, σ1, μ2, σ2 = _common_params(p) MvNormal([μ1, μ2], [σ1 0.;0. σ2]) end _flat_mvnormal_model = MGVI.flat_params ∘ mvnormal_model normal_full_jac = FullJacobianFunc(_flat_normal_model)(true_params) normal_fwdder_jac = FwdDerJacobianFunc(_flat_normal_model)(true_params) normal_fwdrevad_jac = FwdRevADJacobianFunc(_flat_normal_model)(true_params) mvnormal_full_jac = FullJacobianFunc(_flat_mvnormal_model)(true_params) mvnormal_fwdder_jac = FwdDerJacobianFunc(_flat_mvnormal_model)(true_params) mvnormal_fwdrevad_jac = FwdRevADJacobianFunc(_flat_mvnormal_model)(true_params) for i in 1:min(size(normal_full_jac)...) vec = rand(size(normal_full_jac, 2)) # We have to reorder jacobian for MvNormal and pick only relevant parts # While stacked Normals have parameters [μ1, σ1, μ2, σ2] # MvNormal is parametrized as [μ1, μ2, Σ11, Σ12, Σ22] # Moreover. In our example Σ12 = 0. Thus we skip this element mv_reorder = [1, 3, 2, 5] Test.@test norm(normal_full_jac*vec - (mvnormal_full_jac*vec)[mv_reorder]) < epsilon Test.@test norm(normal_fwdder_jac*vec - (mvnormal_fwdder_jac*vec)[mv_reorder]) < epsilon Test.@test norm(normal_fwdrevad_jac*vec - (mvnormal_fwdrevad_jac*vec)[mv_reorder]) < epsilon end end Test.@testset "test_normal_mvnormal_logpdf_der" begin epsilon = 1E-5 Random.seed!(145) dim = 2 data = randn(dim) pardim = dim + dim true_params = randn(pardim) function _common_params(p) μ1 = p[1] - p[2] μ2 = p[2] * p[1] σ1 = p[3]^2 + 10. σ2 = (p[3] + p[4])^2 + 10. μ1, σ1, μ2, σ2 end function normal_model(p) μ1, σ1, μ2, σ2 = _common_params(p) n1 = Normal(μ1, σ1) n2 = Normal(μ2, σ2) Product([n1, n2]) end # est_res_sampler = MGVI._create_residual_sampler(normal_model, true_params; # residual_sampler=ImplicitResidualSampler, # jacobian_func=FwdRevADJacobianFunc, # residual_sampler_options=(;)) # residual_samples = rand(Random.GLOBAL_RNG, est_res_sampler, 5) residual_samples = [ 1.57327 -0.545016 -0.468532 -0.148169 -0.0476087 0.889662 -0.32206 -0.776208 -1.3703 -0.262721 0.535246 -0.0152493 0.847152 0.723876 -0.0277677 2.13597 0.252785 -0.278254 1.11853 -0.189659 ] normal_par_dim = dim + dim normal_kl(params::AbstractVector) = MGVI.mgvi_kl(normal_model, data, residual_samples, params) normal_grad = zeros(pardim) MGVI._gradient_for_optim(normal_kl)(normal_grad, true_params) function mvnormal_model(p) μ1, σ1, μ2, σ2 = _common_params(p) MvNormal([μ1, μ2], [σ1^2 0.;0. σ2^2]) end mvnormal_kl(params::AbstractVector) = MGVI.mgvi_kl(mvnormal_model, data, residual_samples, params) mvnormal_grad = zeros(pardim) MGVI._gradient_for_optim(mvnormal_kl)(mvnormal_grad, true_params) Test.@test norm(normal_grad - mvnormal_grad) < epsilon end
function printUpdate(o...) if isinteractive() print("\u1b[1G") print(o...) print("\u1b[K") end end function printlnFlush(o...) println(o...) if !isinteractive() flush(STDOUT) end end function saveNetwork(weights,filename) w = map(Array,weights) save(pretrainedPath("$(filename).jld"),"w",w,compress=true) end function loadNetwork(filename) w = load(pretrainedPath(filename),"w") w = map(KnetArray,w) end function pixelwiseSoftloss(ypred,y) -sum(y.*logp(ypred,3)) / (size(y,1)*size(y,2)*size(y,4)) end function pixelwiseAccuracy(ypred,y) ncorrect = sum(y.*(ypred.==maximum(ypred,3))) ncount = size(ypred,1)*size(ypred,2)*size(ypred,4) return ncorrect,ncount end
#= Provides calc_model_rv(theta, time) Computes the velocity of the star due to the perturbations of multiple planets, as the linear superposition of the circular orbit induced by each planet, i.e., neglecting eccentricity and mutual planet-planet interactions =# # Calculate Keplerian velocity of star due to one planet (with parameters displaced by offset) function calc_rv_circ_one_planet{T1,T2}( theta::Array{T1,1}, time::T2; plid::Integer = 1 ) (P,K,M0) = extract_PKM0(theta,plid=plid) #(P,Kc,Ks) = extract_PKcKs(theta,plid=plid) n = 2pi/P #M = mod2pi(time*n-M0) M = time*n-M0 return K*cos(M) #return Kc*cos(M)+Ks*sin(M) end # Calculate Keplerian velocity of star due to num_pl planets function calc_rv_circ_multi_planet{T1,T2}( theta::Array{T1,1}, time::T2) zdot = zero(T1) for plid in 1:num_planets(theta) zdot += calc_rv_circ_one_planet(theta,time,plid=plid) end return zdot end # Assumes model parameters = [ Period_1, K_1, M0_1, Period_2, K_2, M0_2, ... C ] function calc_model_rv{T1,T2}( theta::Array{T1,1}, t::T2; obsid::Integer = 1, tol::Real = 1.e-8) Offset = extract_rvoffset(theta, obsid=obsid) calc_rv_circ_multi_planet(theta, t) + Offset end export calc_model_rv
# Read in file of helper functions # This file includes: cleantext, countwords include("../word_count_helpers.jl") # Load the file names dataLoc = "../../../data/word_count/"; fnames = dataLoc.*readdir(dataLoc) # Grab the argument that is passed in # This is the index into fnames for this process task_id = parse(Int,ARGS[1]) num_tasks = parse(Int,ARGS[2]) # Check to see if the index is valid (so the program exits cleanly if the wrong indices are passed) for i in task_id+1:num_tasks:length(fnames) # Read in file and clean the text f = open(fnames[i]) text=cleantext(readlines(f)) # Count number of times each word appears wordCounts = countwords(text) # Sort and print the top 5 words with their counts rankedwords = sort(collect(wordCounts), by=x->x[2], rev=true) println(rankedwords[1:5,:]) end
function Base.truncate(uv::TheoreticalFittedUncertainScalar, constraint::TruncateStd; n_draws::Int = 10000) m = mean(uv.distribution.distribution) s = std(uv.distribution.distribution) lower_bound = m - s upper_bound = m + s truncated(uv.distribution, lower_bound, upper_bound) end
filename = ARGS[1] input = readlines(filename) orbits = Dict() for orbit in input planet, moon = split(orbit, ')') orbits[String(moon)] = String(planet) end function get_paths() paths = [] for planet in keys(orbits) i = planet path = [i] while haskey(orbits, i) i = orbits[i] push!(path, i) end if "SAN" in path || "YOU" in path push!(paths, path) end end return paths end function find_orbital_transfer(paths) path_one = pop!(paths) path_two = pop!(paths) transfers = -2 # offset planet jumping meet_at = nothing # common root # find common root and distance from planet a for planet in path_one if planet in path_two meet_at = planet break end transfers += 1 end # find distance from planet b for planet in path_two if planet == meet_at break end transfers += 1 end return transfers end println( find_orbital_transfer( get_paths() ) )
using PtFEM nf_path = joinpath(dirname(@__FILE__), "Ex57.1.nf.dat") loads_path = joinpath(dirname(@__FILE__), "Ex57.1.loads.dat") data = Dict( # Solid(ndim, nst, nxe, nye, nze, nip, direction=:r, finite_element(nod, nodof)) :struc_el => Solid(3, 6, 20, 60, 40, 8, Hexahedron(20, 3)), :properties => [ 100.0 0.3; ], :x_coords => [ 0.0000, 0.0250, 0.0500, 0.0750, 0.1000, 0.1250, 0.1500, 0.1750, 0.2000, 0.2250, 0.2500, 0.2750, 0.3000, 0.3250, 0.3500, 0.3750, 0.4000, 0.4250, 0.4500, 0.4750, 0.5000 ], :y_coords => [ 0.0000, 0.0500, 0.1000, 0.1500, 0.2000, 0.2500, 0.3000, 0.3500, 0.4000, 0.4500, 0.5000, 0.5500, 0.6000, 0.6500, 0.7000, 0.7500, 0.8000, 0.8500, 0.9000, 0.9500, 1.0000, 1.0500, 1.1000, 1.1500, 1.2000, 1.2500, 1.3000, 1.3500, 1.4000, 1.4500, 1.5000, 1.5500, 1.6000, 1.6500, 1.7000, 1.7500, 1.8000, 1.8500, 1.9000, 1.9500, 2.0000, 2.0500, 2.1000, 2.1500, 2.2000, 2.2500, 2.3000, 2.3500, 2.4000, 2.4500, 2.5000, 2.5500, 2.6000, 2.6500, 2.7000, 2.7500, 2.8000, 2.8500, 2.9000, 2.9500, 3.0000 ], :z_coords => [ 0.0000, -0.0500, -0.1000, -0.1500, -0.2000, -0.2500, -0.3000, -0.3500, -0.4000, -0.4500, -0.5000, -0.5500, -0.6000, -0.6500, -0.7000, -0.7500, -0.8000, -0.8500, -0.9000, -0.9500, -1.0000, -1.0500, -1.1000, -1.1500, -1.2000, -1.2500, -1.3000, -1.3500, -1.4000, -1.4500, -1.5000, -1.5500, -1.6000, -1.6500, -1.7000, -1.7500, -1.8000, -1.8500, -1.9000, -1.9500, -2.0000 ], :support => PtFEM.read_nf_file(nf_path), :loaded_nodes => PtFEM.read_loads_file(loads_path), :cg_tol => 1.0e-5, :cg_limit => 2000 ) @time m = p56(data) println()
# Put in a separate page so it can be used by SciMLDocs.jl pages=[ "Home" => "index.md", "Example: Nice DiffEq Syntax Without A DSL" => "Example_dsl.md", "SLArrays" => "SLArrays.md", "LArrays" => "LArrays.md", "Relation to NamedTuples" => "NamedTuples_relation.md", "Note_labelled_slices.md" ]
# automatically generated by the FlatBuffers compiler, do not modify # module: Example import ..InParentNamespace import FlatBuffers FlatBuffers.@with_kw mutable struct Monster{T} #= # an example documentation comment: monster object =# pos::Union{Vec3, Nothing} = nothing mana::Int16 = 150 hp::Int16 = 100 name::String = "" inventory::Vector{UInt8} = [] color::Color = 8 test_type::UInt8 = 0 test::T = nothing test4::Vector{Test} = [] testarrayofstring::Vector{String} = [] #= # an example documentation comment: this will end up in the generated code # multiline too =# testarrayoftables::Vector{Monster{T}} = [] enemy::Union{Monster{T}, Nothing} = nothing testnestedflatbuffer::Vector{UInt8} = [] testempty::Union{Stat, Nothing} = nothing testbool::Bool = false testhashs32_fnv1::Int32 = 0 testhashu32_fnv1::UInt32 = 0 testhashs64_fnv1::Int64 = 0 testhashu64_fnv1::UInt64 = 0 testhashs32_fnv1a::Int32 = 0 testhashu32_fnv1a::UInt32 = 0 testhashs64_fnv1a::Int64 = 0 testhashu64_fnv1a::UInt64 = 0 testarrayofbools::Vector{Bool} = [] testf::Float32 = 3.14159 testf2::Float32 = 3.0 testf3::Float32 = 0.0 testarrayofstring2::Vector{String} = [] testarrayofsortedstruct::Vector{Ability} = [] flex::Vector{UInt8} = [] test5::Vector{Test} = [] vector_of_longs::Vector{Int64} = [] vector_of_doubles::Vector{Float64} = [] parent_namespace_test::Union{InParentNamespace, Nothing} = nothing vector_of_referrables::Vector{Referrable} = [] single_weak_reference::UInt64 = 0 vector_of_weak_references::Vector{UInt64} = [] vector_of_strong_referrables::Vector{Referrable} = [] co_owning_reference::UInt64 = 0 vector_of_co_owning_references::Vector{UInt64} = [] non_owning_reference::UInt64 = 0 vector_of_non_owning_references::Vector{UInt64} = [] #= any_unique_type::UInt8 = 0 =# #= any_unique::AnyUniqueAliases = nothing =# #= any_ambiguous_type::UInt8 = 0 =# #= any_ambiguous::AnyAmbiguousAliases = nothing =# vector_of_enums::Vector{Color} = [] end FlatBuffers.@ALIGN(Monster, 1) FlatBuffers.slot_offsets(::Type{T}) where {T<:Monster} = [ 0x00000004, 0x00000006, 0x00000008, 0x0000000A, 0x0000000E, 0x00000010, 0x00000012, 0x00000014, 0x00000016, 0x00000018, 0x0000001A, 0x0000001C, 0x0000001E, 0x00000020, 0x00000022, 0x00000024, 0x00000026, 0x00000028, 0x0000002A, 0x0000002C, 0x0000002E, 0x00000030, 0x00000032, 0x00000034, 0x00000036, 0x00000038, 0x0000003A, 0x0000003C, 0x0000003E, 0x00000040, 0x00000042, 0x00000044, 0x00000046, 0x00000048, 0x0000004A, 0x0000004C, 0x0000004E, 0x00000050, 0x00000052, 0x00000054, 0x00000056, 0x00000058, 0x0000005A, 0x0000005C, 0x0000005E, 0x00000060, 0x00000062 ] FlatBuffers.root_type(::Type{T}) where {T<:Monster} = true FlatBuffers.file_identifier(::Type{T}) where {T<:Monster} = "MONS" FlatBuffers.file_extension(::Type{T}) where {T<:Monster} = "mon" Monster{T}(buf::AbstractVector{UInt8}) where {T} = FlatBuffers.read(Monster{T}, buf) Monster{T}(io::IO) where {T} = FlatBuffers.deserialize(io, Monster{T})
""" function read_pdb(file_pdb) This will read a .pdb file, getting all the coordinate information. - `file_pdb`: path of target .pdb file. # Output - `id_vec` - `` # Example ```julia-repl file_pdb = "gb1.pdb" coord = read_pdb(file_pdb) ``` """ function read_pdb(file_pdb) # Setting variabls col_range_id = 7:11 col_range_atom_name = 13:16 col_range_mol = 23:26 col_range_x = 31:38 col_range_y = 39:46 col_range_z = 47:54 # Reading file io = open(file_pdb) str = read(io, String) reg = r"ATOM..*[A-Z]" res = findall(reg, str) res = [str[n] for n in res] # Ansys num_atoms = length(res) atom_vec = [String(strip(res[atom][col_range_atom_name], ' ')) for atom=1:num_atoms] mol_vec = zeros(Int, num_atoms, 1) id_vec = zeros(Int, num_atoms, 1) coord_mat = zeros(num_atoms, 3) for atom = 1:num_atoms id_vec[atom, 1] = parse(Int, res[atom][col_range_id]) mol_vec[atom, 1] = parse(Int, res[atom][col_range_mol]) coord_mat[atom, 1] = parse(Float64, res[atom][col_range_x]) coord_mat[atom, 2] = parse(Float64, res[atom][col_range_y]) coord_mat[atom, 3] = parse(Float64, res[atom][col_range_z]) end return id_vec, atom_vec, mol_vec, coord_mat end """ function read_pdb() This will read a .pdb file, getting all the coordinate information. - `file_pdb`: path of target .pdb file. # Example ```julia-repl file_pdb = "gb1.pdb" coord = read_pdb(file_pdb) ``` """ function read_psf(file_psf) # Read psf file io = open(file_psf) raw_info = split(read(io, String), "\n") raw_start = findall(x->occursin("!N", x), raw_info)[2:7] .+ 1 # Ignore !NTITLE raw_end = raw_start .- 3 # Atom info col_type = 6 col_charge = 7 num_atoms = raw_end[2] - raw_start[1] + 1 type_vec = [String(split(raw_info[i])[col_type]) for i=raw_start[1]:raw_end[2]] charge_vec = [parse(Float64, String(split(raw_info[i])[col_charge])) for i=raw_start[1]:raw_end[2]] # Bond info bond_topo = [strvec2intvec(split(raw_info[i])) for i=raw_start[2]:raw_end[3]] bond_topo = Array(reshape(vcat(bond_topo...), (2, :))') # Angle info angle_topo = [strvec2intvec(split(raw_info[i])) for i=raw_start[3]:raw_end[4]] angle_topo = Array(reshape(vcat(angle_topo...), (3, :))') # Dihedral info dihedral_topo = [strvec2intvec(split(raw_info[i])) for i=raw_start[4]:raw_end[5]] dihedral_topo = Array(reshape(vcat(dihedral_topo...), (4, :))') # Improper info improper_topo = [strvec2intvec(split(raw_info[i])) for i=raw_start[5]:raw_end[6]] improper_topo = Array(reshape(vcat(improper_topo...), (4, :))') return type_vec, charge_vec, bond_topo, angle_topo, dihedral_topo, improper_topo end function assign_para_atom(id_vec, mol_vec, type_vec, charge_vec, coord_mat, potential::T) where T <:Potential num_atoms = size(id_vec, 1) type_list = unique(type_vec) mol_vec = mol_vec .- minimum(mol_vec) .+ 1 # Mol id start from 1 num_atom_types = size(type_list, 1) vec_atom = Vector{Atom}(undef, num_atoms) for atom = 1 : num_atoms vec_atom[atom] = Atom(id_vec[atom], mol_vec[atom], findfirst(x->x==type_vec[atom], type_list), charge_vec[atom], coord_mat[atom, :]) end para_pair = [findfirst(x->judgeequal(x, [type_list[i] for i in id_vec[atom]]), potential.para_pair) for atom = 1:num_atom_types] para_pair = vcat([pair.para for pair in potential.para_pair[para_pair]]...) para_pair = reshape(para_pair, (4, :))' para_mass = [findfirst(x->judgeequal(x, [type_list[i] for i in id_vec[atom]]), potential.para_mass) for atom = 1:num_atom_types] para_mass = vcat([pair.para for pair in potential.para_mass[para_mass]]...) return num_atoms, num_atom_types, vec_atom, para_pair, para_mass, type_list end function assign_para_bond(type_vec, bond_topo, potential) num_bonds = size(bond_topo, 1) num_bond_types = 0 vec_bond = Vector{Bond}(undef, num_bonds) type_list = [0] for id = 1:num_bonds para_type_id = findfirst(x->judgeequal(x, [type_vec[i] for i in bond_topo[id, :]]), potential.para_bond) if para_type_id == nothing print([type_vec[i] for i in bond_topo[id, :]]) error("No matching bond type is found in Charmm36 force filed.") end if !in(para_type_id, type_list) num_bond_types += 1 append!(type_list, para_type_id) end vec_bond[id] = Bond(id, findfirst(x->x==para_type_id, type_list) - 1, bond_topo[id, :]) end para_bond = [bond.para for bond in potential.para_bond[type_list[2:end]]] para_bond = Array(hcat(para_bond...)') return num_bonds, num_bond_types, vec_bond, para_bond end function assign_para_angle(type_vec, angle_topo, potential) num_angles = size(angle_topo, 1) num_angle_types = 0 vec_angle = Vector{Angle}(undef, num_angles) type_list = [0] for id = 1:num_angles para_type_id = findfirst(x->judgeequal(x, [type_vec[i] for i in angle_topo[id, :]]), potential.para_angle) if para_type_id == nothing print([type_vec[i] for i in angle_topo[id, :]]) error("No matching angle type is found in Charmm36 force filed.") end if !in(para_type_id, type_list) num_angle_types += 1 append!(type_list, para_type_id) end vec_angle[id] = Angle(id, findfirst(x->x==para_type_id, type_list)-1, angle_topo[id, :]) end para_angle = [angle.para for angle in potential.para_angle[type_list[2:end]]] para_angle = Array(hcat(para_angle...)') return num_angles, num_angle_types, vec_angle, para_angle end function assign_para_dihedral(type_vec, dihedral_topo, potential) num_dihedrals = size(dihedral_topo, 1) num_dihedral_types = 0 vec_dihedral = Vector{Dihedral}(undef, num_dihedrals) type_list = [0] for id = 1:num_dihedrals para_type_id = findfirst(x->judgeequal(x, [type_vec[i] for i in dihedral_topo[id, :]]), potential.para_dihedral) if para_type_id == nothing print([type_vec[i] for i in dihedral_topo[id, :]]) error("No matching dihedral type is found in Charmm36 force filed.") end if !in(para_type_id, type_list) num_dihedral_types += 1 append!(type_list, para_type_id) end vec_dihedral[id] = Dihedral(id, findfirst(x->x==para_type_id, type_list)-1, dihedral_topo[id, :]) end para_dihedral = [dihedral.para for dihedral in potential.para_dihedral[type_list[2:end]]] para_dihedral = Array(hcat(para_dihedral...)') return num_dihedrals, num_dihedral_types, vec_dihedral, para_dihedral end function assign_para_improper(type_vec, improper_topo, potential) num_impropers = size(improper_topo, 1) num_improper_types = 0 vec_improper = Vector{Improper}(undef, num_impropers) type_list = [0] for id = 1:num_impropers para_type_id = findfirst(x->judgeequal(x, [type_vec[i] for i in improper_topo[id, :]]), potential.para_improper) if para_type_id == nothing print([type_vec[i] for i in improper_topo[id, :]]) error("No matching improper type shwon above is found in Charmm36 force filed.") end if !in(para_type_id, type_list) num_improper_types += 1 append!(type_list, para_type_id) end vec_improper[id] = Improper(id, findfirst(x->x==para_type_id, type_list)-1, improper_topo[id, :]) end para_improper = [improper.para for improper in potential.para_improper[type_list[2:end]]] para_improper = Array(hcat(para_improper...)') return num_impropers, num_improper_types, vec_improper, para_improper end """ function convert_vmd(file_pdb::String, file_psf::String, potential::Potential) This will convert a set of files which created by VMD (.pdb and .psf) file into a `Data` variable that can be used to write a .data file. - `file_pdb`: String of path of .pdb file. - `file_psf`: String of path of .psf file. - `poetntial`: Subclass of `Potential` which contains all information of forcefiled to automatically generate parameters, e.g. pair_coeff, bond_coeff etc. """ function converter_vmd(file_pdb::String, file_psf::String, potential::Potential, box_padding=2) # Reading Input id_vec, atom_vec, mol_vec, coord_mat = read_pdb(file_pdb) type_vec, charge_vec, bond_topo, angle_topo, dihedral_topo, improper_topo = read_psf(file_psf) box_size = Array(cat(minimum(coord_mat, dims=1), maximum(coord_mat, dims=1), dims=1)') #box_size[:, 1] .-= box_padding / 2 #box_size[:, 2] .+= box_padding / 2 box_tilt = [0, 0, 0] # Assign parameters num_atoms, num_atom_types, vec_atom, para_pair, para_mass, type_list = assign_para_atom(id_vec, mol_vec, type_vec, charge_vec, coord_mat, potential_charmm36) num_bonds, num_bond_types, vec_bond, para_bond = assign_para_bond(type_vec, bond_topo, potential) num_angles, num_angle_types, vec_angle, para_angle = assign_para_angle(type_vec, angle_topo, potential) num_dihedrals, num_dihedral_types, vec_dihedral, para_dihedral = assign_para_dihedral(type_vec, dihedral_topo, potential) num_impropers, num_improper_types, vec_improper, para_improper = assign_para_improper(type_vec, improper_topo, potential) # Judgement if num_bonds == 0 vec_bond = 0 end if num_angles == 0 vec_angle = 0 end if num_dihedrals == 0 vec_dihedral = 0 end if num_impropers == 0 vec_improper = 0 end # Creat Data instance data_basic = Data_Basic(num_atoms, num_bonds, num_angles, num_dihedrals, num_impropers, num_atom_types, num_bond_types, num_angle_types, num_dihedral_types, num_improper_types, box_size, box_tilt) data_str = Structure_VMD(type_list, num_atom_types, num_bond_types, num_angle_types, num_dihedral_types, num_improper_types, para_mass, para_pair, para_bond, para_angle, para_dihedral, para_improper) data = Data_Unit(data_basic, data_str, vec_atom, vec_bond, vec_angle, vec_dihedral, vec_improper) return data end
# Autogenerated wrapper script for github_release_jll for i686-linux-musl export github_release JLLWrappers.@generate_wrapper_header("github_release") JLLWrappers.@declare_executable_product(github_release) function __init__() JLLWrappers.@generate_init_header() JLLWrappers.@init_executable_product( github_release, "bin/github-release", ) JLLWrappers.@generate_init_footer() end # __init__()
using Documenter, AverageShiftedHistograms makedocs( format = Documenter.HTML(), sitename = "AverageShiftedHistograms.jl", authors = "Josh Day", clean = true, pages = [ "index.md", "api.md" ] ) deploydocs( repo = "github.com/joshday/AverageShiftedHistograms.jl.git", )
using COSMO using SketchyCGAL using LinearAlgebra, SparseArrays using BSON include("../utils.jl") blas_threads = BLAS.get_num_threads() # Run experiments single threaded blas_threads = BLAS.set_num_threads(1) ## Data Load G = graph_from_file(joinpath(dirname(@__DIR__), "data/gset/G72")) # n = size(G, 1) # C = -0.25*(Diagonal(G*ones(n)) - G) ## COSMO (try to get true opt) cosmo_tt = @timed solve_with_COSMO(C; settings = COSMO.Settings( verbose = true, eps_abs = 1e-5, eps_rel = 1e-5, decompose = true, merge_strategy = COSMO.CliqueGraphMerge, max_iter = 5_000, # rho = 1e-5, # alpha = 1.6, kkt_solver = COSMO.QdldlKKTSolver, # kkt_solver = with_options(COSMO.MKLPardisoKKTSolver, msg_level_on = true), verbose_timing = true, )) cosmo_results = tt.value cosmo_time = tt.time cosmo_alloc = tt.bytes/1e6 #(MB) ## SCGAL (run for awhile to get "true" opt) ## ---------- Problem setup ---------- function setup_maxcut_scgal(G::SparseMatrixCSC) # Parameters n = size(G, 1) d = n # Data # objective = min -1/4( ∑_ij w_ij*(1-yi*yj) ) = -1/4⟨diag(∑ᵢ w_ij) - W), Y⟩ # note that this reformulation uses the fact that Tr(Y) = 1 C = -0.25*(Diagonal(G*ones(n)) - G) b = ones(n) # Scaling variables -- so trace is bounded by 1 scale_C = 1 / norm(C) scale_X = 1 / n # b .= b .* scale_X # const C_const = C * scale_C # Linear map # AX = diag(X) function A!(y, X) n = size(X, 1) for i in 1:n y[i] = X[i,i] end return nothing end # Adjoint # A*z = Diagonal(z) function A_adj!(S::SparseMatrixCSC, z) for (i, j, v) ∈ zip(findnz(S)...) S[i,j] = 0.0 end S[diagind(S)] .= z return nothing end # primative 1: u -> C*u function C_u!(v, u) mul!(v, C_const, u) end #primative 2: (u, z) -> (A*z)u function Aadj_zu!(v, u, z) v .= u .* z end #primative 3: u -> A(uu^T) function A_uu!(z, u) z .= u.*u end return C, b, A!, A_adj!, n, d, scale_X, scale_C end ## Long Run function maxcut_scgal_long(G) C, b, A!, A_adj!, n, d, scale_X, scale_C = setup_maxcut_scgal(G) R = 10 ηt(t) = 2.0/(t + 1.0) δt(t) = 1.0 tt = @timed scgal_full( C, b, A!, A_adj!; n=n, d=d, scale_X=scale_X, scale_C=scale_C, max_iters=100_000, print_iter=1_000, R=R, # logging=true, # logging_primal=true, ηt=ηt, δt=δt ) # soln = tt.value # trial_time = tt.time # trial_alloc = tt.bytes/1e6 #(MB) return tt end BLAS.set_num_threads(1) long_run = maxcut_scgal_long(G) BSON.bson(joinpath(@__DIR__, "output/long_run.bson"), Dict("data" => long_run)) # 100000 -7.743749e+03 5.253496e-01 7.271706e-05 1067.732 ## SCGAL Trials for R, Fig 7.1 Recreation Rs = [10; 25; 50; 100] function run_trials_R(G, Rs) trial_data = Dict("time" => Dict(), "iter" => Dict()) C, b, A!, A_adj!, n, d, scale_X, scale_C = setup_maxcut_scgal(G) ηt(t) = 2.0/(t + 1.0) δt(t) = 1.0 for R in Rs tt = @timed scgal_full( C, b, A!, A_adj!; n=n, d=d, scale_X=scale_X, scale_C=scale_C, max_iters=10_000, print_iter=1_000, R=R, logging=true, # logging_primal=true, ηt=ηt, δt=δt ) trial_data["time"][R] = tt tt2 = @timed scgal_full( C, b, A!, A_adj!; n=n, d=d, scale_X=scale_X, scale_C=scale_C, max_iters=10_000, print_iter=1_000, R=R, logging=true, logging_primal=true, ηt=ηt, δt=δt ) trial_data["iter"][R] = tt2 end return trial_data end trial_data = run_trials_R(G, Rs) BSON.bson(joinpath(@__DIR__, "output/trials_R_G72.bson"), trial_data) ## SCGAL trials for weight (fix R = 10) function run_trials_weights(G; R=10, max_iters=10_000, print_iter=1000, rseed=0, δs=[]) trial_data = Dict() C, b, A!, A_adj!, n, d, scale_X, scale_C = setup_maxcut_scgal(G) tt = @timed scgal_full( C, b, A!, A_adj!; n=n, d=d, scale_X=scale_X, scale_C=scale_C, max_iters=max_iters, print_iter=print_iter, R=R, logging=true, # logging_primal=true, ηt=t->2.0/(t + 1.0), δt=t->1.0, rseed=rseed ) trial_data["std"] = tt tt_sa = @timed scgal_full( C, b, A!, A_adj!; n=n, d=d, scale_X=scale_X, scale_C=scale_C, max_iters=max_iters, print_iter=print_iter, R=R, logging=true, # logging_primal=true, ηt=t->2.0/(t + 2.0), δt=t->1.0t/(1.0t + 1), rseed=rseed ) trial_data["sa"] = tt_sa for δ in δs tt_ea = @timed scgal_full( C, b, A!, A_adj!; n=n, d=d, scale_X=scale_X, scale_C=scale_C, max_iters=max_iters, print_iter=print_iter, R=R, logging=true, # logging_primal=true, ηt=t->2.0/(t + 3.0), δt=t->δ, rseed=rseed ) trial_data["ea_$δ"] = tt_ea end return trial_data end δs = [0.01, 0.05, 0.1, 0.3, 0.5, 0.8, 0.9, 0.95, 0.99] trial_data_weights = run_trials_weights(G; max_iters=10_000, print_iter=1_000, rseed=0, δs=δs) BSON.bson(joinpath(@__DIR__, "output/trials_weights_G72.bson"), trial_data_weights) # ## # function condition_check(δ, c0) # return (1 - (1-δ)*(2+1)^2/2^2)*δ*c0^2 # end # # condition_check.(δs, 4)
#!/usr/bin/env julia --project=. using JuliaEchoServer port = get(ENV, "PORT", "8000") server = JuliaEchoServer.EchoServer(parse(Int, port)) JuliaEchoServer.listen(server)
""" MH(n_iters::Int) Metropolis-Hasting sampler. Usage: ```julia MH(100, (:m, (x) -> Normal(x, 0.1))) ``` Example: ```julia # Define a simple Normal model with unknown mean and variance. @model gdemo(x) = begin s ~ InverseGamma(2,3) m ~ Normal(0,sqrt(s)) x[1] ~ Normal(m, sqrt(s)) x[2] ~ Normal(m, sqrt(s)) return s, m end sample(gdemo([1.5, 2]), MH(1000, (:m, (x) -> Normal(x, 0.1)), :s))) ``` """ mutable struct MH{T} <: InferenceAlgorithm n_iters :: Int # number of iterations proposals :: Dict{Symbol,Any} # Proposals for paramters space :: Set{T} # sampling space, emtpy means all gid :: Int # group ID end function MH(n_iters::Int, space...) new_space = Set() proposals = Dict{Symbol,Any}() # parse random variables with their hypothetical proposal for element in space if isa(element, Symbol) push!(new_space, element) else @assert isa(element[1], Symbol) "[MH] ($element[1]) should be a Symbol. For proposal, use the syntax MH(N, (:m, (x) -> Normal(x, 0.1)))" push!(new_space, element[1]) proposals[element[1]] = element[2] end end set = Set(new_space) MH{eltype(set)}(n_iters, proposals, set, 0) end MH{T}(alg::MH, new_gid::Int) where T = MH{T}(alg.n_iters, alg.proposals, alg.space, new_gid) Sampler(alg::MH) = begin alg_str = "MH" # Sanity check for space if alg.gid == 0 && !isempty(alg.space) @assert issubset(Turing._compiler_[:pvars], alg.space) "[$alg_str] symbols specified to samplers ($alg.space) doesn't cover the model parameters ($(Turing._compiler_[:pvars]))" if Turing._compiler_[:pvars] != alg.space warn("[$alg_str] extra parameters specified by samplers don't exist in model: $(setdiff(alg.space, Turing._compiler_[:pvars]))") end end info = Dict{Symbol, Any}() info[:accept_his] = [] info[:total_eval_num] = 0 info[:proposal_ratio] = 0.0 info[:prior_prob] = 0.0 info[:violating_support] = false Sampler(alg, info) end propose(model::Function, spl::Sampler{<:MH}, vi::VarInfo) = begin spl.info[:proposal_ratio] = 0.0 spl.info[:prior_prob] = 0.0 spl.info[:violating_support] = false runmodel!(model, vi ,spl) end step(model::Function, spl::Sampler{<:MH}, vi::VarInfo, is_first::Bool) = begin if is_first push!(spl.info[:accept_his], true) vi else if spl.alg.gid != 0 # Recompute joint in logp runmodel!(model, vi, nothing) end old_θ = copy(vi[spl]) old_logp = getlogp(vi) @debug "Propose new parameters from proposals..." propose(model, spl, vi) @debug "computing accept rate α..." is_accept, logα = mh_accept(-old_logp, -getlogp(vi), spl.info[:proposal_ratio]) @debug "decide wether to accept..." if is_accept && !spl.info[:violating_support] # accepted push!(spl.info[:accept_his], true) else # rejected push!(spl.info[:accept_his], false) vi[spl] = old_θ # reset Θ setlogp!(vi, old_logp) # reset logp end vi end end function sample(model::Function, alg::MH; save_state=false, # flag for state saving resume_from=nothing, # chain to continue reuse_spl_n=0, # flag for spl re-using ) spl = reuse_spl_n > 0 ? resume_from.info[:spl] : Sampler(alg) alg_str = "MH" # Initialization time_total = 0.0 n = reuse_spl_n > 0 ? reuse_spl_n : alg.n_iters samples = Array{Sample}(undef, n) weight = 1 / n for i = 1:n samples[i] = Sample(weight, Dict{Symbol, Any}()) end vi = if resume_from == nothing vi_ = VarInfo() Base.invokelatest(model, vi_, HamiltonianRobustInit()) vi_ else resume_from.info[:vi] end if spl.alg.gid == 0 runmodel!(model, vi, spl) end # MH steps PROGRESS[] && (spl.info[:progress] = ProgressMeter.Progress(n, 1, "[$alg_str] Sampling...", 0)) for i = 1:n @debug "$alg_str stepping..." time_elapsed = @elapsed vi = step(model, spl, vi, i == 1) time_total += time_elapsed if spl.info[:accept_his][end] # accepted => store the new predcits samples[i].value = Sample(vi, spl).value else # rejected => store the previous predcits samples[i] = samples[i - 1] end samples[i].value[:elapsed] = time_elapsed PROGRESS[] && (ProgressMeter.next!(spl.info[:progress])) end println("[$alg_str] Finished with") println(" Running time = $time_total;") accept_rate = sum(spl.info[:accept_his]) / n # calculate the accept rate println(" Accept rate = $accept_rate;") if resume_from != nothing # concat samples pushfirst!(samples, resume_from.value2...) end c = Chain(0, samples) # wrap the result by Chain if save_state # save state save!(c, spl, model, vi) end c end assume(spl::Sampler{<:MH}, dist::Distribution, vn::VarName, vi::VarInfo) = begin if isempty(spl.alg.space) || vn.sym in spl.alg.space if ~haskey(vi, vn) error("[MH] does not handle stochastic existence yet") end old_val = vi[vn] if vn.sym in keys(spl.alg.proposals) # Custom proposal for this parameter proposal = spl.alg.proposals[vn.sym](old_val) if typeof(proposal) == Distributions.Normal{Float64} # If Gaussian proposal σ = std(proposal) lb = support(dist).lb ub = support(dist).ub stdG = Normal() r = rand(TruncatedNormal(proposal.μ, proposal.σ, lb, ub)) # cf http://fsaad.scripts.mit.edu/randomseed/metropolis-hastings-sampling-with-gaussian-drift-proposal-on-bounded-support/ spl.info[:proposal_ratio] += log(cdf(stdG, (ub-old_val)/σ) - cdf(stdG,(lb-old_val)/σ)) spl.info[:proposal_ratio] -= log(cdf(stdG, (ub-r)/σ) - cdf(stdG,(lb-r)/σ)) else # Other than Gaussian proposal r = rand(proposal) if (r < support(dist).lb) | (r > support(dist).ub) # check if value lies in support spl.info[:violating_support] = true r = old_val end spl.info[:proposal_ratio] -= logpdf(proposal, r) # accumulate pdf of proposal reverse_proposal = spl.alg.proposals[vn.sym](r) spl.info[:proposal_ratio] += logpdf(reverse_proposal, old_val) end else # Prior as proposal r = rand(dist) spl.info[:proposal_ratio] += (logpdf(dist, old_val) - logpdf(dist, r)) end spl.info[:prior_prob] += logpdf(dist, r) # accumulate prior for PMMH vi[vn] = vectorize(dist, r) setgid!(vi, spl.alg.gid, vn) else r = vi[vn] end # acclogp!(vi, logpdf(dist, r)) # accumulate pdf of prior r, logpdf(dist, r) end assume(spl::Sampler{<:MH}, dists::Vector{D}, vn::VarName, var::Any, vi::VarInfo) where D<:Distribution = error("[Turing] MH doesn't support vectorizing assume statement") observe(spl::Sampler{<:MH}, d::Distribution, value::Any, vi::VarInfo) = observe(nothing, d, value, vi) # accumulate pdf of likelihood observe(spl::Sampler{<:MH}, ds::Vector{D}, value::Any, vi::VarInfo) where D<:Distribution = observe(nothing, ds, value, vi) # accumulate pdf of likelihood
using AirSeaFluxes using Test @testset "AirSeaFluxes.jl" begin mld=10 #mixed layer depth (m) tim=86400*30 #relaxation time scale (s) pisvel=mld/tim #piston velocity (m/s) Co=0.0 #ocean value (e.g. concentration of some compound) Ca=1.0 #atmospeheric value (e.g. equivalent compound concentration) flx=simpleflux(Ca,Co,pisvel) @test isapprox(flx,3.858024691358025e-6; atol=1e-2) atemp=300.;aqh=0.001;speed=1.; sst=10. all=bulkformulae(atemp,aqh,speed,sst) @test isapprox(all["hl"],-3.0606099804357885; rtol=1e-2) @test isapprox(all["hs"],2.0282408526727473; rtol=1e-2) @test isapprox(all["evap"],1.2244888899523058e-9; rtol=1e-2) @test isapprox(all["tau"],0.00915548218468587; rtol=1e-2) end
# The code to simulate 200 artificial participants given the SurNoR parameters # fitted to behavior using SurNoR_2020 using MAT using PyPlot using CSV using JLD i = 3 # -------------------------------------------------------------------------- # Algorithm update_form = "VarSMiLe" if update_form == "SMiLe" surprise_form="CC" else surprise_form="BF" end novelty_form="log-count" update_form_model_free = "Q_learning" gamma_form="satur" # -------------------------------------------------------------------------- # Defining Hyper Parameters HyperParam = SurNoR_2020.Str_HyperParam(; gamma_form=gamma_form, surprise_form=surprise_form, novelty_form=novelty_form, update_form=update_form, update_form_model_free=update_form_model_free) # -------------------------------------------------------------------------- # Fitting the models Block_Set = 1:2 Epi_Set = 1:5 # -------------------------------------------------------------------------- # Defining Parameters Path_Params = "data/Fitted_parameters/Overall/OverAll_SurNoR_BestParams_diff5.csv" Param_Data = CSV.read(Path_Params) η0 = Array(Param_Data[i,2:end]) σ0 = [0.01,1e-5,2,0.1,0.1,0.01,0.1,0.01,0.1,0.1,0.1,1,5,0.1,0.1,0.1,1,2] noise_free = true # ------------------------------------------------------------------------------ # Loading the environment Path = string("data/HardEnvironment11s.mat") EnvGraph_MAT = matread(Path) EnvGraph1 = SurNoR_2020.Str_EnvGraph(; TranMat = EnvGraph_MAT["Hard_NoSwitch"]["tm"].-1, InitObs = EnvGraph_MAT["Hard_NoSwitch"]["initS"].-1, Goal=0) EnvGraph2 = SurNoR_2020.Str_EnvGraph(; TranMat = EnvGraph_MAT["Hard_Switch411"]["tm"].-1, InitObs = EnvGraph_MAT["Hard_Switch411"]["initS"].-1, Goal=0) InitObs = [9,6,8,4,2] for i = 1:5 EnvGraph1.InitObs[i] = InitObs[i] EnvGraph2.InitObs[i] = InitObs[i] end EnvGraph_Array = [EnvGraph1, EnvGraph2] # ------------------------------------------------------------------------------ # Simulate N = 200 Seed_start = 2021 N_lost = [0] SimAgent = [] for n = 1:N println("----------------------------------------") @show n @show Seed_start + n Param = SurNoR_2020.Func_param_generator(η0; σ = σ0./10, noise_free=noise_free, Seed= Seed_start + n) Temp_Age = SurNoR_2020.Func_simulate_Agent_Blocks(EnvGraph_Array; Epi_Set=1:5, Block_Set=1:2, Param=Param, HyperParam=HyperParam, Greedy = false, Seed= Seed_start + n, T_stop = 500) if size(Temp_Age) == (2,5) @show length(Temp_Age[1,1].Input.act') @show length(Temp_Age[2,1].Input.act') push!(SimAgent,Temp_Age) else N_lost[1] = N_lost[1]+1 end end N = N - N_lost[1] Inputs = Array{SurNoR_2020.Str_Input,3}(undef,N,2,5) for n = 1:N for Block = 1:2 for Epi = 1:5 Inputs[n,Block,Epi] = SimAgent[n][Block,Epi].Input end end end save("data/Simulated_data/Simulated_data.jld", "Inputs", Inputs, "N_lost", N_lost)
export Material # --------- # # Materials # # --------- # """ Material This Type stores information about the material of an [`Object`](@ref). We compute the color of a point by dispatching on the type of the material. That is why we store `nothing` when a particular field is absent. !!! note `texture_*` and `uv_coordinates` fields are applicable only if the object used is a [`Triangle`](@ref). If any of the texture fields are present, `uv_coordinates` must be present. ### Fields: * `color_ambient` - The Ambient Color of the Material. * `color_diffuse` - The Diffuse Color of the Material. * `color_specular` - The Specular Color of the Material. * `specular_exponent` - Specular Exponent of the Material. * `reflection` - The reflection coefficient of the material. * `texture_ambient` - Stores the ambient texture image (if present) in Vec3 format. * `texture_diffuse` - Stores the diffuse texture image (if present) in Vec3 format. * `texture_specular` - Stores the specular texture image (if present) in VEc3 format. * `uv_coordinates` - The uv coordinates are stored as a vector (of length 3) of tuples. ### Available Constructors ``` Material(;color_ambient = Vec3(1.0f0), color_diffuse = Vec3(1.0f0), color_specular = Vec3(1.0f0), specular_exponent::Real = 50.0f0, reflection::Real = 0.5f0, texture_ambient = nothing, texture_diffuse = nothing, texture_specular = nothing, uv_coordinates = nothing) ``` """ struct Material{T<:AbstractArray, R<:AbstractVector, U<:Union{Vec3, Nothing}, V<:Union{Vec3, Nothing}, W<:Union{Vec3, Nothing}, S<:Union{Vector, Nothing}} # Color Information color_ambient::Vec3{T} color_diffuse::Vec3{T} color_specular::Vec3{T} # Surface Properties specular_exponent::R reflection::R # Texture Information texture_ambient::U texture_diffuse::V texture_specular::W # UV coordinates (relevant only for triangles) uv_coordinates::S end Material(;color_ambient = Vec3(1.0f0), color_diffuse = Vec3(1.0f0), color_specular = Vec3(1.0f0), specular_exponent::Real = 50.0f0, reflection::Real = 0.5f0, texture_ambient = nothing, texture_diffuse = nothing, texture_specular = nothing, uv_coordinates = nothing) = Material(color_ambient, color_diffuse, color_specular, [specular_exponent], [reflection], texture_ambient, texture_diffuse, texture_specular, uv_coordinates) @diffops Material function Base.zero(m::Material) texture_ambient = isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient) texture_diffuse = isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse) texture_specular = isnothing(m.texture_specular) ? nothing : zero(m.texture_specular) uv_coordinates = isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates) return Material(zero(m.color_ambient), zero(m.color_diffuse), zero(m.color_specular), zero(m.specular_exponent), zero(m.reflection), texture_ambient, texture_diffuse, texture_specular, uv_coordinates) end """ get_color(m::Material, pt::Vec3, ::Val{T}, obj::Object) Returns the color at the point `pt`. We use `T` and the type of the Material `m` for efficiently dispatching to the right function. The right function is determined by the presence/absence of the texture field. The possible values of `T` are `:ambient`, `:diffuse`, and `:specular`. """ get_color(m::Material{T, R, Nothing, V, W, S}, pt::Vec3, ::Val{:ambient}, obj) where {T<:AbstractArray, R<:AbstractVector, V<:Union{Vec3, Nothing}, W<:Union{Vec3, Nothing}, S<:Union{Vector, Nothing}} = m.color_ambient get_color(m::Material{T, R, U, Nothing, W, S}, pt::Vec3, ::Val{:diffuse}, obj) where {T<:AbstractArray, R<:AbstractVector, U<:Union{Vec3, Nothing}, W<:Union{Vec3, Nothing}, S<:Union{Vector, Nothing}} = m.color_diffuse get_color(m::Material{T, R, U, V, Nothing, S}, pt::Vec3, ::Val{:specular}, obj) where {T<:AbstractArray, R<:AbstractVector, U<:Union{Vec3, Nothing}, V<:Union{Vec3, Nothing}, S<:Union{Vector, Nothing}} = m.color_specular # This function is only available for triangles. Maybe I should put a # type constraint # The three functions are present only for type inference. Ideally Julia # should figure it out not sure why it is not the case. function get_color(m::Material, pt::Vec3, ::Val{:ambient}, obj) v1v2 = obj.v2 - obj.v1 v1v3 = obj.v3 - obj.v1 normal = cross(v1v2, v1v3) denom = l2norm(normal) edge2 = obj.v3 - obj.v2 vp2 = pt - obj.v2 u_bary = dot(normal, cross(edge2, vp2)) ./ denom edge3 = obj.v1 - obj.v3 vp3 = pt - obj.v3 v_bary = dot(normal, cross(edge3, vp3)) ./ denom w_bary = 1 .- u_bary .- v_bary u = u_bary .* m.uv_coordinates[1][1] .+ v_bary .* m.uv_coordinates[2][1] .+ w_bary .* m.uv_coordinates[3][1] v = u_bary .* m.uv_coordinates[1][2] .+ v_bary .* m.uv_coordinates[2][2] .+ w_bary .* m.uv_coordinates[3][2] # which_texture, which_color = infer_index(f) image = Zygote.literal_getproperty(m, Val(:texture_ambient)) width, height = size(image) x_val = mod1.((Int.(ceil.(u .* width)) .- 1), width) y_val = mod1.((Int.(ceil.(v .* height)) .- 1), height) # Zygote doesn't like me using a splat operation here :'( img = image[x_val .+ (y_val .- 1) .* stride(image.x, 2)] return Zygote.literal_getproperty(m, Val(:color_ambient)) * Vec3(img.x, img.y, img.z) end function get_color(m::Material, pt::Vec3, ::Val{:diffuse}, obj) v1v2 = obj.v2 - obj.v1 v1v3 = obj.v3 - obj.v1 normal = cross(v1v2, v1v3) denom = l2norm(normal) edge2 = obj.v3 - obj.v2 vp2 = pt - obj.v2 u_bary = dot(normal, cross(edge2, vp2)) ./ denom edge3 = obj.v1 - obj.v3 vp3 = pt - obj.v3 v_bary = dot(normal, cross(edge3, vp3)) ./ denom w_bary = 1 .- u_bary .- v_bary u = u_bary .* m.uv_coordinates[1][1] .+ v_bary .* m.uv_coordinates[2][1] .+ w_bary .* m.uv_coordinates[3][1] v = u_bary .* m.uv_coordinates[1][2] .+ v_bary .* m.uv_coordinates[2][2] .+ w_bary .* m.uv_coordinates[3][2] # which_texture, which_color = infer_index(f) image = Zygote.literal_getproperty(m, Val(:texture_diffuse)) width, height = size(image) x_val = mod1.((Int.(ceil.(u .* width)) .- 1), width) y_val = mod1.((Int.(ceil.(v .* height)) .- 1), height) # Zygote doesn't like me using a splat operation here :'( img = image[x_val .+ (y_val .- 1) .* stride(image.x, 2)] return Zygote.literal_getproperty(m, Val(:color_diffuse)) * Vec3(img.x, img.y, img.z) end function get_color(m::Material, pt::Vec3, ::Val{:specular}, obj) v1v2 = obj.v2 - obj.v1 v1v3 = obj.v3 - obj.v1 normal = cross(v1v2, v1v3) denom = l2norm(normal) edge2 = obj.v3 - obj.v2 vp2 = pt - obj.v2 u_bary = dot(normal, cross(edge2, vp2)) ./ denom edge3 = obj.v1 - obj.v3 vp3 = pt - obj.v3 v_bary = dot(normal, cross(edge3, vp3)) ./ denom w_bary = 1 .- u_bary .- v_bary u = u_bary .* m.uv_coordinates[1][1] .+ v_bary .* m.uv_coordinates[2][1] .+ w_bary .* m.uv_coordinates[3][1] v = u_bary .* m.uv_coordinates[1][2] .+ v_bary .* m.uv_coordinates[2][2] .+ w_bary .* m.uv_coordinates[3][2] # which_texture, which_color = infer_index(f) image = Zygote.literal_getproperty(m, Val(:texture_specular)) width, height = size(image) x_val = mod1.((Int.(ceil.(u .* width)) .- 1), width) y_val = mod1.((Int.(ceil.(v .* height)) .- 1), height) # Zygote doesn't like me using a splat operation here :'( img = image[x_val .+ (y_val .- 1) .* stride(image.x, 2)] return Zygote.literal_getproperty(m, Val(:color_specular)) * Vec3(img.x, img.y, img.z) end """ specular_exponent(m::Material) Returns the `specular_exponent` of the Material `m`. """ specular_exponent(m::Material) = m.specular_exponent[] """ reflection(m::Material) Returns the `reflection coefficient` of the Material `m`. """ reflection(m::Material) = m.reflection[]
#jl #! format: off # # Bar and stack plots with [PowerGraphics.jl](github.com/nrel-siip/PowerGraphics.jl) # PowerGraphics also provides some basic specifications for plotting `SimulationResults`. # This example demonstrates some simple plotting capabilities using different Plots.julia # backends. # # The plotting capabilities use the Julia Plots package which can generate plots using # several different graphics packages. We'll use GR.jl and PlotlyJS.jl. # # ## Dependencies using SIIPExamples #for path locations pkgpath = pkgdir(SIIPExamples) using PowerSystems #to load results using PowerSimulations #to load results using PowerGraphics using PowerSystemCaseBuilder # ### Results file # If you have already run some of the other examples, you should have generated some results # (If you haven't run some of the other simulations, you can run include( joinpath(pkgpath, "test", "3_PowerSimulations_examples", "03_5_bus_mkt_simulation.jl"), ) # Alternatively, you can load the results into memory with: # ```julia # simulation_folder = joinpath(pkgdir(SIIPExamples), "rts-test") # simulation_folder = # joinpath(simulation_folder, "$(maximum(parse.(Int64,readdir(simulation_folder))))") # # results = SimulationResults(simulation_folder); # uc_results = get_decision_problem_results(results, "UC") # ``` # Since some of the plotting capabilities rely on input data as well as output data (e.g. fuel plots) # but the result deserialization doesn't load the `System`, we can add the `System` to the `results` # so that the plotting routines can find the requisite data. set_system!(uc_results, sys_DA) # ## Plots # By default, PowerGraphics uses the GR graphics package as the backend for Plots.jl to # generate figures. This creates static plots and should execute without any extra steps. # For example, we can create a plot of a particular variable in the `uc_results` object: gr() # loads the GR backend timestamps = get_realized_timestamps(uc_results) variable = read_realized_variable(uc_results, "ActivePowerVariable__ThermalStandard") plot_dataframe(variable, timestamps) # However, interactive plotting can generate much more insightful figures, especially when # creating somewhat complex stacked figures. So, we can use the PlotlyJS backend for Plots, # but it requires that PlotlyJS.jl is installed in your Project.toml (if in a notebook, # WebIO.jl is required too). To startup the PlotlyJS backend, run: plotlyjs() # PowerGraphics creates an un-stacked line plot by default, but supports kwargs to # create a variety of different figure styles. For example, a stacked area figure can be # created with the `stack = true` kwarg: plot_dataframe(variable, timestamps; stack = true) # Or a bar chart can be created with `bar = true`: plot_dataframe(variable, timestamps; bar = true) # Or a stacked bar chart... plot_dataframe(variable, timestamps; bar = true, stack = true) # PowerGraphics also supports some basic aggregation to create cleaner plots. For example, # we can create a plot of the different variables: generation = get_generation_data(uc_results) plot_pgdata(generation, stack = true) reserves = get_service_data(uc_results) plot_pgdata(reserves) # Another standard aggregation is available to plot demand values: plot_demand(uc_results) # The `plot_demand` function can also be called with the `System` rather than the `StageResults` # to inspect the input data. This method can also display demands aggregated by a specified # `<:Topology`: plot_demand(uc_results.system, aggregation = Area) # Another standard aggregation exists based on the fuel categories of the generators in the # `System` plot_fuel(uc_results)
#= test_parser3: - Julia version: 1.1.0 - Author: bramb - Date: 2019-03-05 =# using Test using HyperCollate, LightGraphs include("util.jl") @testset "hypercollate" begin @testset "test 1" begin xml = "<text><s><subst><del>Dit kwam van een</del><add>De</add></subst> te streng doorgedreven rationalisatie</s></text>" @show(xml) tokens = tokenize(xml) @test map(string_value,tokens) == ["<text>", "<s>", "<subst>", "<del>", "Dit kwam van een", "</del>", "<add>", "De", "</add>", "</subst>", " te streng doorgedreven rationalisatie", "</s>", "</text>"] g = to_graph(xml) @show(g.graph) ts = topological_sort_by_dfs(g) @show(ts) dot = to_dot(g) expected=""" digraph VariantGraph { rankdir=LR labelloc=b color=white edge [arrowsize=0.5] v1[shape=circle;width=0.05;label=""] v2[shape=box;label="Dit kwam van een"] v3[shape=box;label="De"] v4[shape=circle;width=0.05;label=""] v5[shape=box;label=" te streng doorgedreven rationalisatie"] v1 -> v2 v1 -> v3 v2 -> v4 v3 -> v4 v4 -> v5 } """ _test_normalized_strings_are_equal(dot,expected) _print_dot(dot) end @testset "test 2" begin expected = """ digraph VariantGraph { rankdir=LR labelloc=b color=white edge [arrowsize=0.5] v1[shape=box;label="To be, or "] v2[shape=circle;width=0.05;label=""] v3[shape=box;label="whatever"] v4[shape=box;label="not to "] v5[shape=circle;width=0.05;label=""] v6[shape=box;label="butterfly"] v7[shape=box;label="be"] v8[shape=circle;width=0.05;label=""] v9[shape=circle;width=0.05;label=""] v1 -> v2 v2 -> v3 v2 -> v4 v3 -> v9 v4 -> v5 v5 -> v6 v5 -> v7 v6 -> v8 v7 -> v8 v8 -> v9 } """ dot = (to_dot(to_graph("<xml>To be, or <subst><del>whatever</del><add>not to <subst><del>butterfly</del><add>be</add></subst></add></subst></xml>"))) _test_normalized_strings_are_equal(dot,expected) _print_dot(dot) end @testset "test 3" begin expected = """ digraph VariantGraph { rankdir=LR labelloc=b color=white edge [arrowsize=0.5] v1[shape=box;label="pre "] v2[shape=circle;width=0.05;label=""] v3[shape=box;label="one "] v4[shape=box;label="golden goose"] v5[shape=box;label=" waddling"] v6[shape=box;label="two "] v7[shape=box;label="cooked hens"] v8[shape=box;label=" smelling"] v9[shape=box;label="three "] v10[shape=box;label="roasted ducks"] v11[shape=box;label=" cooling"] v12[shape=circle;width=0.05;label=""] v13[shape=box;label=" post"] v1 -> v2 v2 -> v3 v2 -> v6 v2 -> v9 v3 -> v4 v4 -> v5 v5 -> v12 v6 -> v7 v7 -> v8 v8 -> v12 v9 -> v10 v10 -> v11 v11 -> v12 v12 -> v13 } """ dot = (to_dot(to_graph("<x>pre <app><rdg>one <b>golden goose</b> waddling</rdg><rdg>two <b>cooked hens</b> smelling</rdg><rdg>three <b>roasted ducks</b> cooling</rdg></app> post</x>"))) _test_normalized_strings_are_equal(dot,expected) _print_dot(dot) end @testset "tokenize" begin xml = """ <xml> <p> newlines are fun! </p> </xml> """ tokens = tokenize(xml) @show(tokens) @test length(tokens) == 7 end @testset "solitary add" begin xml = "<x>bla1 <add>bla2</add> bla3</x>" expected = """ digraph VariantGraph { rankdir=LR labelloc=b color=white edge [arrowsize=0.5] v1[shape=box;label="bla1 "] v2[shape=circle;width=0.05;label=""] v3[shape=box;label="bla2"] v4[shape=circle;width=0.05;label=""] v5[shape=box;label=" bla3"] v1 -> v2 v2 -> v3 v2 -> v4 v3 -> v4 v4 -> v5 } """ dot = (to_dot(to_graph(xml))) _test_normalized_strings_are_equal(dot,expected) _print_dot(dot) end @testset "solitary del" begin xml = "<x>bla1 <del>bla2</del> bla3</x>" expected = """ digraph VariantGraph { rankdir=LR labelloc=b color=white edge [arrowsize=0.5] v1[shape=box;label="bla1 "] v2[shape=circle;width=0.05;label=""] v3[shape=box;label="bla2"] v4[shape=circle;width=0.05;label=""] v5[shape=box;label=" bla3"] v1 -> v2 v2 -> v3 v2 -> v4 v3 -> v4 v4 -> v5 } """ dot = (to_dot(to_graph(xml))) _test_normalized_strings_are_equal(dot,expected) _print_dot(dot) end # println(to_dot(to_graph("<x>De <a>kat</a> krabt <b>de krullen</b> van de trap</x>"))) # println(to_dot(to_graph("<x>Donald smacked <choice><option>Huey</option><option>Dewey</option><option>Louie</option></choice> on his beak.</x>"))) end
@testset "episode_turn_buffer" begin b = episode_RTSA_buffer(; state_eltype = Int) @test length(b) == 0 @test isfull(b) == false @test isempty(b) == true push!(b; reward = 0.0, terminal = true, state = 1, action = 1) @test length(b) == 0 @test isfull(b) == false @test isempty(b) == false push!(b; reward = 1.0, terminal = false, state = 2, action = 2) @test length(b) == 1 @test isfull(b) == false @test isempty(b) == false push!(b; reward = 2.0, terminal = true, state = 3, action = 3) @test length(b) == 2 @test isfull(b) == true @test isempty(b) == false @test b[end] == ( state = 2, action = 2, reward = 2.0, terminal = true, next_state = 3, next_action = 3, ) push!(b; reward = 0.0, terminal = false, state = 3, action = 3) push!(b; reward = 3.0, terminal = false, state = 4, action = 4) @test b[end] == ( state = 3, action = 3, reward = 3.0, terminal = false, next_state = 4, next_action = 4, ) @test length(b) == 2 end
# call this function to complete all the iteration update steps function updateParameters!(sys::System, ens::Ensemble) # calculate useful vectors using CE-update formula rxnActual, rxnExpect = computeRxnStats(sys, ens) # update hyper-parameters meanHyper, varHyper = hyperUpdate(sys, ens) # update kinetic rate parameters θstep = computeRateMeans!(sys, rxnActual, rxnExpect, meanHyper) # update variances computeRateVar!(sys, ens, rxnActual, rxnExpect, θstep, varHyper) append!(sys.state.θs, sys.state.θ) end function computeRxnStats(sys::System, ens::Ensemble) len = length(ens) pl = length(sys.model.ps) # ---- pre-allocate rxnActual = zeros(Float64, (pl, len)) rxnExpect = zeros(Float64, (pl, len)) a = zeros(Float64, sys.model.nr) for k in eachindex(ens) sys.model.F(ens[k]) for j in sys.model.ps @inbounds for j2 in sys.model.mapping[j] rxnActual[j, k] += ens[k].ra[j2] rxnExpect[j, k] += ens[k].fly[j2] rxnExpect[j, k] += (sys.times[end] - ens[k].t) .* ens[k].a[j2] end end rxnActual[:, k] ./= getCostVal(ens[k]) rxnExpect[:, k] ./= getCostVal(ens[k]) end return rxnActual, rxnExpect end function hyperUpdate(sys::System, ens::Ensemble) n = length(sys.model.bounds[1]) - length(sys.model.ps) meanHyper = Vector{Float64}(undef, n) varHyper = Vector{Float64}(undef, n) for j in eachindex(meanHyper) v = Float64[] for k in eachindex(ens) push!(v,log(ens[k].θ[j+length(sys.model.ps)])) end meanHyper[j] = mean(v) varHyper[j] = var(v) end return meanHyper, varHyper end function computeRateMeans!(sys::System, rxnActual::Matrix{Float64}, rxnExpect::Matrix{Float64}, arm) θstep = vec(sum(rxnActual, dims = 2) ./ sum(rxnExpect, dims = 2)) if sys.routine.sampling == :log θstep = log.(θstep) end append!(θstep, arm) if sys.state.i == 1 sys.state.θ = θstep return θstep else sys.state.θ .= sys.routine.smoothingParameter .* θstep .+ (1.0 - sys.routine.smoothingParameter) .* sys.state.θ return θstep end end function computeRateVar!(sys::System, ens::Ensemble, rxnActual::Matrix{Float64}, rxnExpect::Matrix{Float64}, θstep::Vector{Float64}, ars) if sys.routine.sampling == :log tmp = log.((rxnActual.+0.01) ./ rxnExpect) σ2step = vec(var(tmp, dims = 2)) else σ2step = vec(var(tmp, dims = 2)) end append!(σ2step, ars) if sys.state.i == 1 sys.state.σ2 = diagm(σ2step) else β = 0.8 - 0.8 * (1.0 - 1.0 / sys.state.i)^5 sys.state.σ2 .= β .* diagm(σ2step) .+ (1.0 - β) .* sys.state.σ2 end end
module BDPlusRest using HTTP using JSON include("BDPlusExceptions.jl") # Current URL to discovery the bigquery REST API documents (JSON) const DISCOVERY_DOCUMENT = "https://bigquery.googleapis.com/discovery/v1/apis/bigquery/v2/rest" try bigquery_docs = HTTP.request("GET", DISCOVERY_DOCUMENT) catch raise_discoverydoc_err() exit() end struct rest_resources end end const
include("./Legendre_polynomials.jl") function Spherical_harmonics_a!(x::Float64, lmax::Int64; Yₗ = nothing, Pₗ = nothing) #### Returns an array of size lmax_half. Each cell contains one (even axisymmetric) spherical harmonic at point cos(θ) = x #### #### The "a" in the name is here to outline that this function only gives the "a"xisymmetric harmonics (i.e. m = 0). #### # getting the constants we will need lmax_half = div(lmax, 2) # let's preallocate the arrays that haven't been given if isnothing(Yₗ) Yₗ = zeros(lmax_half) # WIll hold the spherical harmonics end if isnothing(Pₗ) Pₗ = zeros(lmax_half) # WIll hold the Legendre polynomials end # let's comptute the (even) Legendre polynomials at point x Legendre_polynomials!(x, lmax, Pₗ = Pₗ) # let's compute the spherical harmonics for l_half = 1:lmax_half l = 2 * l_half Yₗ[l_half] = Pₗ[l_half] * sqrt((2 * l + 1) / (4 * π)) # Yₗ₀ = Pₗ₀ * sqrt((2 l + 1) / 4 π) end return(Yₗ) end function Spherical_harmonics!(θ::Float64, ϕ::Float64, lmax::Int64; Yₗₘ = nothing, Pₗₘ = nothing) #### Returns an array of size lmax_half * (2 lmax + 1). Each cell contains one (even) spherical harmonic at point (θ, ϕ) #### #### This function has no "a" in its title because it returns ALL the spherical harmonics (i.e. m = 0 and m != 0) #### # getting the constants we will need lmax_half = div(lmax, 2) # let's preallocate the arrays that haven't been given if isnothing(Yₗₘ) Yₗₘ = zeros(2 * lmax + 1, lmax_half) # Will hold the spherical harmonics end if isnothing(Pₗₘ) Pₗₘ = zeros(lmax + 1, lmax_half) # Will hold the normalized associated Legendre polynomials end # Let's compute the normalzed associated Legendre polynomials Normalized_associated_Legendre_polynomials!(cos(θ), lmax, P = Pₗₘ) # Let's compute the spherical harmonics for l_half = 1:lmax_half l = 2 * l_half for m = 0:l # The passage from Pₗₘ to Yₗₘ is not the same if m is positive, null or negative. # Cf Wikipedia : https://en.wikipedia.org/wiki/Spherical_harmonics#Real_form if (m != 0) Yₗₘ[lmax + 1 - m, l_half] = (-1)^(m) * sqrt(2) * Pₗₘ[m + 1, l_half] * sin(m * ϕ) Yₗₘ[lmax + 1 + m, l_half] = (-1)^(m) * sqrt(2) * Pₗₘ[m + 1, l_half] * cos(m * ϕ) else Yₗₘ[lmax + 1, l_half] = Pₗₘ[1, l_half] end end end return(Yₗₘ) end
using ModelObjectsLH, Test mo = ModelObjectsLH; function single_id_test() @testset "SingleId" begin id1 = SingleId(:id1, [1, 2]) println(id1); @test mo.index(id1) == [1,2] @test has_index(id1) id11 = SingleId(:id1, [1, 2]); @test isequal(id1, id11) id2 = SingleId(:id2, 3) @test mo.index(id2) == [3] id3 = SingleId(:id3); @test isempty(mo.index(id3)) @test !has_index(id3) @test isequal(id3, SingleId(:id3)) @test isequal([id1, id2], [id1, id2]) @test !isequal([id1, id1], [id2, id1]) @test !isequal([id1, id2], [id1]) id4 = SingleId(:id4); s4 = make_string(id4); @test isequal(s4, "id4") id4a = make_single_id(s4); @test isequal(id4, id4a) id5 = SingleId(:id5, [4, 2]); s5 = make_string(id5); id5a = make_single_id(s5); @test isequal(id5, id5a) id6 = SingleId(:id6, 4) s6 = make_string(id6); id6a = make_single_id(s6); @test isequal(id6, id6a) end end function dict_single_id_test() @testset "Dict Single Id" begin d = Dict{SingleId, Any}([SingleId(:id1) => 1, SingleId(:id2, 1) => 2]); for (id1, val) in d @test id1 isa SingleId; @test val isa Integer; end end end function broadcast_test() @testset "Broadcasting" begin sV = [SingleId(:x), SingleId(:y)]; eqV = SingleId(:x) .== sV; @test eqV[1] @test !eqV[2] end end @testset "SingleId" begin single_id_test(); dict_single_id_test(); broadcast_test(); end # -------------
module SAOImageDS9Tests using Test using SAOImageDS9, XPA using XPA: TupleOf proc = Base.Process[] function ds9start(timeout::Real = 30.0) global proc elapsed = 0.0 seconds = 0.5 while true try return SAOImageDS9.connect() catch if length(proc) < 1 push!(proc, run(`/usr/bin/ds9`; wait=false)) end if elapsed > timeout error("cannot connect to SAOImage/DS9") end seconds = min(timeout - elapsed, 2*seconds) sleep(seconds) end end end function ds9kill() global proc if length(proc) ≥ 1 kill(pop!(proc)) end nothing end ds9start() @testset "Get requests" begin @test typeof(SAOImageDS9.get(VersionNumber)) === VersionNumber @test typeof(SAOImageDS9.get(Int, "width")) === Int @test typeof(SAOImageDS9.get(Int, "height")) === Int end ds9kill() end # module
using GLPlot; GLPlot.init() using Plots; glvisualize() using GLVisualize, FileIO, Colors, Images imfolder = filter(readdir(GLVisualize.assetpath())) do path endswith(path, "jpg") || endswith(path, "png") end images = map(imfolder) do impath convert(Matrix{RGBA{N0f8}}, restrict(loadasset(impath))) end; mean_colors = map(mean, images) x = map(comp1, mean_colors); y = map(comp2, mean_colors); z = map(comp3, mean_colors); p1 = scatter( x,y,z, markercolor=mean_colors, shape = :circle, markerstrokewidth = 1, markerstrokecolor = "white", hover = images, ms = 12 ) p2 = scatter(x,y,z, markerstrokecolor = mean_colors, shape = images, ms = 15) plot(p1, p2) gui()
using VrpAnt using Test @testset "VrpAnt.jl" begin m = Map(12) @testset "Creation of the Map" begin @test length(m.cities) == 12 @testset "Solution" begin @test m.solution.length == Inf @test m.solution.path == Vector{City}[] @test m.solution.state == InProgress() @test m.solution.usedSpace == 0 @test m.solution.usedTime == 0 end @test m.ways == Dict{VrpAnt.CityIndex,Dict{VrpAnt.CityIndex,VrpAnt.Way}}() @test length(m.listModification) == 12 @test length(m.transitions) == 12 end optimize!(m) @testset "After the optimize function" begin end end
using ModernGL, GLWindow, GLAbstraction, GLFW, ColorTypes, Reactive, GeometryTypes const window = create_glcontext("Example") const vert = vert""" {{GLSL_VERSION}} in vec2 vertices; in vec2 texturecoordinates; // must be this name, because collect_for_gl assumes them out vec2 f_uv; void main() { f_uv = texturecoordinates; gl_Position = vec4(vertices, 0.0, 1.0); } """ # you can also load the shader from a file, which you can then edit in any editor and the changes will show up in your opengl program. #using FileIO; prrogram = TemplateProgram(load("path_to_frag.frag"), load("path_to_vert.vert")) const frag = frag""" {{GLSL_VERSION}} out vec4 outColor; uniform sampler2D image; in vec2 f_uv; void main() { outColor = texture(image, f_uv); } """ program = LazyShader(vert, frag) #= {{GLSL_VERSION}} is a template, you could add your own with the kwarg view=Dict{Compat.UTF8String, Compat.UTF8String}(key->replacement) =# tex = Texture([RGBA{U8}(x,y,sin(x*pi), 1.0) for x=0:0.1:1., y=0:0.1:1.]) #automatically creates the correct texture data = merge(Dict( :image => tex, :primitive => GLUVMesh2D(SimpleRectangle{Float32}(-1,-1,2,2)) )) # Transforms the rectangle into a 2D mesh with uv coordinates and then extracts the buffers for the shader robj = std_renderobject(data, program) # creates a renderable object from the shader and the data. glClearColor(0, 0, 0, 1) while isopen(window) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) render(robj) swapbuffers(window) pollevents() end
Ω = Circle(-1,1) × Circle(-1,1) × Circle(-1,1) ex, ey, ez = (3,5,7)[1:ndims(Ω)] (npx, npy, npz) = (1,1,1)[1:ndims(Ω)] ClimateMachine.gpu_allowscalar(true) grid = DiscontinuousSpectralElementGrid(Ω, elements = (ex, ey, ez), polynomialorder = (npx, npy, npz), array = ArrayType) gridhelper = GridHelper(grid) x, y, z = coordinates(grid) ϕ = ScalarField(copy(x), gridhelper) @testset "Check Interpolation 3D" begin ϕ .= x @test ϕ(0.1, 0.2, 0.3) ≈ 0.1 ϕ .= y @test ϕ(0.1, 0.2, 0.3) ≈ 0.2 ϕ .= z @test ϕ(0.1, 0.2, 0.3) ≈ 0.3 end ## Ω = Circle(0,2) × Circle(-4,2) elements = (3,5,7)[1:ndims(Ω)] polynomialorder = (1,1,1)[1:ndims(Ω)] ClimateMachine.gpu_allowscalar(true) grid = DiscontinuousSpectralElementGrid(Ω, elements = elements, polynomialorder = polynomialorder, array = ArrayType) gridhelper = GridHelper(grid) x, y, z = coordinates(grid) ϕ = ScalarField(copy(x), gridhelper) @testset "Check Interpolation 2D" begin ϕ .= x @test ϕ(0.1, 0.2) ≈ 0.1 ϕ .= y @test ϕ(0.1, 0.2) ≈ 0.2 end
using Bolt using Test using DelimitedFiles using LinearAlgebra @testset "FFTLog" begin N = 64 μ = 0 q = 0.0 r₀ = 1.0 L = 8.0 Nhalf = N ÷ 2 n = range(-Nhalf,Nhalf,length=N) r = r₀ .* 10 .^ (n .* L ./ N ) pl = Bolt.plan_fftlog(r, μ, q, 1.0; kropt=true) aₙ = r .^ (μ + 1) .* exp.(-r.^2 / 2) y = similar(r, ComplexF64) fftdata = readdlm("data/fftlog_example.txt", ' ', Float64, '\n') # test forward mul!(y, pl, aₙ) f_ref = fftdata[:,2] @test all(abs.(y .- f_ref) .< 1e-15) @test isapprox(y, f_ref) # test backward y2 = similar(r, ComplexF64) ldiv!(y2, pl, y) @test all(abs.(y2 .- aₙ) .< 1e-15) end # test U with more naive result # U_μ(μ, x) = 2^x * gamma((μ + 1 + x)/2) / gamma((μ + 1 - x)/2) ## hand-written ℋ derivative for testing # function ℋ′(x, par::AbstractCosmoParams) # a = x2a(x) # return -H₀(par) * (2par.Ω_r + (par.Ω_b + par.Ω_m) * a - 2Ω_Λ(par) * a^4) / # (2 * a * √(par.Ω_r + (par.Ω_b + par.Ω_m) * a + Ω_Λ(par) * a^4)) # end
export PlusOperator, TimesOperator, mul_coefficients struct PlusOperator{T,BI} <: Operator{T} ops::Vector{Operator{T}} bandwidths::BI function PlusOperator{T,BI}(opsin::Vector{Operator{T}},bi::BI) where {T,BI} n,m=size(first(opsin)) for k=2:length(opsin) @assert size(opsin[k],1)==n && size(opsin[k],2)==m end new{T,BI}(opsin,bi) end end Base.size(P::PlusOperator,k::Integer) = size(first(P.ops),k) PlusOperator(opsin::Vector{Operator{T}},bi::Tuple{UT,VT}) where {T,UT,VT} = PlusOperator{T,typeof(bi)}(opsin,bi) bandwidths(P::PlusOperator) = P.bandwidths israggedbelow(P::PlusOperator) = isbandedbelow(P) || all(israggedbelow,P.ops) for (OP,mn) in ((:colstart,:min),(:colstop,:max),(:rowstart,:min),(:rowstop,:max)) defOP = Meta.parse("default_"*string(OP)) @eval function $OP(P::PlusOperator,k::Integer) if isbanded(P) $defOP(P,k) else mapreduce(op->$OP(op,k),$mn,P.ops) end end end function PlusOperator(ops::Vector) # calculate bandwidths b1,b2=-720,-720 # approximates ∞,-∞ for op in ops br=bandwidths(op) b1=max(br[1],b1) b2=max(br[end],b2) end PlusOperator(ops,(b1,b2)) end function convert(::Type{Operator{T}},P::PlusOperator) where T if T==eltype(P) P else PlusOperator{T,typeof(P.bandwidths)}(Vector{Operator{T}}(P.ops),P.bandwidths) end end function promoteplus(opsin::Vector{Operator{T}}) where T ops=Vector{Operator{T}}() # prune zero ops for op in opsin if !iszeroop(op) push!(ops,op) end end PlusOperator(promotespaces(ops)) end for OP in (:domainspace,:rangespace) @eval $OP(P::PlusOperator) = $OP(first(P.ops)) end domain(P::PlusOperator) = commondomain(P.ops) +(A::PlusOperator,B::PlusOperator) = promoteplus(Operator{promote_type(eltype(A),eltype(B))}[A.ops...,B.ops...]) +(A::PlusOperator,B::PlusOperator,C::PlusOperator) = promoteplus(Operator{promote_type(eltype(A),eltype(B),eltype(C))}[A.ops...,B.ops...,C.ops...]) +(A::PlusOperator,B::Operator) = promoteplus(Operator{promote_type(eltype(A),eltype(B))}[A.ops...,B]) +(A::PlusOperator,B::ZeroOperator) = A +(A::PlusOperator,B::Operator,C::Operator) = promoteplus(Operator{promote_type(eltype(A),eltype(B),eltype(C))}[A.ops...,B,C]) +(A::Operator,B::PlusOperator) = promoteplus(Operator{promote_type(eltype(A),eltype(B))}[A,B.ops...]) +(A::ZeroOperator,B::PlusOperator) = B +(A::Operator,B::Operator) = promoteplus(Operator{promote_type(eltype(A),eltype(B))}[A,B]) +(A::Operator,B::Operator,C::Operator) = promoteplus(Operator{promote_type(eltype(A),eltype(B),eltype(C))}[A,B,C]) Base.stride(P::PlusOperator)=mapreduce(stride,gcd,P.ops) function getindex(P::PlusOperator{T},k::Integer...) where T ret=P.ops[1][k...]::T for j=2:length(P.ops) ret+=P.ops[j][k...]::T end ret end for TYP in (:RaggedMatrix,:Matrix,:BandedMatrix, :BlockBandedMatrix,:BandedBlockBandedMatrix) @eval begin $TYP(P::SubOperator{T,PP,NTuple{2,BlockRange1}}) where {T,PP<:PlusOperator} = convert_axpy!($TYP,P) # use axpy! to copy $TYP(P::SubOperator{T,PP}) where {T,PP<:PlusOperator} = convert_axpy!($TYP,P) # use axpy! to copy $TYP(P::SubOperator{T,PP,NTuple{2,UnitRange{Int}}}) where {T,PP<:PlusOperator} = convert_axpy!($TYP,P) # use axpy! to copy end end function BLAS.axpy!(α,P::SubOperator{T,PP},A::AbstractMatrix) where {T,PP<:PlusOperator} for op in parent(P).ops BLAS.axpy!(α, view(op,P.indexes[1],P.indexes[2]), A) end A end +(A::Operator,f::Fun) = A+Multiplication(f,domainspace(A)) +(f::Fun,A::Operator) = Multiplication(f,domainspace(A))+A -(A::Operator,f::Fun) = A+Multiplication(-f,domainspace(A)) -(f::Fun,A::Operator) = Multiplication(f,domainspace(A))-A for TYP in (:ZeroOperator,:Operator) @eval function +(A::$TYP,B::ZeroOperator) if spacescompatible(A,B) A else promotespaces(A,B)[1] end end end +(A::ZeroOperator,B::Operator) = B+A # We need to support A+1 in addition to A+I primarily for matrix case: A+Matrix(I,2,2) for OP in (:+,:-) @eval begin $OP(c::Union{UniformScaling,Number},A::Operator) = $OP(convert(Operator{promote_type(eltype(A),eltype(c))},c),A) $OP(A::Operator,c::Union{UniformScaling,Number}) = $OP(A,convert(Operator{promote_type(eltype(A),eltype(c))},c)) end end ## Times Operator struct ConstantTimesOperator{B,T} <: Operator{T} λ::T op::B ConstantTimesOperator{B,T}(c,op) where {B,T} = new{B,T}(c,op) end function ConstantTimesOperator(c::Number,op::Operator{TT}) where TT<:Number T=promote_type(typeof(c),eltype(op)) B=convert(Operator{T},op) ConstantTimesOperator{typeof(B),T}(T(c),B) end ConstantTimesOperator(c::Number,op::ConstantTimesOperator) = ConstantTimesOperator(c*op.λ,op.op) @wrapperstructure ConstantTimesOperator @wrapperspaces ConstantTimesOperator convert(::Type{T},C::ConstantTimesOperator) where {T<:Number} = T(C.λ)*convert(T,C.op) choosedomainspace(C::ConstantTimesOperator,sp::Space) = choosedomainspace(C.op,sp) for OP in (:promotedomainspace,:promoterangespace),SP in (:UnsetSpace,:Space) @eval $OP(C::ConstantTimesOperator,k::$SP) = ConstantTimesOperator(C.λ,$OP(C.op,k)) end function convert(::Type{Operator{T}},C::ConstantTimesOperator) where T if T==eltype(C) C else op=convert(Operator{T},C.op) ConstantTimesOperator{typeof(op),T}(T(C.λ),op) end end getindex(P::ConstantTimesOperator,k::Integer...) = P.λ*P.op[k...] for TYP in (:RaggedMatrix,:Matrix,:BandedMatrix, :BlockBandedMatrix,:BandedBlockBandedMatrix) @eval begin $TYP(S::SubOperator{T,OP,NTuple{2,BlockRange1}}) where {T,OP<:ConstantTimesOperator} = convert_axpy!($TYP, S) $TYP(S::SubOperator{T,OP,NTuple{2,UnitRange{Int}}}) where {T,OP<:ConstantTimesOperator} = convert_axpy!($TYP, S) $TYP(S::SubOperator{T,OP}) where {T,OP<:ConstantTimesOperator} = convert_axpy!($TYP, S) end end BLAS.axpy!(α,S::SubOperator{T,OP},A::AbstractMatrix) where {T,OP<:ConstantTimesOperator} = unwrap_axpy!(α*parent(S).λ,S,A) struct TimesOperator{T,BI} <: Operator{T} ops::Vector{Operator{T}} bandwidths::BI function TimesOperator{T,BI}(ops::Vector{Operator{T}},bi::BI) where {T,BI} # check compatible for k=1:length(ops)-1 @assert size(ops[k],2) == size(ops[k+1],1) end # remove TimesOperators buried inside ops hastimes = false for k=1:length(ops)-1 @assert spacescompatible(domainspace(ops[k]),rangespace(ops[k+1])) hastimes = hastimes || isa(ops[k],TimesOperator) end if hastimes newops=Vector{Operator{T}}(0) for op in ops if isa(op,TimesOperator) for op2 in op.ops push!(newops,op2) end else push!(newops,op) end end ops=newops end new{T,BI}(ops,bi) end end function bandwidthsum(P,k) ret=0 for op in P ret+=bandwidths(op)[k] end ret end bandwidthssum(P) = (bandwidthsum(P,1),bandwidthsum(P,2)) TimesOperator(ops::Vector{Operator{T}},bi::Tuple{N1,N2}) where {T,N1,N2} = TimesOperator{T,typeof(bi)}(ops,bi) TimesOperator(ops::Vector{Operator{T}}) where {T} = TimesOperator(ops,bandwidthssum(ops)) TimesOperator(ops::Vector{OT}) where {OT<:Operator} = TimesOperator(convert(Vector{Operator{eltype(OT)}},ops),bandwidthssum(ops)) TimesOperator(A::TimesOperator,B::TimesOperator) = TimesOperator(Operator{promote_type(eltype(A),eltype(B))}[A.ops...,B.ops...]) TimesOperator(A::TimesOperator,B::Operator) = TimesOperator(Operator{promote_type(eltype(A),eltype(B))}[A.ops...,B]) TimesOperator(A::Operator,B::TimesOperator) = TimesOperator(Operator{promote_type(eltype(A),eltype(B))}[A,B.ops...]) TimesOperator(A::Operator,B::Operator) = TimesOperator(Operator{promote_type(eltype(A),eltype(B))}[A,B]) ==(A::TimesOperator,B::TimesOperator)=A.ops==B.ops function convert(::Type{Operator{T}},P::TimesOperator) where T if T==eltype(P) P else TimesOperator(Operator{T}[P.ops...]) end end function promotetimes(opsin::Vector{B},dsp) where B<:Operator ops=Vector{Operator{mapreduce(eltype,promote_type,opsin)}}(undef,0) for k=length(opsin):-1:1 if !isa(opsin[k],Conversion) op=promotedomainspace(opsin[k],dsp) if op==() # do nothing elseif isa(op,TimesOperator) for j=length(op.ops):-1:1 push!(ops,op.ops[j]) end dsp=rangespace(op) else push!(ops,op) dsp=rangespace(op) end end end if isempty(ops) ConstantOperator(1.0,dsp) elseif length(ops)==1 first(ops) else TimesOperator(reverse!(ops)) # change order in TImesOperator if this is slow end end promotetimes(opsin::Vector{B}) where {B<:Operator}=promotetimes(opsin,domainspace(last(opsin))) domainspace(P::TimesOperator)=domainspace(last(P.ops)) rangespace(P::TimesOperator)=rangespace(first(P.ops)) domain(P::TimesOperator)=commondomain(P.ops) bandwidths(P::TimesOperator) = P.bandwidths israggedbelow(P::TimesOperator) = isbandedbelow(P) || all(israggedbelow,P.ops) Base.stride(P::TimesOperator) = mapreduce(stride,gcd,P.ops) for OP in (:rowstart,:rowstop) defOP=Meta.parse("default_"*string(OP)) @eval function $OP(P::TimesOperator,k::Integer) if isbanded(P) return $defOP(P,k) end for j=eachindex(P.ops) k=$OP(P.ops[j],k) end k end end for OP in (:colstart,:colstop) defOP=Meta.parse("default_"*string(OP)) @eval function $OP(P::TimesOperator, k::Integer) if isbanded(P) return $defOP(P, k) end for j=reverse(eachindex(P.ops)) k=$OP(P.ops[j],k) end k end end getindex(P::TimesOperator,k::Integer,j::Integer) = P[k:k,j:j][1,1] function getindex(P::TimesOperator,k::Integer) @assert isafunctional(P) P[1:1,k:k][1,1] end function getindex(P::TimesOperator,k::AbstractVector) @assert isafunctional(P) vec(Matrix(P[1:1,k])) end for TYP in (:Matrix, :BandedMatrix, :RaggedMatrix) @eval function $TYP(V::SubOperator{T,TO,Tuple{UnitRange{Int},UnitRange{Int}}}) where {T,TO<:TimesOperator} P = parent(V) if isbanded(P) if $TYP ≠ BandedMatrix return $TYP(BandedMatrix(V)) end elseif isbandedblockbanded(P) N = block(rangespace(P), last(parentindices(V)[1])) M = block(domainspace(P), last(parentindices(V)[2])) B = P[Block(1):N, Block(1):M] return $TYP(view(B, parentindices(V)...), _colstops(V)) end kr,jr = parentindices(V) (isempty(kr) || isempty(jr)) && return $TYP(Zeros, V) if maximum(kr) > size(P,1) || maximum(jr) > size(P,2) || minimum(kr) < 1 || minimum(jr) < 1 throw(BoundsError()) end @assert length(P.ops) ≥ 2 if size(V,1)==0 return $TYP(Zeros, V) end # find optimal truncations for each operator # by finding the non-zero entries krlin = Matrix{Union{Int,Infinity}}(undef,length(P.ops),2) krlin[1,1],krlin[1,2]=kr[1],kr[end] for m=1:length(P.ops)-1 krlin[m+1,1]=rowstart(P.ops[m],krlin[m,1]) krlin[m+1,2]=rowstop(P.ops[m],krlin[m,2]) end krlin[end,1]=max(krlin[end,1],colstart(P.ops[end],jr[1])) krlin[end,2]=min(krlin[end,2],colstop(P.ops[end],jr[end])) for m=length(P.ops)-1:-1:2 krlin[m,1]=max(krlin[m,1],colstart(P.ops[m],krlin[m+1,1])) krlin[m,2]=min(krlin[m,2],colstop(P.ops[m],krlin[m+1,2])) end krl = Matrix{Int}(krlin) # Check if any range is invalid, in which case return zero for m=1:length(P.ops) if krl[m,1]>krl[m,2] return $TYP(Zeros, V) end end # The following returns a banded Matrix with all rows # for large k its upper triangular BA = convert($TYP{T}, P.ops[end][krl[end,1]:krl[end,2],jr]) for m = (length(P.ops)-1):-1:1 BA = convert($TYP{T}, P.ops[m][krl[m,1]:krl[m,2],krl[m+1,1]:krl[m+1,2]])*BA end $TYP{T}(BA) end end for TYP in (:BlockBandedMatrix, :BandedBlockBandedMatrix) @eval function $TYP(V::SubOperator{T,TO,Tuple{BlockRange1,BlockRange1}}) where {T,TO<:TimesOperator} P = parent(V) KR,JR = parentindices(V) @assert length(P.ops) ≥ 2 if size(V,1)==0 || isempty(KR) || isempty(JR) return $TYP(Zeros, V) end if Int(maximum(KR)) > nblocks(P,1) || Int(maximum(JR)) > nblocks(P,2) || Int(minimum(KR)) < 1 || Int(minimum(JR)) < 1 throw(BoundsError()) end # find optimal truncations for each operator # by finding the non-zero entries KRlin = Matrix{Union{Block,Infinity}}(undef,length(P.ops),2) KRlin[1,1],KRlin[1,2] = first(KR),last(KR) for m=1:length(P.ops)-1 KRlin[m+1,1]=blockrowstart(P.ops[m],KRlin[m,1]) KRlin[m+1,2]=blockrowstop(P.ops[m],KRlin[m,2]) end KRlin[end,1]=max(KRlin[end,1],blockcolstart(P.ops[end],first(JR))) KRlin[end,2]=min(KRlin[end,2],blockcolstop(P.ops[end],last(JR))) for m=length(P.ops)-1:-1:2 KRlin[m,1]=max(KRlin[m,1],blockcolstart(P.ops[m],KRlin[m+1,1])) KRlin[m,2]=min(KRlin[m,2],blockcolstop(P.ops[m],KRlin[m+1,2])) end KRl = Matrix{Block{1}}(KRlin) # Check if any range is invalid, in which case return zero for m=1:length(P.ops) if KRl[m,1]>KRl[m,2] return $TYP(Zeros, V) end end # The following returns a banded Matrix with all rows # for large k its upper triangular BA = convert($TYP, view(P.ops[end],KRl[end,1]:KRl[end,2],JR)) for m = (length(P.ops)-1):-1:1 BA = convert($TYP, view(P.ops[m],KRl[m,1]:KRl[m,2],KRl[m+1,1]:KRl[m+1,2]))*BA end convert($TYP, BA) end end ## Algebra: assume we promote for OP in (:(adjoint),:(transpose)) @eval $OP(A::TimesOperator)=TimesOperator(reverse!(map($OP,A.ops))) end *(A::TimesOperator,B::TimesOperator) = promotetimes(Operator{promote_type(eltype(A),eltype(B))}[A.ops...,B.ops...]) function *(A::TimesOperator,B::Operator) if isconstop(B) promotedomainspace(convert(Number,B)*A,domainspace(B)) else promotetimes(Operator{promote_type(eltype(A),eltype(B))}[A.ops...,B]) end end function *(A::Operator,B::TimesOperator) if isconstop(A) promoterangespace(convert(Number,A)*B,rangespace(A)) else promotetimes(Operator{promote_type(eltype(A),eltype(B))}[A,B.ops...]) end end function *(A::Operator,B::Operator) if isconstop(A) promoterangespace(convert(Number,A)*B,rangespace(A)) elseif isconstop(B) promotedomainspace(convert(Number,B)*A,domainspace(B)) else promotetimes(Operator{promote_type(eltype(A),eltype(B))}[A,B]) end end # Conversions we always assume are intentional: no need to promote *(A::ConversionWrapper{TO1},B::ConversionWrapper{TO}) where {TO1<:TimesOperator,TO<:TimesOperator} = ConversionWrapper(TimesOperator(A.op,B.op)) *(A::ConversionWrapper{TO},B::Conversion) where {TO<:TimesOperator} = ConversionWrapper(TimesOperator(A.op,B)) *(A::Conversion,B::ConversionWrapper{TO}) where {TO<:TimesOperator} = ConversionWrapper(TimesOperator(A,B.op)) *(A::Conversion,B::Conversion) = ConversionWrapper(TimesOperator(A,B)) *(A::Conversion,B::TimesOperator) = TimesOperator(A,B) *(A::TimesOperator,B::Conversion) = TimesOperator(A,B) *(A::Operator,B::Conversion) = isconstop(A) ? promoterangespace(convert(Number,A)*B,rangespace(A)) : TimesOperator(A,B) *(A::Conversion,B::Operator) = isconstop(B) ? promotedomainspace(convert(Number,B)*A,domainspace(B)) : TimesOperator(A,B) ^(A::Operator, p::Integer) = Base.power_by_squaring(A, p) +(A::Operator) = A -(A::Operator) = ConstantTimesOperator(-1,A) -(A::Operator,B::Operator) = A+(-B) function *(f::Fun, A::Operator) if isafunctional(A) && (isinf(bandwidth(A,1)) || isinf(bandwidth(A,2))) LowRankOperator(f,A) else TimesOperator(Multiplication(f,rangespace(A)),A) end end function *(c::Number,A::Operator) if c==1 A elseif c==0 ZeroOperator(domainspace(A),rangespace(A)) else ConstantTimesOperator(c,A) end end *(A::Operator,c::Number) = A*(c*one(domainspace(A))) /(B::Operator,c::Number) = (1.0/c)*B /(B::Operator,c::Fun) = (1.0/c)*B ## Operations function mul_coefficients(A::Operator,b) n=size(b,1) ret = n>0 ? mul_coefficients(view(A,FiniteRange,1:n),b) : b end function mul_coefficients(A::TimesOperator,b) ret = b for k=length(A.ops):-1:1 ret = mul_coefficients(A.ops[k],ret) end ret end function *(A::Operator, b) ds = domainspace(A) rs = rangespace(A) if isambiguous(ds) promotedomainspace(A,space(b))*b elseif isambiguous(rs) error("Assign spaces to $A before multiplying.") else Fun(rs, mul_coefficients(A,coefficients(b,ds))) end end mul_coefficients(A::PlusOperator,b::Fun) = mapreduce(x->mul_coefficients(x,b),+,A.ops) *(A::Operator, b::AbstractMatrix{<:Fun}) = A*Fun(b) *(A::Vector{<:Operator}, b::Fun) = map(a->a*b,convert(Array{Any,1},A)) ## promotedomain function promotedomainspace(P::PlusOperator{T},sp::Space,cursp::Space) where T if sp==cursp P else ops = [promotedomainspace(op,sp) for op in P.ops] promoteplus(Vector{Operator{mapreduce(eltype,promote_type,ops)}}(ops)) end end function choosedomainspace(P::PlusOperator,sp::Space) ret=UnsetSpace() for op in P.ops sp2=choosedomainspace(op,sp) if !isa(sp2,AmbiguousSpace) # we will ignore this result in hopes another opand # tells us a good space ret=union(ret,sp2) end end ret end function promotedomainspace(P::TimesOperator,sp::Space,cursp::Space) if sp==cursp P elseif length(P.ops)==2 P.ops[1]*promotedomainspace(P.ops[end],sp) else promotetimes([P.ops[1:end-1];promotedomainspace(P.ops[end],sp)]) end end function choosedomainspace(P::TimesOperator,sp::Space) for op in P.ops sp=choosedomainspace(op,sp) end sp end
export prior """ prior(m, xs...) Returns the minimal model required to sample random variables `xs...`. Useful for extracting a prior distribution from a joint model `m` by designating `xs...` and the variables they depend on as the prior and hyperpriors. # Example ```jldoctest m = @model n begin α ~ Gamma() β ~ Gamma() θ ~ Beta(α,β) x ~ Binomial(n, θ) end; Soss.prior(m, :x) # output @model begin β ~ Gamma() α ~ Gamma() θ ~ Beta(α, β) end ``` """ prior(m::Model, xs...) = before(m, xs..., inclusive = false, strict = true) export likelihood """ likelihood(m, xs...) Return a model with only the specified variables in the body. Required dependencies will be included as arguments. """ function likelihood(m::Model, xs...) M = getmodule(m) result = foldl(merge, (Model(M, findStatement(m,x)) for x in xs)) for x in xs for pa in parents(digraph(m), x) pa ∈ xs && continue result = merge(result, Model(M, Arg(pa))) end end return result end export prune """ prune(m, xs...) Returns a model transformed by removing `xs...` and all variables that depend on `xs...`. Unneeded arguments are also removed. # Examples ```jldoctest m = @model n begin α ~ Gamma() β ~ Gamma() θ ~ Beta(α,β) x ~ Binomial(n, θ) end; prune(m, :θ) # output @model begin β ~ Gamma() α ~ Gamma() end ``` ```jldoctest m = @model n begin α ~ Gamma() β ~ Gamma() θ ~ Beta(α,β) x ~ Binomial(n, θ) end; prune(m, :n) # output @model begin β ~ Gamma() α ~ Gamma() θ ~ Beta(α, β) end ``` """ prune(m::Model, xs...) = before(m, xs..., inclusive = false, strict = false) export predictive """ predictive(m, xs...) Returns a model transformed by adding `xs...` to arguments with a body containing only statements that depend on `xs`, or statements that are depended upon by children of `xs` through an open path. Unneeded arguments are trimmed. # Examples ```jldoctest m = @model (n, k) begin β ~ Gamma() α ~ Gamma() θ ~ Beta(α, β) x ~ Binomial(n, θ) z ~ Binomial(k, α / (α + β)) end; predictive(m, :θ) # output @model (n, θ) begin x ~ Binomial(n, θ) end ``` """ predictive(m::Model, xs...) = _predictive(m, namedtuple(xs)(xs)) # predictive(m::Model, xs...) = after(m, xs..., strict = true) @generated function _predictive(m::Model, xs) return after(type2model(m), getntkeys(xs)...; strict=true) end export Do """ Do(m, xs...) Returns a model transformed by adding `xs...` to arguments. The remainder of the body remains the same, consistent with Judea Pearl's "Do" operator. Unneeded arguments are trimmed. # Examples ```jldoctest m = @model (n, k) begin β ~ Gamma() α ~ Gamma() θ ~ Beta(α, β) x ~ Binomial(n, θ) z ~ Binomial(k, α / (α + β)) end; Do(m, :θ) # output @model (n, k, θ) begin β ~ Gamma() α ~ Gamma() x ~ Binomial(n, θ) z ~ Binomial(k, α / (α + β)) end ``` """ Do(m::Model, xs...) = after(m, xs..., strict = false)
using CFTime using Dates # only for daily scale function dates_miss(dates) date_begin = first(dates) date_end = last(dates) dates_full = date_begin:Dates.Day(1):date_end setdiff(dates_full, dates) end # only for daily scale function dates_nmiss(dates) date_begin = first(dates) date_end = last(dates) n_full = (date_end - date_begin) / convert(Dates.Millisecond, Dates.Day(1)) + 1 |> Int n_full - length(dates) # n_miss end year = Dates.year month = Dates.month day = Dates.day Year = Dates.Year Month = Dates.Month Day = Dates.Day make_datetime = DateTime make_date = DateTime export dates_miss, dates_nmiss, year, month, day, Year, Month, Day, make_datetime, make_date
import FractionalCalculus.FracDiffAlg """ Grünwald–Letnikov sense fractional derivative algorithms, please refer to [Grünwald–Letnikov derivative](https://en.wikipedia.org/wiki/Gr%C3%BCnwald%E2%80%93Letnikov_derivative) for more details """ abstract type GL <: FracDiffAlg end """ # Grünwald–Letnikov sense fractional dervivative. fracdiff(f, α, start_point, end_point, GL_Direct()) ### Example: ```julia-repl julia> fracdiff(x->x^5, 0, 0.5, GL_Direct()) ``` !!! info "Scope" Please note Grunwald-Letnikov sense fracdiff only support ``0 < \\alpha < 1``. Please refer to [Grünwald–Letnikov derivative](https://en.wikipedia.org/wiki/Gr%C3%BCnwald%E2%80%93Letnikov_derivative) for more details. Grunwald Letnikov direct compute method to obtain fractional derivative, precision are guaranteed but cause more memory allocation and compilation time. """ struct GL_Direct <: GL end """ # Grünwald Letnikov sense derivative approximation fracdiff(f, α, end_point, h, GL_Multiplicative_Additive()) Grünwald–Letnikov multiplication-addition-multiplication-addition··· method to approximate fractional derivative. ### Example ```julia-repl julia> fracdiff(x->x, 0.5, 1, 0.007, GL_Multiplicative_Additive()) 1.127403405642918 ``` !!! danger "Inaccurate" The `GL_Multiplicative_Additive` method is not accruate, please use it at your own risk. ```tex @book{oldham_spanier_1984, title={The fractional calculus: Theory and applications of differentiation and integration to arbitrary order}, author={Oldham, Keith B. and Spanier, Jerome}, year={1984}} ``` """ struct GL_Multiplicative_Additive <: GL end """ # Grünwald Letnikov sense derivative approximation fracdiff(f, α, end_point, h, GL_Lagrange_Three_Point_Interp()) Using Lagrange three poitns interpolation to approximate the fractional derivative. ### Example ```julia-repl julia> fracdiff(x->x, 0.5, 1, 0.007, GL_Lagrange_Three_Point_Interp()) 1.1283963376811044 ``` !!! danger "Inaccurate" The `GL_Lagrange_Three_Point_Interp` method is not accruate, please use it at your own risk. """ struct GL_Lagrange_Three_Point_Interp <: GL end """ # Grünwald Letnikov sense derivative approximation fracdiff(f::Union{Function, Number}, α::AbstractArray, end_point, h, ::GL_Finite_Difference)::Vector Use finite difference method to obtain Grünwald Letnikov sense fractional derivative. ### Example ```julia-repl julia> fracdiff(x->x, 0.5, 1, 0.01, GL_Finite_Difference()) 1.1269695801851276 ``` !!! danger "Inaccurate" `GL_Finite_Difference` method is not accruate, please use it at your own risk. """ struct GL_Finite_Difference <: GL end """ fracdiff(f, α, point, h, GL_High_Precision()) Use the high precision algorithms to compute the Grunwald letnikov fractional derivative. !!! note The value interval passing in the function should be a array! """ struct GL_High_Precision <: GL end ################################################################ ### Type defination done ### ################################################################ #= Grunwald Letnikov direct method =# function fracdiff(f::Union{Function, Number}, α::Float64, start_point, end_point, ::GL_Direct) #checks(f, α, start_point, end_point) g(τ) = (f(end_point)-f(τ)) ./ (end_point - τ) .^ (1+α) result = f(end_point)/(gamma(1-α) .* (end_point - start_point) .^ α) .+ quadgk(g, start_point, end_point) .* α ./ gamma(1-α) return result end #TODO: Use the improved alg!! This algorithm is not accurate #This algorithm is not good, still more to do function fracdiff(f::Union{Function, Number}, α, end_point, h, ::GL_Multiplicative_Additive)::Float64 summation = zero(Float64) n = Int64(floor(end_point/h)) for i ∈ 0:n-1 summation += gamma(i-α)/gamma(i+1)*f(end_point-i*h) end result = summation*end_point^(-α)*n^α/gamma(-α) return result end function fracdiff(f::Union{Number, Function}, α::Float64, end_point::AbstractArray, h, ::GL_Multiplicative_Additive)::Vector ResultArray = Float64[] for (_, value) in enumerate(end_point) append!(ResultArray, fracdiff(f, α, value, h, GL_Multiplicative_Additive())) end return ResultArray end #TODO: This algorithm is same with the above one, not accurate!!! #This algorithm is not good, still more to do function fracdiff(f::Union{Function, Number}, α::Float64, end_point, h, ::GL_Lagrange_Three_Point_Interp)::Float64 #checks(f, α, 0, end_point) n = Int64(floor(end_point/h)) summation = zero(Float64) for i ∈ 0:n-1 summation += gamma(i-α)/gamma(i+1)*(f(end_point-i*h)+1/4*α*(f(end_point-(i-1)*h)-f(end_point-(i+1)*h))+1/8*α^2*(f(end_point-(i-1)*h)-2*f(end_point-i*h)+f(end_point-(i+1)*h))) end result = summation*end_point^(-α)*n^α/gamma(-α) return result end function fracdiff(f::Union{Number, Function}, α::Float64, end_point::AbstractArray, h, ::GL_Lagrange_Three_Point_Interp)::Vector ResultArray = Float64[] for (_, value) in enumerate(end_point) append!(ResultArray, fracdiff(f, α, value, h, GL_Lagrange_Three_Point_Interp())) end return ResultArray end function fracdiff(f::Union{Number, Function}, α::Float64, end_point::Real, h, ::GL_Finite_Difference)::Float64 n = Int64(floor(end_point/h)) result = zero(Float64) @fastmath @simd for i ∈ 0:n result += (-1)^i/(gamma(i+1)*gamma(α-i+1))*f(end_point-i*h) end result1=result*h^(-α)*gamma(α+1) return result1 end function fracdiff(f::Union{Function, Number}, α::AbstractArray, end_point, h, ::GL_Finite_Difference)::Vector ResultArray = Float64[] for (_, value) in enumerate(end_point) append!(ResultArray, fracint(f, α, value, h, GL_Finite_Difference())) end return ResultArray end function fracdiff(f, α, t, p, ::GL_High_Precision) if isa(f, Function) y=f.(t) elseif isa(f, Vector) y=f[:] end h = t[2] - t[1] t = t[:] n = length(t) u = 0 du = 0 r = collect(0:p)*h R = reverse(Vandermonde(r), dims=2) c = inv(R)*y[1:p+1] for i = 1:p+1 u = u.+c[i]*t.^(i-1) du = du.+c[i]*t.^(i-1-α)*gamma(i)/gamma(i-α) end v = y.-u g = genfun(p) w = getvec(α, n, g) dv = zeros(n) for i=1:n dv[i] = w[1:i]'*v[i:-1:1]/h^α end dy = dv .+ du if abs(y[1])<1e-10 dy[1]=0 end return dy end """ P-th precision polynomial generate function ```math g_p(z)=\\sum_{k=1}^p \\frac{1}{k}(1-z)^k ``` """ function genfun(p) a=collect(1:p+1) A=Vandermonde(a)' return (1 .-a')*inv(A') end function getvec(α, n, g) p = length(g)-1 b = 1 + α g0 = g[1] w = Float64[] push!(w, g[1]^α) for m = 2:p M = m-1 dA = b/M temp = (-(g[2:m] .*collect((1-dA):-dA:(1-b))))' *w[M:-1:1]/g0 push!(w, temp) end for k = p+1:n M = k-1 dA = b/M temp = (-(g[2:(p+1)] .*collect((1-dA):-dA:(1-p*dA))))' *w[M:-1:(k-p)]./g0 #FIXME: When p is greater than 2 threw DimensionMismatch push!(w, temp) end return w end
## Display code """ Access SymPy's docstrings There are several calling styles, as finding the underlying SymPy object from a Julia object is a bit tricky. Examples ``` @vars x import Base.Docs.doc doc(sin(x)) # doc(sympy[:sin]) # explicit module lookup doc(SymPy.mpmath[:hypercomb]) # explicit module lookup doc(Poly(x^2,x), :coeffs) # coeffs is an object method of the poly instance doc([x 1;1 x], :LUsolve) # LUsolve is a matrix method ``` """ Base.Docs.doc(x::SymbolicObject) = Base.Docs.doc(PyObject(x)) Base.Docs.doc(x::SymbolicObject, s::Symbol) = Base.Docs.doc(PyObject(x)[s]) Base.Docs.doc(x::Array{T,N}, s::Symbol) where {T <: SymbolicObject, N} = Base.Docs.doc(PyObject(x)[s]) ## Add some of SymPy's displays ## Some pretty printing #doc(x::SymbolicObject) = print(x[:__doc__]) "Map a symbolic object to a string" _str(s::SymbolicObject) = s[:__str__]() "Map an array of symbolic objects to a string" _str(a::AbstractArray{SymbolicObject}) = map(_str, a) "call SymPy's pretty print" pprint(s::SymbolicObject, args...; kwargs...) = sympy_meth(:pprint, s, args...; kwargs...) "Call SymPy's `latex` function. Not exported. " latex(s::SymbolicObject, args...; kwargs...) = sympy_meth(:latex, s, args...; kwargs...) "create basic printed output" function jprint(x::SymbolicObject) out = PyCall.pycall(pybuiltin("str"), String, PyObject(x)) if ismatch(r"\*\*", out) out = replace(out, "**", "^") end out end jprint(x::AbstractArray) = map(jprint, x) ## show is called in printing tuples, ... ## we would like to use pprint here, but it does a poor job on complicated multi-line expressions Base.show(io::IO, s::Sym) = print(io, jprint(s)) ## We add show methods for the REPL (text/plain) and IJulia (text/latex) ## text/plain show(io::IO, ::MIME"text/plain", s::SymbolicObject) = print(io, sympy["pretty"](s)) show(io::IO, ::MIME"text/latex", x::Sym) = print(io, latex(x, mode="equation*", itex=true)) function show(io::IO, ::MIME"text/latex", x::AbstractArray{Sym}) function toeqnarray(x::Vector{Sym}) a = join([latex(x[i]) for i in 1:length(x)], "\\\\") "\\begin{bmatrix}$a\\end{bmatrix}" end function toeqnarray(x::AbstractArray{Sym,2}) sz = size(x) a = join([join(map(latex, x[i,:]), "&") for i in 1:sz[1]], "\\\\") "\\begin{bmatrix}$a\\end{bmatrix}" end print(io, toeqnarray(x)) end ## Pretty print dicts function show(io::IO, ::MIME"text/latex", d::Dict{T,S}) where {T<:Sym, S<:Any} Latex(x::Sym) = latex(x) Latex(x) = sprint(Base.showcompact, x) out = "\\begin{equation*}\\begin{cases}" for (k,v) in d out = out * Latex(k) * " & \\text{=>} &" * Latex(v) * "\\\\" end out = out * "\\end{cases}\\end{equation*}" print(io, out) end ## Convert SymPy symbol to Julia expression convert(::Type{Expr}, x::SymbolicObject) = parse(jprint(x))
function FDivRhoGrad2Vec!(F,cCG,RhoCG,CG,Param) nz=Param.Grid.nz; OP=CG.OrdPoly+1; NF=Param.Grid.NumFaces; D1cCG = Param.CacheC1 D2cCG = Param.CacheC2 grad1CG = Param.CacheC3 grad2CG = Param.CacheC4 D1gradCG = Param.CacheC1 D2gradCG = Param.CacheC2 vC1 = Param.CacheC3 vC2 = Param.CacheC4 JC = Param.cache.JC mul!(reshape(D1cCG,OP,OP*NF*nz),CG.DS,reshape(cCG,OP,OP*nz*NF)) mul!(reshape(PermutedDimsArray(D2cCG,(2,1,3,4)),OP,OP*NF*nz),CG.DS,reshape(PermutedDimsArray(cCG,(2,1,3,4)),OP,OP*nz*NF)) grad1CG .= RhoCG .* (Param.dXdxIC11.*D1cCG .+ Param.dXdxIC21.*D2cCG) grad2CG .= RhoCG .* (Param.dXdxIC12.*D1cCG .+ Param.dXdxIC22.*D2cCG) D1gradCG .= Param.dXdxIC11.*grad1CG .+ Param.dXdxIC12.*grad2CG D2gradCG .= Param.dXdxIC21.*grad1CG .+ Param.dXdxIC22.*grad2CG mul!(reshape(vC1,OP,OP*NF*nz),CG.DW,reshape(D1gradCG,OP,OP*nz*NF)) mul!(reshape(PermutedDimsArray(vC2,(2,1,3,4)),OP,OP*NF*nz),CG.DW,reshape(PermutedDimsArray(D2gradCG,(2,1,3,4)),OP,OP*nz*NF)) F .= F .- Param.HyperDDiv .* (vC1 .+ vC2) ./ JC end function FDivRhoGrad2Vec(cCG,RhoCG,CG,Param) nz=Param.Grid.nz; OP=CG.OrdPoly+1; NF=Param.Grid.NumFaces; dXdxIC = Param.cache.dXdxIC JC = Param.cache.JC D1cCG=reshape( CG.DS*reshape(cCG,OP,OP*NF*nz) ,OP,OP,NF,nz); D2cCG=permute(reshape( CG.DS*reshape( permute( reshape(cCG,OP,OP,NF,nz) ,[2 1 3 4]) ,OP,OP*NF*nz) ,OP,OP,NF,nz) ,[2 1 3 4]); gradCG1=RhoCG .* (dXdxIC[:,:,:,:,1,1].*D1cCG + dXdxIC[:,:,:,:,2,1].*D2cCG); gradCG2=RhoCG .* (dXdxIC[:,:,:,:,1,2].*D1cCG + dXdxIC[:,:,:,:,2,2].*D2cCG); divCG=(reshape( CG.DW*(reshape(gradCG1,OP,OP*NF*nz) .* reshape(dXdxIC[:,:,:,:,1,1],OP,OP*NF*nz) + reshape(gradCG2,OP,OP*NF*nz) .* reshape(dXdxIC[:,:,:,:,1,2],OP,OP*NF*nz)) ,OP,OP,NF,nz) + permute( reshape( CG.DW*reshape( permute( (reshape(gradCG1,OP,OP,NF,nz) .* dXdxIC[:,:,:,:,2,1] + reshape(gradCG2,OP,OP,NF,nz) .* dXdxIC[:,:,:,:,2,2]) ,[2 1 3 4]) ,OP,OP*NF*nz) ,OP,OP,NF,nz) ,[2 1 3 4]))./JC; return divCG end
function charttype_to_dict(chart::GoogleChart) [ :chart_type => chart.chart_type, :chart_id => chart.id, :width=>chart.width, :height=>chart.height, :chart_data => chart.data, :chart_options => JSON.json(chart.options) ] end ## take vector of google charts function charts_to_dict(charts) packages = union([chart.packages for chart in charts]...) [:chart_packages => JSON.json(packages), :charts => [charttype_to_dict(chart) for chart in charts], :chart_xtra => join([chart.xtra for chart in charts],"\n") ] end ## Render charts ## io -- render to io stream ## fname -- render to file ## none -- create html file, show in browser function render{T <: GoogleChart}(io::IO, charts::Vector{T}, # chart objects tpl::Union(Nothing, Mustache.MustacheTokens) # Mustache template. Default is entire page ) details = charts_to_dict(charts) ## defaults _tpl = isa(tpl, Nothing) ? chart_tpl : tpl Mustache.render(io, _tpl, details) end function render{T <: GoogleChart}(fname::String, charts::Vector{T}, tpl::Union(Nothing, Mustache.MustacheTokens)) io = open(fname, "w") render(io, charts, tpl) close(io) end function render{T <: GoogleChart}(charts::Vector{T}, tpl::Union(Nothing, Mustache.MustacheTokens)) fname = tempname() * ".html" render(fname, charts, tpl) open_url(fname) end ## no tpl render{T <: GoogleChart}(io::IO, charts::Vector{T}) = render(io, charts, nothing) render{T <: GoogleChart}(fname::String, charts::Vector{T}) = render(fname, charts, nothing) ## no io or file name specified, render to browser render{T <: GoogleChart}(charts::Vector{T}) = render(charts, nothing) render{T <: GoogleChart}(io::Nothing, charts::Vector{T}, tpl::Union(Nothing, Mustache.MustacheTokens)) = render(charts, tpl) render(io::IO, chart::GoogleChart, tpl::Union(Nothing, Mustache.MustacheTokens)) = render(io, [chart], tpl) render(io::IO, chart::GoogleChart) = render(io, chart, nothing) render(fname::String, chart::GoogleChart, tpl::Union(Nothing, Mustache.MustacheTokens)) = render(fname, [chart], tpl) render(fname::String, chart::GoogleChart) = render(fname, [chart], nothing) render(chart::GoogleChart, tpl::Union(Nothing, Mustache.MustacheTokens)) = render([chart], tpl) render(chart::GoogleChart) = render([chart]) render(io::Nothing, chart::GoogleChart, tpl::Union(Nothing, Mustache.MustacheTokens)) = render([chart], tpl) render(io::Nothing, chart::GoogleChart) = render([chart], nothing) ## for using within Gadfly.weave: gadfly_weave_tpl = """ <div id={{:id}} style="width:{{:width}}px; height:{{:height}}px;"></div> <script> var {{:id}}_data = {{{:chart_data}}}; var {{:id}}_options = {{{:chart_options}}}; var {{:id}}_chart = new google.visualization.{{:chart_type}}(document.getElementById('{{:id}}'));{{:id}}_chart.draw({{:id}}_data, {{:id}}_options); </script> """ ## this is used by weave... function gadfly_format(x::CoreChart) d = [:id => x.id, :width => 600, :height => 400, :chart_data => x.data, :chart_options => json(x.options), :chart_type => x.chart_type ] Mustache.render(gadfly_weave_tpl, d) end ## IJulia support import Base.writemime export writemime ## read https://developers.google.com/loader/#GoogleLoad to see if this can be tidied up writemime_tpl = """ <div id={{:id}} style="width:{{:width}}px; height:{{:height}}px;"></div> <script> function load_chart_{{:id}}() { var {{:id}}_data = {{{:chart_data}}}; var {{:id}}_options = {{{:chart_options}}}; var {{:id}}_chart = new google.visualization.{{:chart_type}}(document.getElementById('{{:id}}'));{{:id}}_chart.draw({{:id}}_data, {{:id}}_options); } setTimeout(function(){ google.load('visualization', '1', { 'callback':load_chart_{{:id}}, 'packages':['corechart'] } )}, 10); </script> """ function writemime(io::IO, ::MIME"text/html", x::GoogleChart) d = [:id => x.id, :width => 600, :height => 400, :chart_data => x.data, :chart_options => json(x.options), :chart_type => x.chart_type ] out = Mustache.render(writemime_tpl, d) print(io, out) end ## inject code into browser if displayable inject_javascript() = display("text/html", """ <script type='text/javascript' src='https://www.google.com/jsapi'></script> """) ## inject when package is loaded if displayable("text/html") inject_javascript() end ## in case surface plot is desired (not reliable) inject_surfaceplot_javascript() = Base.display("text/html", """ <script type='text/javascript' src='http://javascript-surface-plot.googlecode.com/svn/trunk/javascript/SurfacePlot.js'></script> <script type='text/javascript' src='http://javascript-surface-plot.googlecode.com/svn/trunk/javascript/ColourGradient.js'></script> """) ## display to browser, or writemime #function Base.repl_show(io::IO, chart::GoogleChart) function writemime(io::IO, ::MIME"text/plain", chart::GoogleChart) if io === STDOUT render(nothing, chart) else writemime(io, "text/html", chart) end end # Base.show(io::IO, chart::GoogleChart) = print(io, "<plot>")
export prune """ prune(m, xs...; trim_args = true) Returns a model transformed by removing `xs...` and all variables that depend on `xs...`. If `trim_args = true`, unneeded arguments are also removed. Use `trim_args = false` to leave arguments unaffected. # Examples ```jldoctest m = @model n begin α ~ Gamma() β ~ Gamma() θ ~ Beta(α,β) x ~ Binomial(n, θ) end; prune(m, :θ) # output @model begin β ~ Gamma() α ~ Gamma() end ``` ```jldoctest m = @model n begin α ~ Gamma() β ~ Gamma() θ ~ Beta(α,β) x ~ Binomial(n, θ) end; prune(m, :n) # output @model begin β ~ Gamma() α ~ Gamma() θ ~ Beta(α, β) end ``` """ function prune(m::Model, xs :: Symbol...; trim_args = true) po = poset(m) #Creates a new SimplePoset, so no need to copy before mutating newvars = variables(m) for x in xs setdiff!(newvars, above(po,x)) setdiff!(newvars, [x]) end # Keep arguments in newvars newargs = arguments(m) ∩ newvars setdiff!(newvars, newargs) if trim_args # keep arguments only if depended upon by newvars dependencies = mapfoldl(var -> below(po, var), vcat, newvars, init = Symbol[]) # mapfoldl needed since newvars can be empty newargs = dependencies ∩ newargs end theModule = getmodule(m) m_init = Model(theModule, newargs, NamedTuple(), NamedTuple(), nothing) m = foldl(newvars; init=m_init) do m0,v merge(m0, Model(theModule, findStatement(m, v))) end end
module Core import FileIO; include("res_dir_tree.jl"); include("add_to_log.jl"); include("build_description.jl"); include("save_and_load_data.jl"); include("save_and_load_desc.jl"); include("load_log.jl"); end
abstract type AbstractStdShape{T} end ##### # StdPoint ##### struct StdPoint{T} <: AbstractStdShape{T} end ##### # StdLine ##### struct StdLine{T} <: AbstractStdShape{T} half_length::T end get_half_length(line::StdLine) = line.half_length # head, tail, and vertices for StdLine get_head(line::StdLine{T}) where {T} = SA.SVector(get_half_length(line), zero(T)) get_tail(line::StdLine{T}) where {T} = SA.SVector(-get_half_length(line), zero(T)) get_vertices(line::StdLine) = (get_tail(line), get_head(line)) # head, tail, and vertices for StdLine at arbitrary position get_head(line::StdLine{T}, pos::SA.SVector{2, T}) where {T} = pos + get_head(line) get_tail(line::StdLine{T}, pos::SA.SVector{2, T}) where {T} = pos + get_tail(line) get_vertices(line::StdLine{T}, pos::SA.SVector{2, T}) where {T} = (get_tail(line, pos), get_head(line, pos)) # head, tail, and vertices for StdLine at arbitrary position and orientation get_head(line::StdLine{T}, pos::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T} = pos + get_half_length(line) * dir get_tail(line::StdLine{T}, pos::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T} = pos - get_half_length(line) * dir get_vertices(line::StdLine{T}, pos::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T} = (get_tail(line, pos, dir), get_head(line, pos, dir)) ##### # StdCircle ##### struct StdCircle{T} <: AbstractStdShape{T} radius::T end get_radius(circle::StdCircle) = circle.radius function get_area(circle::StdCircle{T}) where {T} radius = get_radius(circle) return convert(T, pi * radius * radius) end ##### # StdRect ##### struct StdRect{T} <: AbstractStdShape{T} half_width::T half_height::T end get_half_width(rect::StdRect) = rect.half_width get_half_height(rect::StdRect) = rect.half_height get_width(rect::StdRect) = 2 * get_half_width(rect) get_height(rect::StdRect) = 2 * get_half_height(rect) # bottom_left, bottom_right, top_left, top_right, and vertices for StdRect get_bottom_left(rect::StdRect) = SA.SVector(-get_half_width(rect), -get_half_height(rect)) get_bottom_right(rect::StdRect) = SA.SVector(get_half_width(rect), -get_half_height(rect)) get_top_right(rect::StdRect) = SA.SVector(get_half_width(rect), get_half_height(rect)) get_top_left(rect::StdRect) = SA.SVector(-get_half_width(rect), get_half_height(rect)) get_vertices(rect::StdRect{T}) where {T} = (get_bottom_left(rect), get_bottom_right(rect), get_top_right(rect), get_top_left(rect)) # bottom_left, bottom_right, top_left, top_right, and vertices for StdRect at arbitrary position get_bottom_left(rect::StdRect{T}, pos::SA.SVector{2, T}) where {T} = pos + SA.SVector(-get_half_width(rect), -get_half_height(rect)) get_bottom_right(rect::StdRect{T}, pos::SA.SVector{2, T}) where {T} = pos + SA.SVector(get_half_width(rect), -get_half_height(rect)) get_top_right(rect::StdRect{T}, pos::SA.SVector{2, T}) where {T} = pos + SA.SVector(get_half_width(rect), get_half_height(rect)) get_top_left(rect::StdRect{T}, pos::SA.SVector{2, T}) where {T} = pos + SA.SVector(-get_half_width(rect), get_half_height(rect)) get_vertices(rect::StdRect{T}, pos::SA.SVector{2, T}) where {T} = (get_bottom_left(rect, pos), get_bottom_right(rect, pos), get_top_right(rect, pos), get_top_left(rect, pos)) # bottom_left, bottom_right, top_left, top_right, and vertices for StdRect at arbitrary position and orientation get_bottom_left(rect::StdRect{T}, pos::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T} = pos - get_half_width(rect) * dir - get_half_height(rect) * rotate_plus_90(dir) get_bottom_right(rect::StdRect{T}, pos::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T} = pos + get_half_width(rect) * dir - get_half_height(rect) * rotate_plus_90(dir) get_top_right(rect::StdRect{T}, pos::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T} = pos + get_half_width(rect) * dir + get_half_height(rect) * rotate_plus_90(dir) get_top_left(rect::StdRect{T}, pos::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T} = pos - get_half_width(rect) * dir + get_half_height(rect) * rotate_plus_90(dir) get_vertices(rect::StdRect{T}, pos::SA.SVector{2, T}, dir::SA.SVector{2, T}) where {T} = (get_bottom_left(rect, pos, dir), get_bottom_right(rect, pos, dir), get_top_right(rect, pos, dir), get_top_left(rect, pos, dir)) get_area(rect::StdRect{T}) where {T} = convert(T, 4 * get_half_width(rect) * get_half_height(rect)) get_normals(rect::StdRect{T}) where {T} = get_normals(rect, SA.SVector(one(T), zero(T))) function get_normals(rect::StdRect{T}, dir::SA.SVector{2, T}) where {T} x_cap = dir y_cap = rotate_plus_90(dir) return (-y_cap, x_cap, y_cap, -x_cap) end
using RasterShadow using Test using JLD @testset "basic input" begin flat = ones(20,10) flat_sh = shadowing(flat,45,45,1) @test size(flat_sh) == size(flat) @test flat_sh == ones(20,10) end testdata = JLD.load(joinpath(@__DIR__,"testdata","testdata.jld")) dem = testdata["dem"] @testset "shadowing" begin @test testdata["sh_30_30"] == shadowing(dem,30,30,0.5) @test testdata["sh_150_80"] == shadowing(dem,150,80,0.5) @test testdata["sh_150_80"] == shadowing(dem,150,80,0.5) end
# -*- encoding: utf-8 -*- # # The MIT License (MIT) # # Copyright © 2021 Matteo Foglieni and Riccardo Gervasoni # """ Scene( materials::Dict{String, Material} = Dict{String, Material}(), world::World = World(), camera::Union{Camera, Nothing} = nothing, float_variables::Dict{String, Float64} = Dict{String, Float64}(), string_variables::Dict{String, String} = Dict{String, String}(), bool_variables::Dict{String, Bool} = Dict{String, Bool}(), vector_variables::Dict{String,Vec} = Dict{String,Vec}(), color_variables::Dict{String,RGB{Float32}} = Dict{String,RGB{Float32}}(), pigment_variables::Dict{String,Pigment} = Dict{String,Pigment}(), brdf_variables::Dict{String,BRDF} = Dict{String,BRDF}(), transformation_variables::Dict{String,Transformation} = Dict{String,Transformation}(), variable_names::Set{String} = Set{String}(), overridden_variables::Set{String} = Set{String}(), ) A scene read from a scene file. See also: [`Material`](@ref), [`World`](@ref), [`Camera`](@ref), [`Vec`](@ref), [`Pigment`](@ref), [`BRDF`](@ref), [`Transformation`](@ref) """ mutable struct Scene materials::Dict{String, Material} world::World camera::Union{Camera, Nothing} float_variables::Dict{String, Float64} string_variables::Dict{String, String} bool_variables::Dict{String,Bool} vector_variables::Dict{String,Vec} color_variables::Dict{String,RGB{Float32}} pigment_variables::Dict{String,Pigment} brdf_variables::Dict{String,BRDF} transformation_variables::Dict{String,Transformation} variable_names::Set{String} overridden_variables::Set{String} Scene( materials::Dict{String, Material} = Dict{String, Material}(), world::World = World(), camera::Union{Camera, Nothing} = nothing, float_variables::Dict{String, Float64} = Dict{String, Float64}(), string_variables::Dict{String, String} = Dict{String, String}(), bool_variables::Dict{String, Bool} = Dict{String, Bool}(), vector_variables::Dict{String,Vec} = Dict{String,Vec}(), color_variables::Dict{String,RGB{Float32}} = Dict{String,RGB{Float32}}(), pigment_variables::Dict{String,Pigment} = Dict{String,Pigment}(), brdf_variables::Dict{String,BRDF} = Dict{String,BRDF}(), transformation_variables::Dict{String,Transformation} = Dict{String,Transformation}(), variable_names::Set{String} = Set{String}(), overridden_variables::Set{String} = Set{String}(), ) = new( materials, world, camera, float_variables, string_variables, bool_variables, vector_variables, color_variables, pigment_variables, brdf_variables, transformation_variables, variable_names, overridden_variables, ) end ##########################################################################################92 function expect_symbol(inputstream::InputStream, symbol::String) token = read_token(inputstream) if (typeof(token.value) ≠ SymbolToken) || (token.value.symbol ≠ symbol) throw(GrammarError(token.location, "got $(token) insted of $(symbol)")) end end function expect_symbol(inputstream::InputStream, vec_symbol::Vector{String}) token = read_token(inputstream) if (typeof(token.value) ≠ SymbolToken) || (token.value.symbol ∉ vec_symbol) throw(GrammarError(token.location, "got $(token) instead of $(vec_symbol)")) end return token.value.symbol end """ expect_symbol(inputstream::InputStream, symbol::String) expect_symbol(inputstream::InputStream, vec_symbol::Vector{String}) :: String Read a token from `inputstream` and check that its type is `SymbolToken` and its value is `symbol`(first method) or a value inside `vec_symbol` (second method, and return it), throwing `GrammarError` otherwise. Call internally [`read_token`](@ref). See also: [`InputStream`](@ref), [`KeywordEnum`](@ref), [`SymbolToken`](@ref) """ expect_symbol """ expect_keywords(inputstream::InputStream, keywords::Vector{KeywordEnum}) :: KeywordEnum Read a token from `inputstream` and check that its type is `KeywordToken` and its value is one of the keywords in `keywords`, throwing `GrammarError` otherwise. Call internally [`read_token`](@ref). See also: [`InputStream`](@ref), [`KeywordEnum`](@ref), [`KeywordToken`](@ref) """ function expect_keywords(inputstream::InputStream, keywords::Vector{KeywordEnum}) token = read_token(inputstream) if typeof(token.value) ≠ KeywordToken throw(GrammarError(token.location, "expected a keyword instead of '$(token)' ")) end if token.value.keyword ∉ keywords throw(GrammarError( token.location, "expected one of the keywords $([x for x in keywords]) instead of '$(token)'" )) end return token.value.keyword end """ expect_number(inputstream::InputStream, scene::Scene) :: Float64 Read a token from `inputstream` and check that its type is `LiteralNumberToken` (i.e. a number) or `IdentifierToken` (i.e. a variable defined in `scene`), throwing `GrammarError` otherwise. Return the float64-parsed number or the identifier associated float64-parsed number, respectively. Call internally [`read_token`](@ref). See also: [`InputStream`](@ref), [`Scene`](@ref), [`LiteralNumberToken`](@ref), [`IdentifierToken`](@ref) """ function expect_number(inputstream::InputStream, scene::Scene, open::Bool=false) token = read_token(inputstream) result = "" if typeof(token.value) == SymbolToken && token.value.symbol == "(" result *= "("*expect_number(inputstream, scene, true) expect_symbol(inputstream, ")") result *= ")" token = read_token(inputstream) end if typeof(token.value) == SymbolToken && token.value.symbol == "-" result *= "-" token = read_token(inputstream) end while true if (typeof(token.value) == SymbolToken) && (token.value.symbol ∈ OPERATIONS) result *= token.value.symbol elseif (typeof(token.value) == IdentifierToken) && (token.value.identifier ∈ keys(SYM_NUM)) result *= string(SYM_NUM[token.value.identifier]) elseif typeof(token.value) == IdentifierToken variable_name = token.value.identifier if (variable_name ∈ keys(scene.float_variables) ) next_number = scene.float_variables[variable_name] result *= repr(next_number) elseif isdefined(Raytracing, Symbol(variable_name)) || isdefined(Base, Symbol(variable_name)) unread_token(inputstream, token) result *= parse_function(inputstream, scene) else throw(GrammarError(token.location, "unknown variable '$(token)'")) end elseif typeof(token.value) == LiteralNumberToken result *= repr(token.value.number) elseif (typeof(token.value) == SymbolToken) && (token.value.symbol=="(") result *= "("*expect_number(inputstream, scene, true) expect_symbol(inputstream, ")") result *= ")" else unread_token(inputstream, token) break end #= elseif (typeof(token.value) == SymbolToken) && (token.value.symbol==")") unread_token(inputstream, token) break else throw(GrammarError(token.location, "unknown variable '$(token)'")) end =# token = read_token(inputstream) end if open == true return result else return eval(Meta.parse(result)) end end """ expect_bool(inputstream::InputStream, scene::Scene) :: Bool Read a token from `inputstream` and check that its type is `KeywordToken` or `IdentifierToken` (i.e. a variable defined in `scene`), throwing `GrammarError` otherwise. Return the parsed bool or the identifier associated parsed bool, respectively. Call internally [`read_token`](@ref). See also: [`InputStream`](@ref), [`Scene`](@ref), [`KeywordToken`](@ref), [`IdentifierToken`](@ref) """ function expect_bool(inputstream::InputStream, scene::Scene) token = read_token(inputstream) if typeof(token.value) == KeywordToken unread_token(inputstream, token) keyword = expect_keywords(inputstream, [ TRUE, FALSE]) if keyword == TRUE return true elseif keyword == FALSE return false else throw(ArgumentError("how did you come here?")) end elseif typeof(token.value) == IdentifierToken variable_name = token.value.identifier (variable_name ∈ keys(scene.bool_variables) ) || throw(GrammarError(token.location, "unknown bool variable '$(token)'")) return scene.bool_variables[variable_name] else throw(GrammarError(token.location, "got '$(token)' instead of a bool variable")) end end """ expect_string(inputstream::InputStream, scene::Scene) :: String Read a token from `inputstream` and check that its type is `StringToken`, throwing `GrammarError` otherwise. Return the string associated with the readed `StringToken`. Call internally [`read_token`](@ref). See also: [`InputStream`](@ref), [`Scene`](@ref), [`StringToken`](@ref), """ function expect_string(inputstream::InputStream, scene::Scene) token = read_token(inputstream) if typeof(token.value) == StringToken return token.value.string elseif typeof(token.value) == IdentifierToken variable_name = token.value.identifier if variable_name ∉ keys(scene.string_variables) throw(GrammarError(token.location, "unknown string variable '$(token)'")) end return scene.string_variables[variable_name] else throw(GrammarError(token.location, "got $(token) instead of a string")) end end """ expect_identifier(inputstream::InputStream) :: String Read a token from `inputstream` and check that it is an identifier. Return the name of the identifier. Read a token from `inputstream` and check that its type is `IdentifierToken`, throwing `GrammarError` otherwise. Return the name of the identifier as a `String`. Call internally [`read_token`](@ref). See also: [`InputStream`](@ref), [`Scene`](@ref), [`IdentifierToken`](@ref), """ function expect_identifier(inputstream::InputStream) token = read_token(inputstream) if (typeof(token.value) ≠ IdentifierToken) throw(GrammarError(token.location, "got $(token) instead of an identifier")) end return token.value.identifier end ##########################################################################################92 """ parse_vector(inputstream::InputStream, scene::Scene) :: Vec Parse a vector from the given `inputstream` and return it. Call internally [`expect_number`](@ref) and [`expect_symbol`](@ref). See also: [`InputStream`](@ref), [`Scene`](@ref), [`Vec`](@ref) """ function parse_vector(inputstream::InputStream, scene::Scene, open::Bool=false) token = read_token(inputstream) result = "" if typeof(token.value) == SymbolToken && token.value.symbol == "(" result *= "("*parse_vector(inputstream, scene, true) expect_symbol(inputstream, ")") result *= ")" token = read_token(inputstream) end if typeof(token.value) == SymbolToken && token.value.symbol == "-" result *= "-" token = read_token(inputstream) end while true if (typeof(token.value) == SymbolToken) && (token.value.symbol ∈ OPERATIONS) result *= token.value.symbol elseif (typeof(token.value) == IdentifierToken) && (token.value.identifier ∈ keys(SYM_NUM)) result *= string(SYM_NUM[token.value.identifier]) elseif typeof(token.value) == IdentifierToken variable_name = token.value.identifier if (variable_name ∈ keys(scene.vector_variables) ) next_vector = scene.vector_variables[variable_name] result *= repr(next_vector) elseif (variable_name ∈ keys(scene.float_variables) ) next_number = scene.float_variables[variable_name] result *= repr(next_number) elseif isdefined(Raytracing, Symbol(variable_name)) || isdefined(Base, Symbol(variable_name)) unread_token(inputstream, token) result *= parse_function(inputstream, scene) else throw(GrammarError(token.location, "unknown float/vector variable '$(token)'")) end elseif typeof(token.value) == SymbolToken && token.value.symbol =="[" unread_token(inputstream, token) expect_symbol(inputstream, "[") x = expect_number(inputstream, scene) expect_symbol(inputstream, ",") y = expect_number(inputstream, scene) expect_symbol(inputstream, ",") z = expect_number(inputstream, scene) expect_symbol(inputstream, "]") result*= repr(Vec(x, y, z)) elseif (typeof(token.value) == SymbolToken) && (token.value.symbol=="(") result *= "("*parse_vector(inputstream, scene, true) expect_symbol(inputstream, ")") result *= ")" elseif typeof(token.value) == LiteralNumberToken result *= repr(token.value.number) else unread_token(inputstream, token) break end #= elseif (typeof(token.value) == SymbolToken) && (token.value.symbol==")") unread_token(inputstream, token) break else throw(GrammarError(token.location, "unknown variable '$(token)'")) end =# token = read_token(inputstream) end if open == true return result else return eval(Meta.parse(result)) end end #= function parse_vector(inputstream::InputStream, scene::Scene) token = read_token(inputstream) if typeof(token.value) == SymbolToken unread_token(inputstream, token) expect_symbol(inputstream, "[") x = expect_number(inputstream, scene) expect_symbol(inputstream, ",") y = expect_number(inputstream, scene) expect_symbol(inputstream, ",") z = expect_number(inputstream, scene) expect_symbol(inputstream, "]") return Vec(x, y, z) elseif typeof(token.value) == IdentifierToken variable_name = token.value.identifier if variable_name ∉ keys(scene.vector_variables) throw(GrammarError(token.location, "unknown variable '$(token)'")) end return scene.vector_variables[variable_name] end end =# """ parse_color(inputstream::InputStream, scene::Scene) :: RGB{Float32} Read the color from the given `inputstream` and return it. Call internally ['expect_symbol'](@ref) and ['expect_number'](@ref). See also: ['InputStream'](@ref), ['Scene'](@ref) """ function parse_color(inputstream::InputStream, scene::Scene, open::Bool=false) token = read_token(inputstream) result = "" if typeof(token.value) == SymbolToken && token.value.symbol == "(" result *= "("*parse_vector(inputstream, scene, true) expect_symbol(inputstream, ")") result *= ")" token = read_token(inputstream) end if typeof(token.value) == SymbolToken && token.value.symbol == "-" result *= "-" token = read_token(inputstream) end while true if (typeof(token.value) == SymbolToken) && (token.value.symbol ∈ OPERATIONS) result *= token.value.symbol elseif (typeof(token.value) == IdentifierToken) && (token.value.identifier ∈ keys(SYM_NUM)) result *= string(SYM_NUM[token.value.identifier]) elseif typeof(token.value) == IdentifierToken variable_name = token.value.identifier if (variable_name ∈ keys(scene.color_variables) ) next_color = scene.color_variables[variable_name] result *= repr(next_color) elseif (variable_name ∈ keys(scene.float_variables) ) next_number = scene.float_variables[variable_name] result *= repr(next_number) elseif isdefined(Raytracing, Symbol(variable_name)) || isdefined(Base, Symbol(variable_name)) unread_token(inputstream, token) result *= parse_function(inputstream, scene) else throw(GrammarError(token.location, "unknown float/color variable '$(token)'")) end elseif typeof(token.value) == SymbolToken && token.value.symbol =="<" unread_token(inputstream, token) expect_symbol(inputstream, "<") x = expect_number(inputstream, scene) expect_symbol(inputstream, ",") y = expect_number(inputstream, scene) expect_symbol(inputstream, ",") z = expect_number(inputstream, scene) expect_symbol(inputstream, ">") result*= repr(RGB{Float32}(x, y, z)) elseif (typeof(token.value) == SymbolToken) && (token.value.symbol=="(") result *= "("*parse_color(inputstream, scene, true) expect_symbol(inputstream, ")") result *= ")" elseif typeof(token.value) == LiteralNumberToken result *= repr(token.value.number) else unread_token(inputstream, token) break end #= elseif (typeof(token.value) == SymbolToken) && (token.value.symbol==")") unread_token(inputstream, token) break else throw(GrammarError(token.location, "unknown variable '$(token)'")) end =# token = read_token(inputstream) end if open == true return result else return eval(Meta.parse(result)) end end #= function parse_color(inputstream::InputStream, scene::Scene) token = read_token(inputstream) if typeof(token.value) == SymbolToken unread_token(inputstream, token) expect_symbol(inputstream, "<") red = expect_number(inputstream, scene) expect_symbol(inputstream, ",") green = expect_number(inputstream, scene) expect_symbol(inputstream, ",") blue = expect_number(inputstream, scene) expect_symbol(inputstream, ">") return RGB{Float32}(red, green, blue) elseif typeof(token.value) == IdentifierToken variable_name = token.value.identifier if variable_name ∉ keys(scene.color_variables) throw(GrammarError(token.location, "unknown variable '$(token)'")) end return scene.color_variables[variable_name] end end =# """ parse_pigment(inputstream::InputStream, scene::Scene) :: Pigment Parse a pigment from the given `inputstream` and return it. Call internally the following parsing functions: - [`expect_keywords`](@ref) - [`expect_symbol`](@ref) - [`parse_color`](@ref) - [`expect_number`](@ref) - [`expect_string`](@ref) Call internally the following functions and structs of the program: - [`UniformPigment`](@ref) - [`CheckeredPigment`](@ref) - [`ImagePigment`](@ref) - [`load_image`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`Pigment`](@ref) """ function parse_pigment(inputstream::InputStream, scene::Scene) token = read_token(inputstream) if typeof(token.value) == IdentifierToken variable_name = token.value.identifier if variable_name ∉ keys(scene.pigment_variables) throw(GrammarError(token.location, "unknown pigment '$(token)'")) end return scene.pigment_variables[variable_name] else unread_token(inputstream, token) end keyword = expect_keywords(inputstream, [ UNIFORM, CHECKERED, IMAGE]) expect_symbol(inputstream, "(") if keyword == UNIFORM color = parse_color(inputstream, scene) result = UniformPigment(color) elseif keyword == CHECKERED color1 = parse_color(inputstream, scene) expect_symbol(inputstream, ",") color2 = parse_color(inputstream, scene) expect_symbol(inputstream, ",") num_of_steps = Int(expect_number(inputstream, scene)) result = CheckeredPigment(color1, color2, num_of_steps) elseif keyword == IMAGE file_name = expect_string(inputstream, scene) image = open(file_name, "r") do image_file; load_image(image_file); end result = ImagePigment(image) else @assert false "This line should be unreachable" end expect_symbol(inputstream, ")") return result end """ parse_brdf(inputstream::InputStream, scene::Scene) :: BRDF Parse a BRDF from the given `inputstream` and return it. Call internally the following parsing functions: - [`expect_keywords`](@ref) - [`expect_symbol`](@ref) - [`parse_pigment`](@ref) Call internally the following functions and structs of the program: - [`DiffuseBRDF`](@ref) - [`SpecularBRDF`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`BRDF`](@ref) """ function parse_brdf(inputstream::InputStream, scene::Scene) token = read_token(inputstream) if typeof(token.value) == IdentifierToken variable_name = token.value.identifier if variable_name ∉ keys(scene.brdf_variables) throw(GrammarError(token.location, "unknown BRDF '$(token)'")) end return scene.brdf_variables[variable_name] else unread_token(inputstream, token) end brdf_keyword = expect_keywords(inputstream, [ DIFFUSE, SPECULAR]) expect_symbol(inputstream, "(") pigment = parse_pigment(inputstream, scene) expect_symbol(inputstream, ")") if (brdf_keyword == DIFFUSE) return DiffuseBRDF(pigment) elseif (brdf_keyword == SPECULAR) return SpecularBRDF(pigment) else @assert false "This line should be unreachable" end end """ parse_material(inputstream::InputStream, scene::Scene) :: (String, Material) Parse a Material from the given `inputstream` and return a tuple with the identifier name of the material and the material itself. Call internally the following parsing functions: - [`expect_identifier`](@ref) - [`expect_symbol`](@ref) - [`parse_brdf`](@ref) - [`parse_pigment`](@ref) Call internally the following functions and structs of the program: - [`Material`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`Token`](@ref), [`Material`](@ref) """ function parse_material(inputstream::InputStream, scene::Scene) name = expect_identifier(inputstream) expect_symbol(inputstream, "(") brdf = parse_brdf(inputstream, scene) expect_symbol(inputstream, ",") emitted_radiance = parse_pigment(inputstream, scene) expect_symbol(inputstream, ")") return name, Material(brdf, emitted_radiance) end """ parse_transformation(inputstream::InputStream, scene::Scene) :: Transformation Parse a Transformation from the given `inputstream` and return it. Call internally the following parsing functions: - [`expect_keywords`](@ref) - [`expect_symbol`](@ref) - [`expect_number`](@ref) - [`parse_vector`](@ref) - [`read_token`](@ref) - [`unread_token`](@ref) Call internally the following functions and structs of the program: - [`translation`](@ref) - [`rotation_x`](@ref) - [`rotation_y`](@ref) - [`rotation_z`](@ref) - [`scaling`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`Transformation`](@ref) """ function parse_transformation(inputstream::InputStream, scene::Scene) token = read_token(inputstream) if typeof(token.value) == IdentifierToken variable_name = token.value.identifier if variable_name ∉ keys(scene.transformation_variables) throw(GrammarError(token.location, "unknown pigment '$(token)'")) end return scene.transformation_variables[variable_name] else unread_token(inputstream, token) end result = Transformation() while true transformation_kw = expect_keywords(inputstream, [ IDENTITY, TRANSLATION, ROTATION_X, ROTATION_Y, ROTATION_Z, SCALING, ]) if transformation_kw == IDENTITY nothing # Do nothing (this is a primitive form of optimization!) elseif transformation_kw == TRANSLATION expect_symbol(inputstream, "(") result *= translation(parse_vector(inputstream, scene)) expect_symbol(inputstream, ")") elseif transformation_kw == ROTATION_X expect_symbol(inputstream, "(") result *= rotation_x(expect_number(inputstream, scene)) expect_symbol(inputstream, ")") elseif transformation_kw == ROTATION_Y expect_symbol(inputstream, "(") result *= rotation_y(expect_number(inputstream, scene)) expect_symbol(inputstream, ")") elseif transformation_kw == ROTATION_Z expect_symbol(inputstream, "(") result *= rotation_z(expect_number(inputstream, scene)) expect_symbol(inputstream, ")") elseif transformation_kw == SCALING expect_symbol(inputstream, "(") result *= scaling(parse_vector(inputstream, scene)) expect_symbol(inputstream, ")") end # We must peek the next token to check if there is another transformation that is being # chained or if the sequence ends. Thus, this is a LL(1) parser. next_kw = read_token(inputstream) if (typeof(next_kw.value) ≠ SymbolToken) || (next_kw.value.symbol ≠ "*") # Pretend you never read this token and put it back! unread_token(inputstream, next_kw) break end end return result end """ parse_camera(inputstream::InputStream, scene::Scene) :: Camera Parse a Camera from the given `inputstream` and return it. Call internally the following parsing functions: - [`expect_symbol`](@ref) - [`expect_keywords`](@ref) - [`expect_number`](@ref) - [`parse_transformation`](@ref) Call internally the following functions and structs of the program: - [`OrthogonalCamera`](@ref) - [`PerspectiveCamera`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`Camera`](@ref) """ function parse_camera(inputstream::InputStream, scene::Scene) expect_symbol(inputstream, "(") type_kw = expect_keywords(inputstream, [ PERSPECTIVE, ORTHOGONAL]) expect_symbol(inputstream, ",") transformation = parse_transformation(inputstream, scene) if type_kw == PERSPECTIVE expect_symbol(inputstream, ",") distance = expect_number(inputstream, scene) expect_symbol(inputstream, ")") result = PerspectiveCamera(distance, 1.0, transformation) elseif type_kw == ORTHOGONAL expect_symbol(inputstream, ")") result = OrthogonalCamera(1.0, transformation) end return result end ##########################################################################################92 """ parse_pointlight(inputstream::InputStream, scene::Scene) :: PointLight Parse a PointLight from the given `inputstream` and return it. Call internally the following parsing functions: - [`read_token`](@ref) - [`unread_token`](@ref) - [`expect_number`](@ref) - [`expect_symbol`](@ref) - [`parse_vector`](@ref) - [`parse_color`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`PointLight`](@ref) """ function parse_pointlight(inputstream::InputStream, scene::Scene) expect_symbol(inputstream, "(") point = parse_vector(inputstream, scene) expect_symbol(inputstream, ",") color = parse_color(inputstream, scene) token = read_token(inputstream) if typeof(token.value) == SymbolToken && token.value.symbol == "," unread_token(inputstream, token) expect_symbol(inputstream, ",") linear_radius = expect_number(inputstream, scene) else unread_token(inputstream, token) linear_radius = 0.0 end expect_symbol(inputstream, ")") return PointLight( Point(point.x, point.y, point.z), color, linear_radius, ) end """ parse_sphere(inputstream::InputStream, scene::Scene) :: Sphere Parse a Sphere from the given `inputstream` and return it. Throws `GrammarError` if the specified `Material` does not exist. Call internally the following parsing functions: - [`expect_symbol`](@ref) - [`expect_identifier`](@ref) - [`parse_transformation`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`Sphere`](@ref) [`Material`](@ref) """ function parse_sphere(inputstream::InputStream, scene::Scene) expect_symbol(inputstream, "(") material_name = expect_identifier(inputstream) if material_name ∉ keys(scene.materials) # We raise the exception here because inputstream is pointing to the end of the wrong identifier throw(GrammarError(inputstream.location, "unknown material $(material_name)")) end expect_symbol(inputstream, ",") transformation = parse_transformation(inputstream, scene) token = read_token(inputstream) if typeof(token.value) == SymbolToken && token.value.symbol == "," unread_token(inputstream, token) expect_symbol(inputstream, ",") flag_pointlight = expect_bool(inputstream, scene) expect_symbol(inputstream, ",") flag_background = expect_bool(inputstream, scene) expect_symbol(inputstream, ")") else unread_token(inputstream, token) expect_symbol(inputstream, ")") flag_pointlight = false flag_background = false end return Sphere(transformation, scene.materials[material_name], flag_pointlight, flag_background) end """ parse_plane(inputstream::InputStream, scene::Scene) :: Plane Parse a Plane from the given `inputstream` and return it. Throws `GrammarError` if the specified `Material` does not exist. Call internally the following parsing functions: - [`expect_symbol`](@ref) - [`expect_identifier`](@ref) - [`parse_transformation`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`Plane`](@ref), [`Material`](@ref) """ function parse_plane(inputstream::InputStream, scene::Scene) expect_symbol(inputstream, "(") material_name = expect_identifier(inputstream) if material_name ∉ keys(scene.materials) # We raise the exception here because inputstream is pointing to the end of the wrong identifier throw(GrammarError(inputstream.location, "unknown material $(material_name)")) end expect_symbol(inputstream, ",") transformation = parse_transformation(inputstream, scene) token = read_token(inputstream) if typeof(token.value) == SymbolToken && token.value.symbol == "," unread_token(inputstream, token) expect_symbol(inputstream, ",") flag_pointlight = expect_bool(inputstream, scene) expect_symbol(inputstream, ",") flag_background = expect_bool(inputstream, scene) expect_symbol(inputstream, ")") else unread_token(inputstream, token) expect_symbol(inputstream, ")") flag_pointlight = false flag_background = false end return Plane(transformation, scene.materials[material_name], flag_pointlight, flag_background) end """ parse_cube(inputstream::InputStream, scene::Scene) :: Cube Parse a Cube from the given `inputstream` and return it. Throws `GrammarError` if the specified `Material` does not exist. Call internally the following parsing functions: - [`expect_symbol`](@ref) - [`expect_identifier`](@ref) - [`parse_transformation`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`Cube`](@ref) [`Material`](@ref) """ function parse_cube(inputstream::InputStream, scene::Scene) expect_symbol(inputstream, "(") material_name = expect_identifier(inputstream) if material_name ∉ keys(scene.materials) # We raise the exception here because inputstream is pointing to the end of the wrong identifier throw(GrammarError(inputstream.location, "unknown material $(material_name)")) end expect_symbol(inputstream, ",") transformation = parse_transformation(inputstream, scene) token = read_token(inputstream) if typeof(token.value) == SymbolToken && token.value.symbol == "," unread_token(inputstream, token) expect_symbol(inputstream, ",") flag_pointlight = expect_bool(inputstream, scene) expect_symbol(inputstream, ",") flag_background = expect_bool(inputstream, scene) expect_symbol(inputstream, ")") else unread_token(inputstream, token) expect_symbol(inputstream, ")") flag_pointlight = false flag_background = false end return Cube(transformation, scene.materials[material_name], flag_pointlight, flag_background) end """ parse_triangle(inputstream::InputStream, scene::Scene) :: Triangle Parse a Triangle from the given `inputstream` and return it. Throws `GrammarError` if the specified `Material` does not exist. Call internally the following parsing functions: - [`expect_symbol`](@ref) - [`expect_identifier`](@ref) - [`parse_transformation`](@ref) See also: [`InputStream`](@ref), [`Scene`](@ref), [`Triangle`](@ref) [`Material`](@ref) """ function parse_triangle(inputstream::InputStream, scene::Scene) expect_symbol(inputstream, "(") material_name = expect_identifier(inputstream) if material_name ∉ keys(scene.materials) # We raise the exception here because inputstream is pointing to the end of the wrong identifier throw(GrammarError(inputstream.location, "unknown material $(material_name)")) end expect_symbol(inputstream, ",") p1 = parse_vector(inputstream, scene) expect_symbol(inputstream, ",") p2 = parse_vector(inputstream, scene) expect_symbol(inputstream, ",") p3 = parse_vector(inputstream, scene) token = read_token(inputstream) if typeof(token.value) == SymbolToken && token.value.symbol == "," unread_token(inputstream, token) expect_symbol(inputstream, ",") flag_pointlight = expect_bool(inputstream, scene) expect_symbol(inputstream, ",") flag_background = expect_bool(inputstream, scene) expect_symbol(inputstream, ")") else unread_token(inputstream, token) expect_symbol(inputstream, ")") flag_pointlight = false flag_background = false end return Triangle(p1, p2, p3, scene.materials[material_name], flag_pointlight, flag_background) end
struct SystemMatrix rows::Any cols::Any vals::Any function SystemMatrix(rows, cols, vals) @assert length(rows) == length(cols) == length(vals) new(rows, cols, vals) end end function SystemMatrix() rows = Int[] cols = Int[] vals = zeros(0) SystemMatrix(rows, cols, vals) end function Base.show(io::IO, sysmatrix::SystemMatrix) numvals = length(sysmatrix.rows) str = "SystemMatrix with $numvals entries" print(io, str) end function assemble!(matrix::SystemMatrix, rows, cols, vals) @assert length(rows) == length(cols) == length(vals) append!(matrix.rows, rows) append!(matrix.cols, cols) append!(matrix.vals, vals) end struct SystemRHS rows::Any vals::Any function SystemRHS(rows, vals) @assert length(rows) == length(vals) new(rows, vals) end end function SystemRHS() SystemRHS(Int[], zeros(0)) end function Base.show(io::IO, sysrhs::SystemRHS) numvals = length(sysrhs.rows) str = "SystemRHS with $numvals entries" print(io, str) end function assemble!(systemrhs::SystemRHS, rows, vals) @assert length(rows) == length(vals) append!(systemrhs.rows, rows) append!(systemrhs.vals, vals) end function node_to_dof_id(nodeid, dof, dofspernode) return (nodeid - 1) * dofspernode + dof end function element_dofs(nodeids, dofspernode) numnodes = length(nodeids) extnodeids = repeat(nodeids, inner = dofspernode) dofs = repeat(1:dofspernode, numnodes) edofs = [node_to_dof_id(n, d, dofspernode) for (n, d) in zip(extnodeids, dofs)] return edofs end function element_dofs_to_operator_dofs(rowdofs, coldofs) nr = length(rowdofs) nc = length(coldofs) rows = repeat(rowdofs, outer = nc) cols = repeat(coldofs, inner = nr) return rows, cols end function assemble_couple_cell_matrix!(sysmatrix, nodeids1, nodeids2, dofspernode, vals) edofs1 = element_dofs(nodeids1, dofspernode) edofs2 = element_dofs(nodeids2, dofspernode) rows, cols = element_dofs_to_operator_dofs(edofs1, edofs2) assemble!(sysmatrix, rows, cols, vals) end function assemble_cell_matrix!(sysmatrix::SystemMatrix, nodeids, dofspernode, vals) edofs = element_dofs(nodeids, dofspernode) rows, cols = element_dofs_to_operator_dofs(edofs, edofs) assemble!(sysmatrix, rows, cols, vals) end function assemble_bilinear_form!( sysmatrix::SystemMatrix, cellmatrix, nodalconnectivity, dofspernode, ) ncells = size(nodalconnectivity)[2] vals = vec(cellmatrix) for cellid = 1:ncells nodeids = nodalconnectivity[:, cellid] assemble_cell_matrix!(sysmatrix, nodeids, dofspernode, vals) end end function assemble_bilinear_form!(sysmatrix::SystemMatrix, cellmatrix, mesh::Mesh) dofspernode = dimension(mesh) nodalconnectivity = nodal_connectivity(mesh) assemble_bilinear_form!(sysmatrix, cellmatrix, nodalconnectivity, dofspernode) end function assemble_cell_rhs!(sysrhs, nodeids, dofspernode, vals) rows = element_dofs(nodeids, dofspernode) assemble!(sysrhs, rows, vals) end function assemble_body_force_linear_form!( systemrhs, rhsfunc, basis, quad, cellmaps, nodalconnectivity, ) ncells = length(cellmaps) nf = number_of_basis_functions(basis) dim = dimension(basis) @assert size(nodalconnectivity) == (nf, ncells) for (idx, cellmap) in enumerate(cellmaps) rhs = linear_form(rhsfunc, basis, quad, cellmap) edofs = element_dofs(nodalconnectivity[:, idx], dim) assemble!(systemrhs, edofs, rhs) end end function assemble_body_force_linear_form!(systemrhs, rhsfunc, basis, quad, mesh::Mesh) cellmaps = cell_maps(mesh) nodalconnectivity = nodal_connectivity(mesh) assemble_body_force_linear_form!( systemrhs, rhsfunc, basis, quad, cellmaps, nodalconnectivity, ) end function assemble_traction_force_linear_form!( systemrhs, tractionfunc, basis, facequads, cellmaps, nodalconnectivity, cellconnectivity, istractionboundary, ) dim = dimension(basis) refmidpoints = reference_face_midpoints() isboundarycell = is_boundary_cell(cellconnectivity) cellids = findall(isboundarycell) facedetjac = face_determinant_jacobian(cellmaps[1]) for cellid in cellids cellmap = cellmaps[cellid] for (faceid, nbrcellid) in enumerate(cellconnectivity[:, cellid]) if nbrcellid == 0 if istractionboundary(cellmap(refmidpoints[faceid])) rhs = linear_form( tractionfunc, basis, facequads[faceid], cellmap, facedetjac[faceid], ) edofs = element_dofs(nodalconnectivity[:, cellid], dim) assemble!(systemrhs, edofs, rhs) end end end end end function assemble_traction_force_component_linear_form!( systemrhs, tractionfunc, basis, facequads, cellmaps, nodalconnectivity, cellconnectivity, istractionboundary, component, ) dim = dimension(basis) refmidpoints = reference_face_midpoints() isboundarycell = is_boundary_cell(cellconnectivity) cellids = findall(isboundarycell) facedetjac = face_determinant_jacobian(cellmaps[1]) for cellid in cellids cellmap = cellmaps[cellid] for (faceid, nbrcellid) in enumerate(cellconnectivity[:, cellid]) if nbrcellid == 0 if istractionboundary(cellmap(refmidpoints[faceid])) rhs = component_linear_form( tractionfunc, basis, facequads[faceid], component, cellmap, facedetjac[faceid], ) edofs = element_dofs(nodalconnectivity[:, cellid], dim) assemble!(systemrhs, edofs, rhs) end end end end end function assemble_stress_linear_form!( systemrhs, basis, quad, stiffness, nodaldisplacement, nodalconnectivity, jacobian, ) dim = dimension(basis) sdim = number_of_symmetric_degrees_of_freedom(dim) nf, ncells = size(nodalconnectivity) for cellid = 1:ncells nodeids = nodalconnectivity[:, cellid] elementdofs = element_dofs(nodeids, dim) celldisp = nodaldisplacement[elementdofs] rhs = stress_cell_rhs(basis, quad, stiffness, celldisp, jacobian) stressdofs = element_dofs(nodeids, sdim) assemble!(systemrhs, stressdofs, rhs) end end function make_sparse(sysmatrix::SystemMatrix, ndofs::Int) return dropzeros!(sparse(sysmatrix.rows, sysmatrix.cols, sysmatrix.vals, ndofs, ndofs)) end function make_sparse(sysmatrix::SystemMatrix, mesh) totaldofs = number_of_degrees_of_freedom(mesh) return make_sparse(sysmatrix, totaldofs) end function make_sparse_stress_operator(sysmatrix, mesh) dim = dimension(mesh) sdim = number_of_symmetric_degrees_of_freedom(dim) numnodes = number_of_nodes(mesh) totaldofs = sdim * numnodes return make_sparse(sysmatrix, totaldofs) end function rhs(sysrhs::SystemRHS, ndofs::Int) return Array(sparsevec(sysrhs.rows, sysrhs.vals, ndofs)) end function rhs(sysrhs::SystemRHS, mesh) totaldofs = number_of_degrees_of_freedom(mesh) return rhs(sysrhs, totaldofs) end function stress_rhs(sysrhs, mesh) dim = dimension(mesh) sdim = number_of_symmetric_degrees_of_freedom(dim) numnodes = number_of_nodes(mesh) totaldofs = sdim * numnodes return rhs(sysrhs, totaldofs) end
module GameDataManager using Printf using REPL.TerminalMenus using JSON, JSONPointer, JSONSchema using XLSXasJSON using OrderedCollections using PrettyTables export init_project, xl, xlookup include("abstractmeta.jl") include("config.jl") include("tables.jl") include("init.jl") include("setup.jl") include("exporter.jl") include("localizer.jl") include("schema.jl") include("show.jl") include("utils.jl") end # module
using Hooks using Test @testset "Hooks.jl" begin @testset "Basic Notification" begin run = false handle(hook"test") do run = true end notify(hook"test") @test run reset(hook"test") end @testset "Multiple handlers" begin run1 = false run2 = false handle(hook"test") do run1 = true end handle(hook"test") do run2 = true end notify(hook"test") @test run1 @test run2 reset(hook"test") end @testset "Hook Resetting" begin run1 = false run2 = false handle(hook"test") do run1 = true end handle(hook"test") do run2 = true end reset(hook"test") notify(hook"test") @test !run1 @test !run2 reset(hook"test") end @testset "Reverse order registration" begin run1 = false run2 = false notify(hook"foobar") handle(hook"foobar") do run1 = true end handle(hook"foobar") do run2 = true end @test run1 @test run2 reset(hook"foobar") end @testset "Deregistration" begin run1 = false run2 = false h1 = handle(hook"test") do run1 = true end h2 = handle(hook"test") do run2 = true end unhandle(h1, hook"test") notify(hook"test") @test !run1 @test run2 reset(hook"test") end @testset "Multiple Hooks" begin run1 = false run2 = false h1 = handle(hook"test1") do run1 = true end h2 = handle(hook"test2") do run2 = true end notify(hook"test1") notify(hook"test2") @test run1 @test run2 reset(hook"test1") reset(hook"test2") end @testset "Errors on resettinging nonexistent hook" begin @test_throws ErrorException reset(hook"does-not-exist") end @testset "Errors on unhandling nonexistent hook" begin @test_throws ErrorException unhandle(()->100, hook"does-not-exist") end @testset "Errors on unhandling nonexistent handler" begin handle(()->42, hook"test") @test_throws ErrorException unhandle(()->100, hook"test") reset(hook"test") end @testset "Duplicate Handlers are merged" begin called = 0 function duphandle() called += 1 end handle(duphandle, hook"test") handle(duphandle, hook"test") notify(hook"test") @test called == 1 reset(hook"test") end @testset "Handlers can take arguments" begin args1 = nothing args2 = nothing handle(hook"test") do x, y args1 = (x,y) end notify(hook"test", 100, 200) # also test the handlers get called when registered afterwards handle(hook"test") do x, y args2 = (x,y) end @test args1 == (100, 200) @test args2 == (100, 200) reset(hook"test") end end
# MIPLearn: Extensible Framework for Learning-Enhanced Mixed-Integer Optimization # Copyright (C) 2020-2021, UChicago Argonne, LLC. All rights reserved. # Released under the modified BSD license. See COPYING.md for more details. function init_miplearn_ext(model)::Dict if :miplearn ∉ keys(model.ext) model.ext[:miplearn] = Dict() model.ext[:miplearn]["instance_features"] = [0.0] model.ext[:miplearn]["variable_features"] = Dict{AbstractString,Vector{Float64}}() model.ext[:miplearn]["variable_categories"] = Dict{AbstractString,String}() model.ext[:miplearn]["constraint_features"] = Dict{AbstractString,Vector{Float64}}() model.ext[:miplearn]["constraint_categories"] = Dict{AbstractString,String}() end return model.ext[:miplearn] end function set_features!(m::Model, f::Array{Float64})::Nothing ext = init_miplearn_ext(m) ext["instance_features"] = f return end function set_features!(v::VariableRef, f::Array{Float64})::Nothing ext = init_miplearn_ext(v.model) n = _get_and_check_name(v) ext["variable_features"][n] = f return end function set_category!(v::VariableRef, category::String)::Nothing ext = init_miplearn_ext(v.model) n = _get_and_check_name(v) ext["variable_categories"][n] = category return end function set_features!(c::ConstraintRef, f::Array{Float64})::Nothing ext = init_miplearn_ext(c.model) n = _get_and_check_name(c) ext["constraint_features"][n] = f return end function set_category!(c::ConstraintRef, category::String)::Nothing ext = init_miplearn_ext(c.model) n = _get_and_check_name(c) ext["constraint_categories"][n] = category return end function set_lazy_callback!(model::Model, find_cb::Function, enforce_cb::Function)::Nothing ext = init_miplearn_ext(model) ext["lazy_find_cb"] = find_cb ext["lazy_enforce_cb"] = enforce_cb return end macro feature(obj, features) quote set_features!($(esc(obj)), $(esc(features))) end end macro category(obj, category) quote set_category!($(esc(obj)), $(esc(category))) end end macro lazycb(obj, find_cb, enforce_cb) quote set_lazy_callback!($(esc(obj)), $(esc(find_cb)), $(esc(enforce_cb))) end end function _get_and_check_name(obj) n = name(obj) length(n) > 0 || error( "Features and categories can only be assigned to variables and " * "constraints that have names. Unnamed model element detected.", ) return n end export @feature, @category, @lazycb
const tf = TensorFlow function _make_infeed_op(sess, eltypes, sizes, inputs; device=nothing, device_ordinal=0) desc = tf.NodeDescription(tf_graph(sess), "InfeedEnqueueTuple", tf.get_name("InfeedEnqueueTuple")) tf.set_attr_shape_list(desc, "shapes", Vector{Int64}[collect(x) for x in sizes]) tf.set_attr_list(desc, "dtypes", DataType[eltypes...]) desc["device_ordinal"] = device_ordinal tf.add_input(desc, inputs) if device !== nothing tf.set_device(desc, device) end eq = tf.Tensor(tf.Operation(desc)); eq end function make_infeed_op(sess, tup::NTuple{N, AbstractArray} where N; device=nothing, device_ordinal=0) placeholders = [tf.placeholder(eltype(el), shape=size(el)) for el in tup] eq = _make_infeed_op(sess, map(eltype, tup), map(size, tup), placeholders; device=device, device_ordinal=device_ordinal) feeds = Dict((x=>y for (x, y) in zip(placeholders, tup))...) eq, feeds end function make_outfeed_op(sess, tup::Type{<:NTuple}; device=nothing, device_ordinal=0) desc = tf.NodeDescription(tf_graph(sess), "OutfeedDequeueTuple", tf.get_name("OutfeedDequeueTuple")) tf.set_attr_shape_list(desc, "shapes", Vector{Int64}[collect(size(x)) for x in tup.parameters]) tf.set_attr_list(desc, "dtypes", DataType[eltype(x) for x in tup.parameters]) desc["device_ordinal"] = device_ordinal if device !== nothing tf.set_device(desc, device) end eq = tf.Tensor(tf.Operation(desc)); eq end function infeed(sess, tup::NTuple{N, AbstractArray} where N; device=nothing) eq, feeds = make_infeed_op(sess, tup; device=device) run(sess, eq, feeds) end function outfeed(sess, tup::Type{<:NTuple}; device=nothing) eq = make_outfeed_op(sess, tup; device=device) run(sess, eq) end function infeed_and_outfeed(sess, infeed_tup::NTuple{N, AbstractArray} where N, outfeed_tup::Type{<:NTuple}; device=nothing) eq_infeed, feeds = make_infeed_op(sess, infeed_tup; device=device) eq_outfeed = make_outfeed_op(sess, outfeed_tup; device=device) run(sess, [eq_infeed, eq_outfeed], feeds)[2] end
using Pkg; using Flux; using DifferentialEquations; using DiffEqSensitivity; using StochasticDiffEq; using Zygote; using LinearAlgebra; using Optim; using Plots; using Serialization; using PyCall; Pkg.activate("./"); Pkg.instantiate(); include("learningProb.jl"); include("mleLearning.jl"); include("postProcess.jl"); # for this test args will be ignored function generateFullTetradLearningProblem(args) #--------------------begin problem setup--------------------# vgtDataPath = "/groups/chertkov/data/tetradData/InertialRangeData/aij_1024_gaus8_tetrad.bin"; rhoDataPath = "/groups/chertkov/data/tetradData/InertialRangeData/roij_1024_gaus8_tetrad.bin"; py""" import numpy as np mij = np.fromfile(file=$vgtDataPath, dtype=float) mij = mij.reshape([32768, 1500, 3, 3]) roij = np.fromfile(file=$rhoDataPath, dtype=float) roij = roij.reshape([32768, 1500, 3, 3]) """ roij = PyArray(py"roij"o); mij = PyArray(py"mij"o); roij = reshape(roij, (32768, 1500, 9)); mij = reshape(mij, (32768, 1500, 9)); trainingData = cat(roij,mij,dims=3); trainingData = permutedims(trainingData, (3, 2, 1)); trainingData = trainingData[:,1:200,:]; #only look at first 200 timesteps initialConditions = trainingData[:,1,:]; #split into training/test validationData = trainingData[:,:,:]; trainingData = trainingData[:,:,:]; numDims, numSteps, numTrajs = size(trainingData); dt = 4e-4; tsteps = Array{Float64, 1}(range(0.0, step=dt, length=numSteps)); x,y = parseTrainingData(trainingData, dt); miniBatchSize = 1000; #see HyperParameterTuning for justification maxiters = 5000; #plateau's around 4k #optimizer = Flux.Optimise.Optimiser(ExpDecay(0.001, 0.5, 1000, 1e-7), ADAM(0.001)); optimizer = ADAM(0.01); # see https://fluxml.ai/Flux.jl/stable/training/optimisers/ hiddenDim = 80; θ_f, drift_nn = Flux.destructure(Chain(Dense(18,hiddenDim,tanh), Dense(hiddenDim,hiddenDim,tanh), Dense(hiddenDim,9))); function encode(u,p,args...) return u; end function decode(u,p,args...) return u; end function trueDrift(u,p,t) return nothing; end function truePrecisionMat(u,p,t) return nothing; end function trueDiff(u, p, t) return nothing; end function parameterizedDriftClosure(u,p) return drift_nn(p)(u); end function parameterizedPrecisionMat(u,p) matPiece = p[1:9]; biasPiece = p[10:end]; prescribedMat = (matPiece .* (u)).^2 + biasPiece; return prescribedMat; end driftLength = length(θ_f); diffLength = 0; driftStart = 1; if (driftLength > 0) driftEnd = driftStart + (driftLength-1); diffStart = driftEnd+1; else driftEnd = 0; diffStart = 1; end diffEnd = diffStart + (diffLength-1); function modelDrift(u,p,t) numSamples = size(u)[end]; ρ = [reshape(u[1:9,i], (3,3)) for i in 1:numSamples]; M = [reshape(u[10:18,i], (3,3)) for i in 1:numSamples]; closure = parameterizedDriftClosure(u,p); placeholder = [ reshape(-M[i]^2 + reshape(closure[:,i],(3,3)), 9) for i in 1:numSamples]; return hcat(placeholder...); end function fullSystemDrift(u,p,t) return modelDrift(u,p,t); end function createNoiseRateForcingHIT(D_a, D_s) c = zeros(3,3,3,3); delta(i,j) = (i==j) ? 1 : 0; for i in 1:3 for j in 1:3 for k in 1:3 for l in 1:3 term1 = -(1/3)*sqrt(D_s/5)*delta(i,j)*delta(k,l); term2 = (1/2)*(sqrt(D_s/5) + sqrt(D_a/3))*delta(i,k)*delta(j,l); term3 = (1/2)*(sqrt(D_s/5) - sqrt(D_a/3))*delta(i,l)*delta(j,k); c[i,j,k,l] = term1 + term2 + term3; end end end end return c; end c = reshape(createNoiseRateForcingHIT(15,15), (9,9)); function modelDiff(u,p,t) return [Matrix(I,9,9) zeros(9,9) zeros(9,9) c]; end #statically allocate for training driftGrad = zeros(driftLength); driftGradHolder = zeros(driftLength, miniBatchSize); predictionErrorGrad = zeros(diffLength); predictionErrorGradHolder = zeros(diffLength, miniBatchSize); detPiece = zeros(diffLength); detPieceHolder = zeros(diffLength, miniBatchSize); precisionMat = zeros(9,miniBatchSize); lossPerStep = zeros(miniBatchSize); debiasWeight = zeros(miniBatchSize); function predict_(x, p) #assume autonomous return prob.modelDrift_(x, p, 0.0); end function lossAndGrads(x,y,p,_drift,_precisionMat) eps = 64.0; #approximately median(\dot M) δ = _drift(x,p,0.0) .- y[10:18,:]; for i in 1:miniBatchSize debiasWeight[i] = 1.0/(norm(reshape(y[10:18,i], (3,3)))^2 + eps); lossPerStep[i] = debiasWeight[i]*dot(δ[:,i],δ[:,i]); end sumLoss = (dt*eps/miniBatchSize)*sum(lossPerStep); #-----------------------------drift grad-----------------------------# if (driftLength > 0) #x is state variable, w is weight vector, pullback(p->f(x,p), p)[2](w)[1] performs the tensor contraction # (∂/∂p_i f_k) w^k ∂f(x,w) = pullback(p->parameterizedDriftClosure(x,p), p[driftStart:driftEnd])[2](w)[1]; Threads.@threads for i in 1:miniBatchSize driftGradHolder[:,i] .= ∂f(x[:,i], debiasWeight[i]*δ[:,i]); end driftGrad = ((2*dt*eps)/miniBatchSize)*sum(driftGradHolder, dims=2); end #-----------------------------diff grad-----------------------------# diffGrad = zeros(diffLength); if (diffLength > 0) #x is state variable, w is weight vector, pullback(p->f(x,p), p)[2](w)[1] performs the tensor contraction # (∂/∂p_i f_k) w^k ∂Π(x,w) = pullback(p_->_precisionMat(x,p_), p[diffStart:diffEnd])[2](w)[1]; #Threads.@threads for i in 1:miniBatchSize for i in 1:miniBatchSize predictionErrorGradHolder[:,i] .= ∂Π(x[:,i], abs2.(δ[:,i])); detPieceHolder[:,i] .= ∂Π(x[:,i], precisionMat[:,i].^(-1)); end predictionErrorGrad = dt*sum(predictionErrorGradHolder, dims=2); detPiece = sum(detPieceHolder, dims=2); diffGrad = (predictionErrorGrad - detPiece)/miniBatchSize; #add in bias regularization gradient piece: regularizationGrad = zeros(18); for i in 1:size(regularizationGrad)[1] if ((-p[diffStart+17+i] + biasRegularizationOffset) > 0) regularizationGrad[i] = -1.0; end end diffGrad[19:36] .+= biasRegularizationWeight*regularizationGrad; end grads = vcat(driftGrad, diffGrad); grads = reshape(grads, size(grads)[1]); return sumLoss,grads; end #covariance matrix is length(u)^2 initialParams = []; if (driftLength > 0) initialParams = vcat(initialParams, θ_f) end if (diffLength > 0) initialParams = vcat(initialParams, ones(diffLength)); #currently using diagonal covariance end initialParams = Array{Float64}(initialParams); @assert length(initialParams) == (driftLength + diffLength) #--------------------end problem setup--------------------# lProb = LearningProblem(initialConditions, trainingData, x, y, validationData, tsteps, miniBatchSize, maxiters, optimizer, trueDrift, trueDiff, encode, decode, modelDrift, modelDiff, fullSystemDrift, nothing, lossAndGrads, initialParams, driftLength, diffLength, parameterizedDriftClosure, parameterizedPrecisionMat); println("Setup complete, beginning learning"); return lProb; end #prob = main(nothing); #Learn(prob); #myserialize("/groups/chertkov/cmhyett/DNSLearning/MLCoarseGrainedVGT/results/prob.dat",prob);
module Spatial # types export CartesianFrame3D, Transform3D, FreeVector3D, Point3D, GeometricJacobian, PointJacobian, Twist, SpatialAcceleration, MomentumMatrix, # TODO: consider combining with WrenchMatrix WrenchMatrix, # TODO: consider combining with MomentumMatrix Momentum, Wrench, SpatialInertia # functions export transform, rotation, translation, angular, linear, point_velocity, point_acceleration, change_base, log_with_time_derivative, center_of_mass, newton_euler, torque, torque!, kinetic_energy, rotation_vector_rate, quaternion_derivative, spquat_derivative, angular_velocity_in_body, velocity_jacobian, linearized_rodrigues_vec # macros export @framecheck using LinearAlgebra using Random using StaticArrays using Rotations using DocStringExtensions using Base: promote_eltype include("frame.jl") include("util.jl") include("transform3d.jl") include("threevectors.jl") include("spatialmotion.jl") include("spatialforce.jl") include("motion_force_interaction.jl") include("common.jl") end # module
mutable struct CanvasPlot # command list passed to javascript jsdict::Dict{String,Any} # size in canvas coordinates w::Float64 h::Float64 # world coordinates xmin::Float64 xmax::Float64 ymin::Float64 ymax::Float64 # transformation data ax::Float64 bx::Float64 ay::Float64 by::Float64 # unique identifier of html entity uuid::UUID CanvasPlot(::Nothing)=new() end """ ```` CanvasPlot(;resolution=(300,300), xrange::AbstractVector=0:1, yrange::AbstractVector=0:1) ```` Create a canvas plot with given resolution in the notebook and given "world coordinate" range. """ function CanvasPlot(;resolution=(300,300), xrange::AbstractVector=0:1, yrange::AbstractVector=0:1) p=CanvasPlot(nothing) p.uuid=uuid1() p.jsdict=Dict{String,Any}("cmdcount" => 0) p.w=resolution[1] p.h=resolution[2] _world!(p,extrema(xrange)...,extrema(yrange)...) p end const canvasdraw = read(joinpath(@__DIR__, "..", "assets", "canvasdraw.js"), String) """ Show plot """ function Base.show(io::IO, ::MIME"text/html", p::CanvasPlot) result=""" <script> $(canvasdraw) const jsdict = $(Main.PlutoRunner.publish_to_js(p.jsdict)) canvasdraw("$(p.uuid)",jsdict) </script> <canvas id="$(p.uuid)" width="$(p.w)" height="$(p.h)"></canvas> """ write(io,result) end """ lines!(p::CanvasPlot,x,y) Plot lines. Every two coordinates define a line. """ function lines!(p::CanvasPlot,x,y) _poly!(p,"lines",x,y) end """ polyline!(p::CanvasPlot,x,y) Plot a polyline. """ function polyline!(p::CanvasPlot,x,y) _poly!(p,"polyline",x,y) end """ polygon!(p::CanvasPlot,x,y) Plot a polygon and fill it. """ function polygon!(p::CanvasPlot,x,y) _poly!(p,"polygon",x,y) end """ linecolor!(p::CanvasPlot,r,g,b) Set line color. """ function linecolor!(p::CanvasPlot,r,g,b) pfx=command!(p,"linecolor") p.jsdict[pfx*"_rgb"]=255*Float32[r,g,b] end """ linewidth!(p::CanvasPlot,w) Set line width in pixels """ function linewidth!(p::CanvasPlot,w) pfx=command!(p,"linewidth") p.jsdict[pfx*"_w"]=w end """ fillcolor!(p::CanvasPlot,r,g,b) Set polygon fill color. """ function fillcolor!(p::CanvasPlot,r,g,b) pfx=command!(p,"fillcolor") p.jsdict[pfx*"_rgb"]=255*Float32[r,g,b] end """ textcolor!(p::CanvasPlot,r,g,b) Set text color """ function textcolor!(p::CanvasPlot,r,g,b) pfx=command!(p,"textcolor") p.jsdict[pfx*"_rgb"]=255*Float32[r,g,b] end """ textsize!(p::CanvasPlot,px) Set text size in pixels """ function textsize!(p::CanvasPlot,px) pfx=command!(p,"textsize") p.jsdict[pfx*"_pt"]=px end const halign=Dict("c"=>"center", "l"=>"left", "r"=>"right") const valign=Dict("b"=>"bottom", "c"=>"middle", "t"=>"top") """ textalign!(p::CanvasPlot,align) Set text alignment. `align:` one of `[:lt,:lc,lb,:ct,:cc,:cb,:rt,:rc,:rb]` """ function textalign!(p::CanvasPlot,align) a=String(align) pfx=command!(p,"textalign") p.jsdict[pfx*"_align"]=halign[a[1:1]] pfx=command!(p,"textbaseline") p.jsdict[pfx*"_align"]=valign[a[2:2]] end """ text!(p::CanvasPlot,txt,x,y) Draw text at position x,y. """ function text!(p::CanvasPlot,txt,x,y) pfx=command!(p,"text") tx,ty=_tran2d(p,x,y) p.jsdict[pfx*"_x"]=tx p.jsdict[pfx*"_y"]=ty p.jsdict[pfx*"_txt"]=txt end """ axis!(p::CanvasPlot; xtics=0:1, ytics=0:1, axislinewidth=2, gridlinewidth=1.5, ticlength=7, ticsize=15, xpad=30, ypad=30) Draw an axis with grid and tics, set new world coordinates according to tics. """ function axis!(p::CanvasPlot; xtics=0:1, ytics=0:1, axislinewidth=2, gridlinewidth=1.5, ticlength=7, ticsize=15, xpad=30, ypad=30) linecolor!(p,0,0,0) xmin,xmax=extrema(xtics) ymin,ymax=extrema(ytics) world_ypad=ypad*(ymax-ymin)/p.h world_xpad=xpad*(xmax-xmin)/p.w _world!(p,xmin-world_xpad,xmax+world_xpad/2,ymin-world_ypad,ymax+world_ypad/2) linewidth!(p,gridlinewidth) linecolor!(p,0.85,0.85,0.85) for y in ytics lines!(p,[xmin,xmax],[y,y]) end for x in xtics lines!(p,[x,x],[ymin,ymax]) end linewidth!(p,axislinewidth) linecolor!(p,0,0,0) lines!(p,[xmin,xmax],[ymin,ymin]) lines!(p,[xmin,xmax],[ymax,ymax]) lines!(p,[xmin,xmin],[ymin,ymax]) lines!(p,[xmax,xmax],[ymin,ymax]) linewidth!(p,gridlinewidth) linecolor!(p,0,0,0) world_xticlength=-ticlength/p.ay world_yticlength=ticlength/p.ax textcolor!(p,0,0,0) textsize!(p,ticsize) textalign!(p,:rc) for y in ytics lines!(p,[xmin-world_yticlength,xmin],[y,y]) text!(p, string(y), xmin-world_yticlength,y) end textalign!(p,:ct) for x in xtics lines!(p,[x,x],[ymin-world_xticlength,ymin]) text!(p, string(x), x,ymin-world_xticlength) end end
# basic test that parsing works correctly testdir = dirname(@__FILE__) @test_throws Gumbo.InvalidHTMLException parsehtml("", strict=true) let page = open("$testdir/example.html") do example example |> readstring |> parsehtml end @test page.doctype == "html" root = page.root @test tag(root[1][1]) == :meta @test root[2][1][1].text == "A simple test page." @test is(root[2][1][1].parent, root[2][1]) end # test that nonexistant tags are parsed as their actual name and not "unknown" let page = parsehtml("<weird></weird") @test tag(page.root[2][1]) == :weird end
# This file is part of Fatou.jl. It is licensed under the MIT license # Copyright (C) 2017 Michael Reed import Base: invokelatest rdpm(tex) = split(split(tex,"\n\\end{displaymath}")[1],"\\begin{displaymath}\n")[2] # we can substitute the expression into Newton's method and display it with LaTeX function newton_raphson(F,m) f = RExpr(F) return Algebra.:-(R"z",Algebra.:*(m,Algebra.:/(f,Algebra.df(f,:z)))) |> factor |> parse end # define recursive composition on functions recomp(E,x,j::Int) = Algebra.sub((Expr(:(=),:z,j > 1 ? recomp(E,x,j-1) : x),:(c=0)),E) # we can convert the j-th function composition into a latex expresion nL(E,m,j) = recomp(newton_raphson(E,m),:z,j) |> Algebra.latex |> rdpm jL(E,j) = recomp(E,:z,j) |> Algebra.latex |> rdpm # set of points that are within an ϵ neighborhood of the roots ri of the function f ds = "\\displaystyle" set0 = "D_0(\\epsilon) = \\left\\{ z\\in\\mathbb{C}: \\left|\\,z" setj(j) = "$ds D_$j(\\epsilon) = \\left\\{z\\in\\mathbb{C}:\\left|\\," nsetstr = "- r_i\\,\\right|<\\epsilon,\\,\\forall r_i(\\,f(r_i)=0 )\\right\\}" jsetstr = "\\,\\right|>\\epsilon\\right\\}" nset0 = latexstring("$set0 $nsetstr") jset0 = latexstring("$set0 $jsetstr") nrset(f,m,j) = latexstring( j == 0 ? "$set0 $nsetstr" : "$(setj(j))$(nL(f,m,j)) $nsetstr") jset(f,j) = latexstring( j == 0 ? "$set0 $jsetstr" : "$(setj(j))$(jL(f,j)) $jsetstr")
""" mutable struct DynamicGenerator{ M <: Machine, S <: Shaft, A <: AVR, TG <: TurbineGov, P <: PSS, } <: DynamicInjection name::String ω_ref::Float64 machine::M shaft::S avr::A prime_mover::TG pss::P n_states::Int states::Vector{Symbol} ext::Dict{String, Any} internal::InfrastructureSystemsInternal end A dynamic generator is composed by 5 components, namely a Machine, a Shaft, an Automatic Voltage Regulator (AVR), a Prime Mover (o Turbine Governor) and Power System Stabilizer (PSS). It requires a Static Injection device that is attached to it. # Arguments - `name::String`: Name of generator. - `ω_ref::Float64`: Frequency reference set-point in pu. - `machine <: Machine`: Machine model for modeling the electro-magnetic phenomena. - `shaft <: Shaft`: Shaft model for modeling the electro-mechanical phenomena. - `avr <: AVR`: AVR model of the excitacion system. - `prime_mover <: TurbineGov`: Prime Mover and Turbine Governor model for mechanical power. - `pss <: PSS`: Power System Stabilizer model. - `n_states::Int`: Number of states (will depend on the components). - `states::Vector{Symbol}`: Vector of states (will depend on the components). - `ext::Dict{String, Any}` - `internal::InfrastructureSystemsInternal`: power system internal reference, do not modify """ mutable struct DynamicGenerator{ M <: Machine, S <: Shaft, A <: AVR, TG <: TurbineGov, P <: PSS, } <: DynamicInjection name::String ω_ref::Float64 machine::M shaft::S avr::A prime_mover::TG pss::P n_states::Int states::Vector{Symbol} ext::Dict{String, Any} internal::InfrastructureSystemsInternal end function DynamicGenerator( name::String, ω_ref::Float64, machine::M, shaft::S, avr::A, prime_mover::TG, pss::P, ext::Dict{String, Any} = Dict{String, Any}(), ) where {M <: Machine, S <: Shaft, A <: AVR, TG <: TurbineGov, P <: PSS} n_states = _calc_n_states(machine, shaft, avr, prime_mover, pss) states = _calc_states(machine, shaft, avr, prime_mover, pss) return DynamicGenerator{M, S, A, TG, P}( name, ω_ref, machine, shaft, avr, prime_mover, pss, n_states, states, ext, InfrastructureSystemsInternal(), ) end function DynamicGenerator(; name::String, ω_ref::Float64, machine::M, shaft::S, avr::A, prime_mover::TG, pss::P, n_states = _calc_n_states(machine, shaft, avr, prime_mover, pss), states = _calc_states(machine, shaft, avr, prime_mover, pss), ext::Dict{String, Any} = Dict{String, Any}(), internal = InfrastructureSystemsInternal(), ) where {M <: Machine, S <: Shaft, A <: AVR, TG <: TurbineGov, P <: PSS} DynamicGenerator( name, ω_ref, machine, shaft, avr, prime_mover, pss, n_states, states, ext, internal, ) end IS.get_name(device::DynamicGenerator) = device.name get_states(device::DynamicGenerator) = device.states get_n_states(device::DynamicGenerator) = device.n_states get_ω_ref(device::DynamicGenerator) = device.ω_ref get_machine(device::DynamicGenerator) = device.machine get_shaft(device::DynamicGenerator) = device.shaft get_avr(device::DynamicGenerator) = device.avr get_prime_mover(device::DynamicGenerator) = device.prime_mover get_pss(device::DynamicGenerator) = device.pss get_ext(device::DynamicGenerator) = device.ext get_internal(device::DynamicGenerator) = device.internal get_V_ref(value::DynamicGenerator) = get_V_ref(get_avr(value)) get_P_ref(value::DynamicGenerator) = get_P_ref(get_prime_mover(value)) function _calc_n_states(machine, shaft, avr, prime_mover, pss) return get_n_states(machine) + get_n_states(shaft) + get_n_states(avr) + get_n_states(prime_mover) + get_n_states(pss) end function _calc_states(machine, shaft, avr, prime_mover, pss) return vcat( get_states(machine), get_states(shaft), get_states(avr), get_states(prime_mover), get_states(pss), ) end
module MitosisStochasticDiffEq using Mitosis using RecursiveArrayTools using StochasticDiffEq using OrdinaryDiffEq using DiffEqNoiseProcess import DiffEqNoiseProcess.pCN using LinearAlgebra using Random using UnPack using Statistics using StaticArrays using ForwardDiff using PaddedViews import SciMLBase.isinplace export pCN include("types.jl") include("sample.jl") include("filter.jl") include("guiding.jl") include("regression.jl") include("utils.jl") include("derivative_utils.jl") include("solver.jl") end
export chebyshev, chebyshev! chebyshev(A, b, λmin::Real, λmax::Real, Pr = 1, n = size(A,2); tol::Real = sqrt(eps(typeof(real(b[1])))), maxiter::Int = n^3) = chebyshev!(zerox(A, b), A, b, λmin, λmax, Pr, n; tol=tol,maxiter=maxiter) function chebyshev!(x, A, b, λmin::Real, λmax::Real, Pr = 1, n = size(A,2); tol::Real = sqrt(eps(typeof(real(b[1])))), maxiter::Int = n^3) K = KrylovSubspace(A, n, 1, Adivtype(A, b)) init!(K, x) chebyshev!(x, K, b, λmin, λmax, Pr; tol = tol, maxiter = maxiter) end function chebyshev!(x, K::KrylovSubspace, b, λmin::Real, λmax::Real, Pr = 1; tol::Real = sqrt(eps(typeof(real(b[1])))), maxiter::Int = K.n^3) local α, p K.order = 1 tol = tol*norm(b) r = b - nextvec(K) d::eltype(b) = (λmax + λmin)/2 c::eltype(b) = (λmax - λmin)/2 resnorms = zeros(typeof(real(b[1])), maxiter) for iter = 1:maxiter z = Pr\r if iter == 1 p = z α = 2/d else β = (c*α/2)^2 α = 1/(d - β) p = z + β*p end append!(K, p) update!(x, α, p) r -= α*nextvec(K) #Check convergence resnorms[iter] = norm(r) if resnorms[iter] < tol resnorms = resnorms[1:iter] break end end x, ConvergenceHistory(resnorms[end] < tol, tol, K.mvps, resnorms) end
using CompScienceMeshes, BEAST fn = joinpath(dirname(pathof(BEAST)),"../examples/assets/torus.msh") m = CompScienceMeshes.read_gmsh_mesh(fn) @show numcells(m) X = raviartthomas(m) @show numfunctions(X) Y = buffachristiansen(m) @show numfunctions(Y) verts = skeleton(m,0) edges = skeleton(m,1) faces = skeleton(m,2) Λ = connectivity(verts, edges) Σᵀ = connectivity(edges, faces) @assert all(sum(Σᵀ,dims=1) .== 0) κ = 1.0e-5 S = Maxwell3D.singlelayer(wavenumber=κ) D = Maxwell3D.doublelayer(wavenumber=κ) C = BEAST.DoubleLayerRotatedMW3D(im*κ) J = BEAST.Identity() N = BEAST.NCross() # Sxx = assemble(S,X,X) # Myx = assemble(D+0.5N,Y,X) # Mxx = assemble(C-0.5J,X,X) using JLD2 @load "temp/matrices.jld2" using LinearAlgebra norm(Σᵀ*Myx*Λ) ϵ, μ = 1.0, 1.0 ω = κ / √(ϵ*μ) E = Maxwell3D.planewave(direction=ẑ, polarization=x̂, wavenumber=κ) H = -1/(im*μ*ω)*curl(E) e = (n × E) × n h = (n × H) × n ex = assemble(e, X) hy = assemble(h, Y) hx = assemble(n × H,X) u1 = Sxx \ ex u2 = Myx \ hy u3 = Mxx \ hx Φ, Θ = [0.0], range(0,stop=π,length=100) pts = [point(cos(ϕ)*sin(θ), sin(ϕ)*sin(θ), cos(θ)) for ϕ in Φ for θ in Θ] ff1 = potential(MWFarField3D(wavenumber=κ), pts, u1, X) ff2 = potential(MWFarField3D(wavenumber=κ), pts, u2, X) ff3 = potential(MWFarField3D(wavenumber=κ), pts, u3, X) #Why: projectors Σ = copy(transpose(Σᵀ)) Ps = Σ*pinv(Array(Σᵀ*Σ))*Σᵀ Pl = I - Ps u1s = Ps*u1 u2s = Ps*u2 u3s = Ps*u3 u1l = Pl*u1 u2l = Pl*u2 u3l = Pl*u3 # s = svdvals(M) # h = nullspace(M,s[end]*1.0001) # # fcr, geo = facecurrents(h[:,end],X) # # V,F = vertexarray(m), cellarray(m) # B = [real(f[i]) for f in fcr, i in 1:3] # using MATLAB # mat"mesh = Mesh($V,$F)" # mat"[C,N] = faceNormals(mesh)" # mat"figure; hold on" # mat"patch(mesh,$(norm.(fcr)))" # mat"quiver3x(C,$B)"
l=[ "l=[","print(l[1]", "for i in l print(\" \$(repr(i))\") end", "print(l[end])", "for i in l[2:end-1] print(\"\$i\") end", "]", ] println(l[1]) for i in l println(" $(repr(i)),") end println(l[end]) for i in l[2:end-1] println("$i") end
import ProximalBundleMethod import Printf import Convex import Gurobi import SCS using LinearAlgebra using Random using SparseArrays include("utils.jl") include("csv_exporter.jl") include("plot_utils.jl") """ The following functions are used to process LIBSVM files. """ mutable struct LearningData feature_matrix::SparseMatrixCSC{Float64,Int64} labels::Vector{Float64} end function load_libsvm_file(file_name::String) open(file_name, "r") do io target = Array{Float64,1}() row_indicies = Array{Int64,1}() col_indicies = Array{Int64,1}() matrix_values = Array{Float64,1}() row_index = 0 for line in eachline(io) row_index += 1 split_line = split(line) label = parse(Float64, split_line[1]) # This ensures that labels are 1 or -1. Different dataset use {-1, 1}, {0, 1}, and {1, 2}. if abs(label - 1.0) < 1e-05 label = 1.0 else label = -1.0 end push!(target, label) for i = 2:length(split_line) push!(row_indicies, row_index) matrix_coef = split(split_line[i], ":") push!(col_indicies, parse(Int64, matrix_coef[1])) push!(matrix_values, parse(Float64, matrix_coef[2])) end end feature_matrix = sparse(row_indicies, col_indicies, matrix_values) return LearningData(feature_matrix, target) end end function normalize_columns(feature_matrix::SparseMatrixCSC{Float64,Int64}) m = size(feature_matrix, 2) normalize_columns_by = ones(m) for j = 1:m col_vals = feature_matrix[:, j].nzval if length(col_vals) > 0 normalize_columns_by[j] = 1.0 / norm(col_vals, 2) end end return feature_matrix * sparse(1:m, 1:m, normalize_columns_by) end function remove_empty_columns(feature_matrix::SparseMatrixCSC{Float64,Int64}) keep_cols = Array{Int64,1}() for j = 1:size(feature_matrix, 2) if length(feature_matrix[:, j].nzind) > 0 push!(keep_cols, j) end end return feature_matrix[:, keep_cols] end function add_intercept(feature_matrix::SparseMatrixCSC{Float64,Int64}) return [sparse(ones(size(feature_matrix, 1))) feature_matrix] end function preprocess_learning_data(result::LearningData) result.feature_matrix = remove_empty_columns(result.feature_matrix) result.feature_matrix = add_intercept(result.feature_matrix) result.feature_matrix = normalize_columns(result.feature_matrix) return result end function svm_objective(w, Xp, y, coeff) n, _ = size(Xp) soft_margin = map(x -> max(0, x), ones(length(y)) - y .* (Xp * w)) return sum(soft_margin) / n + coeff / 2 * LinearAlgebra.norm(w)^2 end function svm_subgradient(w, Xp, y, coeff) n, m = size(Xp) soft_margin = map(x -> max(0, x), ones(length(y)) - y .* (Xp * w)) result = zeros(length(w)) for i = 1:length(soft_margin) if soft_margin[i] > 0.0 result += -y[i] * Xp[i, :] / n end end return result + coeff * w end function compute_minimum_with_cvx(Xp, y, reg_coeff) n, m = size(Xp) w = Convex.Variable(m) problem = Convex.minimize( (reg_coeff / 2) * Convex.sumsquares(w) + Convex.sum(Convex.pos((1 - y .* (Xp * w)) / n)), ) Convex.solve!( problem, () -> Gurobi.Optimizer(BarConvTol = 1e-10, BarQCPConvTol = 1e-10), ) #() -> SCS.Optimizer(verbose=false), verbose=false) return problem end function main() Random.seed!(2625) instance_names = ["colon-cancer", "duke", "leu"] coefficients = [0.001, 0.01, 0.1, 0.5, 1.0, 1.5, 2.0, 10.0] step_sizes = [1e-15 * 100^j for j = 0:10] instances = Dict() for name in instance_names instances[name] = preprocess_learning_data(load_libsvm_file("data/" * name)) end errors = DataFrame( instance = String[], coeff = Float64[], error_subg = Float64[], error_bundle = Float64[], ) params_subgradient = create_subgradient_method_parameters( iteration_limit = 2000, verbose = true, printing_frequency = 100, ) params_bundle = create_bundle_method_parameters( iteration_limit = 2000, verbose = true, printing_frequency = 100, full_memory = false, ) for (name, instance) in instances Xp = (instance.feature_matrix) y = instance.labels _, m = size(Xp) x_init = randn(m) / m for coeff in coefficients print("\n------------------------------------\n") Printf.@printf("Instance %s, coeff %12g\n", name, coeff) println("Solving with Convex.jl first") problem = compute_minimum_with_cvx(Xp, y, coeff) Printf.@printf("Obj=%12g\n", problem.optval,) objective = (w -> svm_objective(w, Xp, y, coeff) - problem.optval) gradient = (w -> svm_subgradient(w, Xp, y, coeff)) poly_step_size = ((_, _, t) -> 1 / (coeff * t)) println("\nAbout to solve a random SVM problem using subgradient method.") sol_subgradient = ProximalBundleMethod.solve( objective, gradient, params_subgradient, poly_step_size, x_init, ) println("\nAbout to solve a random SVM problem using adaptive parallel method.") sol_bundle, iter_info_agents = ProximalBundleMethod.solve_adaptive( objective, gradient, params_bundle, step_sizes, x_init, ) push!( errors, [ name, coeff, objective(sol_subgradient.solution), objective(sol_bundle.solution), ], ) # Uncomment this block of code if you want to save stats about each run. # csv_path_sol = # "results/svm/results_subgradient_" * name * "_" * string(coeff) * "_svm.csv" # output_stepsize_plot = # "results/svm/results_subgradient_" * name * "_" * # string(coeff) * # "_stepsize_svm.pdf" # output_objective_plot = # "results/svm/results_subgradient_" * name * "_" * # string(coeff) * # "_objective_svm.pdf" # export_statistics(sol_subgradient, csv_path_sol) # plot_step_sizes(csv_path_sol, output_stepsize_plot) # plot_objective(csv_path_sol, output_objective_plot) # csv_path_sol = # "results/svm/results_bundle_" * name * "_" * string(coeff) * "_svm.csv" # output_stepsize_plot = # "results/svm/results_bundle_" * name * "_" * # string(coeff) * # "_stepsize_svm.pdf" # output_objective_plot = # "results/svm/results_bundle_" * name * "_" * # string(coeff) * # "_objective_svm.pdf" # csv_path = # "results/svm/results_" * name * "_" * string(coeff) * "_agents_svm.csv" # output_path = # "results/svm/results_" * name * "_" * string(coeff) * "_agents_svm.pdf" # export_statistics(sol_bundle, csv_path_sol) # plot_step_sizes(csv_path_sol, output_stepsize_plot) # plot_objective(csv_path_sol, output_objective_plot) # export_losses_agents(iter_info_agents, step_sizes, csv_path) # plot_agent_losses(csv_path, output_path) end end print(errors) CSV.write("results/svm/results_svm.csv", errors) end main()
type Trie{T} value::T children::Dict{Char,Trie{T}} is_key::Bool function Trie() self = new() self.children = (Char=>Trie{T})[] self.is_key = false self end end Trie() = Trie{Any}() function setindex!{T}(t::Trie{T}, val::T, key::String) node = t for char in key if !haskey(node.children, char) node.children[char] = Trie{T}() end node = node.children[char] end node.is_key = true node.value = val end function subtrie(t::Trie, prefix::String) node = t for char in prefix if !haskey(node.children, char) return nothing else node = node.children[char] end end node end function haskey(t::Trie, key::String) node = subtrie(t, key) node != nothing && node.is_key end get(t::Trie, key::String) = get(t, key, nothing) function get(t::Trie, key::String, notfound) node = subtrie(t, key) if node != nothing && node.is_key return node.value end notfound end function keys(t::Trie, prefix::String, found) if t.is_key push(found, prefix) end for (char,child) in t.children keys(child, strcat(prefix,char), found) end end keys(t::Trie, prefix::String) = (found=String[]; keys(t, prefix, found); found) keys(t::Trie) = keys(t, "") function keys_with_prefix(t::Trie, prefix::String) st = subtrie(t, prefix) st != nothing ? keys(st,prefix) : [] end
using CImGui using CImGui.CSyntax using CImGui.CSyntax.CSwitch using CImGui.CSyntax.CStatic using Printf """ ShowExampleAppLongText(p_open::Ref{Bool}) Test rendering huge amount of text, and the incidence of clipping. """ function ShowExampleAppLongText(p_open::Ref{Bool}) CImGui.SetNextWindowSize((520,600), CImGui.ImGuiCond_FirstUseEver) CImGui.Begin("Example: Long text display", p_open) || (CImGui.End(); return) @cstatic test_type=Cint(0) lines=0 log=CImGui.TextBuffer() begin CImGui.Text("Printing unusually long amount of text.") @c CImGui.Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped (slow)\0") CImGui.Text("Buffer contents: $lines lines, $(CImGui.Size(log)) bytes") if CImGui.Button("Clear") @info "Trigger Clear | find me here: $(@__FILE__) at line $(@__LINE__)" CImGui.Clear(log) lines = 0 end CImGui.SameLine() if CImGui.Button("Add 1000 lines") @info "Trigger Add 1000 lines | find me here: $(@__FILE__) at line $(@__LINE__)" foreach(i->CImGui.Append(log, "$(lines+i) The quick brown fox jumps over the lazy dog\n"), 1:1000) lines += 1000 end CImGui.BeginChild("Log") @cswitch test_type begin @case 0 # single call to TextUnformatted() with a big buffer CImGui.TextUnformatted(CImGui.Begin(log), CImGui.End(log)) break @case 1 # multiple calls to Text(), manually coarsely clipped - demonstrate how to use the ImGuiListClipper helper. CImGui.PushStyleVar(CImGui.ImGuiStyleVar_ItemSpacing, (0,0)) clipper = CImGui.Clipper() CImGui.Begin(clipper, lines) while CImGui.Step(clipper) s = CImGui.Get(clipper, :DisplayStart) e = CImGui.Get(clipper, :DisplayEnd)-1 foreach(i->CImGui.Text("$i The quick brown fox jumps over the lazy dog"), s:e) end CImGui.PopStyleVar() CImGui.Destroy(clipper) break @case 2 # multiple calls to Text(), not clipped (slow) CImGui.PushStyleVar(CImGui.ImGuiStyleVar_ItemSpacing, (0,0)) foreach(i->CImGui.Text("$i The quick brown fox jumps over the lazy dog"), 1:lines) CImGui.PopStyleVar() break end CImGui.EndChild() CImGui.End() end # @cstatic end
using HypothesisTests, Test using HypothesisTests: default_tail using StableRNGs @testset "F-tests" begin @testset "Basic variance F-test" begin rng = StableRNG(12) y1_h0 = 4 .+ randn(rng, 500) y2_h0 = 4 .+ randn(rng, 400) t = VarianceFTest(y1_h0, y2_h0) @test t.n_x == 500 @test t.n_y == 400 @test t.df_x == 499 @test t.df_y == 399 @test t.F ≈ 0.859582 rtol=1e-5 @test pvalue(t) ≈ 0.109714 rtol=1e-5 @test pvalue(t, tail=:left) ≈ 0.0548572 rtol=1e-5 @test pvalue(t, tail=:right) ≈ 0.945143 rtol=1e-5 @test default_tail(t) == :both t = VarianceFTest(y2_h0, y1_h0) @test t.n_x == 400 @test t.n_y == 500 @test t.df_x == 399 @test t.df_y == 499 @test t.F ≈ 1.163355 rtol=1e-5 @test pvalue(t) ≈ 0.109714 rtol=1e-5 @test pvalue(t, tail=:right) ≈ 0.0548572 rtol=1e-5 @test pvalue(t, tail=:left) ≈ 0.945143 rtol=1e-5 @test default_tail(t) == :both y1_h1 = 0.7*randn(rng, 200) y2_h1 = 1.3*randn(rng, 120) t = VarianceFTest(y1_h1, y2_h1) @test t.n_x == 200 @test t.n_y == 120 @test t.df_x == 199 @test t.df_y == 119 @test t.F ≈ 0.264161 rtol=1e-5 @test pvalue(t) < 1e-8 @test default_tail(t) == :both @test pvalue(t, tail=:left) < 1e-8 @test pvalue(t, tail=:right) > 1.0 - 1e-8 end end
using Random: randperm! using HDF5 """ MODIFIED DataLoader Class Modifications: - Altered "Base.iterate" implementation to handle hdf5 (.h5) files - Files are only read from disk when they're needed Original version: https://github.com/boathit/Benchmark-Flux-PyTorch/blob/master/dataloader.jl Original documentation: DataLoader(dataset::AbstractArray...; batchsize::Int, shuffle::Bool) DataLoader provides iterators over the dataset. ```julia X = rand(10, 1000) Y = rand(1, 1000) m = Dense(10, 1) loss(x, y) = Flux.mse(m(x), y) opt = ADAM(params(m)) trainloader = DataLoader(X, Y, batchsize=256, shuffle=true) Flux.train!(loss, trainloader, opt) ``` """ struct DataLoader dataset::Tuple batchsize::Int shuffle::Bool indices::Vector{Int} n::Int end function DataLoader( dataset::Tuple{AbstractArray,Vararg{AbstractArray}}; batchsize::Int, shuffle::Bool, ) l = last.(size.(dataset)) n = first(l) all(n .== l) || throw(DimensionMismatch("All data should have the same length.")) indices = collect(1:n) shuffle && randperm!(indices) DataLoader(dataset, batchsize, shuffle, indices, n) end DataLoader(dataset::AbstractArray...; batchsize::Int, shuffle::Bool) = DataLoader(dataset, batchsize = batchsize, shuffle = shuffle) function Base.iterate(it::DataLoader, start = 1) if start > it.n it.shuffle && randperm!(it.indices) return nothing end nextstart = min(start + it.batchsize, it.n + 1) i = it.indices[start:nextstart-1] # Select batch data raw_batch = Tuple(copy(selectdim(x, ndims(x), i)) for x in it.dataset) # Prepare empty batch arrays of size (dim1, dim2 .... dimN, 1) # Added dimension: index in batch X_batch = Array{Float32}(undef, 40, 40, 4, it.batchsize) Y_batch = Array{Float32}(undef, 1, it.batchsize) for i in 1:length(raw_batch[1]) # last batch could be smaller than (it.batchsize) # raw_batch[1][i] here includes the path to the h5 file to be read # img = permutedims(cpu(h5open(raw_batch[1][i], "r"))["data"][1:4,:,1:40], [2, 3, 1]) f = cpu(h5open(raw_batch[1][i], "r")) img = permutedims(f["data"][1:4,:,1:40], [2, 3, 1]) close(f) X_batch[:, :, :, i] = img depth = raw_batch[2][i] Y_batch[1, i] = depth end new_element = (X_batch, Y_batch) return gpu(new_element), nextstart end Base.length(it::DataLoader) = it.n Base.eltype(it::DataLoader) = typeof(it.dataset) function Base.show(io::IO, it::DataLoader) print(io, "DataLoader(dataset size = $(it.n)") print(io, ", batchsize = $(it.batchsize), shuffle = $(it.shuffle)") print(io, ")") end
# ---------------------------------------------------------------------------- # # # master.jl # # Abstract master element type # This allows for writing an n-dimensional version of solver methods # # λυτέος # Fall 2017 # # Max Opgenoord # # ---------------------------------------------------------------------------- # """ Master Master abstract type: Overarching abstract type for master element types. Currently triangle and tetrahedron implemented. """ abstract type Master end include("../integration/quadratureLine.jl") include("../integration/quadratureTriangle.jl") include("../integration/quadratureTet.jl") include("../integration/basisFuncLineLag.jl") include("../integration/basisFuncTriangleLag.jl") include("../integration/basisFuncTetLag.jl") include("master2D.jl") include("master3D.jl")
function Temperature_dist(T,theta_l,theta_v,q_l,q_v,rho_vs,soil_parameters, Ta, Hr_atm, St,u, psi_H, psi_m, soil_numerical_parameters,constants,atm_parameters,dt) theta_top = theta_l[end]; # top layer water content rs = 10*exp(35.63*(0.15-theta_top)); # soil surface resistance to vapor flow rv = 1/(u*constants.k^2)*(log((atm_parameters.z_ref-atm_parameters.d+atm_parameters.z_H)/atm_parameters.z_oH)+psi_H)* (log((atm_parameters.z_ref-atm_parameters.d+atm_parameters.z_m)/atm_parameters.z_om)+psi_m); rH = rv; e_a = 0.611*exp(17.27*(Ta-273.15)/(Ta-35.85))*Hr_atm; # atm. vapor pressure rho_sa = 1e-3.*exp(19.84-4975.9./Ta); rho_va = rho_sa*Hr_atm; eps_a = 0.7+5.95e-5*e_a*exp(1500/Ta); # atm. emmisivity; eps_s = min(0.9+0.18*theta_top,1); #soil emmisivity Cp = constants.Cs.*(soil_parameters.theta_s.-theta_l)+constants.Cw.*theta_l.+constants.Cv.*theta_v; lambda = soil_parameters.b1.+soil_parameters.b2.*theta_l+soil_parameters.b3.*sqrt.(theta_l); rho_w = 1000 .-7.3e-3.*(T.-(273+4)).^2 .+ 3.79e-5.*(T.-(273+4)).^3; #water density [kg m^-3] Lw = 2.501e6 .- 2369.2.*(T .- 273); # latent heat [J kg^-1] Lo = Lw.*rho_w; # vol. latent heat [J m^-3] L = 2.260e6; # latent heat for vaporazation [J kg^-1] T_old = T; O=zeros(2) O[1] = 1; LE=0 while O[1]>soil_numerical_parameters.eps_T temp_T_2 = T; temp_T = (T+T_old)./2; for i = 2:soil_numerical_parameters.Ns-1 T[i] = T_old[i]+dt/(soil_numerical_parameters.dz_s^2*Cp[i])*(lambda[i]*(temp_T[i+1]-2*temp_T[i]+temp_T[i-1])+ (lambda[i+1]-lambda[i])*(temp_T[i+1]-temp_T[i])-(constants.Cw*q_l[i]+constants.Cv*q_v[i])*soil_numerical_parameters.dz_s*(temp_T[i+1]-temp_T[i])); end #set bottom boundary T[1] = T_old[1]; #set top boundary Rn = (1-albedo)*St+eps_s*eps_a*constants.sigma*Ta^4- eps_s*constants.sigma*temp_T[end]^4; H = constants.Ca*(temp_T[end]-Ta)/rH; LE = L.*(rho_vs[end].-rho_va)./(rv.+rs); G = Rn.-H.-LE; T[end] = (G+T[end-1]*lambda[end]/soil_numerical_parameters.dz_s+Lo[end]*q_v[end])/(lambda[end]/soil_numerical_parameters.dz_s-constants.Cv*q_v[end]-constants.Cw*q_l[end]); rho_w = 1000 .- 7.3e-3.*(T.-(273+4)).^2 .+ 3.79e-5.*(T.-(273+4)).^3; #water density [kg m^-3] Lw = 2.501e6.-2369.2.*(T.-273); # latent heat [J kg^-1] Lo = Lw.*rho_w; # vol. latent heat [J m^-3] O[2] = mean(abs.(temp_T_2.-T)./temp_T); if O[2]<O[1] O[1] = O[2]; else dt = dt/2; T = T_old; O[1] = 1; end if dt==0 dt = 1; end #println(dt) end E = LE/(L*rho_w[end]); return T,E,dt end
"`base(::Type{T}, i)` singleton (`i`,) of collection type `T` " function base end "Id of Random Variable in projection" function randvarid end "`combine(a, b)` Combine (e.g. concatenate) `a` and `b`" function combine end "`append(a, b)` append `b` to the end of `a`, like `push!` but functional" function append end "`Increment(id::ID)` the id" function increment end
import Base: isidentifier, is_id_start_char, is_id_char const RESERVED_WORDS = Set(["begin", "while", "if", "for", "try", "return", "break", "continue", "function", "macro", "quote", "let", "local", "global", "const", "abstract", "typealias", "type", "bitstype", "immutable", "do", "module", "baremodule", "using", "import", "export", "importall", "end", "else", "elseif", "catch", "finally"]) VERSION < v"0.6.0-dev.2194" && push!(RESERVED_WORDS, "ccall") VERSION >= v"0.6.0-dev.2698" && push!(RESERVED_WORDS, "struct") function identifier(s::AbstractString) s = normalize_string(s) if !isidentifier(s) s = makeidentifier(s) end @compat(Symbol(in(s, RESERVED_WORDS) ? "_"*s : s)) end function makeidentifier(s::AbstractString) i = start(s) done(s, i) && return "x" res = IOBuffer(sizeof(s) + 1) (c, i) = next(s, i) under = if is_id_start_char(c) write(res, c) c == '_' elseif is_id_char(c) write(res, 'x', c) false else write(res, '_') true end while !done(s, i) (c, i) = next(s, i) if c != '_' && is_id_char(c) write(res, c) under = false elseif !under write(res, '_') under = true end end return String(take!(res)) end function make_unique(names::Vector{Symbol}; allow_duplicates=true) seen = Set{Symbol}() names = copy(names) dups = Int[] for i in 1:length(names) name = names[i] in(name, seen) ? push!(dups, i) : push!(seen, name) end if !allow_duplicates && length(dups) > 0 d = unique(names[dups]) msg = """Duplicate variable names: $d. Pass allow_duplicates=true to make them unique using a suffix automatically.""" throw(ArgumentError(msg)) end for i in dups nm = names[i] k = 1 while true newnm = Symbol("$(nm)_$k") if !in(newnm, seen) names[i] = newnm push!(seen, newnm) break end k += 1 end end return names end #' @description #' #' Generate standardized names for columns of a DataTable. The #' first name will be :x1, the second :x2, etc. #' #' @field n::Integer The number of names to generate. #' #' @returns names::Vector{Symbol} A vector of standardized column names. #' #' @examples #' #' DataTables.gennames(10) function gennames(n::Integer) res = Array{Symbol}(n) for i in 1:n res[i] = Symbol(@sprintf "x%d" i) end return res end #' @description #' #' Count the number of null values in an array. #' #' @field a::AbstractArray The array whose missing values are to be counted. #' #' @returns count::Int The number of null values in `a`. #' #' @examples #' #' DataTables.countnull([1, 2, 3]) function countnull(a::AbstractArray) res = 0 for x in a res += _isnull(x) end return res end #' @description #' #' Count the number of missing values in a NullableArray. #' #' @field a::NullableArray The NullableArray whose missing values are to be counted. #' #' @returns count::Int The number of null values in `a`. #' #' @examples #' #' DataTables.countnull(NullableArray([1, 2, 3])) countnull(a::NullableArray) = sum(a.isnull) #' @description #' #' Count the number of missing values in a NullableCategoricalArray. #' #' @field na::CategoricalArray The CategoricalArray whose missing values #' are to be counted. #' #' @returns count::Int The number of null values in `a`. #' #' @examples #' #' DataTables.countnull(CategoricalArray([1, 2, 3])) function countnull(a::CategoricalArray) res = 0 for x in a.refs res += x == 0 end return res end # Gets the name of a function. Used in groupedatatable/grouping.jl function _fnames{T<:Function}(fs::Vector{T}) λcounter = 0 names = map(fs) do f name = string(f) if name == "(anonymous function)" # Anonymous functions with Julia < 0.5 λcounter += 1 name = "λ$(λcounter)" end name end names end _isnull(x::Any) = false _isnull(x::Nullable) = isnull(x)
using DataDeps register(DataDep( "breast-cancer", "http://archive.ics.uci.edu/ml/datasets/Breast+Cancer", "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer/breast-cancer.data", "ca7d3fa97b62ff967b6894ffbb3acaaf4a51062e0149e5950b3ad6f685970b65", post_fetch_method=(path -> begin UCIData.process_dataset(path, target_index=10, feature_indices=1:9, categoric_indices=[1:6; 8:9], ) end), ))
function f(x,y) :: Int64 end
function compute_edge_faces_ring(faces) """ compute_edge_face_ring - compute faces adjacent to each edge e2f = compute_edge_face_ring(faces); e2f(i,j) and e2f(j,i) are the number of the two faces adjacent to edge (i,j). Copyright (c) 2007 Gabriel Peyre """ n = maximum(faces) m = size(faces,2) i = [faces[1,:] faces[2,:] faces[3,:]] j = [faces[2,:] faces[3,:] faces[1,:]] s = [1:m 1:m 1:m]; # first without duplicate tmp = unique(i + (maximum(i) + 1)*j) # unique I = indexin(tmp, i + (maximum(i) + 1)*j) # remaining items J = setdiff(1:length(s), I); # flip the duplicates i1 = [i[I]; j[J]] j1 = [j[I]; i[J]] s = [s[I]; s[J]] # remove doublons tmp = unique(i1 + (maximum(i1) + 1)*j1) I = indexin(tmp, i1 + (maximum(i1) + 1)*j1) i1 = i1[I] j1 = j1[I] s = s[I] A = sparse(i1,j1,s,n,n) # add missing points I = findall(A'.!=0) I = I[A[I].==0] A[I]=-1 return A end;