licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
618
################################### """ track = loadtrack("simlation/path/_output"::AbstractString) track = loadtrack("simlation/path/_output/fort.track"::AbstractString) Function: fort.track reader """ function loadtrack(outdir::AbstractString) ## definition of filename fname = occursin("fort.track", basename(outdir)) ? outdir : joinpath(outdir, "fort.track") ## check isfile(fname) || error("File $fname is not found.") ## load datorg = readdlm(fname) datorg[datorg.>1e30] .= NaN ## return return VisClaw.Track(datorg[:,1], datorg[:,2], datorg[:,3], datorg[:,4]) end
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
9644
###################################### """ plt = plotsamr2d(tiles::AbstractVector{VisClaw.AMRGrid}; AMRlevel=[], wind::Bool=false, region="", kwargs...) plotsamr2d!(plt::Plots.Plot, tiles::AbstractVector{VisClaw.AMRGrid}; AMRlevel=[], wind::Bool=false, region="", kwargs...) Function: plot values of AMR grids in two-dimension """ function plotsamr2d!(plt, tiles::AbstractVector{VisClaw.AMRGrid}; AMRlevel=[], wind::Bool=false, region="", kwargs...) # check arg if isa(tiles[1], VisClaw.SurfaceHeight) var = :eta elseif isa(tiles[1], VisClaw.Velocity) var = :vel elseif isa(tiles[1], VisClaw.Storm) if wind var = :u else var = :slp end else error("Invalid argument") end # parse keyword args kwdict = KWARG(kwargs) # ----------------------------- # linetype seriestype, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_seriestype, :heatmap) # ----------------------------- # color seriescolor, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_seriescolor, :auto) # ----------------------------- # color axis clims, kwdict = VisClaw.parse_clims(kwdict) if clims == nothing vals = getfield.(tiles, var) clims = ( minimum(minimum.(v->isnan(v) ? Inf : v, vals)), maximum(maximum.(v->isnan(v) ? -Inf : v, vals)) ) #clims = (minimum(minimum.(filter.(!isnan, vals))), # maximum(maximum.(filter.(!isnan, vals)))) end # ----------------------------- # background_color_inside bginside, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_bgcolor_inside, Plots.RGB(.7,.7,.7)) if seriestype == :surface; bginside = Plots.RGBA(0.0,0.0,0.0,0.0); end # ----------------------------- # colorbar cb, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_colorbar, :none) # ----------------------------- # colorbar_title cbtitle, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_colorbar_title, "") # ----------------------------- # xlims, ylims xlims, kwdict = VisClaw.parse_xlims(kwdict) ylims, kwdict = VisClaw.parse_ylims(kwdict) # ----------------------------- ## set range if isa(region, VisClaw.AbstractTopo); xlims=extrema(region.x); ylims=extrema(region.y); end if isa(region, VisClaw.Region); xlims=region.xlims; ylims=region.ylims; end # Too fine grids are not plotted if isempty(AMRlevel) && xlims==nothing && ylims==nothing AMRlevel = 1:3 end ## the number of tiles ntile = length(tiles) ## nplot_org = plt.n ## display each tile for i = 1:ntile ## skip when the AMR level of this tile doesn't match any designated level if !isempty(AMRlevel) if isempty(findall(tiles[i].AMRlevel .== AMRlevel)); continue; end end ## set the boundary x = [tiles[i].xlow, tiles[i].xlow+tiles[i].dx*tiles[i].mx] y = [tiles[i].ylow, tiles[i].ylow+tiles[i].dy*tiles[i].my] ## grid info xvec = collect(Float64, x[1]-0.5tiles[i].dx:tiles[i].dx:x[2]+0.5tiles[i].dx+1e-4) yvec = collect(Float64, y[1]-0.5tiles[i].dy:tiles[i].dy:y[2]+0.5tiles[i].dy+1e-4) ## check whether the tile is on the domain if xlims!=nothing if (xvec[end] < xlims[1]) | (xlims[2] < xvec[1]); continue; end end if ylims!=nothing if (yvec[end] < ylims[1]) | (ylims[2] < yvec[1]); continue; end end ## adjust data val = zeros(tiles[i].my+2,tiles[i].mx+2) if !wind val[2:end-1,2:end-1] = getfield(tiles[i], var) else val[2:end-1,2:end-1] = sqrt.(getfield(tiles[i], :u).^2 .+ getfield(tiles[i], :v).^2) end val[2:end-1,1] = val[2:end-1,2] val[2:end-1,end] = val[2:end-1,end-1] val[1,:] = val[2,:] val[end,:] = val[end-1,:] ## plot plt = Plots.plot!(plt, xvec, yvec, val, seriestype=seriestype, c=seriescolor, clims=clims, colorbar=false) end # check the number of added series if plt.n == nplot_org println("Nothing to be plotted. Check xlims and ylims you specified.") plt = Plots.plot!(plt, 0:5, 0:5, repeat([NaN], inner=(6,6)), label="", c=seriescolor, clims=clims, colorbar=cb) return plt end ## xlims, ylims x1, x2, y1, y2 = VisClaw.getlims(tiles) xrange = (x1, x2) yrange = (y1, y2) xlims = xlims==nothing ? xrange : xlims ylims = ylims==nothing ? yrange : ylims plt = Plots.plot!(plt, xlims=xlims, ylims=ylims) if !isempty(kwdict); plt = Plots.plot!(plt; kwdict...); end ## colorbar for i = nplot_org+1:plt.n; plt.series_list[i].plotattributes[:colorbar_entry] = false; end if (cb !== :none) && (cb !== false) plt.series_list[nplot_org+1].plotattributes[:colorbar_entry] = true end ## Appearance plt = Plots.plot!(plt, axis_ratio=:equal, grid=false, bginside=bginside, colorbar=cb, colorbar_title=cbtitle) ## return value return plt end ###################################### """ $(@doc plotsamr2d!) """ plotsamr2d(tiles; kwargs...) = plotsamr2d!(Plots.plot(), tiles; kwargs...) ###################################### ####################################### """ gridnumber!(plt::Plots.Plot, tiles; AMRlevel::AbstractVector=[], font::Plots.Font=Plots.font(12, :hcenter, :black), xlims=(), ylims=()) Function: add the grid numbers of tiles """ function gridnumber!(plt, tiles; AMRlevel::AbstractVector=[], font::Plots.Font=Plots.font(12, :hcenter, :black), xlims=(), ylims=()) # Too fine grids are not plotted if isempty(AMRlevel) && isempty(xlims) && isempty(ylims) AMRlevel = 1:3 end # get current lims if plt.n != 0 if isempty(xlims) xlims = Plots.xlims(plt) end if isempty(ylims) ylims = Plots.ylims(plt) end end ## the number of tiles ntile = length(tiles) for i = 1:ntile ## skip when the AMR level of this tile doesn't match any designated level if !isempty(AMRlevel) if isempty(findall(tiles[i].AMRlevel .== AMRlevel)); continue; end end ## set the boundary x = [tiles[i].xlow, tiles[i].xlow+tiles[i].dx*tiles[i].mx] y = [tiles[i].ylow, tiles[i].ylow+tiles[i].dy*tiles[i].my] ann = @sprintf("%02d", tiles[i].gridnumber) ## check whether the tile is on the domain if !isempty(xlims) if (mean(x) < xlims[1]) | (xlims[2] < mean(x)); continue; end end if !isempty(ylims) if (mean(y) < ylims[1]) | (ylims[2] < mean(y)); continue; end end ## annotations plt = Plots.plot!(plt; annotations=(mean(x),mean(y), Plots.text(ann, font))) end return plt end ####################################### ####################################### """ tilebound!(plt, tiles; AMRlevel=[], kwargs...) Function: draw boundaries of tiles """ function tilebound!(plt, tiles; AMRlevel=[], kwargs...) # parse keyword args kwdict = KWARG(kwargs) # ----------------------------- # linestyle linestyle, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_linestyle, :solid) # ----------------------------- # linecolor linecolor, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_linecolor, :black) # ----------------------------- # xlims, ylims xlims, kwdict = VisClaw.parse_xlims(kwdict) ylims, kwdict = VisClaw.parse_ylims(kwdict) # get current lims if plt.n != 0 if xlims == nothing xlims = Plots.xlims(plt) end if ylims == nothing ylims = Plots.ylims(plt) end end # ----------------------------- # Too fine grids are not plotted if isempty(AMRlevel) && xlims==nothing && ylims==nothing; AMRlevel = 1:3; end ## the number of tiles ntile = length(tiles) for i = 1:ntile ## skip when the AMR level of this tile doesn't match any designated level if !isempty(AMRlevel); if isempty(findall(tiles[i].AMRlevel .== AMRlevel)); continue; end; end ## set the boundary x = [tiles[i].xlow, tiles[i].xlow+tiles[i].dx*tiles[i].mx] y = [tiles[i].ylow, tiles[i].ylow+tiles[i].dy*tiles[i].my] ## check whether the tile is on the domain if xlims!=nothing if (x[2] < xlims[1]) | (xlims[2] < x[1]); continue; end end if ylims!=nothing if (y[2] < ylims[1]) | (ylims[2] < y[1]); continue; end end plt = Plots.plot!(plt, [x[1], x[1], x[2], x[2], x[1]], [y[1], y[2], y[2], y[1], y[1]]; label="", linestyle=linestyle, linecolor=linecolor, kwdict...) end return plt end ####################################### ####################################### """ plts = plotsamr(amrs::VisClaw.AMR, timeindex=1:amrs.nstep; kwargs...) Function: plot VisClaw.AMR data. The keyword arguments follow [`plotsamr2d`](@ref) """ function plotsamr(amrs::VisClaw.AMR, timeindex=1:amrs.nstep; kwargs...) ## plot time-series plt = Array{Plots.Plot}(undef, length(timeindex)) for i = timeindex if isempty(amrs.amr[i]); plt[i-timeindex[1]+1] = Plots.plot(); continue; end plt[i-timeindex[1]+1] = VisClaw.plotsamr2d(amrs.amr[i]; kwargs...) end ## return plots return plt end #############################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
2334
""" val, d = parse_from_keys(d::Dict, symbs) This function is based on find_in_dict() in GMT. Check if d (Dict) contains either of symbs (list of symbol). If true, return corresponding value """ function parse_from_keys(d::Dict, symbs) for symb in symbs if haskey(d, symb) val = d[symb] delete!(d,symb) return val, d end end # return if nothing return nothing, d end # Plots # ----------------------------- """ key: seriestype To parse a value of the key in kwargs """ parse_seriestype(d::Dict) = parse_from_keys(d, [:seriestype, :st, :t, :typ, :linetype, :lt]) # ----------------------------- parse_seriescolor(d::Dict) = parse_from_keys(d, [:seriescolor, :c, :color, :colour]) # ----------------------------- parse_clims(d::Dict) = parse_from_keys(d, [:clims, :clim, :cbarlims, :cbar_lims, :climits, :color_limits]) # ----------------------------- parse_bgcolor_inside(d::Dict) = parse_from_keys(d, [:background_color_inside, :bg_inside, :bginside, :bgcolor_inside, :bg_color_inside, :background_inside, :background_colour_inside, :bgcolour_inside, :bg_colour_inside]) # ----------------------------- parse_xlims(d::Dict) = parse_from_keys(d, [:xlims, :xlim, :xlimit, :xlimits]) # ----------------------------- parse_ylims(d::Dict) = parse_from_keys(d, [:ylims, :ylim, :ylimit, :ylimits]) # ----------------------------- parse_colorbar(d::Dict) = parse_from_keys(d, [:colorbar,:cb, :cbar, :colorkey]) # ----------------------------- parse_colorbar_title(d::Dict) = parse_from_keys(d, [:colorbar_title]) # ----------------------------- parse_linewidth(d::Dict) = parse_from_keys(d, [:linewidth, :w, :width, :lw]) # ----------------------------- parse_linestyle(d::Dict) = parse_from_keys(d, [:linestyle, :style, :s, :ls]) # ----------------------------- parse_linecolor(d::Dict) = parse_from_keys(d, [:linecolor, :lc, :lcolor, :lcolour, :linecolour]) # ----------------------------- parse_label(d::Dict) = parse_from_keys(d, [:lab, :labels, :label]) # ----------------------------- # ----------------------------- parse_B(d::Dict) = parse_from_keys(d, [:B, :frame, :axis]) # ----------------------------- function kwarg_default(d::Dict, func::Function, default_value) val, d = func(d) if val==nothing; val=default_value; end return val, d end
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
3182
############################################################################## """ plt = plotscheck("simlation/path/_output"::AbstractString; vartype::Symbol=:surface, AMRlevel=[], runup=true, region="", kwargs...) Quick checker of the spatial distribution """ function plotscheck(simdir::AbstractString; vartype::Symbol=:surface, AMRlevel=[], runup::Bool=true, region="", testplot::Bool=false, kwargs...) !any([vartype==s for s in [:surface, :storm, :current]]) && error("Invalid input argument vartype: $vartype") ## define the filepath & filename if vartype==:surface fnamekw = r"^fort\.q\d+$" loadfunction = VisClaw.loadsurface kwargs_load = Dict([(:runup, runup)]) elseif vartype==:current fnamekw = r"^fort\.q\d+$" loadfunction = VisClaw.loadcurrent kwargs_load = Dict([]) elseif vartype==:storm fnamekw = r"^fort\.a\d+$" loadfunction = VisClaw.loadstorm kwargs_load = Dict([]) end ## parse keyword args kwdict = KWARG(kwargs) ## xlims, ylims xlims, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_xlims, (-Inf,Inf)) ylims, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_ylims, (-Inf,Inf)) ## set range if isa(region, VisClaw.AbstractTopo); xlims=extrema(region.x); ylims=extrema(region.y); end if isa(region, VisClaw.Region); xlims=region.xlims; ylims=region.ylims; end ## make a list isdir(simdir) || error("Not found: directory $simdir") flist = readdir(simdir) filter!(x->occursin(fnamekw, x), flist) isempty(flist) && error("File named $fnamekw was not found") ## load geoclaw.data params = VisClaw.geodata(simdir) ## the number of files nfile = length(flist) ### draw figures until nothing or invalid number is input println(">> Press ENTER with a blank to finish") println(">> Input a file sequence number you want to plot:") ex=0 # initial value cnt=0 while ex==0 ## accept input the step number of interest @printf("checkpoint time (1 to %d) = ", nfile) i = testplot ? "1" : readline(stdin) if testplot; ex=1; end ## check whether the input is integer if isempty(i); ex=1; continue; end; ## parse to interger i = try; parse(Int64,i) catch; "cannot be parsed to integer"; ex=1; continue; end ## check whether the input is valid number if ( (i>nfile) || (i<1) ); println("Invalid number"); ex=1; continue; end ## load data amrs = loadfunction(simdir, i; AMRlevel=AMRlevel, xlims=xlims, ylims=ylims, kwargs_load...) runup && (coarsegridmask!(amrs)) ## draw figure plt = VisClaw.plotsamr2d(amrs.amr[1]; AMRlevel=AMRlevel, xlims=xlims, ylims=ylims, kwdict...) plt = Plots.plot!(plt, title=@sprintf("%8.1f",amrs.timelap[1])*" s") ## show #plt = Plots.plot!(plt, show=true) display(plt) cnt += 1 end ## if no plot is done if cnt==0; plt = nothing; end ## return value return plt end ##############################################################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
2506
############################################################################### """ plt = plotsfgmax(fg::VisClaw.FixedGrid, fgmax::VisClaw.FGmax, var::Symbol; kwargs...) plotsfgmax!(plt::Plots.Plot, fg::VisClaw.FixedGrid, fgmax::VisClaw.FGmax, var::Symbol; kwargs...) """ function plotsfgmax!(plt, fg::VisClaw.FixedGrid, fgmax::VisClaw.FGmax, var::Symbol=:D; kwargs...) # parse keyword args kwdict = KWARG(kwargs) # get var val = copy(getfield(fgmax, var)) # check isempty(val) && error("Empty: $var") # vector if fg.style == 0 || fg.style == 1 || fg.style == 3 # correct (var==:D) && (val = val + fgmax.topo) (var==:Dmin) && (val = val - fgmax.topo) # plot plt = Plots.plot!(plt, fg.x, fg.y, val; kwdict...) elseif fg.style == 2 seriestype, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_seriestype, :heatmap) x = collect(Float64, LinRange(fg.xlims[1], fg.xlims[end], fg.nx)) y = collect(Float64, LinRange(fg.ylims[1], fg.ylims[end], fg.ny)) # wet cells wet = fgmax.D .!= 0.0 land = fgmax.topo .> 0.0 # correct (var==:D) && (val[wet] = val[wet] + fgmax.topo[wet]) (var==:Dmin) && (val[wet] = val[wet] - fgmax.topo[wet]) (var==:Dmin) && (val[land] .= NaN) isa(val, AbstractArray{Dates.DateTime}) || (val[.!wet] .= NaN) #val[.!wet] .= NaN # plot plt = Plots.plot!(plt, x, y, val; ratio=:equal, xlims=fg.xlims, ylims=fg.ylims, seriestype=seriestype, kwdict...) elseif fg.style == 4 seriestype, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_seriestype, :heatmap) x = collect(Float64, LinRange(fg.xlims[1], fg.xlims[end], fg.nx)) y = collect(Float64, LinRange(fg.ylims[1], fg.ylims[end], fg.ny)) # correct (var==:D) && (val = val + fgmax.topo) (var==:Dmin) && (val = val - fgmax.topo) var_vec = copy(val) if !isa(val, AbstractArray{Dates.DateTime}) val = NaN*zeros(Float64 ,(fg.ny, fg.nx)) val[fg.flag] = var_vec end val = reverse(val, dims=1) # plot plt = Plots.plot!(plt, x, y, val; ratio=:equal, xlims=fg.xlims, ylims=fg.ylims, seriestype=seriestype, kwdict...) end # return return plt end ############################################################################### """ $(@doc plotsfgmax!) """ plotsfgmax(fg::VisClaw.FixedGrid, fgmax::VisClaw.FGmax, var::Symbol=:D; kwargs...) = plotsfgmax!(Plots.plot(), fg, fgmax, var; kwargs...) ###############################################################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
2874
ms_default=8 an_default = Plots.font(10,:left,:top,0.0,:black) ########################################### """ plt = plotsgaugelocation(gauge::VisClaw.Gauge; offset=(0,0), font::Plots.Font, annotation_str=@sprintf(" %s",gauge.id), kwargs...) plt = plotsgaugelocation(gauges::Vector{VisClaw.Gauge}; offset=(0,0), font::Plots.Font, annotation_str=" ", kwargs...) plotsgaugelocation!(plt::Plots.Plot, gauge::VisClaw.Gauge; offset=(0,0), font::Plots.Font, annotation_str=@sprintf(" %s",gauge.id), kwargs...) plotsgaugelocation!(plt, gauges::Vector{VisClaw.Gauge}; offset=(0,0), font::Plots.Font, annotation_str=" ", kwargs...) Function: plot a gauge location (with scatter plot) using Plots """ function plotsgaugelocation!(plt, gauge::VisClaw.Gauge; offset=(0,0), label="", font::Plots.Font=an_default, annotation_str=@sprintf(" %s",gauge.id), kwargs...) # plot plt = Plots.scatter!(plt, [gauge.loc[1]], [gauge.loc[2]]; label=label, ann=(gauge.loc[1]+offset[1], gauge.loc[2]+offset[2], Plots.text(annotation_str, font)), kwargs...) # return return plt end ########################################### """ $(@doc plotsgaugelocation!) """ plotsgaugelocation(gauge::VisClaw.Gauge; offset=(0,0), label="", font::Plots.Font=an_default, annotation_str=@sprintf(" %s",gauge.id), kwargs...) = plotsgaugelocation!(Plots.plot(), gauge; offset=(0,0), label=label, font=font, annotation_str=annotation_str, kwargs...) ########################################### function plotsgaugelocation!(plt, gauges::Vector{VisClaw.Gauge}; offset=(0,0), label="", font::Plots.Font=an_default, annotation_str=" ", kwargs...) # get values in all gauges ngauges = length(gauges) loc_all = getfield.(gauges, :loc) loc = zeros(Float64, ngauges,2) for i=1:ngauges; loc[i,:] = loc_all[i]; end if (isa(annotation_str, Vector{String})) || (annotation_str==" ") if length(annotation_str) !== ngauges id_all = getfield.(gauges, :id) # annotation annotation_str = map(x -> @sprintf(" %s",x), id_all) end end if isa(annotation_str, String) annotation_str = fill(annotation_str, ngauges) end annotation_arg = Vector{Tuple}(undef,ngauges) for i=1:ngauges annotation_arg[i] = (loc_all[i][1]+offset[1], loc_all[i][2]+offset[2], Plots.text(annotation_str[i], font)) end # plot plt = Plots.scatter!(plt, loc[:,1], loc[:,2]; kwargs..., label=label, ann=annotation_arg) # return return plt end ########################################### plotsgaugelocation(gauges::Vector{VisClaw.Gauge}; offset=(0,0), label="", font::Plots.Font=an_default, annotation_str=" ", kwargs...) = plotsgaugelocation!(Plots.plot(), gauges::Vector{VisClaw.Gauge}; offset=offset, label=label, font=font, annotation_str=annotation_str, kwargs...)
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
1596
""" plt = plotsgaugevelocity(gauge::VisClaw.Gauge; kwargs...) plt = plotsgaugevelocity(gauges::Vector{VisClaw.Gauge}; kwargs...) plotsgaugevelocity!(plt::Plots.Plot, gauge::VisClaw.Gauge; kwargs...) plotsgaugevelocity!(plt::Plots.Plot, gauges::Vector{VisClaw.Gauge}; kwargs...) Function: plot waveforms of gauges """ function plotsgaugevelocity!(plt, gauge::VisClaw.Gauge; kwargs...) # keyword args d = KWARG(kwargs) # plot plt = Plots.plot!(plt, gauge.time, sqrt.(gauge.u.^2 .+ gauge.v.^2); label=gauge.label, d...) # return return plt end ########################################### """ $(@doc plotsgaugevelocity!) """ plotsgaugevelocity(gauge::VisClaw.Gauge; kwargs...) = plotsgaugevelocity!(Plots.plot(), gauge; kwargs...) ########################################### ########################################### function plotsgaugevelocity!(plt, gauges::Vector{VisClaw.Gauge}; kwargs...) # keyword args d = KWARG(kwargs) # get values in all gauges time_all = getfield.(gauges, :time) u_all = getfield.(gauges, :u) v_all = getfield.(gauges, :v) label_all = getfield.(gauges, :label) # number of gauges ngauge = length(gauges) for i = 1:ngauge # plot plt = Plots.plot!(plt, time_all[i], sqrt.(u_all[i].^2 .+ v_all[i].^2); label=label_all[i], d...) end # return return plt end ########################################### plotsgaugevelocity(gauges::Vector{VisClaw.Gauge}; kwargs...) = plotsgaugevelocity!(Plots.plot(), gauges; kwargs...) ###########################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
1508
""" plt = plotsgaugewaveform(gauge::VisClaw.Gauge; kwargs...) plt = plotsgaugewaveform(gauges::Vector{VisClaw.Gauge}; kwargs...) plotsgaugewaveform!(plt::Plots.Plot, gauge::VisClaw.Gauge; kwargs...) plotsgaugewaveform!(plt::Plots.Plot, gauges::Vector{VisClaw.Gauge}; kwargs...) Function: plot waveforms of gauges """ function plotsgaugewaveform!(plt, gauge::VisClaw.Gauge; kwargs...) # keyword args d = KWARG(kwargs) # plot plt = Plots.plot!(plt, gauge.time, gauge.eta; label=gauge.label, d...) # return return plt end ########################################### """ $(@doc plotsgaugewaveform!) """ plotsgaugewaveform(gauge::VisClaw.Gauge; kwargs...) = plotsgaugewaveform!(Plots.plot(), gauge; kwargs...) ########################################### ########################################### function plotsgaugewaveform!(plt, gauges::Vector{VisClaw.Gauge}; kwargs...) # keyword args d = KWARG(kwargs) # get values in all gauges time_all = getfield.(gauges, :time) eta_all = getfield.(gauges, :eta) label_all = getfield.(gauges, :label) # number of gauges ngauge = length(gauges) for i = 1:ngauge # plot plt = Plots.plot!(plt, time_all[i], eta_all[i]; label=label_all[i], d...) end # return return plt end ########################################### plotsgaugewaveform(gauges::Vector{VisClaw.Gauge}; kwargs...) = plotsgaugewaveform!(Plots.plot(), gauges; kwargs...) ###########################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
562
function plotssavefig(plts, figname="visclaw.svg"; num_start::Integer=1, kwargs...) dn = dirname(figname) bn = basename(figname) for i=1:length(plts) numstr = @sprintf("%03d",(i-1)+num_start) bnnum = occursin(".", bn) ? replace(bn, "." => "-"*numstr*".") : bn*"-"*numstr Plots.savefig(plts[i], joinpath(dn,bnnum); kwargs...) end end function plotsgif(plts, gifname::AbstractString="visclaw.gif"; kwargs...) anim = Plots.Animation() map(p->Plots.frame(anim, p), plts) Plots.gif(anim, gifname; kwargs...) end
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
4988
#################################################### """ plt = plotstopo(topo::VisClaw.Topo; kwargs...) plotstopo!(plt::Plots.Plot, topo::VisClaw.Topo; kwargs...) plot topography and bathymetry data using Plots """ function plotstopo!(plt, topo::VisClaw.Topo; kwargs...) # parse keyword args kwdict = KWARG(kwargs) seriestype, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_seriestype, :heatmap) xlims, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_xlims, extrema(topo.x)) ylims, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_ylims, extrema(topo.y)) # plot plt = Plots.plot!(plt, topo.x, topo.y, topo.elevation; seriestype=seriestype, xlims=xlims, ylims=ylims, axis_ratio=:equal, kwdict...) # return return plt end #################################################### """ $(@doc plotstopo!) """ plotstopo(topo::VisClaw.Topo; kwargs...) = plotstopo!(Plots.plot(), topo; kwargs...) #################################################### """ plt = plotsdtopo(dtopo::VisClaw.DTopo, itime::Integer=0; kwargs...) plotsdtopo!(plt::Plots.Plot, dtopo::VisClaw.DTopo, itime::Integer=0; kwargs...) plot dtopo data using Plots """ function plotsdtopo!(plt, dtopo::VisClaw.DTopo, itime::Integer=0; kwargs...) ( (itime < 0) || (dtopo.mt < itime) ) && error("Invalid time") if dtopo.mt==1; z = dtopo.deform elseif itime == 0; z = dtopo.deform[:,:,end] else; z = dtopo.deform[:,:,itime] end # parse keyword args kwdict = KWARG(kwargs) seriestype, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_seriestype, :heatmap) # plot plt = Plots.plot!(plt, dtopo.x, dtopo.y, z; seriestype=seriestype, xlims=extrema(dtopo.x), ylims=extrema(dtopo.y), axis_ratio=:equal, kwdict...) # return return plt end #################################################### """ $(@doc plotsdtopo!) """ plotsdtopo(dtopo::VisClaw.DTopo, itime::Integer=0; kwargs...) = plotsdtopo!(Plots.plot(), dtopo, itime; kwargs...) #################################################### """ plt = plotstoporange(geo::VisClaw.AbstractTopo; kwargs...) plotstoporange!(plt::Plots.Plot, geo::VisClaw.AbstractTopo; kwargs...) plot a range of topo/bath using Plots """ function plotstoporange!(plt, geo::VisClaw.AbstractTopo; kwargs...) # parse keyword args kwdict = KWARG(kwargs) label, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_label, "") xp = [geo.x[1], geo.x[1] , geo.x[end], geo.x[end], geo.x[1]] yp = [geo.y[1], geo.y[end], geo.y[end], geo.y[1] , geo.y[1]] # plot plt = Plots.plot!(plt, xp, yp; label=label, kwdict...) return plt end #################################################### """ $(@doc plotstoporange!) """ plotstoporange(geo::VisClaw.AbstractTopo; kwargs...) = plotstoporange!(Plots.plot(), geo; kwargs...) #################################################### #################################################### """ plt = plotscoastline(topo::VisClaw.Topo; kwargs...) plt = plotscoastline(topo::VisClaw.Topo, wetdry::VisClaw.Topo; kwargs...) plotscoastline!(plt::Plots.Plot, topo::VisClaw.Topo; kwargs...) plotscoastline!(plt::Plots.Plot, topo::VisClaw.Topo, wetdry::VisClaw.Topo; kwargs...) plot coastlines from topography and bathymetry data using Plots """ function plotscoastline!(plt, topo::VisClaw.Topo; kwargs...) # parse keyword args kwdict = KWARG(kwargs) label, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_label, "") xlims, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_xlims, extrema(topo.x)) ylims, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_ylims, extrema(topo.y)) # plot plt = Plots.contour!(plt, topo.x, topo.y, topo.elevation; levels=[0], label=label, xlims=xlims, ylims=ylims, axis_ratio=:equal, kwdict...) return plt end #################################################### """ $(@doc plotscoastline!) """ plotscoastline(topo::VisClaw.Topo; kwargs...) = plotscoastline!(Plots.plot(), topo; kwargs...) #################################################### #################################################### function plotscoastline!(plt, topo::VisClaw.Topo, wetdry::VisClaw.Topo; kwargs...) ## check args (size(topo.elevation) == size(wetdry.elevation)) || error("size of wetdry array should correspond to that of topo array.") ## make a new VisClaw.Topo for coastline plot dry = findall(convert(BitArray, wetdry.elevation)) topotmp = copy(topo.elevation) topotmp[dry] .= 1e3 topo_coastline = VisClaw.Topo(topo.ncols, topo.nrows, topo.x, topo.y, topo.dx, topo.dy, topotmp) ## plot plt = plotscoastline!(plt, topo_coastline; kwargs...) return plt end #################################################### plotscoastline(topo::VisClaw.Topo, wetdry::VisClaw.Topo; kwargs...) = plotscoastline!(Plots.plot(), topo, wetdry; kwargs...) ####################################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
940
#################################################### """ plt = plotstrack(track::VisClaw.Track, index::AbstractVector=1:length(track.lon); kwargs...) plotstrack!(plt::Plots.Plot, track::VisClaw.Track, index::AbstractVector=1:length(track.lon); kwargs...) plot a typhoon/hurricane track using Plots """ function plotstrack!(plt, track::VisClaw.Track, index::AbstractVector=1:length(track.lon); kwargs...) # parse keyword args kwdict = KWARG(kwargs) label, kwdict = VisClaw.kwarg_default(kwdict, VisClaw.parse_label, "") # plot plt = Plots.plot!(plt, track.lon[index], track.lat[index]; axis_ratio=:equal, label=label, kwdict...) return plt end #################################################### """ $(@doc plotstrack!) """ plotstrack(track::VisClaw.Track, index::AbstractVector=1:length(track.lon); kwargs...) = plotstrack!(Plots.plot(), track, index; kwargs...) ####################################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
3244
############################################ """ printtopoESRI(topo::VisClaw.Topo, filename::AbstractString; nodatavalue::Integer=-9999, center::Bool=true) print topo data as a file (ESRI ASCII format) """ function printtopoESRI(topo::VisClaw.Topo, filename::AbstractString="topo.asc"; nodatavalue::Integer=-9999, center::Bool=true) nrows, ncols = size(topo.elevation) ## print open(filename, "w") do fileIO ## header @printf(fileIO, "%d ncols\n", ncols) @printf(fileIO, "%d nrows\n", nrows) if center @printf(fileIO, "%e xllcenter\n", topo.x[1]) @printf(fileIO, "%e yllcenter\n", topo.y[1]) else @printf(fileIO, "%e xllcorner\n", topo.x[1]) @printf(fileIO, "%e yllcorner\n", topo.y[1]) end @printf(fileIO, "%e cellsize\n", topo.dx) @printf(fileIO, "%d nodatavalue\n", nodatavalue) ## elevation if isa(topo.elevation, BitArray) || isa(topo.elevation, Array{Int,2}) || isa(topo.elevation, Array{UInt,2}) [(if j != ncols @printf(fileIO, "%d ", topo.elevation[i,j]) else @printf(fileIO, "%d\n", topo.elevation[i,j]) end) for j=1:ncols, i=nrows:-1:1] else [(if j != ncols @printf(fileIO, "%14.6e ", topo.elevation[i,j]) else @printf(fileIO, "%14.6e\n", topo.elevation[i,j]) end) for j=1:ncols, i=nrows:-1:1] end end ## close return nothing end ############################################ const printtopo = printtopoESRI ############################################ """ printdtopo(dtopo::VisClaw.DTopo, filename::AbstractString; center::Bool=true) print dtopo data as a topotype-3-file """ function printdtopo(dtopo::VisClaw.DTopo, filename::AbstractString="dtopo.asc"; center::Bool=true) ## print open(filename, "w") do fileIO ## header @printf(fileIO, "%d mx\n", dtopo.mx) @printf(fileIO, "%d my\n", dtopo.my) @printf(fileIO, "%d mt\n", dtopo.mt) if center @printf(fileIO, "%e xllcenter\n", dtopo.x[1]) @printf(fileIO, "%e yllcenter\n", dtopo.y[1]) else @printf(fileIO, "%e xllcorner\n", dtopo.x[1]) @printf(fileIO, "%e yllcorner\n", dtopo.y[1]) end @printf(fileIO, "%e t0\n", dtopo.t0) @printf(fileIO, "%e dx\n", dtopo.dx) @printf(fileIO, "%e dy\n", dtopo.dy) @printf(fileIO, "%e dt\n", dtopo.dt) ## dtopo if dtopo.mt == 1 [(if j != dtopo.mx @printf(fileIO, "%14.6e ", dtopo.deform[i,j]) else @printf(fileIO, "%14.6e\n", dtopo.deform[i,j]) end) for j=1:dtopo.mx, i=dtopo.my:-1:1] else [(if j != dtopo.mx @printf(fileIO, "%14.6e ", dtopo.deform[i,j,k]) else @printf(fileIO, "%14.6e\n", dtopo.deform[i,j,k]) end) for j=1:dtopo.mx, i=dtopo.my:-1:1, k=1:dtopo.mt] end end ## close return nothing end ############################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
2492
################################# """ replaceunit!(fgmax::VisClaw.FGmax, unit::Symbol) replaceunit!(gauge::VisClaw.Gauge, unit::Symbol) replaceunit!(amrs::VisClaw.AMR, unit::Symbol) replaceunit!(track::VisClaw.Track, unit::Symbol) Time unit converter The second arg unit must be any one of :second, :minute, :hour, or :day. """ function replaceunit!(fgmax::VisClaw.FGmax, unit::Symbol) !haskey(timedict, unit) && error("Invalid specification of unit") !haskey(timedict, fgmax.unittime) && error("Invalid symbol in fgmax") ratio = timedict[fgmax.unittime]/timedict[unit] if abs(ratio - 1.0) < 1e-5; return fgmax; end # convert fgmax.unittime = unit fgmax.tD = ratio.*fgmax.tD fgmax.tarrival = ratio.*fgmax.tarrival !isempty(fgmax.tv) && (fgmax.tv = ratio.*fgmax.tv) if !isempty(fgmax.tM) fgmax.tM = ratio.*fgmax.tM fgmax.tMflux = ratio.*fgmax.tMflux fgmax.tDmin = ratio.*fgmax.tDmin end return fgmax end ################################# ################################# function replaceunit!(gauge::VisClaw.Gauge, unit::Symbol) !haskey(timedict, unit) && error("Invalid specification: unit") !haskey(timedict, gauge.unittime) && error("Invalid symbol in gauge") ratio = timedict[gauge.unittime]/timedict[unit] if abs(ratio - 1.0) < 1e-5; return gauge; end # convert gauge.unittime = unit gauge.time = ratio.*gauge.time # return value return gauge end ################################# ################################# function replaceunit!(amrs::VisClaw.AMR, unit::Symbol) !haskey(timedict, unit) && error("Invalid specification: unit") !haskey(timedict, amrs.unittime) && error("Invalid symbol in AMR") ratio = timedict[amrs.unittime]/timedict[unit] if abs(ratio - 1.0) < 1e-5; return amrs; end # convert amrs.unittime = unit amrs.timelap = ratio.*amrs.timelap # return value return amrs end ################################# ################################# function replaceunit!(track::VisClaw.Track, unit::Symbol) !haskey(timedict, unit) && error("Invalid specification: unit") !haskey(timedict, track.unittime) && error("Invalid symbol in AMR") ratio = timedict[track.unittime]/timedict[unit] if abs(ratio - 1.0) < 1e-5; return track; end # convert track.unittime = unit track.timelap = ratio.*track.timelap # return value return track end #################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
1963
############################################# """ eta_uniformgrid = interpsurface(amrgrid::Vector{VisClaw.AMRGrid}, topo::VisClaw.Topo) eta_uniformgrid = interpsurface(amr::VisClaw.AMR, topo::VisClaw.Topo) Convert AMR tile data into uniform grid data using the SciPy scattered interpolation.\n Interpolation of inundation height (land) is not supported. \n """ function interpsurface(amrgrid::Vector{VisClaw.AMRGrid}, topo::VisClaw.Topo) ## import scipyinterpolate = PyCall.pyimport("scipy.interpolate") ## make grid data from topo xmesh_all = repeat(topo.x', inner=(topo.nrows,1)) ymesh_all = repeat(topo.y , inner=(1,topo.ncols)) land = topo.elevation .>= 0.0 ## get lims of the designated region xmin, xmax = extrema(topo.x) ymin, ymax = extrema(topo.y) ## scattered x y data ntile = length(amrgrid) x_all = empty([0.0]) y_all = empty([0.0]) z_all = empty([0.0]) for i_tile = 1:ntile tile = amrgrid[i_tile] x1, x2, y1, y2 = VisClaw.getlims(tile) x2 < xmin && (continue) xmax < x1 && (continue) y2 < ymin && (continue) ymax < y1 && (continue) xmesh, ymesh = VisClaw.meshtile(tile) ind = isnan.(tile.eta) push!(x_all, xmesh[.!ind]...) push!(y_all, ymesh[.!ind]...) push!(z_all, tile.eta[.!ind]...) end ## nodata if length(z_all) == 0 v_all = zeros(topo.nrows,topo.ncols) else v_all = scipyinterpolate.griddata([x_all y_all], z_all, (xmesh_all,ymesh_all), method="cubic") end v_all[land] .= NaN return v_all end ############################################# ############################################# function interpsurface(amrall::VisClaw.AMR, topo::VisClaw.Topo; timestep=1:amrall.nstep) eta_uniformgrid = [interpsurface(amrall.amr[k], topo) for k=timestep] eta_uniformgrid = cat(eta_uniformgrid...; dims=3) return eta_uniformgrid end
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
8379
### Define Structs abstract type AbstractAMR end abstract type AMRGrid <: VisClaw.AbstractAMR end ################################### """ Struct: storm data """ mutable struct Storm <: VisClaw.AMRGrid gridnumber::Integer AMRlevel::Integer mx::Integer my::Integer xlow::Float64 ylow::Float64 dx::Float64 dy::Float64 u::AbstractArray{Float64,2} v::AbstractArray{Float64,2} slp::AbstractArray{Float64,2} # Constructor VisClaw.Storm(gridnumber, AMRlevel, mx, my, xlow, ylow, dx, dy, u, v, slp) = new(gridnumber, AMRlevel, mx, my, xlow, ylow, dx, dy, u, v, slp) end ################################### ################################### """ Struct: Water veloccity """ mutable struct Velocity <: VisClaw.AMRGrid gridnumber::Integer AMRlevel::Integer mx::Integer my::Integer xlow::Float64 ylow::Float64 dx::Float64 dy::Float64 u :: AbstractArray{Float64,2} v :: AbstractArray{Float64,2} vel :: AbstractArray{Float64,2} # Constructor VisClaw.Velocity(gridnumber, AMRlevel, mx, my, xlow, ylow, dx, dy, u, v, vel) = new(gridnumber, AMRlevel, mx, my, xlow, ylow, dx, dy, u, v, vel) end ################################### ################################### """ Struct: Sea Surface Height """ mutable struct SurfaceHeight <: VisClaw.AMRGrid gridnumber::Integer AMRlevel::Integer mx::Integer my::Integer xlow::Float64 ylow::Float64 dx::Float64 dy::Float64 eta::AbstractArray{Float64,2} # Constructor VisClaw.SurfaceHeight(gridnumber, AMRlevel, mx, my, xlow, ylow, dx, dy, eta) = new(gridnumber, AMRlevel, mx, my, xlow, ylow, dx, dy, eta) end ################################### ################################### """ Struct: time-seies of AMR data """ mutable struct AMR <: VisClaw.AbstractAMR nstep::Integer timelap::AbstractVector amr :: AbstractVector{Vector{VisClaw.AMRGrid}} unittime :: Symbol # Constructor VisClaw.AMR(nstep, timelap, amr) = new(nstep, timelap, amr, :second) end ################################### abstract type AbstractTopo end ################################### """ Struct: topography and bathymetry """ struct Topo <: AbstractTopo ncols :: Integer nrows :: Integer x :: AbstractVector y :: AbstractVector dx :: Float64 dy :: Float64 elevation :: AbstractArray # Constructor VisClaw.Topo(ncols, nrows, x, y, dx, dy, elevation) = new(ncols, nrows, x, y, dx, dy, elevation) end ################################### ########################################################## """ Struct: seafloor deformation for tsunami computation """ struct DTopo <: AbstractTopo mx :: Integer my :: Integer x :: AbstractVector y :: AbstractVector dx :: Float64 dy :: Float64 mt :: Integer t0 :: Float64 dt :: Float64 deform :: AbstractArray{Float64} # Constructor VisClaw.DTopo(mx,my,x,y,dx,dy,mt,t0,dt,deform) = new(mx,my,x,y,dx,dy,mt,t0,dt,deform) end ########################################################## ########################################################## """ Struct: region """ struct Region level :: AbstractVector tlims :: Tuple xlims :: Tuple ylims :: Tuple # Constructor VisClaw.Region(level, tlims, xlims, ylims) = new(level, tlims, xlims, ylims) end ########################################################## ######################################## """ Struct: parameters in geoclaw.data """ struct GeoParam cs :: Integer # coordinate system p0:: Float64 # ambient pressure R :: Float64 # earth radious eta0 :: Float64 # sea level n ::Float64 # manning coafficient dmin :: Float64 # dry tolerance # Constructor VisClaw.GeoParam() = new(2,101300.0,6367500.0,0.0,0.025,0.001) VisClaw.GeoParam(cs,p0,R,eta0,n,dmin) = new(cs,p0,R,eta0,n,dmin) end ######################################## ######################################## """ Struct: parameters in amr.data """ struct AMRParam maxlevel::Integer # Constructor VisClaw.AMRParam(maxlevel) = new(maxlevel) end ######################################## ######################################## """ Struct: parameters in surge.data """ struct SurgeParam windindex::Integer slpindex::Integer stormtype::Integer # Constructor VisClaw.SurgeParam() = new(5,7,1) VisClaw.SurgeParam(windindex,slpindex,stormtype) = new(windindex,slpindex,stormtype) end ######################################## ######################################## """ Struct: gauge data """ mutable struct Gauge label :: AbstractString # Name id :: Integer # gauge id nt :: Integer # number of time step loc :: AbstractVector{Float64} # gauge location AMRlevel :: AbstractVector{Integer} time :: AbstractVector # time eta :: AbstractVector{Float64} # surface u :: AbstractVector{Float64} # u v :: AbstractVector{Float64} # v unittime :: Symbol # Constructor VisClaw.Gauge(label,id,nt,loc) = new(label,id,nt,loc,[],[],[],[],[], :second) VisClaw.Gauge(label,id,nt,loc,AMRlevel,time,eta) = new(label,id,nt,loc,AMRlevel,time,eta,[],[], :second) VisClaw.Gauge(label,id,nt,loc,AMRlevel,time,eta,u,v) = new(label,id,nt,loc,AMRlevel,time,eta,u,v, :second) end ######################################## ######################################## """ Struct: max values at a gauge """ mutable struct Gaugemax label :: AbstractString # Name id :: Integer # gauge id loc :: AbstractVector{Float64} # gauge location AMRlevel :: Integer eta :: Float64 vel :: Float64 t_eta t_vel unittime :: Symbol # Constructor VisClaw.Gaugemax(label,id,loc,AMRlevel,eta,vel,t_eta,t_vel,unittime) = new(label,id,loc,AMRlevel,eta,vel,t_eta,t_vel,unittime) end ######################################## ######################################## """ Struct: Fixed grid """ struct FixedGrid id :: Integer style :: Integer nval :: Integer ## point_style = 2, 4 nx :: Integer ny :: Integer xlims :: Tuple ylims :: Tuple ## point_style = 0, 1, 4 npts :: Integer x :: AbstractVector{Float64} y :: AbstractVector{Float64} ## point_style = 4 flag :: AbstractArray # Constructor ## point_style = 0, 1 VisClaw.FixedGrid(id,style,nval,npts,x,y) = new(id,style,nval,0,0,(NaN,NaN),(NaN,NaN),npts,x,y,[]) ## point_style = 2 VisClaw.FixedGrid(id,style,nval,nx,ny,xlims,ylims) = new(id,style,nval,nx,ny,xlims,ylims,0,[NaN],[NaN],[]) ## point_style = 3 VisClaw.FixedGrid(id,style,nval,nx,ny,xlims,ylims,npts,x,y) = new(id,style,nval,nx,ny,xlims,ylims,npts,x,y,[]) ## point_style = 4 VisClaw.FixedGrid(id,style,nval,nx,ny,xlims,ylims,npts,x,y,flag) = new(id,style,nval,nx,ny,xlims,ylims,npts,x,y,flag) end ######################################## ######################################## """ Struct: fgmax values """ mutable struct FGmax topo :: AbstractArray{Float64} D :: AbstractArray{Float64} v :: AbstractArray{Float64} M :: AbstractArray{Float64} Mflux :: AbstractArray{Float64} Dmin :: AbstractArray{Float64} tD :: AbstractArray tv :: AbstractArray tM :: AbstractArray tMflux :: AbstractArray tDmin :: AbstractArray tarrival :: AbstractArray unittime :: Symbol # Constructor VisClaw.FGmax(topo,D,tD,tarrival) = new(topo,D,emptyF,emptyF,emptyF,emptyF,tD,emptyF,emptyF,emptyF,emptyF,tarrival,:second) VisClaw.FGmax(topo,D,v,tD,tv,tarrival) = new(topo,D,v,emptyF,emptyF,emptyF,tD,tv,emptyF,emptyF,emptyF,tarrival,:second) VisClaw.FGmax(topo,D,v,M,Mflux,Dmin,tD,tv,tM,tMflux,tDmin,tarrival) = new(topo,D,v,M,Mflux,Dmin,tD,tv,tM,tMflux,tDmin,tarrival,:second) end ######################################## ######################################## """ Struct: track data container """ mutable struct Track timelap :: AbstractVector lon :: AbstractVector{Float64} lat :: AbstractVector{Float64} direction :: AbstractVector{Float64} unittime :: Symbol # Constructor VisClaw.Track(lon,lat) = new(empty([0.0]),lon,lat,empty([0.0]),:second) VisClaw.Track(timelap,lon,lat,direction) = new(timelap,lon,lat,direction,:second) end ########################################
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
code
1119
using VisClaw using Test using Printf # make a list exdir = joinpath(dirname(pathof(VisClaw)), "../example") filelist = readdir(exdir) filter!(x->occursin(".jl", x), filelist) #map(s->filter!(x->!occursin(s, x), filelist), ["check", "fgmax"]) map(s->filter!(x->!occursin(s, x), filelist), ["check"]) #filter!(x->occursin("current_Plots_ike", x), filelist) # number nf = length(filelist) println(@sprintf("%d", nf)*" files are going to be tested...") using GR: GR GR.inline("png") @testset "VisClaw.jl" begin # Write your own tests here. # for loop for f in filelist println(f) @test !isa(try include(joinpath(exdir,f)) catch ex ex end, Exception) #= try @test_nowarn include(joinpath(exdir,f)) catch e try include(joinpath(exdir,f)) catch e println("Failed "*f) bt = backtrace() msg = sprint(showerror, e, bt) println(msg) println() continue end continue end =# end end
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "BSD-3-Clause" ]
0.7.8
cef0143fee828ea605960108f18eed15efb232ef
docs
4041
# VisClaw.jl **NOTE:** this package is unofficial and the author is not engaged in the Clawpack Development Team. [![Build Status](https://travis-ci.com/hydrocoast/VisClaw.jl.svg?branch=master)](https://travis-ci.com/hydrocoast/VisClaw.jl) [![Codecov](https://codecov.io/gh/hydrocoast/VisClaw.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/hydrocoast/VisClaw.jl) [![Coveralls](https://coveralls.io/repos/github/hydrocoast/VisClaw.jl/badge.svg?branch=master)](https://coveralls.io/github/hydrocoast/VisClaw.jl?branch=master) <p align="center"> <img src="/figure/ex1.svg", width="250"> <img src="/figure/ex2.svg", width="250"> <img src="/figure/ex3.svg", width="250"> </p> VisClaw.jl is a Julia package of the Clawpack visualization tools (see http://www.clawpack.org). This allows to draw figures and animations using the Julia language. ## Requirements - [Julia](https://github.com/JuliaLang/julia) v1.6.0 or later - [GMT](https://github.com/GenericMappingTools/gmt) (Generic Mapping Tools) ## Installation - If you want to plot using [GMT.jl](https://github.com/GenericMappingTools/GMT.jl), install the [GMT](https://github.com/GenericMappingTools/gmt) in advance. Note that GMT.jl does NOT install the GMT program. - You can install the latest VisClaw.jl using the built-in package manager (accessed by pressing `]` in the Julia REPL) to add the package. ```julia pkg> add VisClaw ``` ## Usage - In preparation, run some of the Clawpack simulations (e.g. chile2010 `$CLAW/geoclaw/examples/tsunami/chile2010` and ike `$CLAW/geoclaw/examples/storm-surge/ike`). - This package uses either GMT.jl or Plots.jl to plot results of the numerical simulation. Plots.jl is more suitable for a quick check. The following codes generate a spatial distribution of the sea surface height using Plots: ```julia julia> using VisClaw julia> simdir = joinpath(CLAW, "geoclaw/examples/tsunami/chile2010/_output") julia> plt = plotscheck(simdir; color=:balance, clims=(-0.5,0.5)) >> Press ENTER with a blank to finish >> Input a file sequence number you want to plot: checkpoint time (1 to 19) = ``` Topography data also can be easily plotted: ```julia julia> topo = loadtopo(simdir) julia> plt = plotstopo(topo) ``` See [Examples_using_Plots.ipynb](https://github.com/hydrocoast/VisClawJuliaExamples/blob/master/Examples_using_Plots.ipynb) and [Examples_using_GMT.ipynb](https://github.com/hydrocoast/VisClawJuliaExamples/blob/master/Examples_using_GMT.ipynb) for more information. ## Plot gallery The following figures are generated with the Julia scripts in `example/` . ### using GMT.jl #### sea surface elevation <p align="center"> <img src="/figure/chile2010_eta_GMT.gif", width="375"> <img src="/figure/ike_eta_GMT.gif", width="425"> </p> #### topography and bathymetry <p align="center"> <img src="/figure/chile2010_topo.png", width="350"> <img src="/figure/ike_topo.png", width="450"> </p> #### seafloor deformation (dtopo) <p align="center"> <img src="/figure/chile2010_dtopo.png", width="400"> </p> #### wind and pressure fields <p align="center"> <img src="/figure/ike_storm_GMT.gif", width="400"> </p> ### using Plots.jl #### sea surface elevation <p align="center"> <img src="/figure/chile2010_eta.gif", width="400"> <img src="/figure/ike_eta.gif", width="400"> </p> #### flow velocity <p align="center"> <img src="/figure/chile2010_velo.gif", width="400"> <img src="/figure/ike_velo.gif", width="400"> </p> #### topography and bathymetry <p align="center"> <img src="/figure/chile2010_topo.svg", width="400"> <img src="/figure/ike_topo.svg", width="400"> </p> #### wave gauge <p align="center"> <img src="/figure/chile2010_waveform_gauge.svg", width="400"> <img src="/figure/ike_waveform_gauge.svg", width="400"> </p> #### fixed grid monitoring (fgmax) <p align="center"> <img src="/figure/fgmax4vars.svg", width="700"> </p> ## License BSD 3-Clause ## Author [Takuya Miyashita](https://hydrocoast.jp) Disaster Prevention Research Institute, Kyoto University
VisClaw
https://github.com/hydrocoast/VisClaw.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
313
using Documenter using JQuants makedocs( modules=[JQuants], sitename="JQuants.jl", authors="ki-chi <k.brilliant@gmail.com>", doctest=false ) deploydocs( repo = "https://github.com/ki-chi/JQuants.jl.git", target = "build", deps = nothing, make = nothing, devbranch = "main" )
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
849
module JQuants using Dates using HTTP using JSON using DataFrames using Reexport # Authorization function export authorize # APIs export fetch export TokenAuthUser, TokenAuthRefresh, ListedInfo, PricesDailyQuotes, PricesAM, MarketsTradeSpec, MarketsWeeklyMarginInterest, MarketsShortSelling, MarketsBreakdown, Indices, IndicesTopix, FinsStatements, FinsDividend, FinsAnnouncement, OptionIndexOption, TradingCalendar, FinsDetails const JQUANTS_URI = "https://api.jquants.com/v1" # Errors include("errors.jl") # API specification include("specs.jl") # endpoints include("endpoints.jl") # Get & Post functions include("http.jl") # Authorization include("auth.jl") # Data types for the type conversion include("datatypes.jl") # Fetch market data include("fetch.jl") # Utility functions include("utils.jl") end # module
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
1948
const REFRESH_TOKEN = Ref{AbstractString}() const ID_TOKEN = Ref{AbstractString}() isvalid_auth() = isdefined(REFRESH_TOKEN, 1) && isdefined(ID_TOKEN, 1) check_refresh_token() = REFRESH_TOKEN[] check_id_token() = ID_TOKEN[] function update_ref_token(emailaddress, password) body = JSON.json(Dict("mailaddress"=>emailaddress, "password"=>password)) resp = JSON.parse(post(TokenAuthUser(), body=body)) REFRESH_TOKEN[] = resp["refreshToken"] end function update_id_token() resp = JSON.parse( post(TokenAuthRefresh(), query=["refreshtoken"=>REFRESH_TOKEN[]]) ) ID_TOKEN[] = resp["idToken"] end """ authorize(refresh_token::AbstractString) authorize(emailaddress::AbstractString, password::AbstractString) Authorize by the refresh token `refresh_token`, or the combination of email address `emailaddress` and password `password`. Return `true` after the authorization. The details of this API are [here](https://jpx.gitbook.io/j-quants-api-en/api-reference/refreshtoken) and [here](https://jpx.gitbook.io/j-quants-api-en/api-reference/refresh). This package temporally holds your ID Token and Refresh Token as the package-internal variables. Once authorized, reauthorization is not required until that the process of Julia exits or the tokens expires. You can check your tokens using `JQuants.check_refresh_token()` and `JQuants.check_id_token()`. # Examples ```jldoctest julia> reftoken = [YOUR REFRESH TOKEN]; julia> authorize(reftoken) true ``` ```jldoctest julia> email, pass = [YOUR EMAIL ADDRESS], [YOUR PASSWORD] julia> authorize(email, pass) true ``` """ function authorize end function authorize(refresh_token::AbstractString) REFRESH_TOKEN[] = refresh_token update_id_token() return isvalid_auth() end function authorize(emailaddress::AbstractString, password::AbstractString) update_ref_token(emailaddress, password) update_id_token() return isvalid_auth() end
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
25452
""" ColType The definition of the column type conversion. # Fields - `name::Symbol`: The column name. - `original::Union{DataType,Union}`: The original type of the column. - `target::Union{DataType,Union}`: The target type of the column. - `convert::Union{Function,Nothing}`: The function to convert the column to the target type. """ struct ColType name::Symbol original::Union{DataType,Union} target::Union{DataType,Union} convert::Union{Function,Nothing} end ColType(name, original, target) = ColType(name, original, target, nothing) """ DataScheme The definition of the data scheme. """ const DataScheme = Vector{ColType} const NULL_STR = ["", "-"] """ convert(scheme::DataScheme, df::DataFrame) Convert the DataFrame's columns to the target types defined in `scheme`. # Arguments - `scheme::DataScheme`: The data scheme of the DataFrame. - `df::DataFrame`: The DataFrame to be converted. # Returns - `df_conv::DataFrame`: The converted DataFrame. """ function Base.convert(scheme::DataScheme, df) df_conv = copy(df) isempty(df) && return df_conv # Return empty DataFrame if the input DataFrame is empty for coltype in scheme string(coltype.name) ∈ names(df_conv) || continue # Skip if the column is not in the DataFrame if coltype.original != coltype.target # Convert Nothing to Missing if coltype.original >: Nothing && coltype.target >: Missing df_conv[!, coltype.name] = map(x -> isnothing(x) ? missing : x, df_conv[!, coltype.name]) end # Replace null strings to missing if coltype.original <: AbstractString && coltype.target >: Missing allowmissing!(df_conv, coltype.name) replace!(x -> x ∈ NULL_STR ? missing : x, df_conv[!, coltype.name]) end # Skip if the column is already converted Base.nonnothingtype(coltype.original) == Base.nonmissingtype(coltype.target) && continue # Convert the column to the target type if isnothing(coltype.convert) if Base.nonmissingtype(coltype.target) <: Number df_conv[!, coltype.name] = map(x -> ismissing(x) ? x : parse(Base.nonmissingtype(coltype.target), x), df_conv[!, coltype.name]) else df_conv[!, coltype.name] = map(x -> ismissing(x) ? x : Base.nonmissingtype(coltype.target)(x), df_conv[!, coltype.name]) end else df_conv[!, coltype.name] = map(x -> ismissing(x) ? missing : (coltype.convert)(Base.nonmissingtype(coltype.target), x), df_conv[!, coltype.name]) end end end return df_conv end str2bool(::DataType, x) = x == "true" ymd(::DataType, x) = Date(x, "YYYYmmdd") """ datascheme(api::API) Return the data scheme of the API. """ function datascheme(api::API) type = typeof(api) error("The function `datascheme` for the type $(type) is not implemented") end function datascheme(::ListedInfo) DataScheme([ ColType(:Date, String, Date), ColType(:Code, String, String), ColType(:CompanyName, String, String), ColType(:CompanyNameEnglish, String, String), ColType(:Sector17Code, String, String), ColType(:Sector17CodeName, String, String), ColType(:Sector33Code, String, String), ColType(:Sector33CodeName, String, String), ColType(:ScaleCategory, String, String), ColType(:MarketCode, String, String), ColType(:MarketCodeName, String, String), ColType(:MarginCode, String, String), ColType(:MarginCodeName, String, String), ]) end function datascheme(::PricesDailyQuotes) DataScheme([ ColType(:Date, String, Date), ColType(:Code, String, String), ColType(:Open, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:High, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:Low, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:Close, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:UpperLimit, String, String), ColType(:LowerLimit, String, String), ColType(:Volume, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:TurnoverValue, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AdjustmentFactor, Float64, Float64), ColType(:AdjustmentOpen, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AdjustmentHigh, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AdjustmentLow, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AdjustmentClose, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AdjustmentVolume, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningOpen, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningHigh, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningLow, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningClose, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningUpperLimit, String, String), ColType(:MorningLowerLimit, String, String), ColType(:MorningVolume, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningTurnoverValue, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningAdjustmentFactor, Float64, Float64), ColType(:MorningAdjustmentOpen, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningAdjustmentHigh, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningAdjustmentLow, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningAdjustmentClose, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningAdjustmentVolume, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonOpen, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonHigh, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonLow, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonClose, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonVolume, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonUpperLimit, String, String), ColType(:AfternoonLowerLimit, String, String), ColType(:AfternoonTurnoverValue, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonAdjustmentFactor, Float64, Float64), ColType(:AfternoonAdjustmentOpen, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonAdjustmentHigh, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonAdjustmentLow, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonAdjustmentClose, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:AfternoonAdjustmentVolume, Union{Nothing,Float64}, Union{Float64,Missing}), ]) end function datascheme(::PricesAM) DataScheme([ ColType(:Date, String, Date), ColType(:Code, String, String), ColType(:MorningOpen, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningHigh, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningLow, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningClose, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningVolume, Union{Nothing,Float64}, Union{Float64,Missing}), ColType(:MorningTurnoverValue, Union{Nothing,Float64}, Union{Float64,Missing}), ]) end function datascheme(::MarketsTradeSpec) DataScheme([ ColType(:PublishedDate, String, Date), ColType(:StartDate, String, Date), ColType(:EndDate, String, Date), ColType(:Section, String, String), ColType(:ProprietarySales, Float64, Float64), ColType(:ProprietaryPurchases, Float64, Float64), ColType(:ProprietaryTotal, Float64, Float64), ColType(:ProprietaryBalance, Float64, Float64), ColType(:BrokerageSales, Float64, Float64), ColType(:BrokeragePurchases, Float64, Float64), ColType(:BrokerageTotal, Float64, Float64), ColType(:BrokerageBalance, Float64, Float64), ColType(:TotalSales, Float64, Float64), ColType(:TotalPurchases, Float64, Float64), ColType(:TotalTotal, Float64, Float64), ColType(:TotalBalance, Float64, Float64), ColType(:IndividualsSales, Float64, Float64), ColType(:IndividualsPurchases, Float64, Float64), ColType(:IndividualsTotal, Float64, Float64), ColType(:IndividualsBalance, Float64, Float64), ColType(:ForeignersSales, Float64, Float64), ColType(:ForeignersPurchases, Float64, Float64), ColType(:ForeignersTotal, Float64, Float64), ColType(:ForeignersBalance, Float64, Float64), ColType(:SecuritiesCosSales, Float64, Float64), ColType(:SecuritiesCosPurchases, Float64, Float64), ColType(:SecuritiesCosTotal, Float64, Float64), ColType(:SecuritiesCosBalance, Float64, Float64), ColType(:InvestmentTrustsSales, Float64, Float64), ColType(:InvestmentTrustsPurchases, Float64, Float64), ColType(:InvestmentTrustsTotal, Float64, Float64), ColType(:InvestmentTrustsBalance, Float64, Float64), ColType(:BusinessCosSales, Float64, Float64), ColType(:BusinessCosPurchases, Float64, Float64), ColType(:BusinessCosTotal, Float64, Float64), ColType(:BusinessCosBalance, Float64, Float64), ColType(:OtherCosSales, Float64, Float64), ColType(:OtherCosPurchases, Float64, Float64), ColType(:OtherCosTotal, Float64, Float64), ColType(:OtherCosBalance, Float64, Float64), ColType(:InsuranceCosSales, Float64, Float64), ColType(:InsuranceCosPurchases, Float64, Float64), ColType(:InsuranceCosTotal, Float64, Float64), ColType(:InsuranceCosBalance, Float64, Float64), ColType(:CityBKsRegionalBKsEtcSales, Float64, Float64), ColType(:CityBKsRegionalBKsEtcPurchases, Float64, Float64), ColType(:CityBKsRegionalBKsEtcTotal, Float64, Float64), ColType(:CityBKsRegionalBKsEtcBalance, Float64, Float64), ColType(:TrustBanksSales, Float64, Float64), ColType(:TrustBanksPurchases, Float64, Float64), ColType(:TrustBanksTotal, Float64, Float64), ColType(:TrustBanksBalance, Float64, Float64), ColType(:OtherFinancialInstitutionsSales, Float64, Float64), ColType(:OtherFinancialInstitutionsPurchases, Float64, Float64), ColType(:OtherFinancialInstitutionsTotal, Float64, Float64), ColType(:OtherFinancialInstitutionsBalance, Float64, Float64), ]) end function datascheme(::MarketsWeeklyMarginInterest) DataScheme([ ColType(:Date, String, Date), ColType(:Code, String, String), ColType(:ShortMarginTradeVolume, Float64, Float64), ColType(:LongMarginTradeVolume, Float64, Float64), ColType(:ShortNegotiableMarginTradeVolume, Float64, Float64), ColType(:LongNegotiableMarginTradeVolume, Float64, Float64), ColType(:ShortStandardizedMarginTradeVolume, Float64, Float64), ColType(:LongStandardizedMarginTradeVolume, Float64, Float64), ColType(:IssueType, String, String), ]) end function datascheme(::MarketsShortSelling) DataScheme([ ColType(:Date, String, Date), ColType(:Sector33Code, String, String), ColType(:SellingExcludingShortSellingTurnoverValue, Float64, Float64), ColType(:ShortSellingWithRestrictionsTurnoverValue, Float64, Float64), ColType(:ShortSellingWithoutRestrctionsTurnoverValue, Float64, Float64), ]) end function datascheme(::MarketsBreakdown) DataScheme([ ColType(:Date, String, Date), ColType(:Code, String, String), ColType(:LongSellValue, Float64, Float64), ColType(:ShortSellWithoutMarginValue, Float64, Float64), ColType(:MarginSellNewValue, Float64, Float64), ColType(:MarginSellCloseValue, Float64, Float64), ColType(:LongBuyValue, Float64, Float64), ColType(:MarginBuyNewValue, Float64, Float64), ColType(:MarginBuyCloseValue, Float64, Float64), ColType(:LongSellVolume, Float64, Float64), ColType(:ShortSellWithoutMarginVolume, Float64, Float64), ColType(:MarginSellNewVolume, Float64, Float64), ColType(:MarginSellCloseVolume, Float64, Float64), ColType(:LongBuyVolume, Float64, Float64), ColType(:MarginBuyNewVolume, Float64, Float64), ColType(:MarginBuyCloseVolume, Float64, Float64), ]) end function datascheme(::TradingCalendar) DataScheme([ ColType(:Date, String, Date), ColType(:HolydayDivision, String, String), ]) end function datascheme(::IndicesTopix) DataScheme([ ColType(:Date, String, Date), ColType(:Open, Float64, Float64), ColType(:Close, Float64, Float64), ColType(:Low, Float64, Float64), ColType(:High, Float64, Float64), ]) end function datascheme(::FinsStatements) DataScheme([ ColType(:DisclosedDate, String, Date), ColType(:DisclosedTime, String, Time), ColType(:LocalCode, String, String), ColType(:DisclosureNumber, String, Int64), ColType(:TypeOfDocument, String, String), ColType(:TypeOfCurrentPeriod, String, String), ColType(:CurrentPeriodStartDate, String, Date), ColType(:CurrentPeriodEndDate, String, Date), ColType(:NextPeriodStartDate, String, Date), ColType(:NextPeriodEndDate, String, Date), ColType(:NetSales, String, Union{Float64,Missing}), ColType(:OperatingProfit, String, Union{Float64,Missing}), ColType(:OrdinaryProfit, String, Union{Float64,Missing}), ColType(:Profit, String, Union{Float64,Missing}), ColType(:EarningsPerShare, String, Union{Float64,Missing}), ColType(:DilutedEarningsPerShare, String, Union{Float64,Missing}), ColType(:TotalAssets, String, Union{Float64,Missing}), ColType(:Equity, String, Union{Float64,Missing}), ColType(:EquityToAssetRatio, String, Union{Float64,Missing}), ColType(:BookValuePerShare, String, Union{Float64,Missing}), ColType(:CashFlowsFromOperatingActivities, String, Union{Float64,Missing}), ColType(:CashFlowsFromInvestingActivities, String, Union{Float64,Missing}), ColType(:CashFlowsFromFinancingActivities, String, Union{Float64,Missing}), ColType(:CashAndEquivalents, String, Union{Float64,Missing}), ColType(:ResultDividendPerShare1stQuarter, String, Union{Float64,Missing}), ColType(:ResultDividendPerShare2ndQuarter, String, Union{Float64,Missing}), ColType(:ResultDividendPerShare3rdQuarter, String, Union{Float64,Missing}), ColType(:ResultDividendPerShareFiscalYearEnd, String, Union{Float64,Missing}), ColType(:ResultDividendPerShareAnnual, String, Union{Float64,Missing}), ColType(Symbol("DistributionPerUnit(REIT),"), String, Union{Float64,Missing}), ColType(:ResultTotalDividendPaidAnnual, String, Union{Float64,Missing}), ColType(:ResultPayoutRatioAnnual, String, Union{Float64,Missing}), ColType(:ForecastDividendPerShare1stQuarter, String, Union{Float64,Missing}), ColType(:ForecastDividendPerShare2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastDividendPerShare3rdQuarter, String, Union{Float64,Missing}), ColType(:ForecastDividendPerShareFiscalYearEnd, String, Union{Float64,Missing}), ColType(:ForecastDividendPerShareAnnual, String, Union{Float64,Missing}), ColType(Symbol("ForecastDistributionPerUnit(REIT),"), String, Union{Float64,Missing}), ColType(:NextYearForecastDividendPerShare1stQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastDividendPerShare2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastDividendPerShare3rdQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastDividendPerShareFiscalYearEnd, String, Union{Float64,Missing}), ColType(:NextYearForecastDividendPerShareAnnual, String, Union{Float64,Missing}), ColType(Symbol("NextYearForecastDistributionPerUnit(REIT),"), String, Union{Float64,Missing}), # ColType(:NextYearForecastTotalDividendPaidAnnual, String, Union{Float64,Missing} # 定義書にはこれがない ColType(:NextYearForecastPayoutRatioAnnual, String, Union{Float64,Missing}), # こちらは定義が間違ってるかも? ColType(:ForecastNetSales2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastOperatingProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastOrdinaryProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastEarningsPerShare2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastNetSales2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastOperatingProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastOrdinaryProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastEarningsPerShare2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastNetSales, String, Union{Float64,Missing}), ColType(:ForecastOperatingProfit, String, Union{Float64,Missing}), ColType(:ForecastOrdinaryProfit, String, Union{Float64,Missing}), ColType(:ForecastProfit, String, Union{Float64,Missing}), ColType(:ForecastEarningsPerShare, String, Union{Float64,Missing}), ColType(:MaterialChangesInSubsidiaries, String, Union{Bool,Missing}, str2bool), ColType(:ChangesBasedOnRevisionsOfAccountingStandard, String, Union{Bool,Missing}, str2bool), ColType(:ChangesOtherThanOnesBasedOnRevisionsOfAccountingStandard, String, Union{Bool,Missing}, str2bool), ColType(:ChangesInAccountingEstimates, String, Union{Bool,Missing}, str2bool), ColType(:RetrospectiveRestatement, String, Union{Bool,Missing}, str2bool), ColType(:NumberOfIssuedAndOutstandingSharesAtTheEndOfFiscalYearIncludingTreasuryStock, String, Union{Float64,Missing}), ColType(:NumberOfTreasuryStockAtTheEndOfFiscalYear, String, Union{Float64,Missing}), ColType(:AverageNumberOfShares, String, Union{Float64,Missing}), ColType(:NonConsolidatedNetSales, String, Union{Float64,Missing}), ColType(:NonConsolidatedOperatingProfit, String, Union{Float64,Missing}), ColType(:NonConsolidatedOrdinaryProfit, String, Union{Float64,Missing}), ColType(:NonConsolidatedProfit, String, Union{Float64,Missing}), ColType(:NonConsolidatedEarningsPerShare, String, Union{Float64,Missing}), ColType(:NonConsolidatedTotalAssets, String, Union{Float64,Missing}), ColType(:NonConsolidatedEquity, String, Union{Float64,Missing}), ColType(:NonConsolidatedEquityToAssetRatio, String, Union{Float64,Missing}), ColType(:NonConsolidatedBookValuePerShare, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedNetSales2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedOperatingProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedOrdinaryProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedEarningsPerShare2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedNetSales2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedOperatingProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedOrdinaryProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedProfit2ndQuarter, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedEarningsPerShare2ndQuarter, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedNetSales, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedOperatingProfit, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedOrdinaryProfit, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedProfit, String, Union{Float64,Missing}), ColType(:ForecastNonConsolidatedEarningsPerShare, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedNetSales, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedOperatingProfit, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedOrdinaryProfit, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedProfit, String, Union{Float64,Missing}), ColType(:NextYearForecastNonConsolidatedEarningsPerShare, String, Union{Float64,Missing}), ]) end function datascheme(::FinsDetails) DataScheme([ ColType(:DisclosedDate, String, Date), ColType(:DisclosedTime, String, Time), ColType(:LocalCode, String, String), ColType(:DisclosureNumber, String, Int64), ColType(:TypeOfDocument, String, String), ColType(:FinancialStatement, Any, Any), ]) end function datascheme(::FinsDividend) DataScheme([ ColType(:AnnouncementDate, String, Date), ColType(:AnnouncementTime, String, Time), ColType(:Code, String, String), ColType(:ReferenceNumber, String, String), ColType(:StatusCode, String, String), ColType(:BoardMeetingDate, String, Date), ColType(:InterimFinalCode, String, String), ColType(:ForecastResultCode, String, String), ColType(:InterimFinalTerm, String, String), ColType(:GrossDividendRate, String, String), # "-" if undeterminded, "" if not applicable ColType(:RecordDate, String, Date), ColType(:ExDate, String, Date), ColType(:ActulalRecordDate, String, Date), ColType(:PayableDate, String, String), # "-" if undeterminded, "" if not applicable ColType(:CAReferenceNumber, String, String), ColType(:DistributionAmount, String, String), # "-" if undeterminded, "" if not applicable ColType(:RetainedEarnings, String, String), # "-" if undeterminded, "" if not applicable ColType(:DeemedDividend, String, String), # "-" if undeterminded, "" if not applicable ColType(:DeemedCapitalGains, String, String), # "-" if undeterminded, "" if not applicable ColType(:NetAssetDecreaseRatio, String, String), # "-" if undeterminded, "" if not applicable ColType(:CommemorativeSpecialCode, String, String), ColType(:CommemorativeDividendRate, String, String), # "-" if undeterminded, "" if not applicable ColType(:SpecialDividentRate, String, String), # "-" if undeterminded, "" if not applicable ]) end function datascheme(::FinsAnnouncement) DataScheme([ ColType(:Code, String, String), ColType(:Date, String, Date), ColType(:CompanyName, String, String), ColType(:FiscalYear, String, String), ColType(:SectorName, String, String), ColType(:FiscalQuarter, String, String), ColType(:Section, String, String), ]) end function datascheme(::OptionIndexOption) DataScheme([ ColType(:Date, String, Date), ColType(:Code, String, String), ColType(:WholeDayOpen, Float64, Float64), ColType(:WholeDayHigh, Float64, Float64), ColType(:WholeDayLow, Float64, Float64), ColType(:WholeDayClose, Float64, Float64), ColType(:NightSessionOpen, Float64, Float64), ColType(:NightSessionHigh, Float64, Float64), ColType(:NightSessionLow, Float64, Float64), ColType(:NightSessionClose, Float64, Float64), ColType(:DaySessionOpen, Float64, Float64), ColType(:DaySessionHigh, Float64, Float64), ColType(:DaySessionLow, Float64, Float64), ColType(:DaySessionClose, Float64, Float64), ColType(:Volume, Float64, Float64), ColType(:OpenInterest, Float64, Float64), ColType(:TurnoverValue, Float64, Float64), ColType(:ContractMonth, String, String), ColType(:StrikePrice, Float64, Float64), ColType(Symbol("Volume(OnlyAuction)"), Float64, Float64), ColType(:EmergencyMarginTriggerDivision, String, String), ColType(:PutCallDivision, String, String), ColType(:LastTradingDay, String, Date), ColType(:SpecialQuotationDay, String, Date), ColType(:SettlementPrice, Float64, Float64), ColType(:BaseVolatility, Float64, Float64), ColType(:UnderlyingPrice, Float64, Float64), ColType(:ImpliedVolatility, Float64, Float64), ColType(:InterestRate, Float64, Float64), ]) end
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
1993
function endpoint(::Any) error("endpoint not implemented for this type") end endpoint(::TokenAuthUser) = JQUANTS_URI * "/token/auth_user"; endpoint(::TokenAuthRefresh) = JQUANTS_URI * "/token/auth_refresh"; endpoint(::ListedInfo) = JQUANTS_URI * "/listed/info"; endpoint(::PricesDailyQuotes) = JQUANTS_URI * "/prices/daily_quotes"; endpoint(::PricesAM) = JQUANTS_URI * "/prices/prices_am"; endpoint(::MarketsTradeSpec) = JQUANTS_URI * "/markets/trades_spec"; endpoint(::MarketsWeeklyMarginInterest) = JQUANTS_URI * "/markets/weekly_margin_interest"; endpoint(::MarketsShortSelling) = JQUANTS_URI * "/markets/short_selling"; endpoint(::MarketsBreakdown) = JQUANTS_URI * "/markets/breakdown"; endpoint(::TradingCalendar) = JQUANTS_URI * "/markets/trading_calendar"; endpoint(::Indices) = JQUANTS_URI * "/indices"; endpoint(::IndicesTopix) = JQUANTS_URI * "/indices/topix"; endpoint(::FinsStatements) = JQUANTS_URI * "/fins/statements"; endpoint(::FinsDividend) = JQUANTS_URI * "/fins/dividend"; endpoint(::FinsAnnouncement) = JQUANTS_URI * "/fins/announcement"; endpoint(::FinsDetails) = JQUANTS_URI * "/fins/fs_details"; endpoint(::OptionIndexOption) = JQUANTS_URI * "/option/index_option"; function jsonkeyname(::Any) error("jsonkeyname not implemented for this type") end jsonkeyname(::ListedInfo) = "info"; jsonkeyname(::PricesDailyQuotes) = "daily_quotes"; jsonkeyname(::PricesAM) = "prices_am"; jsonkeyname(::MarketsTradeSpec) = "trades_spec"; jsonkeyname(::MarketsWeeklyMarginInterest) = "weekly_margin_interest"; jsonkeyname(::MarketsShortSelling) = "short_selling"; jsonkeyname(::MarketsBreakdown) = "breakdown"; jsonkeyname(::TradingCalendar) = "trading_calendar"; jsonkeyname(::Indices) = "indices"; jsonkeyname(::IndicesTopix) = "topix"; jsonkeyname(::FinsStatements) = "statements"; jsonkeyname(::FinsDividend) = "dividend"; jsonkeyname(::FinsAnnouncement) = "announcement"; jsonkeyname(::FinsDetails) = "fs_details"; jsonkeyname(::OptionIndexOption) = "index_option";
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
1051
abstract type JQuantsError <: Exception end """ JQuantsInvalidTokenError() The refresh token or the id token are not defined. """ struct JQuantsInvalidTokenError <: JQuantsError end function Base.showerror(io::IO, ::JQuantsInvalidTokenError) if !isdefined(REFRESH_TOKEN, 1) && !isdefined(ID_TOKEN, 1) message = "both the refresh token and the id token are" elseif !isdefined(REFRESH_TOKEN, 1) message = "the refresh token is" elseif !isdefined(ID_TOKEN, 1) message = "the id token is" else error("Unexpected Error for JQuantsInvalidTokenError") end print(io, message, " not defined") end """ JQuantsInvalidParameterError() The parameter is invalid. """ struct JQuantsInvalidParameterError <: JQuantsError params::Dict{String, Any} end function Base.showerror(io::IO, e::JQuantsInvalidParameterError) params = replace(replace(string(e.params), "Dict" => ""), r"\{.*,.*\}" => "") print(io, "JQuantsInvalidParameterError: ", params, " are invalid parameter(s)") end
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
2374
const QueryParams = Vector{Pair{String, Any}} """ convert(::Type{Vector{Pair{String, Any}}}, apistruct::API) Convert from struct to vector of pairs for use in HTTP requests. # Arguments - `apistruct::API`: API struct to convert # Returns - `Vector{Pair{String, Any}}`: Vector of pairs for use in HTTP requests # Examples ```julia julia> convert(QueryParams, ListedInfo(code="72030", "")) Vector{Pair{String, Any}} with 1 entry: "code" => "72030" ``` """ function Base.convert(::Type{QueryParams}, apistruct::API) # Convert from struct to vector of pairs pairs = [] for field in fieldnames(typeof(apistruct)) val = getfield(apistruct, field) if !(isnothing(val) || val == "") push!(pairs, string(field) => val) end end return pairs end """ fetch(api::API, kwargs...) Fetch data from JQuants API. # Arguments - `api::API`: API struct to fetch data from - `json::Bool`: If true, return a vector of the raw JSON strings. The number of elements in the vector is equal to the number of pages of the API response. If false, return a DataFrame. Default is false. # Examples ```julia julia> fetch(ListedInfo(code="72030")); julia> fetch(ListedInfo(code="72030"), json=true); ``` """ function Base.fetch(api::API; json=false) query = convert(QueryParams, api) # Convert from struct to vector of pairs for use in HTTP requests keyname = jsonkeyname(api) json_vec = String[] is_empty_query = isempty(query) || all(p -> isempty(p.second), query) resp = is_empty_query ? get(api) : get(api; query=query) push!(json_vec, resp) # Push the first page to the vector of JSON strings result = JSON.parse(resp) # Convert from JSON string to Dict body = result[keyname] # Fetch the rest of the pages while haskey(result, "pagination_key") push!(query, "pagination_key" => result["pagination_key"]) resp = get(api; query=query) push!(json_vec, resp) result = JSON.parse(resp) body = vcat(body, result[keyname]) end # Return raw JSON strings if json=true json && return json_vec # Return DataFrame if json=false df_raw = vcat(DataFrame.(body)...) # Convert from Dict to DataFrame df = convert(datascheme(api), df_raw) # Convert from DataFrame to DataFrame with correct column types return df end
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
1118
""" get(api::API; json=false, kwargs...) Get data from the API endpoint. # Arguments - `api::API`: API endpoint - `kwargs...`: Keyword arguments passed to `HTTP.get` """ function get(api::API; kwargs...) # Check if the token is valid !isvalid_auth() && throw(JQuantsInvalidTokenError()) headers = ["Authorization" => "Bearer $(ID_TOKEN[])"] resp = HTTP.get(endpoint(api), retries=2, headers=headers; kwargs...) body = String(resp.body) if resp.status != 200 statustext = HTTP.Messages.statustext(resp.status) dictbody = JSON.parse(body) message = dictbody["message"] error("Status: $(resp.status) $(statustext)\n Message: $(message)") end return body end function post(api::API; kwargs...) resp = HTTP.post(endpoint(api), retries=2; kwargs...) body = String(resp.body) if resp.status != 200 statustext = HTTP.Messages.statustext(resp.status) dictbody = JSON.parse(body) message = dictbody["message"] error("Status: $(resp.status) $(statustext)\n Message: $(message)") end return body end
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
7449
abstract type API end; struct TokenAuthUser <: API end; struct TokenAuthRefresh <: API end; struct ListedInfo <: API code::AbstractString date::AbstractString end; function ListedInfo(; code="", date="") date_str = date2str(date) return ListedInfo(code, date_str) end struct PricesDailyQuotes <: API code::AbstractString from::AbstractString to::AbstractString date::AbstractString end; function PricesDailyQuotes(;code="", from="", to="", date="") from_str = date2str(from) to_str = date2str(to) date_str = date2str(date) if isempty(code) && !isempty(date_str) PricesDailyQuotes("", "", "", date_str) elseif !isempty(code) if isempty(from_str) || isempty(to_str) PricesDailyQuotes(code, "", "", "") else PricesDailyQuotes(code, from_str, to_str, "") end else throw(JQuantsInvalidParameterError( Dict("code" => code, "from" => from, "to" => to, "date" => date))) end end struct PricesAM <: API code::AbstractString end; function PricesAM(;code="") if isempty(code) PricesAM("") else end end struct MarketsTradeSpec <: API section::AbstractString from::AbstractString to::AbstractString end; function MarketsTradeSpec(;section="", from="", to="") from_str = date2str(from) to_str = date2str(to) if isempty(section) && isempty(from_str) && isempty(to_str) MarketsTradeSpec("", "", "") elseif !isempty(section) if isempty(from_str) || isempty(to_str) MarketsTradeSpec(section, "", "") else MarketsTradeSpec(section, from_str, to_str) end elseif !isempty(from_str) || !isempty(to_str) MarketsTradeSpec("", from_str, to_str) else @show section, from, to error("Unsupported combination.") end end struct MarketsWeeklyMarginInterest <: API code::AbstractString date::AbstractString from::AbstractString to::AbstractString end; function MarketsWeeklyMarginInterest(;code="", from="", to="", date="") from_str = date2str(from) to_str = date2str(to) date_str = date2str(date) if isempty(code) && !isempty(date_str) MarketsWeeklyMarginInterest("", "", "", date_str) elseif !isempty(code) if isempty(from_str) || isempty(to_str) MarketsWeeklyMarginInterest(code, "", "", "") else MarketsWeeklyMarginInterest(code, from_str, to_str, "") end else @show code, from, to, date error("Unsupported combination.") end end struct MarketsShortSelling <: API sector33code::AbstractString date::AbstractString from::AbstractString to::AbstractString end; struct MarketsBreakdown <: API code::AbstractString date::AbstractString from::AbstractString to::AbstractString end; struct Indices <: API code::AbstractString date::AbstractString from::AbstractString to::AbstractString end; function Indices(;code="", date="", from="", to="") from_str = date2str(from) to_str = date2str(to) date_str = date2str(date) if isempty(code) && !isempty(date_str) Indices("", "", "", date_str) elseif !isempty(code) if isempty(from_str) || isempty(to_str) Indices(code, "", "", "") else Indices(code, from_str, to_str, "") end else throw(JQuantsInvalidParameterError( Dict("code" => code, "from" => from, "to" => to, "date" => date))) end end struct IndicesTopix <: API from::AbstractString to::AbstractString end; function IndicesTopix(;from="", to="") from_str = date2str(from) to_str = date2str(to) if isempty(from_str) && isempty(to_str) IndicesTopix("", "") elseif isempty(from_str) IndicesTopix("", to_str) elseif isempty(to_str) IndicesTopix(from_str, "") else IndicesTopix(from_str, to_str) end end struct FinsStatements <: API code::AbstractString date::AbstractString end; function FinsStatements(;code="", date="") date_str = date2str(date) if !(isempty(code) ⊻ isempty(date_str)) error("Only one of \"code\" or \"date\" must be specified.") end if isempty(code) # i.e. 'date' is not nothing FinsStatements("", date_str) else FinsStatements(code, "") end end struct FinsDividend <: API code::AbstractString date::AbstractString from::AbstractString to::AbstractString end; function FinsDividend(;code="", date="", from="", to="") from_str = date2str(from) to_str = date2str(to) date_str = date2str(date) if isempty(code) && !isempty(date_str) FinsDividend("", "", "", date_str) elseif !isempty(code) if isempty(from_str) || isempty(to_str) FinsDividend(code, "", "", "") else FinsDividend(code, from_str, to_str, "") end else throw(JQuantsInvalidParameterError( Dict("code" => code, "from" => from, "to" => to, "date" => date))) end end struct FinsAnnouncement <: API end; struct OptionIndexOption <: API date::AbstractString end; function OptionIndexOption(;date="") if !isempty(date) OptionIndexOption(date2str(date)) else throw(JQuantsInvalidParameterError(Dict("date" => date))) end end """ TradingCalendar(;holidaydivision="", from="", to="") [Trading Calendar API](https://jpx.gitbook.io/j-quants-en/api-reference/trading_calendar) ## Parameters - `holidaydivision::AbstractString`: Holiday division. (Non-business day: "0", Business day: "1", Day of TSE Half-Day Trading Sessions: "2", Non-business days with holiday trading: "3") - `from::AbstractString`: Start date. (e.g. "2018-01-01") - `to::AbstractString`: End date. (e.g. "2018-01-31") ## Examples ```julia julia> using JQuants julia> fetch(TradingCalendar(holidaydivision="1", from="2018-01-01", to="2018-01-31")) ``` """ struct TradingCalendar <: API holidaydivision::AbstractString from::AbstractString to::AbstractString end; function TradingCalendar(;holidaydivision="", from="", to="") from_str = date2str(from) to_str = date2str(to) if isempty(holidaydivision) && isempty(from_str) && isempty(to_str) TradingCalendar("", "", "") elseif !isempty(holidaydivision) if isempty(from_str) || isempty(to_str) TradingCalendar(holidaydivision, "", "") else TradingCalendar(holidaydivision, from_str, to_str) end elseif !isempty(from_str) || !isempty(to_str) TradingCalendar("", from_str, to_str) else @show holidaydivision, from, to error("Unsupported combination.") end end """ FinsDetails(;code="", date="") [Financial Statements Details API](https://jpx.gitbook.io/j-quants-ja/api-reference/statements-1) ## Parameters - `code::AbstractString`: Stock code. (e.g. "8697") - `date::AbstractString`: Date. (e.g. "2018-01-01") ## Examples ```julia julia> using JQuants julia> fetch(FinsDetails(code="8697", date="2018-01-01")) ``` """ struct FinsDetails <: API code::AbstractString date::AbstractString end; function FinsDetails(; code="", date="") isempty(code) && isempty(date) && error("One of \"code\" or \"date\" must be specified.") FinsDetails(code, date2str(date)) end
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
254
using Dates """ date2str(x) Convert `x` to "yyyy-mm-dd" formated string if `x` is `Date`. """ date2str(::Any) = error("argument 'x' must be AbstractString or Date.") date2str(x::AbstractString) = x date2str(x::Date) = Dates.format(x, "yyyy-mm-dd")
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
code
3540
using JQuants using DataFrames using Test using Dates @testset "Undefined tokens error" begin @test_throws JQuants.JQuantsInvalidTokenError fetch(ListedInfo(code="86970")) end @testset "Authorization" begin emailaddress = ENV["JQUANTS_API_EMAIL"] password = ENV["JQUANTS_API_PASSWORD"] @test JQuants.authorize(emailaddress, password) end @testset "Trading Calendar" begin calendar = fetch(TradingCalendar(holidaydivision="1")) expected_colnames = [ "Date", "HolidayDivision", ] @test sort(names(calendar)) == sort(expected_colnames) end # Get the latest date from the trading calendar test_date = fetch(TradingCalendar(holidaydivision="1")) |> last |> row -> row[:Date] test_holiday = fetch(TradingCalendar(holidaydivision="0")) |> last |> row -> row[:Date] @testset "Listed issues information" begin code = "86970" # JPX listed_info = fetch(ListedInfo(code=code, date=test_date)) expected_colnames = [ "Date", "Code", "CompanyName", "CompanyNameEnglish", "Sector17Code", "Sector17CodeName", "Sector33Code", "Sector33CodeName", "ScaleCategory", "MarketCode", "MarketCodeName", ] @test sort(names(listed_info)) == sort(expected_colnames) @test listed_info[begin, :Code] == "86970" @test listed_info[begin, :CompanyName] == "日本取引所グループ" @test listed_info[begin, :CompanyNameEnglish] == "Japan Exchange Group,Inc." @test listed_info[begin, :Sector17Code] == "16" @test listed_info[begin, :Sector17CodeName] == "金融(除く銀行)" @test listed_info[begin, :Sector33Code] == "7200" @test listed_info[begin, :Sector33CodeName] == "その他金融業" @test listed_info[begin, :ScaleCategory] == "TOPIX Large70" @test listed_info[begin, :MarketCode] == "0111" @test listed_info[begin, :MarketCodeName] == "プライム" end @testset "Daily prices" begin daily_quotes = fetch(PricesDailyQuotes(date=test_date)) expected_colnames = [ "AdjustmentClose", "AdjustmentFactor", "AdjustmentHigh", "AdjustmentLow", "AdjustmentOpen", "AdjustmentVolume", "Close", "Code", "Date", "High", "Low", "Open", "TurnoverValue", "Volume", "LowerLimit", "UpperLimit" ] expected_coltypes = [ Union{Missing, Float64}, Float64, Union{Missing, Float64}, Union{Missing, Float64}, Union{Missing, Float64}, Union{Missing, Float64}, Union{Missing, Float64}, String, Date, Union{Missing, Float64}, Union{Missing, Float64}, Union{Missing, Float64}, Union{Missing, Float64}, Union{Missing, Float64} ] @test sort(names(daily_quotes)) == sort(expected_colnames) for (colname, coltype) in zip(expected_colnames, expected_coltypes) @test eltype(daily_quotes[!, colname]) == coltype end # No output on a holiday daily_quotes_null = fetch(PricesDailyQuotes(date=test_holiday)) @test isempty(daily_quotes_null) @test daily_quotes_null == Any[] end @testset "Financial statements" begin statements = fetch(FinsStatements(code="86970")) @test length(names(statements)) == 106 end @testset "Pagination" begin @test_nowarn statements = fetch(FinsStatements(date="2022-05-13")) # A lot of disclosures on this day end @testset "Financial announcement" begin ann = fetch(FinsAnnouncement()) expected_colnames = [ "Code", "Date", "CompanyName", "FiscalYear", "SectorName", "FiscalQuarter", "Section" ] @test sort(names(ann)) == sort(expected_colnames) end
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
docs
2736
# JQuants.jl [![CI](https://github.com/ki-chi/JQuants.jl/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ki-chi/JQuants.jl/actions/workflows/ci.yml) [![][docs-stable-img]][docs-stable-url] [![][docs-dev-img]][docs-dev-url] [The J-Quants API](https://jpx-jquants.com/?lang=en) wrapper for Julia. The J-Quants API is an distribution service that delivers historical stock prices and financial statements data through API, provided by JPX Market Innovation & Research, Inc. This client package helps you easily use the API from Julia. # How to use ## Installation In the Julia REPL: ``` ] JQuants ``` or ``` julia> using Pkg; Pkg.add("JQuants") ``` ## Authorization You have to [register](https://jpx-jquants.com/auth/signup/?lang=en) to use the J-Quants API. You may also grant authentication credentials through employment of a "Refresh token," or alternatively, by employing the email address and password that was previously registered for the J-Quants API. ```julia julia> using JQuants julia> authorize([YOUR REFRESH TOKEN]) true ``` or ```julia julia> authorize([YOUR EMAIL ADDRESS], [PASSWORD]) true ``` ## Fetch market data This package covers [APIs](https://jpx.gitbook.io/j-quants-en/api-reference) for downloading data by the J-Quants API. ```julia # Run after authorization julia> fetch(ListedInfo()); # Fetch listed issues julia> fetch(PricesDailyQuotes(date="2022-09-09")); # Fetch daily stock prices julia> fetch(PricesDailyQuotes(date=Date(2022, 9, 9))); # Dates.Date type is also OK julia> fetch(FinsStatements(code="86970")); # Fetch financial statements julia> fetch(FinsAnnouncement()); # Fetch the announcement dates of financial results ``` See the [documentation][docs-stable-url] for detailed usage of the functions. # Disclaimers - No recommendation to trade in financial instrument using this package - Not responsible for any profit or loss resulting from the use of this package - Not guarantee any of the accuracy of the information obtained through this package # Reference - [J-Quants API](https://jpx-jquants.com/?lang=en) - [J-Quants API Reference](https://jpx.gitbook.io/j-quants-en/api-reference) # Acknowledgments Several ideas were taken from the packages below: - [J-Quants/jquants-api-client-python](https://github.com/J-Quants/jquants-api-client-python): Python package for the J-Quants API - [J-Quants/JQuantsR](https://github.com/J-Quants/JQuantsR): R package for the J-Quants API [docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-dev-url]: https://ki-chi.github.io/JQuants.jl/dev/ [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://ki-chi.github.io/JQuants.jl/stable/
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "MIT" ]
1.0.3
bc1e6f64c6de0ef72a4fc185449602417e786705
docs
767
# JQuants.jl GitHub repo: [https://github.com/ki-chi/JQuants.jl](https://github.com/ki-chi/JQuants.jl) ## Overview A Julia package for using the [J-Quants API](https://jpx-jquants.com/?lang=en) that provide Japanese listed issues' price and financial information. You have to [register](https://jpx-jquants.com/auth/signup/?lang=en) to use the J-Quants API. ## Installation In the Julia REPL: ``` ] JQuants ``` or ``` julia> using Pkg; Pkg.add("JQuants") ``` ## Example ```jldoctest julia> using JQuants julia> authorize([YOUR REFRESH TOKEN]) true julia> fetch(FinsStatements(code="86970")); # Fetch financial statements ``` ## API Wrappers Functions exported from `JQuants`: ```@autodocs Modules = [JQuants] Private = false Order = [:function] ```
JQuants
https://github.com/ki-chi/JQuants.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
1963
# Generate a Lexer for OpenModelica output (Values.Value) # ===================================================================== import Automa import Automa.RegExp: @re_str import MacroTools const re = Automa.RegExp # Describe patterns in regular expression. t = re"[tT][rR][uU][eE]" f = re"[fF][aA][lL][sS][eE]" string = re"\"([^\"\\x5c]|(\\x5c.))*\"" ident = re"[_A-Za-z][_A-Za-z0-9]*|'([^'\\x5c]|(\\x5c.))+'" int = re"[-+]?[0-9]+" prefloat = re"[-+]?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)" float = prefloat | re.cat(prefloat | re"[-+]?[0-9]+", re"[eE][-+]?[0-9]+") operator = re"[={}(),;]|end" number = int | float ws = re"[ ]+" omtoken = number | string | ident | operator omtokens = re.opt(ws) * re.rep(omtoken * re.opt(ws)) # Compile a finite-state machine. tokenizer = Automa.compile( t => :(emit(true)), f => :(emit(false)), operator => :(emit(Symbol(data[ts:te]))), re"record" => :(emit(Record())), string => :(emit(unescape_string(data[ts+1:te-1]))), ident => :(emit(Identifier(unescape_string(data[ts:te])))), # Should this be a symbol instead? int => :(emit(parse(Int, data[ts:te]))), float => :(emit(parse(Float64, data[ts:te]))), re"[\n\t ]" => :(), re"." => :(failed = true) ) # Generate a tokenizing function from the machine. ctx = Automa.CodeGenContext() init_code = MacroTools.prettify(Automa.generate_init_code(ctx, tokenizer)) exec_code = MacroTools.prettify(Automa.generate_exec_code(ctx, tokenizer)) write(open("src/lexer.jl","w"), """# Generated Lexer for OpenModelica Values.Value output function tokenize(data::String) $(init_code) p_end = p_eof = sizeof(data) failed = false tokens = Any[] emit(tok) = push!(tokens, tok) while p ≤ p_eof && cs > 0 $(exec_code) end if cs < 0 || failed throw(LexerError("Error while lexing")) end if p < p_eof throw(LexerError("Did not scan until end of file. Remaining: \$(data[p:p_eof])")) end return tokens end """)
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
544
using Documenter, OMJulia ENV["JULIA_DEBUG"]="Documenter" @info "Make the docs" makedocs( sitename = "OMJulia.jl", format = Documenter.HTML(edit_link = "master"), workdir = joinpath(@__DIR__,".."), pages = [ "Home" => "index.md", "Quickstart" => "quickstart.md", "ModelicaSystem" => "modelicaSystem.md", "OMJulia.API" => "api.md", "sendExpression" => "sendExpression.md" ], modules = [OMJulia], ) @info "Deploy the docs" deploydocs( repo = "github.com/OpenModelica/OMJulia.jl.git", devbranch = "master" )
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
4522
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# using Test """ Run single test process. Start a new Julia process. Kill process and throw an error when timeout is reached. Catch InterruptException, kill process and rethorw InterruptException. # Arguments - `library`: Modelica library name. - `version`: Library version. - `model`: Modelica model from library to test. - `testdir`: Test working directory. # Keywords - `timeout=10*60::Integer`: Timeout in seconds. Defaults to 10 minutes. """ function singleTest(library, version, model, testdir; timeout=10*60::Integer) mkpath(testdir) logFile = joinpath(testdir, "runSingleTest.log") rm(logFile, force=true) @info "Testing $model" cmd = Cmd(`$(joinpath(Sys.BINDIR, "julia")) runSingleTest.jl $(library) $(version) $(model) $(testdir)`, dir=@__DIR__) @info cmd plp = pipeline(cmd, stdout=logFile, stderr=logFile) process = run(plp, wait=false) try timer = Timer(0; interval=1) for _ in 1:timeout wait(timer) if !process_running(process) close(timer) break end end if process_running(process) @error "Killing $(process)" kill(process) end catch e if isa(e, InterruptException) && process_running(p) @error "Killing process $(cmd)." kill(p) end rethrow(e) end println(read(logFile, String)) status = (process.exitcode == 0) && isfile(joinpath(testdir, "$(model).fmu")) && isfile(joinpath(testdir, "FMI_results.csv")) return status end """ Run all tests. # Arguments - `libraries::Vector{Tuple{S,S}}`: Vector of tuples with library and version to test. - `models::Vector{Vector{S}}`: Vector of vectors with models to test for each library. # Keywords - `workdir`: Root working directory. """ function runTests(libraries::Vector{Tuple{S,S}}, models::Vector{Vector{S}}; workdir=abspath(joinpath(@__DIR__, "temp"))) where S<:AbstractString rm(workdir, recursive=true, force=true) # This can break on Windows when some program or file is still open mkpath(workdir) @testset "OpenModelica" begin for (i, (library, version)) in enumerate(libraries) @testset verbose=true "$library" begin libdir = joinpath(workdir, library) mkpath(libdir) for model in models[i] modeldir = joinpath(libdir, model) @testset "$model" begin @test singleTest(library, version, model, modeldir) end end end end end return end libraries = [ ("Modelica", "4.0.0") ] models = [ [ "Modelica.Blocks.Examples.Filter", "Modelica.Electrical.Analog.Examples.CauerLowPassAnalog", "Modelica.Blocks.Examples.RealNetwork1", "Modelica.Electrical.Digital.Examples.FlipFlop", "Modelica.Mechanics.Rotational.Examples.FirstGrounded", "Modelica.Mechanics.Rotational.Examples.CoupledClutches", "Modelica.Mechanics.MultiBody.Examples.Elementary.DoublePendulum", "Modelica.Mechanics.MultiBody.Examples.Elementary.FreeBody", "Modelica.Fluid.Examples.TraceSubstances.RoomCO2WithControls", "Modelica.Clocked.Examples.SimpleControlledDrive.ClockedWithDiscreteTextbookController", "Modelica.Fluid.Examples.PumpingSystem" ] ]
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
4508
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# import Pkg; Pkg.activate(@__DIR__) import OMJulia import FMI using Test using DataFrames using CSV """ Simulate single model to generate a result file. """ function testSimulation(omc::OMJulia.OMCSession, className::String) @info "\tSimulation" @testset "Simulation" begin res = OMJulia.API.simulate(omc, className; outputFormat="csv") resultFile = res["resultFile"] @test isfile(resultFile) return resultFile end end """ Build a FMU for a single model, import the generated FMU, simulate it and compare to given reference results. """ function testFmuExport(omc::OMJulia.OMCSession, className::String, referenceResult, recordValues; workdir::String) fmuPath = "" fmuImportSuccess = false @info "\tFMU Export" @testset "Export" begin fmuPath = OMJulia.API.buildModelFMU(omc, className) @test isfile(fmuPath) @test splitext(splitpath(fmuPath)[end]) == (className, ".fmu") end @info "\tFMU Import" @testset "Import" begin if isfile(fmuPath) fmu = FMI.fmiLoad(fmuPath) solution = FMI.fmiSimulate(fmu; recordValues = recordValues, showProgress=false) # Own implementation of CSV export, workaround for https://github.com/ThummeTo/FMI.jl/issues/198 df = DataFrames.DataFrame(time = solution.values.t) for i in 1:length(solution.values.saveval[1]) for var in FMI.fmi2ValueReferenceToString(fmu, solution.valueReferences[i]) if in(var, recordValues) df[!, Symbol(var)] = [val[i] for val in solution.values.saveval] end end end fmiResult = joinpath(workdir, "FMI_results.csv") CSV.write(fmiResult, df) #FMI.fmiSaveSolution(solution, "FMI_results.csv") fmuImportSuccess = true end @test fmuImportSuccess end @info "\tCheck Results" @testset "Verification" begin if fmuImportSuccess @test (true, String[]) == OMJulia.API.diffSimulationResults(omc, "FMI_results.csv", referenceResult, "diff") else @test false end end end """ Run Simulation and FMU export/import test for all models. """ function runSingleTest(library, version, model, modeldir) local resultFile @info "Testing library: $library, model $model" mkpath(modeldir) omc = OMJulia.OMCSession() try @testset "$model" verbose=true begin @testset "Simulation" begin OMJulia.API.cd(omc, modeldir) @test OMJulia.API.loadModel(omc, library; priorityVersion = [version], requireExactVersion = true) resultFile = testSimulation(omc, model) end @testset "FMI" begin if isfile(resultFile) recordValues = names(CSV.read(resultFile, DataFrame))[2:end] filter!(val -> !startswith(val, "\$"), recordValues) # Filter internal variables testFmuExport(omc, model, resultFile, recordValues; workdir=modeldir) else @test false end end end finally OMJulia.quit(omc) end end # Comand-line interface if !isempty(PROGRAM_FILE) if length(ARGS) == 4 library = ARGS[1] version = ARGS[2] model = ARGS[3] modeldir = ARGS[4] runSingleTest(library, version, model, modeldir) else @error "Wrong number of arguments" for a in ARGS; println(a); end return -1 end end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
2193
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# module OMJulia global IS_FILE_OMJULIA = false using DataFrames using DataStructures using LightXML using Random using ZMQ export sendExpression, ModelicaSystem # getMethods export getParameters, getQuantities, showQuantities, getInputs, getOutputs, getSimulationOptions, getSolutions, getContinuous, getWorkDirectory # setMethods export setInputs, setParameters, setSimulationOptions # simulation export simulate, buildModel # Linearizion export linearize, getLinearInputs, getLinearOutputs, getLinearStates, getLinearizationOptions, setLinearizationOptions # sensitivity analysis export sensitivity # package manager export installPackage, updatePackageIndex, getAvailablePackageVersions, upgradeInstalledPackages include("error.jl") include("parser.jl") include("omcSession.jl") include("sendExpression.jl") include("modelicaSystem.jl") include("api.jl") end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
27010
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# # The functions below are generated using the autoGenerate.jl located # in scripts folder, the generated code is 95 % accurate, and we need to # do some fixes manually for certain API's, but in future this could be improved # and completely use the autoGenerate.jl to get 100% correct generated codes """ """ module API import ..OMJulia """ ScriptingError <: Exception OpenModelica scripting error with message `msg` and additional `error string` from `getErrroString`. """ struct ScriptingError <: Exception "Error message" msg::String "Error string from getErrorString()" errorString::String """ ScriptingError(omc=nothing; msg = "", errorString=nothing) Construct error message from `msg` and `errorString`. If OMCSession `omc` is available and `errorString=nothing` call `API.getErrorString()`. """ function ScriptingError(omc::Union{OMJulia.OMCSession, Nothing} = nothing; msg::String = "", errorString::Union{String, Nothing} = nothing) if isnothing(errorString) && !isnothing(omc) errorString = strip(OMJulia.sendExpression(omc, "getErrorString()")) elseif isnothing(errorString) errorString = "" end return new(msg, errorString) end function Base.showerror(io::IO, e::ScriptingError) println(io, e.msg) println(io, e.errorString) end end """ modelicaString(name) Wrappes string in quotes and replaces Windows style path seperation `\\` with `/`. """ function modelicaString(name::String) formattedString = join(["\"", name, "\""]) return replace(formattedString, "\\" => "/") end """ modelicaString(vec) Wrappes array in brackets and for each elemetn add quotes and replaces Windows style path seperation `\\` with `/`. """ function modelicaString(vec::Vector{String}) return "{" .* join(modelicaString.(vec), ", ") .* "}" end """ makeVectorString(vec) Add quotes around each string element. """ function makeVectorString(vec::Vector{String}) if length(vec) == 0 return "\"\"" end return join("\"" .* vec .* "\"", ", ") end """ loadFile(omc, fileName; encoding = "", uses = true, notify = true, requireExactVersion = false) Load file `fileName` (*.mo) and merge it with the loaded AST. See [OpenModelica scripting API `loadFile`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#loadfile). """ function loadFile(omc::OMJulia.OMCSession, fileName::String; encoding::String = "", uses::Bool = true, notify::Bool = true, requireExactVersion::Bool = false ) exp = join(["loadFile", "(", "fileName", "=", modelicaString(fileName), ",", "encoding", "=", modelicaString(encoding), ",", "uses", "=", uses,",", "notify", "=", notify,",", "requireExactVersion", "=", requireExactVersion,")"]) success = OMJulia.sendExpression(omc, exp) if !success throw(ScriptingError(omc, msg = "Failed to load file $(modelicaString(fileName)).")) end return success end """ loadModel(omc, className; priorityVersion = String[], notify = false, languageStandard = "", requireExactVersion = false) Loads a Modelica library. See [OpenModelica scripting API `loadModel`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#loadmodel). """ function loadModel(omc::OMJulia.OMCSession, className::String; priorityVersion::Vector{String} = String[], notify::Bool = false, languageStandard::String = "", requireExactVersion::Bool = false ) exp = join(["loadModel", "(", "className", "=", className, ",", "priorityVersion", "=", "{", makeVectorString(priorityVersion), "}", ",", "notify", "=", notify,",", "languageStandard", "=", modelicaString(languageStandard), ",", "requireExactVersion", "=", requireExactVersion,")"]) success = OMJulia.sendExpression(omc, exp) if !success throw(ScriptingError(omc, msg = "Failed to load model $(className).")) end return success end """ simulate(omc, className; startTime = 0.0, stopTime = nothing, numberOfIntervals = 500, tolerance = 1e-6, method = "", fileNamePrefix=className, options = "", outputFormat = "mat", variableFilter = ".*", cflags = "", simflags = "") Simulates a modelica model by generating C code, build it and run the simulation executable. See [OpenModelica scripting API `simulate`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#simulate). """ function simulate(omc::OMJulia.OMCSession, className::String; startTime::Float64 = 0.0, stopTime::Union{Float64, Nothing} = nothing, numberOfIntervals::Int64 = 500, tolerance::Float64 = 1e-6, method::String = "", fileNamePrefix::String = className, options::String = "", outputFormat::String = "mat", variableFilter::String = ".*", cflags::String = "", simflags::String = "" ) exp = join(["simulate", "(", className, ",", "startTime", "=", startTime, ","]) # There is no default value for stopTime we can provide that behaves like not giving any value and using the stopTime from the experiment annotation... if !isnothing(stopTime) exp *= "stopTime = $stopTime," end exp *= join(["numberOfIntervals", "=", numberOfIntervals, ",", "tolerance", "=", tolerance, ",", "method", "=", modelicaString(method), ",", "fileNamePrefix", "=", modelicaString(fileNamePrefix), ",", "options", "=", modelicaString(options), ",", "outputFormat", "=", modelicaString(outputFormat), ",", "variableFilter", "=", modelicaString(variableFilter), ",", "cflags", "=", modelicaString(cflags), ",", "simflags", "=", modelicaString(simflags), ")"]) simulationResults = OMJulia.sendExpression(omc, exp) if !haskey(simulationResults, "resultFile") || isempty(simulationResults["resultFile"]) if haskey(simulationResults, "messages") throw(ScriptingError(omc, msg = "Failed to simulate $(className).\n" * simulationResults["messages"] )) else throw(ScriptingError(omc, msg = "Failed to simulate $(className).")) end end return simulationResults end """ buildModel(omc, className; startTime = 0.0, stopTime = 1.0, numberOfIntervals = 500, tolerance = 1e-6, method = "", fileNamePrefix = className, options = "", outputFormat = "mat", variableFilter = ".*", cflags = "", simflags = "") Build Modelica model by generating C code and compiling it into an executable simulation. It does not run the simulation! See [OpenModelica scripting API `buildModel`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#buildmodel). """ function buildModel(omc::OMJulia.OMCSession, className::String; startTime::Float64 = 0.0, stopTime::Float64 = 1.0, numberOfIntervals::Int64 = 500, tolerance::Float64 = 1e-6, method::String = "", fileNamePrefix::String = className, options::String = "", outputFormat::String = "mat", variableFilter::String = ".*", cflags::String = "", simflags::String = "" ) exp = join(["buildModel", "(", className, ",", "startTime", "=", startTime,",", "stopTime", "=", stopTime,",", "numberOfIntervals", "=", numberOfIntervals,",", "tolerance", "=", tolerance,",", "method", "=", modelicaString(method), ",", "fileNamePrefix", "=", modelicaString(fileNamePrefix), ",", "options", "=", modelicaString(options), ",", "outputFormat", "=", modelicaString(outputFormat), ",", "variableFilter", "=", modelicaString(variableFilter), ",", "cflags", "=", modelicaString(cflags), ",", "simflags", "=", modelicaString(simflags),")"]) return OMJulia.sendExpression(omc, exp) end """ getClassNames(omc; class_ = "", recursive = false, qualified = false, sort = false, builtin = false, showProtected = false, includeConstants = false) Returns the list of class names defined in the class. See [OpenModelica scripting API `getClassNames`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#getclassnames). """ function getClassNames(omc::OMJulia.OMCSession; class_::String = "", recursive::Bool = false, qualified::Bool = false, sort::Bool = false, builtin::Bool = false, showProtected::Bool = false, includeConstants::Bool = false ) if (class_ == "") args = join(["recursive", "=", recursive, ", ", "qualified", "=", qualified, ", ", "sort", "=", sort, ", ", "builtin", "=", builtin, ", ", "showProtected", "=", showProtected, ", ", "includeConstants", "=", includeConstants]) else args = join(["class_", "=", class_, ", ", "recursive", "=", recursive, ", ", "qualified", "=", qualified, ", ", "sort", "=", sort, ", ", "builtin", "=", builtin, ", ", "showProtected", "=", showProtected, ", ", "includeConstants", "=", includeConstants]) end exp = "getClassNames($args)" return OMJulia.sendExpression(omc, exp) end """ readSimulationResult(omc, filename, variables = String[], size = 0) Reads a result file, returning a matrix corresponding to the variables and size given. See [OpenModelica scripting API `readSimulationResult`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#readsimulationresult). """ function readSimulationResult(omc::OMJulia.OMCSession, filename::String, variables::Vector{String} = String[], size::Int64 = 0 ) exp = join(["readSimulationResult", "(", modelicaString(filename), ",", "{", join(variables, ", "), "}", ", ", size,")"]) return OMJulia.sendExpression(omc, exp) end """ readSimulationResultSize(omc, fileName) The number of intervals that are present in the output file. See [OpenModelica scripting API `readSimulationResultSize`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#readsimulationresultsize). """ function readSimulationResultSize(omc::OMJulia.OMCSession, fileName::String ) exp = join(["readSimulationResultSize", "(", "fileName", "=", modelicaString(fileName),")"]) return OMJulia.sendExpression(omc, exp) end """ readSimulationResultVars(omc, fileName; readParameters = true, openmodelicaStyle = false) Returns the variables in the simulation file; you can use val() and plot() commands using these names. See [OpenModelica scripting API `readSimulationResultVars`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#readsimulationresultvars). """ function readSimulationResultVars(omc::OMJulia.OMCSession, fileName::String; readParameters::Bool = true, openmodelicaStyle::Bool = false ) exp = join(["readSimulationResultVars", "(", "fileName", "=", modelicaString(fileName), ",", "readParameters", "=", readParameters,",", "openmodelicaStyle", "=", openmodelicaStyle,")"]) return OMJulia.sendExpression(omc, exp) end """ closeSimulationResultFile(omc) Closes the current simulation result file. Only needed by Windows. Windows cannot handle reading and writing to the same file from different processes. To allow OMEdit to make successful simulation again on the same file we must close the file after reading the Simulation Result Variables. Even OMEdit only use this API for Windows. See [OpenModelica scripting API `closeSimulationResultFile`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#closesimulationresultfile). """ function closeSimulationResultFile(omc::OMJulia.OMCSession) return OMJulia.sendExpression(omc, "closeSimulationResultFile()") end """ setCommandLineOptions(omc, option) The input is a regular command-line flag given to OMC, e.g. -d=failtrace or -g=MetaModelica. See [OpenModelica scripting API `setCommandLineOptions`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#setcommandlineoptions). """ function setCommandLineOptions(omc::OMJulia.OMCSession, option::String ) exp = join(["setCommandLineOptions", "(", "option", "=", modelicaString(option),")"]) success = OMJulia.sendExpression(omc, exp) if !success throw(ScriptingError(omc, msg = "Failed to set command line options $(modelicaString(option)).")) end return success end """ cd(omc, newWorkingDirectory="") Change directory to the given path `newWorkingDirectory` (which may be either relative or absolute). Returns the new working directory on success or a message on failure. If the given path is the empty string, the function simply returns the current working directory. See [OpenModelica scripting API `cd`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#cd). """ function cd(omc::OMJulia.OMCSession, newWorkingDirectory::String = ""; ) exp = join(["cd", "(", "newWorkingDirectory", "=", modelicaString(newWorkingDirectory),")"]) workingDirectory = OMJulia.sendExpression(omc, exp) if !ispath(workingDirectory) throw(ScriptingError(omc, msg = "Failed to change directory to $(modelicaString(newWorkingDirectory)).")) end return workingDirectory end """ Creates a model with symbolic linearization matrices. See [OpenModelica scripting API `linearize`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#linearize). """ function linearize(omc::OMJulia.OMCSession, className::String; startTime::Float64 = 0.0, stopTime::Float64 = 1.0, numberOfIntervals::Int64 = 500, stepSize::Float64 = 0.002, tolerance::Float64 = 1e-6, method::String = "", fileNamePrefix::String = className, options::String = "", outputFormat::String = "mat", variableFilter::String = ".*", cflags::String = "", simflags::String = "" ) exp = join(["linearize", "(", className, ",", "startTime", "=", startTime,",", "stopTime", "=", stopTime,",", "numberOfIntervals", "=", numberOfIntervals,",", "stepSize", "=", stepSize,",", "tolerance", "=", tolerance,",", "method", "=", modelicaString(method), ",", "fileNamePrefix", "=", modelicaString(fileNamePrefix), ",", "options", "=", modelicaString(options), ",", "outputFormat", "=", modelicaString(outputFormat), ",", "variableFilter", "=", modelicaString(variableFilter), ",", "cflags", "=", modelicaString(cflags), ",", "simflags", "=", modelicaString(simflags),")"]) return OMJulia.sendExpression(omc, exp) end """ buildModelFMU(omc, className; version = "2.0", fmuType = "me", fileNamePrefix=className, platforms=["static"], includeResources = false) Translates a modelica model into a Functional Mockup Unit. The only required argument is the className, while all others have some default values. See [OpenModelica scripting API `buildModelFMU`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#buildmodelfmu). """ function buildModelFMU(omc::OMJulia.OMCSession, className::String; version::String = "2.0", fmuType::String = "me", fileNamePrefix::String = className, platforms::Vector{String} = String["static"], includeResources::Bool = false ) exp = join(["buildModelFMU", "(", className, ",", "version", "=", modelicaString(version), ",", "fmuType", "=", modelicaString(fmuType), ",", "fileNamePrefix", "=", modelicaString(fileNamePrefix), ",", "platforms", "=", "{", makeVectorString(platforms), "}", ",", "includeResources", "=", includeResources,")"]) generatedFileName = OMJulia.sendExpression(omc, exp) if !isfile(generatedFileName) || !endswith(generatedFileName, ".fmu") throw(ScriptingError(omc, msg = "Failed to load file $(modelicaString(generatedFileName)).")) end return generatedFileName end """ getErrorString(omc, warningsAsErrors = false) Returns the current error message. See [OpenModelica scripting API `getErrorString`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#geterrorstring). """ function getErrorString(omc::OMJulia.OMCSession; warningsAsErrors::Bool = false ) exp = join(["getErrorString", "(", "warningsAsErrors", "=", warningsAsErrors,")"]) return OMJulia.sendExpression(omc, exp) end """ getVersion(omc) Returns the version of the Modelica compiler. See [OpenModelica scripting API `getVersion`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#getversion). """ function getVersion(omc::OMJulia.OMCSession) exp = join(["getVersion()"]) return OMJulia.sendExpression(omc, exp) end """ getInstallationDirectoryPath(omc) This returns `OPENMODELICAHOME` if it is set; on some platforms the default path is returned if it is not set. See [OpenModelica scripting API `getInstallationDirectoryPath`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#getinstallationdirectorypath). """ function getInstallationDirectoryPath(omc::OMJulia.OMCSession) exp = join(["getInstallationDirectoryPath()"]) return OMJulia.sendExpression(omc, exp) end """ diffSimulationResults(omc, actualFile, expectedFile, diffPrefix; relTol = 1e-3, relTolDiffMinMax = 1e-4, rangeDelta = 0.002, vars = String[], keepEqualResults = false) Compares simulation results. See [OpenModelica scripting API `diffSimulationResults`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#diffsimulationresults). """ function diffSimulationResults(omc::OMJulia.OMCSession, actualFile::String, expectedFile::String, diffPrefix::String; relTol::Float64 = 1e-3, relTolDiffMinMax::Float64 = 1e-4, rangeDelta::Float64 = 0.002, vars::Vector{String} = String[], keepEqualResults::Bool = false) exp = "diffSimulationResults($(modelicaString(actualFile)), $(modelicaString(expectedFile)), $(modelicaString(diffPrefix)), relTol=$relTol, relTolDiffMinMax=$relTolDiffMinMax, rangeDelta=$rangeDelta, vars=$(modelicaString(vars)), keepEqualResults=$keepEqualResults)" @debug "$exp" ret = OMJulia.sendExpression(omc, exp) if isnothing(ret) return (true, String[]) else return (ret[1], convert(Vector{String}, ret[2])) end end """ instantiateModel(omc, className) Instantiates the class and returns the flat Modelica code. See [OpenModelica scripting API `instantiateModel`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#instantiatemodel). """ function instantiateModel(omc::OMJulia.OMCSession, className::String) flatModelicaCode = OMJulia.sendExpression(omc, "instantiateModel($className)") if isempty(flatModelicaCode) throw(OMJulia.API.ScriptingError(omc, msg = "instantiateModel($className)")) end return flatModelicaCode end """ installPackage(omc, pkg; version="", exactMatch=false) Install package `pkg` with given `version`. If `version=""` try to install most recent version of package. If `exactMatch` is true install exact version, even if there are more recent backwards.compatible versions available. See [OpenModelica scripting API `installPackage`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#installpackage) or [Package Management](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/packagemanager.html#using-the-package-manager-from-the-interactive-environment). """ function installPackage(omc::OMJulia.OMCSession, pkg::String; version::String="", exactMatch::Bool=false) success = OMJulia.sendExpression(omc, "installPackage($pkg, version=\"$version\", exactMatch=$exactMatch)") if !success throw(OMJulia.API.ScriptingError(omc, msg = "installPackage($pkg, version=$version, exactMatch=$exactMatch)")) end return success end """ updatePackageIndex(omc) Update package index list. The package manager contacts OSMC sersers and updated the internally sotred list of available packages. See [OpenModelica scripting API `updatePackageIndex`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#updatepackageindex) or [Package Management](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/packagemanager.html#using-the-package-manager-from-the-interactive-environment). """ function updatePackageIndex(omc::OMJulia.OMCSession) success = OMJulia.sendExpression(omc, "updatePackageIndex()") if !success throw(OMJulia.API.ScriptingError(omc, msg = "updatePackageIndex()")) end return success end """ getAvailablePackageVersions(omc, pkg; version="") Get available package versions of `pkg`. Lists all available versions of the Buildings library on the OSMC server, starting from the most recent one, in descending order of priority. Note that pre-release versions have lower priority than all other versions. See [OpenModelica scripting API `getAvailablePackageVersions`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#getavailablepackageversions) or [Package Management](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/packagemanager.html#using-the-package-manager-from-the-interactive-environment). """ function getAvailablePackageVersions(omc::OMJulia.OMCSession, pkg::String; version::String="") versions = OMJulia.sendExpression(omc, "getAvailablePackageVersions($pkg, version=\"$version\")") if length(versions) == 0 errorString = strip(OMJulia.sendExpression(omc, "getErrorString()")) if errorString != "" throw(OMJulia.API.ScriptingError(omc, msg = "getAvailablePackageVersions($pkg, version=$version)", errorString=errorString)) end end return versions end """ upgradeInstalledPackages(omc; installNewestVersions=true) Installs the latest available version of all installed packages. See [OpenModelica scripting API `upgradeInstalledPackages`](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html#upgradeinstalledpackages) or [Package Management](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/packagemanager.html#using-the-package-manager-from-the-interactive-environment). """ function upgradeInstalledPackages(omc::OMJulia.OMCSession; installNewestVersions::Bool=true) success = OMJulia.sendExpression(omc, "upgradeInstalledPackages($installNewestVersions)") if !success throw(OMJulia.API.ScriptingError(omc, msg = "upgradeInstalledPackages($installNewestVersions)")) end return success end end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
2017
#= This file is part of OpenModelica. Copyright (c) 1998-CurrentYear, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# """ omc process error """ struct OMCError <: Exception cmd::Cmd stdout_file::Union{String, Missing} stderr_file::Union{String, Missing} function OMCError(cmd, stdout_file=missing, stderr_file=missing) new(cmd, stdout_file, stderr_file) end end """ Show error from log files """ function Base.showerror(io::IO, e::OMCError) println(io, "OMCError ") println(io, "Command $(e.cmd) failed") if !ismissing(e.stdout_file) println(io, read(e.stdout_file, String)) end if !ismissing(e.stdout_file) print(io, read(e.stderr_file, String)) end end """ Timeout error """ struct TimeoutError <: Exception msg::String end function Base.showerror(io::IO, e::TimeoutError) println(io, "TimeoutError") print(e.msg) end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
49726
# Generated Lexer for OpenModelica Values.Value output const lexertable = [3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 6 0 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 0 0 0 0 0; 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 12 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 2 0 13 13 12 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 12 12 12 12 12; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 8 7 7 9 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 10 7 7 7 11 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 8 7 7 9 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 4 0 0 0 0 0 7 7 7 7 7 0 0 0 7 7 7 7 7 7 7 7 7 7 0 0 0 0 0 0 0; 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0; 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] const csarr = [2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 12 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 2 14 2 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 6 -2 -3 -4 -5 -6 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 2 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 4 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 30 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 4 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 30 -29 -30 -31; 5 -2 27 31 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 3 -2 3 3 27 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 27 29 29 29 27; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 17 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 28 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 28 -28 -29 -30 -31; 9 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 18 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 15 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 19 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 10 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 16 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 25 -7 -8 -9 -10 -11 13 14 13 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 25 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 17 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 22 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 8 -2 28 -4 -5 26 21 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 28 -28 -29 -30 -31; 9 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 18 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 20 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 23 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 7 -2 -3 -4 -5 26 11 11 11 15 11 14 14 14 11 11 11 11 11 11 11 11 24 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 19 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 10 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 16 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 11 -2 -3 -4 -5 26 11 11 11 11 11 14 14 14 11 11 11 11 11 11 11 11 11 11 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31; 2 -2 -3 -4 -5 26 -7 -8 -9 -10 -11 14 14 14 -15 -16 -17 -18 -19 -20 -21 -22 -23 -24 26 26 -27 -28 -29 -30 -31] function tokenize(data::String) begin p::Int = 1 p_end::Int = 0 p_eof::Int = -1 ts::Int = 0 te::Int = 0 cs::Int = 1 end p_end = p_eof = sizeof(data) failed = false tokens = Any[] emit(tok) = push!(tokens, tok) while p ≤ p_eof && cs > 0 begin kouprey = (SizedMemory)(data) t = 0 ts = 0 while p ≤ p_end && cs > 0 seal = kouprey[p + 0] @inbounds duck = (lexertable)[(cs - 1) << 8 + seal + 1] cs = (csarr)[(cs - 1) << 8 + seal + 1] if duck == 1 ts = p t = 10 te = p t = 9 te = p else if duck == 2 ts = p t = 10 te = p t = 7 te = p else if duck == 3 ts = p t = 10 te = p else if duck == 4 ts = p t = 10 te = p t = 6 te = p else if duck == 5 ts = p t = 10 te = p t = 3 te = p else if duck == 6 t = 5 te = p else if duck == 7 t = 6 te = p else if duck == 8 t = 6 te = p t = 1 te = p else if duck == 9 t = 6 te = p t = 2 te = p else if duck == 10 t = 6 te = p t = 3 te = p else if duck == 11 t = 6 te = p t = 4 te = p else if duck == 12 t = 8 te = p else if duck == 13 t = 7 te = p else () end end end end end end end end end end end end end p += 1 end if p > p_eof ≥ 0 && cs ∈ Set([12,11,10,15,16,9,17,18,19,8,20,7,21,22,23,24,6,5,27,29,4,3,2]) cs = 0 elseif cs < 0 p -= 1 end if t > 0 && (cs ≤ 0 || p > p_end ≥ 0) if t == 10 failed = true else if t == 9 () else if t == 8 emit(parse(Float64, data[ts:te])) else if t == 7 emit(parse(Int, data[ts:te])) else if t == 6 emit(Identifier(unescape_string(data[ts:te]))) else if t == 5 emit(unescape_string(data[ts + 1:te - 1])) else if t == 4 emit(Record()) else if t == 3 emit(Symbol(data[ts:te])) else if t == 2 emit(false) else if t == 1 emit(true) else () end end end end end end end end end end p = te + 1 if cs != 0 cs = 1 end end end end if cs < 0 || failed throw(LexerError("Error while lexing")) end if p < p_eof throw(LexerError("Did not scan until end of file. Remaining: $(data[p:p_eof])")) end return tokens end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
2807
# SizedMemory # =========== # The Automa.jl package is licensed under the MIT "Expat" License: # Copyright (c) 2016: BioJulia. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. struct SizedMemory ptr::Ptr{UInt8} len::UInt end """ SizedMemory(data) Create a `SizedMemory` object from `data`. `data` must implement `Automa.pointerstart` and `Automa.pointerend` methods. These are used to get the range of the contiguous data memory of `data`. These have default methods which uses `Base.pointer` and `Base.sizeof` methods. For example, `String` and `Vector{UInt8}` support these `Base` methods. Note that it is user's responsibility to keep the `data` object alive during `SizedMemory`'s lifetime because it does not have a reference to the object. """ function SizedMemory(data, len::Integer=(pointerend(data) + 1) - pointerstart(data)) return SizedMemory(pointerstart(data), len) end """ pointerstart(data)::Ptr{UInt8} Return the start position of `data`. The default implementation is `convert(Ptr{UInt8}, pointer(data))`. """ function pointerstart(data)::Ptr{UInt8} return convert(Ptr{UInt8}, pointer(data)) end """ pointerend(data)::Ptr{UInt8} Return the end position of `data`. The default implementation is `Automa.pointerstart(data) + sizeof(data) - 1`. """ function pointerend(data)::Ptr{UInt8} return pointerstart(data) + sizeof(data) - 1 end function Base.checkbounds(mem::SizedMemory, i::Integer) if 1 ≤ i ≤ mem.len return end throw(BoundsError(i)) end function Base.getindex(mem::SizedMemory, i::Integer) @boundscheck checkbounds(mem, i) return unsafe_load(mem.ptr, i) end function Base.lastindex(mem::SizedMemory) return Int(mem.len) end function Base.length(mem::SizedMemory) return Int(mem.len) end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
51454
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# """ ModelicaSystem(omc, fileName, modelName, library=nothing; commandLineOptions=nothing, variableFilter=nothing, customBuildDirectory=nothing) Set command line options for OMCSession and build model `modelName` to prepare for a simulation. ## Arguments - `omc`: OpenModelica compiler session, see `OMCSession()`. - `fileName`: Path to Modelica file. - `modelName`: Name of Modelica model to build, including namespace if the model is wrappen within a Modelica package. - `library`: List of dependent libraries or Modelica files. This argument can be passed as string (e.g. `"Modelica"`) or tuple (e.g. `("Modelica", "4.0")` or array (e.g. ` ["Modelica", "SystemDynamics"]` or `[("Modelica", "4.0"), "SystemDynamics"]`). ## Keyword Arguments - `commandLineOptions`: OpenModelica command line options, see [OpenModelica Compiler Flags](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/omchelptext.html). - `variableFilter`: Regex to filter variables in result file. ## Usage ``` using OMJulia mod = OMJulia.OMCSession() ModelicaSystem(mod, "BouncingBall.mo", "BouncingBall", ["Modelica", "SystemDynamics"], commandLineOptions="-d=newInst") ``` Providing dependent libaries: ``` using OMJulia mod = OMJulia.OMCSession() ModelicaSystem(mod, "BouncingBall.mo", "BouncingBall", ["Modelica", "SystemDynamics", "dcmotor.mo"]) ``` See also [`OMCSession()`](@ref). """ function ModelicaSystem(omc::OMCSession, fileName::Union{AbstractString, Nothing}, modelName::AbstractString, library::Union{<:AbstractString, Tuple{<:AbstractString, <:AbstractString}, Array{<:AbstractString}, Array{Tuple{<:AbstractString, <:AbstractString}}, Nothing} = nothing; commandLineOptions::Union{<:AbstractString, Nothing} = nothing, variableFilter::Union{<:AbstractString, Nothing} = nothing, customBuildDirectory::Union{<:AbstractString, Nothing} = nothing) ## check for commandLineOptions setCommandLineOptions(omc, commandLineOptions) ## set default command Line Options for linearization as ## linearize() will use the simulation executable and runtime ## flag -l to perform linearization sendExpression(omc, "setCommandLineOptions(\"--linearizationDumpLanguage=julia\")") sendExpression(omc, "setCommandLineOptions(\"--generateSymbolicLinearization\")") omc.modelname = modelName omc.variableFilter = variableFilter #loadFile and set temporary directory if !isnothing(fileName) omc.filepath = fileName loadFile(omc, fileName) end #set temp directory for each modelica session setTempDirectory(omc, customBuildDirectory) #load Libraries provided by users loadLibrary(omc, library) # build the model buildModel(omc) end """ ModelicaSystem(omc; modelName, library=nothing, commandLineOptions=nothing, variableFilter=nothing, customBuildDirectory=nothing) Set command line options for OMCSession and build model `modelname` to prepare for a simulation. ## Arguments - `omc`: OpenModelica compiler session, see `OMCSession()`. ## Keyword Arguments - `modelName`: Name of Modelica model to build, including namespace if the model is wrappen within a Modelica package. - `library`: List of dependent libraries or Modelica files. This argument can be passed as string (e.g. `"Modelica"`) or tuple (e.g. `("Modelica", "4.0")` or array (e.g. ` ["Modelica", "SystemDynamics"]` or `[("Modelica", "4.0"), "SystemDynamics"]`). - `commandLineOptions`: OpenModelica command line options, see [OpenModelica Compiler Flags](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/omchelptext.html). - `variableFilter`: Regex to filter variables in result file. ## Usage ``` using OMJulia mod = OMJulia.OMCSession() ModelicaSystem(mod, modelName="Modelica.Electrical.Analog.Examples.CauerLowPassAnalog", library="Modelica") ``` See also [`OMCSession()`](@ref). """ function ModelicaSystem(omc::OMCSession; fileName::Union{AbstractString, Nothing} = nothing, modelName::AbstractString, library::Union{<:AbstractString,Tuple{<:AbstractString,<:AbstractString},Array{<:AbstractString},Array{Tuple{<:AbstractString,<:AbstractString}},Nothing} = nothing, commandLineOptions::Union{<:AbstractString,Nothing} = nothing, variableFilter::Union{<:AbstractString,Nothing} = nothing, customBuildDirectory::Union{<:AbstractString,Nothing} = nothing) ModelicaSystem(omc, fileName, modelName, library; commandLineOptions=commandLineOptions, variableFilter=variableFilter, customBuildDirectory=customBuildDirectory) end function setCommandLineOptions(omc::OMCSession, commandLineOptions::Union{<:AbstractString,Nothing}=nothing) ## check for commandLineOptions if !isnothing(commandLineOptions) exp = join(["setCommandLineOptions(", "", "\"", commandLineOptions, "\"", ")"]) cmdexp = sendExpression(omc, exp) if !cmdexp error(sendExpression(omc, "getErrorString()")) end end end function loadFile(omc::OMCSession, filename::AbstractString) filepath = replace(abspath(filename), r"[/\\]+" => "/") if isfile(filepath) loadmsg = sendExpression(omc, "loadFile(\"" * filepath * "\")") if !loadmsg error(sendExpression(omc, "getErrorString()")) end else error("\"$filename\" not found") end end function setTempDirectory(omc::OMCSession, customBuildDirectory::Union{<:AbstractString,Nothing}=nothing) if !isnothing(customBuildDirectory) if !isdir(customBuildDirectory) error("Directory does not exist \"$(customBuildDirectory)\"") end omc.tempdir = replace(abspath(customBuildDirectory), r"[/\\]+" => "/") else omc.tempdir = replace(mktempdir(), r"[/\\]+" => "/") if !isdir(omc.tempdir) error("Failed to create temp directory \"$(omc.tempdir)\"") end end sendExpression(omc, "cd(\"" * omc.tempdir * "\")") end """ loadLibrary(omc, library) Load libraries. """ function loadLibrary(omc::OMCSession, library::Union{<:AbstractString, Tuple{<:AbstractString, <:AbstractString}, Array{<:AbstractString}, Array{Tuple{<:AbstractString, <:AbstractString}}, Nothing}) if isnothing(library) return end if isa(library, AbstractString) loadLibraryHelper(omc, library) # allow users to provide library version e.g. ("Modelica", "3.2.3") elseif isa(library, Tuple{AbstractString, AbstractString}) if !isempty(library[2]) loadLibraryHelper(omc, library[1], library[2]) else loadLibraryHelper(omc, library[1]) end elseif isa(library, Array) for i in library # allow users to provide library version e.g. ("Modelica", "3.2.3") if isa(i, Tuple{AbstractString, AbstractString}) if !isempty(i[2]) loadLibraryHelper(omc, i[1], i[2]) else loadLibraryHelper(omc, i[1]) end elseif isa(i, AbstractString) loadLibraryHelper(omc, i) else error("Unknown type detected in input argument library[$i]. Is of type $(typeof(i))") end end else error("Unknown type detected in input argument library[$i]. Is of type $(typeof(i))") end end """ loadLibraryHelper(omc, libname, version=nothing) Load library `libname` by calling `loadFile` or `loadModel` via scripting API. """ function loadLibraryHelper(omc::OMCSession, libname, version=nothing) if isfile(libname) libfile = replace(abspath(libname), r"[/\\]+" => "/") libfilemsg = sendExpression(omc, "loadFile(\"" * libfile * "\")") if !libfilemsg error(sendExpression(omc, "getErrorString()")) end else if isnothing(version) libname = join(["loadModel(", libname, ")"]) else libname = join(["loadModel(", libname, ", ", "{", "\"", version, "\"", "}", ")"]) end result = sendExpression(omc, libname) if !result error(sendExpression(omc, "getErrorString()")) end end end """ buildModel(omc; variableFilter=nothing) Build modelica model. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. ## Keyword Arguments - `variableFilter`: Regex to filter variables in result file. """ function buildModel(omc::OMCSession; variableFilter::Union{<:AbstractString, Nothing} = nothing) if !isnothing(variableFilter) omc.variableFilter = variableFilter end if !isnothing(omc.variableFilter) varFilter = join(["variableFilter=", "\"", omc.variableFilter, "\""]) else varFilter = join(["variableFilter=\"", ".*" ,"\""]) end buildmodelexpr = join(["buildModel(",omc.modelname,", ", varFilter,")"]) @debug "buildmodelexpr: $buildmodelexpr" buildModelmsg = sendExpression(omc, buildmodelexpr) if !isempty(buildModelmsg[2]) omc.xmlfile = replace(joinpath(omc.tempdir, buildModelmsg[2]), r"[/\\]+" => "/") xmlparse(omc) else error(sendExpression(omc, "getErrorString()")) end end """ xmlparse(omc) This function parses the XML file generated from the buildModel() and stores the model variable into different categories namely parameter inputs, outputs, continuous etc.. """ function xmlparse(omc::OMCSession) if isfile(omc.xmlfile) xdoc = parse_file(omc.xmlfile) # get the root element xroot = root(xdoc) # an instance of XMLElement for c in child_nodes(xroot) # c is an instance of XMLNode if is_elementnode(c) e = XMLElement(c) # this makes an XMLElement instance if name(e) == "DefaultExperiment" omc.simulateOptions["startTime"] = attribute(e, "startTime") omc.simulateOptions["stopTime"] = attribute(e, "stopTime") omc.simulateOptions["stepSize"] = attribute(e, "stepSize") omc.simulateOptions["tolerance"] = attribute(e, "tolerance") omc.simulateOptions["solver"] = attribute(e, "solver") end if name(e) == "ModelVariables" for r in child_elements(e) scalar = Dict() scalar["name"] = attribute(r, "name") scalar["changeable"] = attribute(r, "isValueChangeable") scalar["description"] = attribute(r, "description") scalar["variability"] = attribute(r, "variability") scalar["causality"] = attribute(r, "causality") scalar["alias"] = attribute(r, "alias") scalar["aliasvariable"] = attribute(r, "aliasVariable") subchild = child_elements(r) for s in subchild value = attribute(s, "start") min = attribute(s, "min") max = attribute(s, "max") if !isnothing(value) scalar["start"] = value else scalar["start"] = "None" end if !isnothing(min) scalar["min"] = min else scalar["min"] = "None" end if !isnothing(max) scalar["max"] = max else scalar["max"] = "None" end end if !omc.linearization.linearFlag if scalar["variability"] == "parameter" if haskey(omc.overridevariables, scalar["name"]) omc.parameterlist[scalar["name"]] = omc.overridevariables[scalar["name"]] else omc.parameterlist[scalar["name"]] = scalar["start"] end end if scalar["variability"] == "continuous" omc.continuouslist[scalar["name"]] = scalar["start"] end if scalar["causality"] == "input" omc.inputlist[scalar["name"]] = scalar["start"] end if scalar["causality"] == "output" omc.outputlist[scalar["name"]] = scalar["start"] end end push!(omc.quantitieslist, scalar) end end end end # return quantities else println("file not generated") return end end """ getQuantities(omc, name=nothing) Return list of all variables parsed from xml file. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}`: Names of variables to read from xml file. If nothing is provided read all variables. See also [`showQuantities`](@ref). """ function getQuantities(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString, 1}, Nothing} = nothing) if isnothing(name) return omc.quantitieslist elseif isa(name, AbstractString) return [x for x in omc.quantitieslist if x["name"] == name] elseif isa(name, Array) return [x for y in name for x in omc.quantitieslist if x["name"] == y] end end function getQuantitiesHelper(omc::OMCSession, name=nothing; verbose=true) for x in omc.quantitieslist if x["name"] == name return x end end if verbose @info "getQuantities() failed: \" $name \" does not exist." end return [] end """ showQuantities(omc, name=nothing) Return `DataFrame` of all variables parsed from xml file. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}`: Names of variables to read from xml file. If nothing is provided read all variables. See also [`getQuantities`](@ref). """ function showQuantities(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing} = nothing) q = getQuantities(omc, name); # assuming that the keys of the first dictionary is representative for them all sym = map(Symbol, collect(keys(q[1]))) arr = [] for d in q push!(arr, Dict(zip(sym, values(d)))) end return df_from_dicts(arr) end """ helper function to return getQuantities as DataFrame """ function df_from_dicts(arr::AbstractArray; missing_value="missing") cols = Set{Symbol}() for di in arr union!(cols, keys(di)) end df = DataFrame() for col = cols # df[col] = [get(di, col, missing_value) for di=arr] df[!,col] = [get(di, col, missing_value) for di = arr] end return df end """ getParameters(omc, name=nothing) Return parameter variables parsed from xml file. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}`: Names of parameters to read from xml file. If nothing is provided read all parameters. """ function getParameters(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing} = nothing) if isnothing(name) return omc.parameterlist elseif isa(name, String) return get(omc.parameterlist, name, 0) elseif isa(name, Array) return [get(omc.parameterlist, x, 0) for x in name] end end """ getSimulationOptions(omc, name=nothing) Return SimulationOption variables parsed from xml file. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}`: Names of parameters to read from xml file. If nothing is provided read all parameters. """ function getSimulationOptions(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing} = nothing) if isnothing(name) return omc.simulateOptions elseif isa(name, String) return get(omc.simulateOptions, name, 0) elseif isa(name, Array) return [get(omc.simulateOptions, x, 0) for x in name] end end """ getContinuous(omc, name=nothing) Return continuous variables parsed from xml file. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}`: Names of continuous variables to read from xml file. If nothing is provided read all continuous variables. """ function getContinuous(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing} = nothing) if !omc.simulationFlag if isnothing(name) return omc.continuouslist elseif isa(name, String) return get(omc.continuouslist, name, 0) elseif isa(name, Array) return [get(omc.continuouslist, x, 0) for x in name] end end if omc.simulationFlag if isnothing(name) for name in keys(omc.continuouslist) ## failing for variables with $ sign ## println(name) try value = getSolutions(omc, name) value1 = value[1] omc.continuouslist[name] = value1[end] catch Exception println(Exception) end end return omc.continuouslist elseif isa(name, String) if haskey(omc.continuouslist, name) value = getSolutions(omc, name) value1 = value[1] omc.continuouslist[name] = value1[end] return get(omc.continuouslist, name, 0) else error("\"$name\" is not continuous") end elseif isa(name, Array) continuousvaluelist = Any[] for x in name if haskey(omc.continuouslist, x) value = getSolutions(omc, x) value1 = value[1] omc.continuouslist[x] = value1[end] push!(continuousvaluelist, value1[end]) else error("\"$x\" is not continuous") end end return continuousvaluelist end end end """ getInputs(omc, name=nothing) Return input variables parsed from xml file. If input variables have no start value the returned value is `\"None\"`. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}`: Names of input variables to read from xml file. If nothing is provided read all input variables. """ function getInputs(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing} = nothing) if isnothing(name) return omc.inputlist elseif isa(name, String) return get(omc.inputlist, name, 0) elseif isa(name, Array) return [get(omc.inputlist, x, 0) for x in name] end end """ getInputs(omc, name=nothing) Return output variables parsed from xml file. If output variables have no start value the returned value is `\"None\"`. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}`: Names of output variables to read from xml file. If nothing is provided read all output variables. """ function getOutputs(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}=nothing) if !omc.simulationFlag if isnothing(name) return omc.outputlist elseif isa(name, String) return get(omc.outputlist, name, 0) elseif isa(name, Array) return [get(omc.outputlist, x, 0) for x in name] end end if omc.simulationFlag if isnothing(name) for name in keys(omc.outputlist) value = getSolutions(omc, name) value1 = value[1] omc.outputlist[name] = value1[end] end return omc.outputlist elseif isa(name, String) if haskey(omc.outputlist, name) value = getSolutions(omc, name) value1 = value[1] omc.outputlist[name] = value1[end] return get(omc.outputlist, name, 0) else error("\"$name\" is not an output variable") end elseif isa(name, Array) valuelist = Any[] for x in name if haskey(omc.outputlist, x) value = getSolutions(omc, x) value1 = value[1] omc.outputlist[x] = value1[end] push!(valuelist, value1[end]) else error("\"$x\" is not an output variable") end end return valuelist end end end """ simulate(omc; resultfile=nothing, simflags="", verbose=false) Simulate modelica model. ## Arguments - `omc::OMCSession`: OpenModelica compiler session, see `OMCSession()`. ## Keyword Arguments - `resultFile::Union{String, Nothing}`: Result file to write simulation results into. - `simflags::String`: Simulation flags, see [Simulation Runtime Flags](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/simulationflags.html). - `verbose::Bool`: [debug] Log cmd call to `log.txt` and `error.txt`. ## Examples ```julia simulate(omc) ``` Specify result file: ```julia simulate(omc, resultfile="tmpresult.mat") ``` Set simulation runtime flags: ```julia simulate(omc, simflags="-noEmitEvent -override=e=0.3,g=9.3") ``` """ function simulate(omc::OMCSession; resultfile::Union{String, Nothing} = nothing, simflags::String = "", verbose::Bool = false) if isnothing(resultfile) r = "" omc.resultfile = replace(joinpath(omc.tempdir, join([omc.modelname,"_res.mat"])), r"[/\\]+" => "/") else r = join(["-r=",resultfile]) omc.resultfile = replace(joinpath(omc.tempdir, resultfile), r"[/\\]+" => "/") end if isfile(omc.xmlfile) if Sys.iswindows() getexefile = replace(joinpath(omc.tempdir, join([omc.modelname,".exe"])), r"[/\\]+" => "/") else getexefile = replace(joinpath(omc.tempdir, omc.modelname), r"[/\\]+" => "/") end if isfile(getexefile) ## change to tempdir cd(omc.tempdir) if !isempty(omc.overridevariables) | !isempty(omc.simoptoverride) tmpdict = merge(omc.overridevariables, omc.simoptoverride) overridefile = replace(joinpath(omc.tempdir, join([omc.modelname,"_override.txt"])), r"[/\\]+" => "/") file = open(overridefile, "w") for k in keys(tmpdict) val = join([k,"=",tmpdict[k],"\n"]) println(val) write(file, val) end close(file) overridevar = join(["-overrideFile=", overridefile]) else overridevar = "" end if omc.inputFlag createcsvdata(omc, omc.simulateOptions["startTime"], omc.simulateOptions["stopTime"]) csvinput = join(["-csvInput=",omc.csvfile]) # run(pipeline(`$getexefile $overridevar $csvinput`,stdout="log.txt",stderr="error.txt")) else csvinput = "" # run(pipeline(`$getexefile $overridevar`,stdout="log.txt",stderr="error.txt")) end # remove empty args in cmd objects cmd = filter!(e -> e ≠ "", [getexefile,overridevar,csvinput,r,simflags]) # println(cmd) if Sys.iswindows() installPath = sendExpression(omc, "getInstallationDirectoryPath()") envPath = ENV["PATH"] newPath = "$(installPath)/bin/;$(installPath)/lib/omc;$(installPath)/lib/omc/cpp;$(installPath)/lib/omc/omsicpp;$(envPath)" # println("Path: $newPath") withenv("PATH" => newPath) do if verbose run(pipeline(`$cmd`)) else run(pipeline(`$cmd`, stdout="log.txt", stderr="error.txt")) end end else if verbose run(pipeline(`$cmd`)) else run(pipeline(`$cmd`, stdout="log.txt", stderr="error.txt")) end end # omc.resultfile=replace(joinpath(omc.tempdir,join([omc.modelname,"_res.mat"])),r"[/\\]+" => "/") omc.simulationFlag = true else error("Simulation Failed") end ## change to currentworkingdirectory cd(omc.currentdir) end end """ function which converts modelica model to FMU convertMo2FMU(omc; version::String = "2.0", fmuType::String = "me_cs", fileNamePrefix::String = "<default>", includeResources::Bool = true) ## Arguments - `omc::OMCSession`: OpenModelica compiler session, see `OMCSession()`. ## Keyword Arguments - `version::String`: version 1.0 or 2.0 - `fmuType::String`: FMU type, me (model exchange), cs (co-simulation), me_cs (both model exchange and co-simulation)" - `fileNamePrefix::String`: modelname will be used as default. ## Examples ```julia convertMo2FMU(omc) ``` """ function convertMo2FMU(omc; version::String = "2.0", fmuType::String = "me_cs", fileNamePrefix::String = "<default>", includeResources::Bool = true) if fileNamePrefix == "<default>" fileNamePrefix = omc.modelname end if length(fileNamePrefix) > 50 ## this approach will work only for MSL or fileNamePrefix seperated with . (e.g) Modelica.Electrical.Analog.Examples.CauerLowPassAnalog fileNamePrefix = String(last(split(fileNamePrefix, "."))) end ## check again for the length if unable to reduce if length(fileNamePrefix) > 50 return println("length of fileNamePrefix", fileNamePrefix, "is too long ", length(fileNamePrefix), "fileNamePrefix prefix should be less than 50 characters") end exp = join(["buildModelFMU(", omc.modelname, ", version=", API.modelicaString(version), ", fmuType=", API.modelicaString(fmuType), ", fileNamePrefix=", API.modelicaString(fileNamePrefix), ", includeResources=", includeResources, ")"]) fmu = sendExpression(omc, exp) if !isfile(fmu) return println(sendExpression(omc, "getErrorString()")) end return fmu end """ function which converts FMU to modelicamodel """ function convertFmu2Mo(omc::OMCSession, fmupath) if !isfile(fmupath) return println(fmupath, " does not exist") end fmupath = replace(fmupath, r"[/\\]+" => "/") filename = sendExpression(omc, "importFMU(\"" * fmupath * "\")") if !isfile(filename) return println(sendExpression(omc, "getErrorString()")) end return filename end """ sensitivity(omc::OMCSession, Vp, Vv, Ve=[1e-2]) Method for computing numeric sensitivity of OpenModelica object. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `Vp::Array{<:AbstractString, 1}`: Modelica Parameter names. - `Vv::Array{<:AbstractString, 1}`: Modelica Variable names. - `Ve::Array{Float64, 1}`: Excitations of parameters; defaults to scalar 1e-2 ## Return - `VSname::Vector{Vector{String}}`: Vector of sensitivity names - `VSarray::Vector{Vector{Vector{Float64}}}`: Vector of sensitivies: vector of elements per parameter Each element containing time series per variable """ function sensitivity(omc::OMCSession, Vp::Array{<:AbstractString, 1}, Vv::Array{<:AbstractString, 1}, Ve::Array{Float64, 1} = [1e-2])::Tuple{Vector{Vector{String}}, Vector{Vector{Vector{Float64}}}} ## Production quality code should check type and form of input arguments Ve = map(Float64, Ve) # converting eVements of excitation to floats nVp = length(Vp) # number of parameter names nVe = length(Ve) # number of excitations in parameters # Adjusting size of Ve to that of Vp if nVe < nVp push!(Ve, Ve[end] * ones(nVp - nVe)...) # extends Ve by adding last eVement of Ve elseif nVe > nVp Ve = Ve[1:nVp] # truncates Ve to same length as Vp end # Nominal parameters p0 par0 = [parse(Float64, pp) for pp in getParameters(omc, Vp)] # eXcitation parameters parX parX = [par0[i] * (1 + Ve[i]) for i in 1:nVp] # Combine parameter names and parameter values into vector of strings Vpar0 = [Vp[i] * "=$(par0[i])" for i in 1:nVp] VparX = [Vp[i] * "=$(parX[i])" for i in 1:nVp] # Simulate nominal system simulate(omc) # Get nominal SOLutions of variabVes of interest (Vv), converted to 2D array sol0 = getSolutions(omc, Vv) # Get vector of eXcited SOLutions (2D arrays), one for each parameter (Vp) solX = Vector{Array{Array{Float64,1},1}}() for p in VparX # change to excited parameter setParameters(omc, p) # simulate perturbed system simulate(omc) # get eXcited SOLutions (Vv) as 2D array, and append to list push!(solX, getSolutions(omc, Vv)) # reset parameters to nominal values setParameters(omc, Vpar0) end ## Compute sensitivities and add to vector, one 2D array per parameter (Vp) VSname = Vector{Vector{String}}() VSarray = Vector{Array{Array{Float64,1},1}}() # same shape as solX for (i, sol) in enumerate(solX) push!(VSarray, ((sol - sol0) / (par0[i] * Ve[i]))) vsname = Vector{String}() for j in 1:nVp push!(vsname, "Sensitivity." * Vp[i] * "." * Vv[j]) end push!(VSname, vsname) end return VSname, VSarray end """ getSolutions(omc::OMCSession, name=nothing; resultfile=nothing) Read result file and return simulation results ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}`: Names of variables to read from result file. If nothing is provided read all variables. ## Keyword Arguments - `resultfile::Union{AbstractString, Nothing}`: Path to result file. If nothing is provided use saved result file. """ function getSolutions(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing} = nothing; resultfile::Union{AbstractString, Nothing} = nothing) if isnothing(resultfile ) resfile = omc.resultfile else resfile = resultfile end # Error handling if !isfile(resfile) error("Result file $(abspath(resfile)) does not exist !") end if isempty(resfile) error("Model not Simulated, Simulate the model to get the results") end # Read variables simresultvars = sendExpression(omc, "readSimulationResultVars(\"" * resfile * "\")") sendExpression(omc, "closeSimulationResultFile()") if isnothing(name) return simresultvars elseif isa(name, String) if !(name in simresultvars) && name != "time" error("'$name' not found in simulation results") end resultvar = join(["{",name,"}"]) simres = sendExpression(omc, "readSimulationResult(\"" * resfile * "\"," * resultvar * ")") sendExpression(omc, "closeSimulationResultFile()") return simres elseif isa(name, Array) for var in name if !(var in simresultvars) && var != "time" error("'$name' not found in simulation results") end end resultvar = join(["{",join(name, ","),"}"]) # println(resultvar) simres = sendExpression(omc, "readSimulationResult(\"" * resfile * "\"," * resultvar * ")") sendExpression(omc, "closeSimulationResultFile()") return simres end end """ setParameters(omc, name; verbose=true) Set parameter values for parameter variables defined by users ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}}`: String \"Name=value\" or vector of strings [\"Name1=value1\",\"Name2=value2\",\"Name3=value3\"]) ## Keyword Arguments - `verbose::Bool`: Display additional info if setParameters failed. """ function setParameters(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}}; verbose::Bool = true) if isa(name, String) name = strip_space(name) value = split(name, "=") # setxmlfileexpr="setInitXmlStartValue(\""* this.xmlfile * "\",\""* value[1]* "\",\""*value[2]*"\",\""*this.xmlfile*"\")" # println(haskey(this.parameterlist, value[1])) if haskey(omc.parameterlist, value[1]) # should we use this ??? # setparameterValue = join(["setParameterValue(",omc.modelname,",", value[1],",",value[2],")"]) # println(setparameterValue) if isParameterChangeable(omc, value[1], value[2]) omc.parameterlist[value[1]] = value[2] omc.overridevariables[value[1]] = value[2] end else if verbose @info("setParameters() failed: \" $(value[1])\" is not a parameter") end end # omc.sendExpression(setxmlfileexpr) elseif isa(name, Array) name = strip_space(name) for var in name value = split(var, "=") if haskey(omc.parameterlist, value[1]) if isParameterChangeable(omc, value[1], value[2]) omc.parameterlist[value[1]] = value[2] omc.overridevariables[value[1]] = value[2] end else if verbose @info("setParameters() failed: \" $(value[1])\" is not a parameter") end end end end end """ check for parameter modifiable or not """ function isParameterChangeable(omc::OMCSession, name, value; verbose=true) q = getQuantities(omc, String(name)) if isempty(q) println(name, " does not exist in the model") return false elseif q[1]["changeable"] == "false" if verbose println("| info | setParameters() failed : It is not possible to set the following signal ", "\"", name, "\"", ", It seems to be structural, final, protected or evaluated or has a non-constant binding, use sendExpression(setParameterValue(", omc.modelname, ", ", name, ", ", value, "), parsed=false)", " and rebuild the model using buildModel() API") end return false end return true end """ setSimulationOptions(omc, name) Set simulation option values like `stopTime` or `stepSize`. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}}`: String \"Name=value\" or vector of strings [\"Name1=value1\",\"Name2=value2\",\"Name3=value3\"]) """ function setSimulationOptions(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}}) if isa(name, String) name = strip_space(name) value = split(name, "=") if haskey(omc.simulateOptions, value[1]) omc.simulateOptions[value[1]] = value[2] omc.simoptoverride[value[1]] = value[2] else error("\"$(value[1])\" is not a simulation option") end elseif isa(name, Array) name = strip_space(name) for var in name value = split(var, "=") if haskey(omc.simulateOptions, value[1]) omc.simulateOptions[value[1]] = value[2] omc.simoptoverride[value[1]] = value[2] else error("\"$(value[1])\" is not a simulation option") end end end end """ setInputs(omc, name) Set new values for input variables. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}}`: String \"Name=value\" or vector of strings [\"Name1=value1\",\"Name2=value2\",\"Name3=value3\"]) """ function setInputs(omc::OMCSession, name) if isa(name, String) name = strip_space(name) value = split(name, "=") if haskey(omc.inputlist, value[1]) newval = Meta.parse(value[2]) if isa(newval, Expr) omc.inputlist[value[1]] = [v.args for v in newval.args] else omc.inputlist[value[1]] = value[2] end omc.inputFlag = true else error("$(value[1]) is not an input variable") end elseif isa(name, Array) name = strip_space(name) for var in name value = split(var, "=") if haskey(omc.inputlist, value[1]) newval = Meta.parse(value[2]) if isa(newval, Expr) omc.inputlist[value[1]] = [v.args for v in newval.args] else omc.inputlist[value[1]] = value[2] end # omc.overridevariables[value[1]]=value[2] omc.inputFlag = true else error("$(value[1]) is not an input variable") end end end end function strip_space(name) if isa(name, String) return filter(x -> !isspace(x), name) elseif isa(name, Array) return [filter(x -> !isspace(x), s) for s in name] end end """ getWorkDirectory(omc) Return working directory of OMJulia.OMCsession `omc`. """ function getWorkDirectory(omc::OMCSession) return omc.tempdir end """ function which creates the csvinput when user specify new values for input variables, this function is used in context with setInputs() """ function createcsvdata(omc::OMCSession, startTime, stopTime) omc.csvfile = joinpath(omc.tempdir, join([omc.modelname,".csv"])) file = open(omc.csvfile, "w") write(file, join(["time",",",join(keys(omc.inputlist), ","),",","end","\n"])) csvdata = deepcopy(omc.inputlist) value = values(csvdata) time = Any[] for val in value if isa(val, Array) checkflag = "true" for v in val push!(time, v[1]) end end end if length(time) == 0 push!(time, startTime) push!(time, stopTime) end previousvalue = Dict() for i in sort(time) if isa(i, SubString{String}) || isa(i, String) write(file, i, ",") else write(file, join(i, ","), ",") end listcount = 1 for val in value if isa(val, Array) newval = val count = 1 found = "false" for v in newval if i == v[1] data = eval(v[2]) write(file, join(data, ","), ",") previousvalue[listcount] = data deleteat!(newval, count) found = "true" break end count = count + 1 end if found == "false" write(file, join(previousvalue[listcount], ","), ",") end end if isa(val, String) if val == "None" val = "0" else val = val end write(file, val, ",") previousvalue[listcount] = val end if isa(val, SubString{String}) if val == "None" val = "0" else val = val end write(file, val, ",") previousvalue[listcount] = val end listcount = listcount + 1 end write(file, "0", "\n") end close(file) end """ function which returns the linearize model of modelica model, The function returns four matrices A, B, C, D linearize(omc; lintime = nothing, simflags= nothing, verbose=true) ## Arguments - `omc::OMCSession`: OpenModelica compiler session. ## Keyword Arguments - `lintime` : Value specifies a time where the linearization of the model should be performed - `simflags`: Simulation flags, see [Simulation Runtime Flags](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/simulationflags.html). ## Examples of using linearize() API ```julia linearize(omc) ``` Specify result file: ```julia linearize(omc, lintime="0.5") ``` Set simulation runtime flags: ```julia linearize(omc, simflags="-noEmitEvent") ``` """ function linearize(omc::OMCSession; lintime = nothing, simflags= nothing, verbose=true) if isempty(omc.xmlfile) error("Linearization cannot be performed as the model is not build, use ModelicaSystem() to build the model first") end if isnothing(simflags) simflags=""; end overridelinearfile = replace(joinpath(omc.tempdir, join([omc.modelname,"_override_linear.txt"])), r"[/\\]+" => "/") # println(overridelinearfile); file = open(overridelinearfile, "w") overridelist = false for k in keys(omc.overridevariables) val = join([k,"=",omc.overridevariables[k],"\n"]) write(file, val) overridelist = true end for t in keys(omc.linearization.linearOptions) val = join([t,"=",omc.linearization.linearOptions[t], "\n"]) write(file, val) overridelist = true end close(file) if overridelist overrideFlag = join(["-overrideFile=", overridelinearfile]) else overrideFlag = ""; end if omc.inputFlag createcsvdata(omc, omc.linearization.linearOptions["startTime"], omc.linearization.linearOptions["stopTime"]) csvinput = join(["-csvInput=", omc.csvfile]) else csvinput = ""; end if isfile(omc.xmlfile) if Sys.iswindows() getexefile = replace(joinpath(omc.tempdir, join([omc.modelname,".exe"])), r"[/\\]+" => "/") else getexefile = replace(joinpath(omc.tempdir, omc.modelname), r"[/\\]+" => "/") end else error("\"$(omc.xmlfile)\" not found, please build the model again using ModelicaSystem()") end if !isnothing(lintime) linruntime = join(["-l=", lintime]) else linruntime = join(["-l=", omc.linearization.linearOptions["stopTime"]]) end finalLinearizationexe = filter!(e -> e ≠ "", [getexefile, linruntime, overrideFlag, csvinput, simflags]) # println(finalLinearizationexe) cd(omc.tempdir) if Sys.iswindows() installPath = sendExpression(omc, "getInstallationDirectoryPath()") envPath = ENV["PATH"] newPath = "$(installPath)/bin/;$(installPath)/lib/omc;$(installPath)/lib/omc/cpp;$(installPath)/lib/omc/omsicpp;$(envPath)" # println("Path: $newPath") withenv("PATH" => newPath) do if verbose run(pipeline(`$finalLinearizationexe`)) else run(pipeline(`$finalLinearizationexe`, stdout="log.txt", stderr="error.txt")) end end else if verbose run(pipeline(`$finalLinearizationexe`)) else run(pipeline(`$finalLinearizationexe`, stdout="log.txt", stderr="error.txt")) end end omc.linearization.linearmodelname = "linearized_model" omc.linearization.linearfile = joinpath(omc.tempdir, join([omc.linearization.linearmodelname,".jl"])) # support older openmodelica versions before OpenModelica v1.16.2 where linearize() generates "linear_modelname.mo" file if(!isfile(omc.linearization.linearfile)) omc.linearization.linearmodelname = join(["linear_", omc.modelname]) omc.linearization.linearfile = joinpath(omc.tempdir, join([omc.linearization.linearmodelname, ".jl"])) end if isfile(omc.linearization.linearfile) omc.linearization.linearFlag = true # this function is called from the generated Julia code linearized_model.jl, # to improve the performance by directly reading the matrices A, B, C and D from the julia code and avoid building the linearized modelica model include(omc.linearization.linearfile) ## to be evaluated at runtime, as Julia expects all functions should be known at the compilation time so efficient assembly code can be generated. result = invokelatest(linearized_model) (n, m, p, x0, u0, A, B, C, D, stateVars, inputVars, outputVars) = result omc.linearization.linearstates = stateVars omc.linearization.linearinputs = inputVars omc.linearization.linearoutputs = outputVars return [A, B, C, D] else errormsg = sendExpression(omc, "getErrorString()") cd(omc.currentdir) error("\"$(omc.linearization.linearfile)\" not found \n$errormsg") end cd(omc.currentdir) end """ getLinearizationOptions(omc, name=nothing) Return linearization options. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing}`: Names of linearization options. If nothing is provided return all linearization options. """ function getLinearizationOptions(omc::OMCSession, name::Union{<:AbstractString, Array{<:AbstractString,1}, Nothing} = nothing) if isnothing(name) return omc.linearization.linearOptions elseif isa(name, String) return get(omc.linearization.linearOptions, name, 0) elseif isa(name, Array) return [get(omc.linearization.linearOptions, x, 0) for x in name] end end """ getLinearInputs(omc) Return linear input variables after the model is linearized ## Arguments - `omc::OMCSession`: OpenModelica compiler session. """ function getLinearInputs(omc::OMCSession) if omc.linearization.linearFlag return omc.linearization.linearinputs else error("Model is not linearized") end end """ getLinearOutputs(omc) Return linear output variables after the model is linearized ## Arguments - `omc::OMCSession`: OpenModelica compiler session. """ function getLinearOutputs(omc::OMCSession) if omc.linearization.linearFlag return omc.linearization.linearoutputs else println("Model is not Linearized") end end """ getLinearStates(omc) Return linear state variables after the model is linearized ## Arguments - `omc::OMCSession`: OpenModelica compiler session. """ function getLinearStates(omc::OMCSession) if omc.linearization.linearFlag return omc.linearization.linearstates else println("Model is not Linearized") end end """ setLinearizationOptions(omc, name) Set linearization options. ## Arguments - `omc::OMCSession`: OpenModelica compiler session. - `name::Union{<:AbstractString, Array{<:AbstractString,1}}`: String \"Name=value\" or vector of strings [\"Name1=value1\",\"Name2=value2\",\"Name3=value3\"]) """ function setLinearizationOptions(omc::OMCSession, name) if isa(name, String) name = strip_space(name) value = split(name, "=") if haskey(omc.linearization.linearOptions, value[1]) omc.linearization.linearOptions[value[1]] = value[2] else error("\"$(value[1])\" is not a linearization option") end elseif isa(name, Array) name = strip_space(name) for var in name value = split(var, "=") if haskey(omc.linearization.linearOptions, value[1]) omc.linearization.linearOptions[value[1]] = value[2] else error("\"$(value[1])\" is not a linearization option") end end end end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
9312
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# """ Linearization <: Any Collection of linearization settings and variables. See also [``] """ mutable struct Linearization "Name of linear model in Julia function `linearfile`" linearmodelname::AbstractString "Julia file linearized_model.jl containing linearization matrices A, B, C and D." linearfile::AbstractString "Experiment settings for linearization" linearOptions::Dict{AbstractString, AbstractString} linearFlag::Bool "Input variables" linearinputs::Union{Missing, Any} "Output variables" linearoutputs::Union{Missing, Any} "State variables" linearstates::Union{Missing, Any} function Linearization() linearmodelname = "" linearfile = "" linearOptions = Dict("startTime" => "0.0", "stopTime" => "1.0", "stepSize" => "0.002", "tolerance" => "1e-6") linearFlag = false new(linearmodelname, linearfile, linearOptions, linearFlag, missing, missing, missing) end end """ ZMQSession <: Any ZeroMQ session running interactive omc process. ----------------------------------------- ZMQSession(omc::Union{String, Nothing}=nothing)::ZMQSession Start new interactive OpenModelica session using ZeroMQ. ## Arguments - `omc::Union{String, Nothing}`: Path to OpenModelica compiler. Use omc from `PATH` if nothing is provided. """ mutable struct ZMQSession context::ZMQ.Context socket::ZMQ.Socket omcprocess::Base.Process function ZMQSession(omc::Union{String, Nothing}=nothing)::ZMQSession args1 = "--interactive=zmq" randPortSuffix = Random.randstring(10) args2 = "-z=julia.$(randPortSuffix)" stdoutfile = "stdout-$(randPortSuffix).log" stderrfile = "stderr-$(randPortSuffix).log" local omcprocess if Sys.iswindows() if !isnothing(omc ) ompath = replace(omc, r"[/\\]+" => "/") dirpath = dirname(dirname(omc)) ## create a omc process with OPENMODELICAHOME set to custom directory @info("Setting environment variable OPENMODELICAHOME=\"$dirpath\" for this session.") withenv("OPENMODELICAHOME" => dirpath) do omcprocess = open(pipeline(`$omc $args1 $args2`, stdout=stdoutfile, stderr=stderrfile)) end else omhome = "" try omhome = ENV["OPENMODELICAHOME"] catch Exception println(Exception, "is not set, Please set the environment Variable") return end ompath = replace(joinpath(omhome, "bin", "omc.exe"), r"[/\\]+" => "/") # ompath=joinpath(omhome,"bin") ## create a omc process with default OPENMODELICAHOME set in environment variable withenv("OPENMODELICAHOME" => omhome) do omcprocess = open(pipeline(`$ompath $args1 $args2`)) end end portfile = join(["openmodelica.port.julia.", randPortSuffix]) else if Sys.isapple() # add omc to path if not exist ENV["PATH"] = ENV["PATH"] * "/opt/openmodelica/bin" if !isnothing(omc ) omcprocess = open(pipeline(`$omc $args1 $args2`, stdout=stdoutfile, stderr=stderrfile)) else omcprocess = open(pipeline(`omc $args1 $args2`, stdout=stdoutfile, stderr=stderrfile)) end else if !isnothing(omc ) omcprocess = open(pipeline(`$omc $args1 $args2`, stdout=stdoutfile, stderr=stderrfile)) else omcprocess = open(pipeline(`omc $args1 $args2`, stdout=stdoutfile, stderr=stderrfile)) end end portfile = join(["openmodelica.", ENV["USER"], ".port.julia.", randPortSuffix]) end fullpath = joinpath(tempdir(), portfile) @info("Path to zmq file=\"$fullpath\"") ## Try to find better approach if possible, as sleep does not work properly across different platform tries = 0 while tries < 100 && !isfile(fullpath) sleep(0.02) tries += 1 end # Catch omc error if process_exited(omcprocess) && omcprocess.exitcode != 0 throw(OMCError(omcprocess.cmd, stdoutfile, stderrfile)) end rm.([stdoutfile, stderrfile], force=true) if tries >= 100 throw(TimeoutError("ZMQ server port file \"$fullpath\" not created yet.")) end filedata = read(fullpath, String) context = ZMQ.Context() socket = ZMQ.Socket(context, REQ) ZMQ.connect(socket, filedata) zmqSession = new(context, socket, omcprocess) # Register finalizer to stop omc process when this OMCsession is no longer reachable f(zmqSession) = kill(zmqSession.omcprocess) finalizer(f, zmqSession) return zmqSession end end """ OMCSession <: Any OMC session struct. -------------- OMCSession(omc=nothing) Create new OpenModelica session. ## Arguments - `omc::Union{String, Nothing}`: Path to OpenModelica compiler. Use omc from `PATH` if nothing is provided. See also [`ModelicaSystem`](@ref), [`OMJulia.quit`](@ref). """ mutable struct OMCSession simulationFlag::Bool inputFlag::Bool simulateOptions::Dict overridevariables::Dict simoptoverride::Dict tempdir::AbstractString "Current directory" currentdir::AbstractString resultfile::AbstractString filepath::AbstractString modelname::AbstractString xmlfile::AbstractString csvfile::AbstractString "Filter for simulation result passed to buildModel" variableFilter::Union{AbstractString, Nothing} quantitieslist::Array{Any, 1} parameterlist::Dict inputlist::Dict outputlist::Dict "List of continuous model variables" continuouslist::Dict zmqSession::ZMQSession linearization::Linearization function OMCSession(omc::Union{String, Nothing}=nothing)::OMCSession this = new() this.overridevariables = Dict() this.simoptoverride = Dict() this.quantitieslist = Any[] this.parameterlist = Dict() this.simulateOptions = Dict() this.inputlist = Dict() this.outputlist = Dict() this.continuouslist = Dict() this.currentdir = pwd() this.filepath = "" this.modelname = "" this.xmlfile = "" this.resultfile = "" this.simulationFlag = false this.inputFlag = false this.csvfile = "" this.variableFilter = nothing this.tempdir = "" this.linearization = Linearization() this.zmqSession = ZMQSession(omc) return this end end """ quit(omc::OMCSession; timeout=4::Integer) Quit OMCSession. # Arguments - `omc::OMCSession`: OMC session. # Keywords - `timeout=4::Integer`: Timeout in seconds. See also [`OMJulia.OMCSession`](@ref). """ function quit(omc::OMCSession; timeout=4::Integer) tsk = @task sendExpression(omc, "quit()", parsed=false) schedule(tsk) Timer(timeout) do timer istaskdone(tsk) || Base.throwto(tsk, InterruptException()) end try fetch(tsk) catch _; if !process_exited(omc.zmqSession.omcprocess) @warn "omc process did not respond to send expression \"quit()\". Killing the process" kill(omc.zmqSession.omcprocess) end end # Wait one second for process to exit, kill otherwise if !process_exited(omc.zmqSession.omcprocess) Timer(1) do timer if !process_exited(omc.zmqSession.omcprocess) @warn "omc process didn't stop after evaluating expression \"quit()\". Killing the process" kill(omc.zmqSession.omcprocess) end end end return end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
2900
module Parser # Proposed for Julia 1.5.x #if isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol("@optlevel")) # @eval Base.Experimental.@optlevel 1 #end struct Identifier id::String end struct Record end struct ParseError <: Exception errmsg::AbstractString end struct LexerError <: Exception errmsg::AbstractString end include("memory.jl") include("lexer.jl") show(io::IO, exc::ParseError) = print(io, string("Parse error: ",exc.errmsg)) function parseOM(t::Union{Int,Float64,String,Bool}, tokens) return t end function checkToken(sym::Symbol, tok) if tok != sym throw(ParseError("Expected token of type $sym, got $(tok)")) end tok end function checkToken(t, tok) if typeof(tok) != t throw(ParseError("Expected token of type $t, got $(typeof(tok))")) end tok end function parseSequence(tokens, last) res = [] tok = popfirst!(tokens) if tok == last return res end push!(res, parseOM(tok, tokens)) tok = popfirst!(tokens) while tok == Symbol(",") push!(res, parseOM(popfirst!(tokens), tokens)) tok = popfirst!(tokens) end checkToken(last, tok) return collect(tuple(res...)) end function parseOM(t::Symbol, tokens) if t == Symbol("(") res = tuple(parseSequence(tokens, Symbol(")"))...) elseif t == Symbol("{") res = parseSequence(tokens, Symbol("}")) end end function parseOM(t::Identifier, tokens) if t.id == "NONE" checkToken(Symbol("("), popfirst!(tokens)) checkToken(Symbol(")"), popfirst!(tokens)) return nothing elseif t.id == "SOME" checkToken(Symbol("("), popfirst!(tokens)) res = parseOM(popfirst!(tokens), tokens) checkToken(Symbol(")"), popfirst!(tokens)) return res else return Symbol(t.id) end end function parseOM(t::Record, tokens) res = Tuple{String,Any}[] checkToken(Identifier, popfirst!(tokens)) tok = popfirst!(tokens) if tok != :end id = checkToken(Identifier, tok) checkToken(Symbol("="), popfirst!(tokens)) val = parseOM(popfirst!(tokens), tokens) push!(res, (id.id, val)) tok = popfirst!(tokens) while tok == Symbol(",") id = checkToken(Identifier, popfirst!(tokens)) checkToken(Symbol("="), popfirst!(tokens)) val = parseOM(popfirst!(tokens), tokens) push!(res, (id.id, val)) tok = popfirst!(tokens) end end checkToken(:end, tok) checkToken(Identifier, popfirst!(tokens)) checkToken(Symbol(";"), popfirst!(tokens)) # Fixes the type of the dictionary if isempty(res) return Dict(res) end return Dict(collect(Base.tuple(res...))) end function parseOM(tokens::AbstractArray{Any,1}) if length(tokens)==0 return nothing end t = popfirst!(tokens) res = parseOM(t, tokens) if !isempty(tokens) throw(ParseError("Expected EOF, got output $tokens")) end res end function parseOM(str::String) parseOM(tokenize(str)) end end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
2891
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# """ sendExpression(omc, expr; parsed=true) Send API call to OpenModelica ZMQ server. See [OpenModelica User's Guide Scripting API](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html) for a complete list of all functions. !!! note Some characters in argument `expr` need to be escaped. E.g. `"` becomes `\\"`. For example scripting API call ```modelica loadFile("/path/to/M.mo") ``` will translate to ```julia sendExpression(omc, "loadFile(\\"/path/to/M.mo\\")") ``` !!! warn On Windows path separation symbol `\\` needs to be escaped `\\\\` or replaced to Unix style path `/` to prevent warnings. ```modelica loadFile("C:\\\\path\\\\to\\\\M.mo") ``` translate to ```julia sendExpression(omc, "loadFile(\\"C:\\\\\\\\path\\\\\\\\to\\\\\\\\M.mo\\")") # Windows sendExpression(omc, "loadFile(\\"/c/path/to/M.mo\\")") # Windows ``` ## Example ```julia using OMJulia omc = OMJulia.OMCSession() OMJulia.sendExpression(omc, "getVersion()") ``` """ function sendExpression(omc::OMCSession, expr::String; parsed=true) if !process_running(omc.zmqSession.omcprocess) return error("Process Exited, No connection with OMC. Create a new instance of OMCSession") end @debug "sending expression: $(expr)" ZMQ.Sockets.send(omc.zmqSession.socket, expr) @debug "Receiving message from ZMQ socket" message = ZMQ.Sockets.recv(omc.zmqSession.socket) @debug "Recieved message" if parsed return Parser.parseOM(unsafe_string(message)) else return unsafe_string(message) end end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
4302
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# using Test using CSV using DataFrames import OMJulia @testset "API" begin workdir = abspath(joinpath(@__DIR__, "test-API")) rm(workdir, recursive=true, force=true) mkpath(workdir) if Sys.iswindows() workdir = replace(workdir, "\\" => "/") end omc = OMJulia.OMCSession() # Install packages @test OMJulia.API.updatePackageIndex(omc) versions = OMJulia.API.getAvailablePackageVersions(omc, "Modelica", version="3.0.0+maint.om") @test "3.0.0+maint.om" in versions @test OMJulia.API.upgradeInstalledPackages(omc) @test OMJulia.API.installPackage(omc, "Modelica", version = "") # Load file @test OMJulia.API.loadFile(omc, joinpath(@__DIR__, "../docs/testmodels/BouncingBall.mo")) # Enter non-existing directory @test_throws OMJulia.API.ScriptingError throw(OMJulia.API.ScriptingError(msg = "Test error message.")) @test_throws OMJulia.API.ScriptingError throw(OMJulia.API.ScriptingError(omc, msg = "Test error message.")) @test_throws OMJulia.API.ScriptingError OMJulia.API.cd(omc, "this/is/not/a/valid/directory/I/hope/otherwise/our/test/does/some/wild/stuff") dir = OMJulia.API.cd(omc, workdir) result = OMJulia.API.buildModel(omc, "BouncingBall") @test result[2] == "BouncingBall_init.xml" resultfile = joinpath(workdir, "BouncingBall_res.mat") # Remove simulation artifacts from previous buildModel if VERSION > v"1.4" foreach(rm, readdir(workdir, join=true)) else foreach(rm, joinpath.(workdir, readdir(workdir))) end OMJulia.API.simulate(omc, "BouncingBall") @test isfile(resultfile) vars = OMJulia.API.readSimulationResultVars(omc, resultfile) @test var = "h" in vars simres = OMJulia.API.readSimulationResult(omc, resultfile, ["time", "h", "v"]) @test simres[2][1] == 1.0 df = DataFrame(:time => simres[1], :h => simres[2], :v => simres[3]) expectedFile = joinpath(workdir, "BouncingBall_ref.csv") wrongExpectedFile = joinpath(workdir, "BouncingBall_wrong.csv") CSV.write(expectedFile, df) df2 = copy(df) df2[:,2] .= df2[:,2] .* 0.01 CSV.write(wrongExpectedFile, df2) @test (true, String[]) == OMJulia.API.diffSimulationResults(omc, resultfile, expectedFile, "diff"; vars=String[]) @test (true, String[]) == OMJulia.API.diffSimulationResults(omc, resultfile, expectedFile, "diff"; vars=["h", "v"]) @test (false, ["h"]) == OMJulia.API.diffSimulationResults(omc, resultfile, wrongExpectedFile, "diff"; vars=["h", "v"]) fmu = joinpath(workdir, "BouncingBall.fmu") OMJulia.API.buildModelFMU(omc, "BouncingBall") @test isfile(fmu) @test OMJulia.API.setCommandLineOptions(omc, "--generateSymbolicLinearization") @test OMJulia.API.loadFile(omc, joinpath(@__DIR__, "../docs/testmodels/ModSeborgCSTRorg.mo")) @test [:BouncingBall, :ModSeborgCSTRorg] == sort(OMJulia.API.getClassNames(omc)) flatModelicaCode = OMJulia.API.instantiateModel(omc, "BouncingBall") @test occursin("class BouncingBall", flatModelicaCode) OMJulia.quit(omc) end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
1876
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# using Test import OMJulia @testset "ModelicaSystem" begin workdir = abspath(joinpath(@__DIR__, "test-modelicasystem")) rm(workdir, recursive=true, force=true) mkpath(workdir) resultfile = joinpath(workdir, "ModSeborgCSTRorg_res.mat") mod = OMJulia.OMCSession() OMJulia.ModelicaSystem(mod, joinpath(@__DIR__, "..", "docs", "testmodels", "ModSeborgCSTRorg.mo"), "ModSeborgCSTRorg") OMJulia.simulate(mod, resultfile = resultfile) @test isfile(resultfile) fmu = OMJulia.convertMo2FMU(mod) @test isfile(fmu) OMJulia.quit(mod) end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
3948
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# using Test import OMJulia @testset "OpenModelica" begin @testset "OMCSession" begin workdir = abspath(joinpath(@__DIR__, "test-session")) rm(workdir, recursive=true, force=true) mkpath(workdir) if Sys.iswindows() workdir = replace(workdir, "\\" => "\\\\") end oldwd = pwd() try omc = OMJulia.OMCSession() OMJulia.sendExpression(omc, "cd(\"$workdir\")") version = OMJulia.sendExpression(omc, "getVersion()") @test (startswith(version, "v1.") || startswith(version, "OpenModelica v1.") || startswith(version, "OpenModelica 1.")) a = OMJulia.sendExpression(omc, "model a end a;") @test a == [:a] classNames = OMJulia.sendExpression(omc, "getClassNames()") @test classNames == [:a] @test true == OMJulia.sendExpression(omc, "loadModel(Modelica)") res = OMJulia.sendExpression(omc, "simulate(Modelica.Electrical.Analog.Examples.CauerLowPassAnalog)") @test isfile(res["resultFile"]) @test occursin("The simulation finished successfully.", res["messages"]) @test 3 == OMJulia.sendExpression(omc, "1+2") OMJulia.quit(omc) finally cd(oldwd) end end @testset "Multiple sessions" begin workdir1 = abspath(joinpath(@__DIR__, "test-omc1")) workdir2 = abspath(joinpath(@__DIR__, "test-omc2")) rm(workdir1, recursive=true, force=true) rm(workdir2, recursive=true, force=true) mkpath(workdir1) mkpath(workdir2) if Sys.iswindows() workdir1 = replace(workdir1, "\\" => "\\\\") workdir2 = replace(workdir2, "\\" => "\\\\") end oldwd = pwd() try omc1 = OMJulia.OMCSession() omc2 = OMJulia.OMCSession() OMJulia.sendExpression(omc1, "cd(\"$workdir1\")") @test true == OMJulia.sendExpression(omc1, "loadModel(Modelica)") res = OMJulia.sendExpression(omc1, "simulate(Modelica.Blocks.Examples.PID_Controller)") @test isfile(joinpath(@__DIR__, "test-omc1", "Modelica.Blocks.Examples.PID_Controller_res.mat")) OMJulia.sendExpression(omc2, "cd(\"$workdir2\")") @test true == OMJulia.sendExpression(omc2, "loadModel(Modelica)") res = OMJulia.sendExpression(omc2, "simulate(Modelica.Blocks.Examples.PID_Controller)") @test isfile(joinpath(@__DIR__, "test-omc2", "Modelica.Blocks.Examples.PID_Controller_res.mat")) OMJulia.quit(omc1) OMJulia.quit(omc2) finally cd(oldwd) end end end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
2333
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# using OMJulia function check(string, expected_value, expected_type) value = OMJulia.Parser.parseOM(string) return expected_value == value && expected_type == typeof(value) end @testset "Parser" begin @test check("123.0", 123.0, Float64) @test check("123", 123, Int) @test check("1.", 1.0, Float64) @test check(".2", 0.2, Float64) @test check("1e3", 1e3, Float64) @test check("1e+2", 1e+2, Float64) @test check("tRuE", true, Bool) @test check("false", false, Bool) @test check("\"ab\\nc\"", "ab\nc", String) @test check("{\"abc\"}", ["abc"], Array{String,1}) @test check("{1}", [1], Array{Int,1}) @test check("{1,2,3}", [1,2,3], Array{Int,1}) @test check("(1,2,3)", (1,2,3), Tuple{Int,Int,Int}) @test check("NONE()", nothing, Nothing) @test check("SOME(1)", 1, Int) @test check("abc_2", :abc_2, Symbol) @test check("record ABC end ABC;", Dict(), Dict{String,Any}) @test check("record ABC a = 1, 'b' = 2,\n c = 3\nend ABC;", Dict("a" => 1, "'b'" => 2, "c" => 3), Dict{String,Int}) @test check("", nothing, Nothing) end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
1545
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# using SafeTestsets using Test @testset "OMJulia" begin @safetestset "Parsing" begin include("parserTest.jl") end @safetestset "OMCSession" begin include("omcTest.jl") end @safetestset "ModelicaSystem" begin include("modelicaSystemTest.jl") end @safetestset "API" begin include("apiTest.jl") end end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
code
1825
#= This file is part of OpenModelica. Copyright (c) 1998-2023, Open Source Modelica Consortium (OSMC), c/o Linköpings universitet, Department of Computer and Information Science, SE-58183 Linköping, Sweden. All rights reserved. THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. =# using Test import OMJulia @testset "testFMIExport" begin workdir = abspath(joinpath(@__DIR__, "test_fmi_export")) rm(workdir, recursive=true, force=true) mkpath(workdir) mod = OMJulia.OMCSession() OMJulia.ModelicaSystem(mod, modelName="Modelica.Electrical.Analog.Examples.CauerLowPassAnalog", library="Modelica") fmu1 = OMJulia.convertMo2FMU(mod) @test isfile(fmu1) OMJulia.ModelicaSystem(mod, modelName="Modelica.Fluid.Examples.DrumBoiler.DrumBoiler", library="Modelica") fmu2 = OMJulia.convertMo2FMU(mod) @test isfile(fmu2) OMJulia.quit(mod) end
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
docs
3707
# OMJulia.jl *Julia scripting [OpenModelica](https://openmodelica.org/) interface.* [![][docs-dev-img]][docs-dev-url] [![][GHA-test-img]][GHA-test-url] [![][GHA-regressions-img]][GHA-regressions-url] ## Requirements - [OpenModelica](https://www.openmodelica.org/) - [Julia](https://julialang.org/) ## Installing OMJulia Make sure [OpenModelica](https://openmodelica.org/) is installed. Install OMJulia.jl with: ```julia julia> import Pkg; Pkg.add("OMJulia") ``` ## Usage ```julia julia> using OMJulia julia> omc = OMJulia.OMCSession() julia> sendExpression(omc, "getVersion()") "OpenModelica v1.21.0-dev-185-g9d983b8e35 (64-bit)" julia> sendExpression(omc, "model a end a;") 1-element Array{Symbol,1}: :a julia> sendExpression(omc, "getClassNames()") 1-element Array{Symbol,1}: :a julia> sendExpression(omc, "loadModel(Modelica)") true julia> sendExpression(omc, "simulate(Modelica.Electrical.Analog.Examples.CauerLowPassAnalog)") Dict{String,Any} with 10 entries: "timeCompile" => 9.97018 "simulationOptions" => "startTime = 0.0, stopTime = 60.0, numberOfIntervals = 500, tolerance = 1e-006, method = 'dassl', fileNamePrefix = 'Modelica.Electrical.Analog.Examples.CauerLowPassAnalog', options = '', outputFormat = 'mat', variableFilter = '.*', cflags = '', simflags = ''" "messages" => "LOG_SUCCESS | info | The initialization finished successfully without homotopy method.\nLOG_SUCCESS | info | The simulation finished successfully.\n" "timeFrontend" => 0.45081 "timeTotal" => 11.04 "timeTemplates" => 0.104619 "timeSimulation" => 0.29745 "resultFile" => "PATH/TO/Modelica.Electrical.Analog.Examples.CauerLowPassAnalog_res.mat" "timeSimCode" => 0.0409317 "timeBackend" => 0.140713 julia> OMJulia.quit(omc) "quit requested, shutting server down\n" ``` ## Bug Reports - Submit OMJulia.jl bugs in this repositories [Issues](../../issues) section. - Submit OpenModelica related bugs through the [OpenModelica GitHub issues](https://github.com/OpenModelica/OpenModelica/issues/new). - [Pull requests](../../pulls) are welcome ❤️ ## License THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE BSD NEW LICENSE OR THE GPL VERSION 3 LICENSE OR THE OSMC PUBLIC LICENSE (OSMC-PL) VERSION 1.2. ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THE OSMC PUBLIC LICENSE OR THE GPL VERSION 3, ACCORDING TO RECIPIENTS CHOICE. The OpenModelica software and the OSMC (Open Source Modelica Consortium) Public License (OSMC-PL) are obtained from OSMC, either from the above address, from the URLs: http://www.openmodelica.org or http://www.ida.liu.se/projects/OpenModelica, and in the OpenModelica distribution. GNU version 3 is obtained from: http://www.gnu.org/copyleft/gpl.html. The New BSD License is obtained from: http://www.opensource.org/licenses/BSD-3-Clause. This program is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, EXCEPT AS EXPRESSLY SET FORTH IN THE BY RECIPIENT SELECTED SUBSIDIARY LICENSE CONDITIONS OF OSMC-PL. [docs-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [docs-dev-url]: https://OpenModelica.github.io/OMJulia.jl/dev/ [GHA-test-img]: https://github.com/OpenModelica/OMJulia.jl/actions/workflows/Test.yml/badge.svg?branch=master [GHA-test-url]: https://github.com/OpenModelica/OMJulia.jl/actions/workflows/Test.yml [GHA-regressions-img]: https://github.com/OpenModelica/OMJulia.jl/actions/workflows/regressionTests.yml/badge.svg?branch=master [GHA-regressions-url]: https://github.com/OpenModelica/OMJulia.jl/actions/workflows/regressionTests.yml
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
docs
444
# Documentation We use Documenter.jl to build the OMJulia documentation that is linked from the OpenModelica User's Guide. ## Build and host locally Make sure you developed OMJulia.jl, so that Documenter.jl is using the correct version to build. To run Documenter.jl along with LiveServer to render the docs and track any modifications run: ```julia using Pkg; Pkg.activate("docs/"); Pkg.resolve() using OMJulia, LiveServer servedocs() ```
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
docs
899
# OMJulia.API Module `OMJulia.API` aims to provide a Julia interface to the OpenModelica scripting API. In contrast to sending the scripting api calls directly via [`sendExpression`](@ref) this API has a Julia-like interface and some level of error handling implemented. This means errors will throw Julia Exception [`OMJulia.API.ScriptingError`](@ref) instead of only printing to stdout. !!! warn Not all `OMJulia.API` functions are tested and some functions could have slightly different default values compared to the OpenModelica scripting API. Instead of escaping strings yourself the API interface handles this for you: ```julia sendExpression(omc, "loadFile(\"$(bouncingBallFile)\")") ``` becomes ```julia API.loadFile(omc, bouncingBallFile) ``` ## Functions ```@autodocs Modules = [OMJulia.API] Order = [:function, :type] Filter = t -> t != OMJulia.API.modelicaString ```
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
docs
1833
# OMJulia.jl **Julia scripting OpenModelica interface.** ## Overview OMJulia - the OpenModelica Julia API is a free, open source, highly portable Julia based interactive session handler for Julia scripting of OpenModelica API functionality. It provides the modeler with components for creating a complete Julia-Modelica modeling, compilation and simulation environment based on the latest OpenModelica implementation and Modelica library standard available. OMJulia is structured to combine both the solving strategy and model building. Thus, domain experts (people writing the models) and computational engineers (people writing the solver code) can work on one unified tool that is industrially viable for optimization of Modelica models, while offering a flexible platform for algorithm development and research. OMJulia is not a standalone package, it depends upon the OpenModelica installation. OMJulia is implemented in Julia and depends on ZeroMQ - high performance asynchronous messaging library and it supports the Modelica Standard Library version 4.0 that is included with OpenModelica. ## Installation Make sure [OpenModelica](https://openmodelica.org/) is installed. Install OMJulia.jl with: ```julia julia> import Pkg; Pkg.add("OMJulia") ``` ## Features of OMJulia The OMJulia package contains the following features: - Interactive session handling, parsing, interpretation of commands and Modelica expressions for evaluation, simulation, plotting, etc. - Connect with the OpenModelica compiler through zmq sockets - Able to interact with the OpenModelica compiler through the available API - Easy access to the Modelica Standard library. - All the API calls are communicated with the help of the sendExpression method implemented in a Julia module - The results are returned as strings
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
docs
6434
# Advanced API A Julia style scripting API that handles low level API calls. ## ModelicaSystem ```@docs ModelicaSystem ``` ```@docs OMJulia.OMCSession OMJulia.quit ``` ### Example Let us see the usage of [`ModelicaSystem`](@ref) with the help of Modelica model `ModSeborgCSTRorg` ```modelica model ModSeborgCSTRorg // Model of original Seborg CSTR in ode form // author: Bernt Lie, University of Southeast Norway,November 7, 2017 // Parameters parameter Real V = 100 "Reactor volume, L"; parameter Real rho = 1e3 "Liquid density, g/L"; parameter Real a = 1 "Stoichiometric constant, -"; parameter Real EdR = 8750 "Activation temperature, K"; parameter Real k0 = exp(EdR/350) "Pre-exponential factor, 1/min"; parameter Real cph = 0.239 "Specific heat capacity of mixture, J.g-1.K-1"; parameter Real DrHt = -5e4 "Molar enthalpy of reaction, J/mol"; parameter Real UA = 5e4 "Heat transfer parameter, J/(min.K)"; // Initial state parameters parameter Real cA0 = 0.5 "Initial concentration of A, mol/L"; parameter Real T0 = 350 "Initial temperature, K"; // Declaring variables // -- states Real cA(start = cA0, fixed = true) "Initializing concentration of A in reactor, mol/L"; Real T(start = T0, fixed = true) "Initializing temperature in reactor, K"; // -- auxiliary variables Real r "Rate of reaction, mol/(L.s)"; Real k "Reaction 'constant', ..."; Real Qd "Heat flow rate, J/min"; // -- input variables input Real Vdi "Volumetric flow rate through reactor, L/min"; input Real cAi "Influent molar concentration of A, mol/L"; input Real Ti "Influent temperature, K"; input Real Tc "Cooling temperature', K"; // -- output variables output Real y_T "Reactor temperature, K"; // Equations constituting the model equation // Differential equations der(cA) = Vdi*(cAi-cA)/V- a*r; der(T) = Vdi*(Ti-T)/V + (-DrHt)*r/(rho*cph) + Qd/(rho*V*cph); // Algebraic equations r = k*cA^a; k = k0*exp(-EdR/T); Qd = UA*(Tc-T); // Outputs y_T = T; end ModSeborgCSTRorg ``` ```@repl ModSeborgCSTRorg-example using OMJulia mod = OMJulia.OMCSession() omcWorkDir = mkpath(joinpath("docs", "omc-temp")) # hide mkpath(omcWorkDir) # hide sendExpression(mod, "cd(\"$(omcWorkDir)\")") # hide ModelicaSystem(mod, joinpath("docs", "testmodels", "ModSeborgCSTRorg.mo"), "ModSeborgCSTRorg") ``` ## WorkDirectory For each [`OMJulia.OMCSession`](@ref) session a temporary work directory is created and the results are published in that working directory. In order to get the work directory use [`getWorkDirectory`](@ref). ```@docs getWorkDirectory ``` ```@repl ModSeborgCSTRorg-example getWorkDirectory(mod) ``` ## Build Model ```@docs buildModel ``` In case the Modelica model needs to be updated or additional simulation flags needs to be set using [`sendExpression`](@ref) The [`buildModel`](@ref) API can be used after [`ModelicaSystem`](@ref). ``` buildModel(omc) buildModel(omc, variableFilter="a|T") ``` ## Get Methods ```@docs getQuantities showQuantities getContinuous getInputs getOutputs getParameters getSimulationOptions getSolutions ``` ### Examples ```@repl ModSeborgCSTRorg-example getQuantities(mod) getQuantities(mod, "T") getQuantities(mod, ["T","cA"]) showQuantities(mod) ``` ```@repl ModSeborgCSTRorg-example getContinuous(mod) getContinuous(mod, ["Qd","Tc"]) ``` ```@repl ModSeborgCSTRorg-example getInputs(mod) getOutputs(mod) ``` ```@repl ModSeborgCSTRorg-example getParameters(mod) getParameters(mod, ["a","V"]) ``` ```@repl ModSeborgCSTRorg-example getSimulationOptions(mod) getSimulationOptions(mod, ["stepSize","tolerance"]) ``` ### Reading Simulation Results To read the simulation results, we need to simulate the model first and use the getSolution() API to read the results ```@repl ModSeborgCSTRorg-example simulate(mod) ``` The getSolution method can be used in two different ways. 1. using default result filename 2. use the result filenames provided by user This provides a way to compare simulation results and perform regression testing ```@repl ModSeborgCSTRorg-example getSolutions(mod) getSolutions(mod, ["time","a"]) ``` ### Examples of using resultFile provided by user location ``` getSolutions(mod, resultfile="C:/BouncingBal/tmpbouncingBall.mat") //returns list of simulation variables for which results are available , the resulfile location is provided by user getSolutions(mod, ["time","h"], resultfile="C:/BouncingBal/tmpbouncingBall.mat") // return list of array ``` ## Set Methods ```@docs setInputs setParameters setSimulationOptions ``` ### Examples ```@repl ModSeborgCSTRorg-example setInputs(mod, "cAi=100") setInputs(mod, ["cAi=100","Ti=200","Vdi=300","Tc=250"]) ``` ```@repl ModSeborgCSTRorg-example setParameters(mod, "a=3") setParameters(mod, ["a=4","V=200"]) ``` ```@repl ModSeborgCSTRorg-example setSimulationOptions(mod, ["stopTime=2.0", "tolerance=1e-08"]) ``` ## Advanced Simulation ```@docs simulate ``` An example of how to do advanced simulation to set parameter values using set methods and finally simulate the "ModSeborgCSTRorg.mo" model is given below . ```@repl ModSeborgCSTRorg-example getParameters(mod) setParameters(mod, "a=3.0") ``` To check whether new values are updated to model , we can again query the getParameters(). ```@repl ModSeborgCSTRorg-example getParameters(mod) ``` Similary we can also use setInputs() to set a value for the inputs during various time interval can also be done using the following. ```@repl ModSeborgCSTRorg-example setInputs(mod, "cAi=100") ``` And finally we simulate the model ```@repl ModSeborgCSTRorg-example simulate(mod) ``` ## Linearization ```@docs linearize getLinearizationOptions setLinearizationOptions getLinearInputs getLinearOutputs getLinearStates ``` ### Examples ```@repl ModSeborgCSTRorg-example getLinearizationOptions(mod) getLinearizationOptions(mod, ["startTime","stopTime"]) ``` ```@repl ModSeborgCSTRorg-example setLinearizationOptions(mod,["stopTime=2.0","tolerance=1e-06"]) ``` ```@repl ModSeborgCSTRorg-example res = linearize(mod) ``` ```@repl ModSeborgCSTRorg-example getLinearInputs(mod) getLinearOutputs(mod) getLinearStates(mod) ``` ## Sensitivity Analysis ```@docs sensitivity ``` ### Examples ```@repl ModSeborgCSTRorg-example (Sn, Sa) = sensitivity(mod, ["UA","EdR"], ["T","cA"], [1e-2,1e-4]) OMJulia.quit(mod) # hide ```
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
docs
5081
# Quickstart There are three ways to interact with OpenModelica: - [`ModelicaSystem`](@ref modelicasystem): A Julia style scripting API that handles low level API calls. - [`OMJulia.API`](@ref omjulia-api): A Julia style scripting API that handles low level [`sendExpression`](@ref) calls and has some degree of error handling. - [Scripting API with sendExpression](@ref scripting-api-with-sendExpression): Send expressions to the low level OpenModelica scripting API. The following examples demonstrate how to simulate Modelica model `BouncingBall` in both ways. ```modelica model BouncingBall parameter Real e=0.7 "coefficient of restitution"; parameter Real g=9.81 "gravity acceleration"; Real h(fixed=true, start=1) "height of ball"; Real v(fixed=true) "velocity of ball"; Boolean flying(fixed=true, start=true) "true, if ball is flying"; Boolean impact; Real v_new(fixed=true); Integer foo; equation impact = h <= 0.0; foo = if impact then 1 else 2; der(v) = if flying then -g else 0; der(h) = v; when {h <= 0.0 and v <= 0.0,impact} then v_new = if edge(impact) then -e*pre(v) else 0; flying = v_new > 0; reinit(v, v_new); end when; end BouncingBall; ``` !!! info The BouncingBall.mo file can be found in your OpenModelica installation directory in `<OpenModelcia>/share/doc/omc/testmodels/BouncingBall.mo`. ## [ModelicaSystem](@id modelicasystem) Start a new [`OMJulia.OMCSession`](@ref) and create a new [`ModelicaSystem`](@ref) to build and simulate the `BouncingBall` model. Afterwards the result can be plotted in Julia. ```@repl ModelicaSystem-example using OMJulia using CSV, DataFrames, PlotlyJS using PlotlyDocumenter # hide mod = OMJulia.OMCSession(); installDir = sendExpression(mod, "getInstallationDirectoryPath()") bouncingBallFile = joinpath(installDir, "share", "doc", "omc", "testmodels", "BouncingBall.mo") ModelicaSystem(mod, bouncingBallFile, "BouncingBall") simulate(mod, resultfile = "BouncingBall_ref.csv", simflags = "-override=outputFormat=csv,stopTime=3") resultfile = joinpath(getWorkDirectory(mod), "BouncingBall_ref.csv") df = DataFrame(CSV.File(resultfile)); plt = plot(df, x=:time, y=:h, mode="lines", Layout(title="Bouncing Ball", height = 700)) OMJulia.quit(mod) ``` ```@example ModelicaSystem-example PlotlyDocumenter.to_documenter(plt) # hide ``` ## [OMJulia.API](@id omjulia-api) ## Example Start a new [`OMJulia.OMCSession`](@ref) and call [scripting API](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html) directly using the [`OMJulia.API`](@ref) module. ```@repl API-example using OMJulia using OMJulia.API: API using CSV, DataFrames, PlotlyJS using PlotlyDocumenter # hide omc = OMJulia.OMCSession(); omcWorkDir = mkpath(joinpath("docs", "omc-temp")) # hide mkpath(omcWorkDir) # hide API.cd(omcWorkDir) # hide installDir = API.getInstallationDirectoryPath(omc) bouncingBallFile = joinpath(installDir, "share", "doc", "omc", "testmodels", "BouncingBall.mo") bouncingBallFile = abspath(bouncingBallFile) # hide API.loadFile(omc, bouncingBallFile) res = API.simulate(omc, "BouncingBall"; stopTime=3.0, outputFormat = "csv") resultfile = res["resultFile"] df = DataFrame(CSV.File(resultfile)); plt = plot(df, x=:time, y=:h, mode="lines", Layout(title="Bouncing Ball", height = 700)) OMJulia.quit(omc) ``` ```@example API-example PlotlyDocumenter.to_documenter(plt) # hide ``` ## [Scripting API with sendExpression](@id scripting-api-with-sendExpression) Start a new [`OMJulia.OMCSession`](@ref) and send [scripting API](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html) expressions to the omc session with [`sendExpression()`](@ref). !!! warn All special characters inside a string argument for an API function need to be escaped when passing to `sendExpression`. E.g. MOS command ```modelica loadFile("/some/path/to/BouncingBall.mo"); ``` becomes Julia code ```julia sendExpression(omc, "loadFile(\"/some/path/to/BouncingBall.mo\")") ``` !!! info On Windows path separation symbol `\` needs to be escaped `\\` or replaced to Unix style path `/` to prevent warnings. ```@repl ModelicaSystem-example using OMJulia omc = OMJulia.OMCSession(); omcWorkDir = mkpath(joinpath("docs", "omc-temp")) # hide mkpath(omcWorkDir) # hide sendExpression(omc, "cd(\"$(omcWorkDir)\")") # hide installDir = sendExpression(omc, "getInstallationDirectoryPath()") bouncingBallFile = joinpath(installDir, "share", "doc", "omc", "testmodels", "BouncingBall.mo") bouncingBallFile = abspath(bouncingBallFile) # hide if Sys.iswindows() bouncingBallFile = replace(bouncingBallFile, "\\" => "/") end sendExpression(omc, "loadFile(\"$(bouncingBallFile)\")") sendExpression(omc, "simulate(BouncingBall)") OMJulia.quit(omc) ```
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "BSD-3-Clause" ]
0.3.2
5f2b4eb7fed3c1ac9108c72996bd1ac47da1c940
docs
393
# sendExpression Start a new `OMCSession` and send [scripting API](https://openmodelica.org/doc/OpenModelicaUsersGuide/latest/scripting_api.html) expressions to the omc session with `sendExpression()`. ```@docs sendExpression ``` ## Examples ```@repl using OMJulia # hide omc = OMJulia.OMCSession() # hide version = OMJulia.sendExpression(omc, "getVersion()") OMJulia.quit(omc) ```
OMJulia
https://github.com/OpenModelica/OMJulia.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
1535
# File : bvh_build.jl # License: MIT # Author : Andrei Leonard Nicusan <a.l.nicusan@bham.ac.uk> # Date : 15.12.2022 using ImplicitBVH using ImplicitBVH: BSphere, BBox using MeshIO using FileIO using BenchmarkTools using Profile using PProf # Types used const LeafType = BSphere{Float32} const NodeType = BBox{Float32} const MortonType = UInt32 # Load mesh and compute bounding spheres for each triangle. Can download mesh from: # https://github.com/alecjacobson/common-3d-test-models/blob/master/data/xyzrgb_dragon.obj mesh = load(joinpath(@__DIR__, "xyzrgb_dragon.obj")) @show size(mesh) bounding_spheres = [LeafType(tri) for tri in mesh] # Pre-compile BVH build bvh = BVH(bounding_spheres, NodeType, MortonType) # Benchmark BVH creation including Morton encoding println("BVH creation including Morton encoding:") display(@benchmark(BVH(bounding_spheres, NodeType, MortonType))) # Collect a pprof profile of the complete build Profile.clear() @profile BVH(bounding_spheres, NodeType, MortonType) # Export pprof profile and open interactive profiling web interface. pprof(; out="bvh_build.pb.gz") # Test for some coding mistakes # using Test # Test.detect_unbound_args(ImplicitBVH, recursive = true) # Test.detect_ambiguities(ImplicitBVH, recursive = true) # More complete report on type stabilities # using JET # JET.@report_opt BVH(bounding_spheres, NodeType, MortonType) # using Profile # BVH(bounding_spheres, NodeType, MortonType) # Profile.clear_malloc_data() # BVH(bounding_spheres, NodeType, MortonType)
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
1844
# File : bvh_contact.jl # License: MIT # Author : Andrei Leonard Nicusan <a.l.nicusan@bham.ac.uk> # Date : 15.12.2022 using ImplicitBVH using ImplicitBVH: BSphere, BBox using MeshIO using FileIO using BenchmarkTools using Profile using PProf # Types used const LeafType = BSphere{Float32} const NodeType = BBox{Float32} const MortonType = UInt32 # Load mesh and compute bounding spheres for each triangle. Can download mesh from: # https://github.com/alecjacobson/common-3d-test-models/blob/master/data/xyzrgb_dragon.obj mesh = load(joinpath(@__DIR__, "xyzrgb_dragon.obj")) @show size(mesh) Threads.nthreads() bounding_spheres = [LeafType(tri) for tri in mesh] # Pre-compile BVH traversal bvh = BVH(bounding_spheres, NodeType, MortonType) @show traversal = traverse(bvh) # Print algorithmic efficiency eff = traversal.num_checks / (length(bounding_spheres) * length(bounding_spheres) / 2) println("Did $eff of the total checks needed for brute-force contact detection") # Benchmark BVH traversal anew println("BVH traversal with dynamic buffer resizing:") display(@benchmark(traverse(bvh))) # Benchmark BVH creation reusing previous cache println("BVH traversal without dynamic buffer resizing:") display(@benchmark(traverse(bvh, bvh.tree.levels ÷ 2, traversal))) # Collect a pprof profile Profile.clear() @profile traverse(bvh) # Export pprof profile and open interactive profiling web interface. pprof(; out="bvh_contact.pb.gz") # Test for some coding mistakes # using Test # Test.detect_unbound_args(ImplicitBVH, recursive = true) # Test.detect_ambiguities(ImplicitBVH, recursive = true) # More complete report on type stabilities # using JET # JET.@report_opt traverse(bvh) # using Profile # traverse(bvh, bvh.tree.levels ÷ 2, traversal) # Profile.clear_malloc_data() # traverse(bvh, bvh.tree.levels ÷ 2, traversal)
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
1654
# File : bvh_build.jl # License: MIT # Author : Andrei Leonard Nicusan <a.l.nicusan@bham.ac.uk> # Date : 15.12.2022 using ImplicitBVH using ImplicitBVH: BSphere, BBox using MeshIO using FileIO using BenchmarkTools using Profile using PProf # Types used const LeafType = BSphere{Float32} const NodeType = BBox{Float32} const MortonType = UInt32 # Load mesh and compute bounding spheres for each triangle. Can download mesh from: # https://github.com/alecjacobson/common-3d-test-models/blob/master/data/xyzrgb_dragon.obj mesh = load(joinpath(@__DIR__, "xyzrgb_dragon.obj")) @show size(mesh) # Example single-threaded user code to compute bounding volumes for each triangle in a mesh function fill_bounding_volumes!(bounding_volumes, mesh) @inbounds for i in axes(bounding_volumes, 1) bounding_volumes[i] = eltype(bounding_volumes)(mesh[i]) end end bounding_spheres = Vector{LeafType}(undef, size(mesh, 1)) display(@benchmark(fill_bounding_volumes!(bounding_spheres, mesh))) # Collect a pprof profile of the complete build Profile.clear() @profile fill_bounding_volumes!(bounding_spheres, mesh) # Export pprof profile and open interactive profiling web interface. pprof(; out="bvh_volumes.pb.gz") # Test for some coding mistakes # using Test # Test.detect_unbound_args(ImplicitBVH, recursive = true) # Test.detect_ambiguities(ImplicitBVH, recursive = true) # More complete report on type stabilities # using JET # JET.@report_opt BVH(bounding_spheres, NodeType, MortonType) # using Profile # fill_bounding_volumes!(bounding_spheres, mesh) # Profile.clear_malloc_data() # fill_bounding_volumes!(bounding_spheres, mesh)
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
1285
# File : morton.jl # License: MIT # Author : Andrei Leonard Nicusan <a.l.nicusan@bham.ac.uk> # Date : 29.06.2023 using ImplicitBVH using ImplicitBVH: BSphere, BBox using MeshIO using FileIO using BenchmarkTools using Profile using PProf # Types used const LeafType = BSphere{Float32} const MortonType = UInt32 # Load mesh and compute bounding spheres for each triangle. Can download mesh from: # https://github.com/alecjacobson/common-3d-test-models/blob/master/data/xyzrgb_dragon.obj mesh = load(joinpath(@__DIR__, "xyzrgb_dragon.obj")) @show size(mesh) Threads.nthreads() bounding_spheres = [LeafType(tri) for tri in mesh] # Pre-compile bounding volume extrema computation ImplicitBVH.bounding_volumes_extrema(bounding_spheres) println("Bounding volume extrema:") display(@benchmark(ImplicitBVH.bounding_volumes_extrema(bounding_spheres))) # Pre-compile morton encoding mortons = ImplicitBVH.morton_encode(bounding_spheres, MortonType) println("Morton encoding:") display(@benchmark(ImplicitBVH.morton_encode(bounding_spheres, MortonType))) # Collect a pprof profile of the complete build Profile.clear() @profile ImplicitBVH.morton_encode(bounding_spheres, MortonType) # Export pprof profile and open interactive profiling web interface. pprof(; out="morton.pb.gz")
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
2172
# File : bvh_contact.jl # License: MIT # Author : Andrei Leonard Nicusan <a.l.nicusan@bham.ac.uk> # Date : 15.12.2022 using ImplicitBVH using ImplicitBVH: BSphere, BBox using MeshIO using FileIO using BenchmarkTools using Profile using PProf using GLMakie # Types used const LeafType = BSphere{Float32} const NodeType = BBox{Float32} const MortonType = UInt32 # Load mesh and compute bounding spheres for each triangle. Can download mesh from: # https://github.com/alecjacobson/common-3d-test-models/blob/master/data/xyzrgb_dragon.obj mesh = load(joinpath(@__DIR__, "stanford-bunny.obj")) bounding_spheres = [LeafType(tri) for tri in mesh] # Pre-compile BVH traversal bvh = BVH(bounding_spheres, NodeType, MortonType) @show traversal = traverse(bvh) function box_lines!(lines, lo, up) # Write lines forming an axis-aligned box from lo to up @assert ndims(lines) == 2 @assert size(lines) == (24, 3) lines[1:24, 1:3] .= [ # Bottom sides lo[1] lo[2] lo[3] up[1] lo[2] lo[3] up[1] up[2] lo[3] lo[1] up[2] lo[3] lo[1] lo[2] lo[3] NaN NaN NaN # Vertical sides lo[1] lo[2] lo[3] lo[1] lo[2] up[3] NaN NaN NaN up[1] lo[2] lo[3] up[1] lo[2] up[3] NaN NaN NaN up[1] up[2] lo[3] up[1] up[2] up[3] NaN NaN NaN lo[1] up[2] lo[3] lo[1] up[2] up[3] NaN NaN NaN # Top sides lo[1] lo[2] up[3] up[1] lo[2] up[3] up[1] up[2] up[3] lo[1] up[2] up[3] lo[1] lo[2] up[3] NaN NaN NaN ] nothing end function boxes_lines(boxes) # Create contiguous matrix of lines representing boxes lines = Matrix{Float64}(undef, 24 * length(boxes), 3) for i in axes(boxes, 1) box_lines!(view(lines, 24 * (i - 1) + 1:24i, 1:3), boxes[i].lo, boxes[i].up) end lines end # Plot a wireframe of the mesh and the bounding boxes above leaf level fig, ax = wireframe( mesh, color = [tri[1][2] for tri in mesh for i in 1:3], colormap=:Spectral, ssao=true, ) lines!(ax, boxes_lines(bvh.nodes), linewidth=0.5) fig
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
54
using PProf PProf.refresh(; file="bvh_volumes.pb.gz")
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
312
using ImplicitBVH using Documenter makedocs( modules = [ImplicitBVH], sitename = "ImplicitBVH.jl", format = Documenter.HTML( # Only create web pretty-URLs on the CI prettyurls = get(ENV, "CI", nothing) == "true", ), ) deploydocs(repo = "github.com/StellaOrg/ImplicitBVH.jl.git")
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
157
# Activate docs environment and use ("develop") local library using Pkg Pkg.activate(@__DIR__) Pkg.develop(path=joinpath(@__DIR__, "..")) include("make.jl")
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
600
# File : ImplicitBVH.jl # License: MIT # Author : Andrei Leonard Nicusan <a.l.nicusan@bham.ac.uk> # Date : 02.06.2022 module ImplicitBVH # Functionality exported by this package by default export BVH, BVHTraversal, traverse, default_start_level export ImplicitTree, memory_index, level_indices, isvirtual # Internal dependencies using LinearAlgebra using DocStringExtensions # Include code from other files include("utils.jl") include("morton.jl") include("implicit_tree.jl") include("bounding_volumes.jl") include("build.jl") include("traverse/traverse.jl") end # module ImplicitBVH
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
10324
""" iscontact(a::BSphere, b::BSphere) iscontact(a::BBox, b::BBox) iscontact(a::BSphere, b::BBox) iscontact(a::BBox, b::BSphere) Check if two bounding volumes are touching or inter-penetrating. """ function iscontact end """ center(b::BSphere) center(b::BBox{T}) where T Get the coordinates of a bounding volume's centre, as a NTuple{3, T}. """ function center end """ $(TYPEDEF) Bounding sphere, highly optimised for computing bounding volumes for triangles and merging into larger bounding volumes. # Methods # Convenience constructors BSphere(x::NTuple{3, T}, r) BSphere{T}(x::AbstractVector, r) where T BSphere(x::AbstractVector, r) # Construct from triangle vertices BSphere{T}(p1, p2, p3) where T BSphere(p1, p2, p3) BSphere{T}(vertices::AbstractMatrix) where T BSphere(vertices::AbstractMatrix) BSphere{T}(triangle) where T BSphere(triangle) # Merging bounding volumes BSphere{T}(a::BSphere, b::BSphere) where T BSphere(a::BSphere{T}, b::BSphere{T}) where T Base.:+(a::BSphere, b::BSphere) """ struct BSphere{T} x::NTuple{3, T} r::T end # Convenience constructors, with and without type parameter BSphere{T}(x::AbstractVector, r) where T = BSphere(NTuple{3, T}(x), T(r)) BSphere(x::AbstractVector, r) = BSphere{eltype(x)}(x, r) # Constructors from triangles function BSphere{T}(p1, p2, p3) where T # Adapted from https://realtimecollisiondetection.net/blog/?p=20 a = (T(p1[1]), T(p1[2]), T(p1[3])) b = (T(p2[1]), T(p2[2]), T(p2[3])) c = (T(p3[1]), T(p3[2]), T(p3[3])) # Unrolled dot(b - a, b - a) abab = (b[1] - a[1]) * (b[1] - a[1]) + (b[2] - a[2]) * (b[2] - a[2]) + (b[3] - a[3]) * (b[3] - a[3]) # Unrolled dot(b - a, c - a) abac = (b[1] - a[1]) * (c[1] - a[1]) + (b[2] - a[2]) * (c[2] - a[2]) + (b[3] - a[3]) * (c[3] - a[3]) # Unrolled dot(c - a, c - a) acac = (c[1] - a[1]) * (c[1] - a[1]) + (c[2] - a[2]) * (c[2] - a[2]) + (c[3] - a[3]) * (c[3] - a[3]) d = T(2.) * (abab * acac - abac * abac) if abs(d) <= eps(T) # a, b, c lie on a line. Find line centre and radius lower = (minimum3(a[1], b[1], c[1]), minimum3(a[2], b[2], c[2]), minimum3(a[3], b[3], c[3])) upper = (maximum3(a[1], b[1], c[1]), maximum3(a[2], b[2], c[2]), maximum3(a[3], b[3], c[3])) centre = (T(0.5) * (lower[1] + upper[1]), T(0.5) * (lower[2] + upper[2]), T(0.5) * (lower[3] + upper[3])) radius = dist3(centre, upper) else s = (abab * acac - acac * abac) / d t = (acac * abab - abab * abac) / d if s <= zero(T) centre = (T(0.5) * (a[1] + c[1]), T(0.5) * (a[2] + c[2]), T(0.5) * (a[3] + c[3])) radius = dist3(centre, a) elseif t <= zero(T) centre = (T(0.5) * (a[1] + b[1]), T(0.5) * (a[2] + b[2]), T(0.5) * (a[3] + b[3])) radius = dist3(centre, a) elseif s + t >= one(T) centre = (T(0.5) * (b[1] + c[1]), T(0.5) * (b[2] + c[2]), T(0.5) * (b[3] + c[3])) radius = dist3(centre, b) else centre = (a[1] + s * (b[1] - a[1]) + t * (c[1] - a[1]), a[2] + s * (b[2] - a[2]) + t * (c[2] - a[2]), a[3] + s * (b[3] - a[3]) + t * (c[3] - a[3])) radius = dist3(centre, a) end end BSphere(centre, radius) end # Convenience constructors, with and without explicit type parameter function BSphere(p1, p2, p3) BSphere{eltype(p1)}(p1, p2, p3) end function BSphere{T}(triangle) where T # Decompose triangle into its 3 vertices. # Works transparently with GeometryBasics.Triangle, Vector{SVector{3, T}}, etc. p1, p2, p3 = triangle BSphere{T}(p1, p2, p3) end function BSphere(triangle) p1, p2, p3 = triangle BSphere{eltype(p1)}(p1, p2, p3) end function BSphere{T}(vertices::AbstractMatrix) where T BSphere{T}(@view(vertices[:, 1]), @view(vertices[:, 2]), @view(vertices[:, 3])) end function BSphere(vertices::AbstractMatrix) BSphere{eltype(vertices)}(@view(vertices[:, 1]), @view(vertices[:, 2]), @view(vertices[:, 3])) end # Overloaded center function center(b::BSphere) = b.x # Merge two bounding spheres function BSphere{T}(a::BSphere, b::BSphere) where T length = dist3(a.x, b.x) # a is enclosed within b if length + a.r <= b.r return BSphere{T}(b.x, b.r) # b is enclosed within a elseif length + b.r <= a.r return BSphere{T}(a.x, a.r) # Bounding spheres are not enclosed else frac = T(0.5) * ((b.r - a.r) / length + T(1)) centre = (a.x[1] + frac * (b.x[1] - a.x[1]), a.x[2] + frac * (b.x[2] - a.x[2]), a.x[3] + frac * (b.x[3] - a.x[3])) radius = T(0.5) * (length + a.r + b.r) return BSphere{T}(centre, radius) end end BSphere(a::BSphere{T}, b::BSphere{T}) where T = BSphere{T}(a, b) Base.:+(a::BSphere, b::BSphere) = BSphere(a, b) # Contact detection function iscontact(a::BSphere, b::BSphere) dist3sq(a.x, b.x) <= (a.r + b.r) * (a.r + b.r) end """ $(TYPEDEF) Axis-aligned bounding box, highly optimised for computing bounding volumes for triangles and merging into larger bounding volumes. Can also be constructed from two spheres to e.g. allow merging [`BSphere`](@ref) leaves into [`BBox`](@ref) nodes. # Methods # Convenience constructors BBox(lo::NTuple{3, T}, up::NTuple{3, T}) where T BBox{T}(lo::AbstractVector, up::AbstractVector) where T BBox(lo::AbstractVector, up::AbstractVector) # Construct from triangle vertices BBox{T}(p1, p2, p3) where T BBox(p1, p2, p3) BBox{T}(vertices::AbstractMatrix) where T BBox(vertices::AbstractMatrix) BBox{T}(triangle) where T BBox(triangle) # Merging bounding boxes BBox{T}(a::BBox, b::BBox) where T BBox(a::BBox{T}, b::BBox{T}) where T Base.:+(a::BBox, b::BBox) # Merging bounding spheres BBox{T}(a::BSphere{T}) where T BBox(a::BSphere{T}) where T BBox{T}(a::BSphere{T}, b::BSphere{T}) where T BBox(a::BSphere{T}, b::BSphere{T}) where T """ struct BBox{T} lo::NTuple{3, T} up::NTuple{3, T} end # Convenience constructors, with and without type parameter function BBox{T}(lo::AbstractVector, up::AbstractVector) where T BBox(NTuple{3, eltype(lo)}(lo), NTuple{3, eltype(up)}(up)) end function BBox(lo::AbstractVector, up::AbstractVector) BBox{eltype(lo)}(lo, up) end # Constructors from triangles function BBox{T}(p1, p2, p3) where T lower = (minimum3(p1[1], p2[1], p3[1]), minimum3(p1[2], p2[2], p3[2]), minimum3(p1[3], p2[3], p3[3])) upper = (maximum3(p1[1], p2[1], p3[1]), maximum3(p1[2], p2[2], p3[2]), maximum3(p1[3], p2[3], p3[3])) BBox{T}(lower, upper) end # Convenience constructors, with and without explicit type parameter function BBox(p1, p2, p3) BBox{eltype(p1)}(p1, p2, p3) end function BBox{T}(triangle) where T # Decompose triangle into its 3 vertices. # Works transparently with GeometryBasics.Triangle, Vector{SVector{3, T}}, etc. p1, p2, p3 = triangle BBox{T}(p1, p2, p3) end function BBox(triangle) p1, p2, p3 = triangle BBox{eltype(p1)}(p1, p2, p3) end function BBox{T}(vertices::AbstractMatrix) where T BBox{T}(@view(vertices[:, 1]), @view(vertices[:, 2]), @view(vertices[:, 3])) end function BBox(vertices::AbstractMatrix) BBox{eltype(vertices)}(@view(vertices[:, 1]), @view(vertices[:, 2]), @view(vertices[:, 3])) end # Overloaded center function center(b::BBox{T}) where T = (T(0.5) * (b.lo[1] + b.up[1]), T(0.5) * (b.lo[2] + b.up[2]), T(0.5) * (b.lo[3] + b.up[3])) # Merge two bounding boxes function BBox{T}(a::BBox, b::BBox) where T lower = (minimum2(a.lo[1], b.lo[1]), minimum2(a.lo[2], b.lo[2]), minimum2(a.lo[3], b.lo[3])) upper = (maximum2(a.up[1], b.up[1]), maximum2(a.up[2], b.up[2]), maximum2(a.up[3], b.up[3])) BBox{T}(lower, upper) end BBox(a::BBox{T}, b::BBox{T}) where T = BBox{T}(a, b) Base.:+(a::BBox, b::BBox) = BBox(a, b) # Convert BSphere to BBox function BBox{T}(a::BSphere{T}) where T lower = (a.x[1] - a.r, a.x[2] - a.r, a.x[3] - a.r) upper = (a.x[1] + a.r, a.x[2] + a.r, a.x[3] + a.r) BBox(lower, upper) end function BBox(a::BSphere{T}) where T BBox{T}(a) end # Merge two BSphere into enclosing BBox function BBox{T}(a::BSphere{T}, b::BSphere{T}) where T length = dist3(a.x, b.x) # a is enclosed within b if length + a.r <= b.r return BBox(b) # b is enclosed within a elseif length + b.r <= a.r return BBox(a) # Bounding spheres are not enclosed else lower = (minimum2(a.x[1] - a.r, b.x[1] - b.r), minimum2(a.x[2] - a.r, b.x[2] - b.r), minimum2(a.x[3] - a.r, b.x[3] - b.r)) upper = (maximum2(a.x[1] + a.r, b.x[1] + b.r), maximum2(a.x[2] + a.r, b.x[2] + b.r), maximum2(a.x[3] + a.r, b.x[3] + b.r)) return BBox(lower, upper) end end function BBox(a::BSphere{T}, b::BSphere{T}) where T BBox{T}(a, b) end # Contact detection function iscontact(a::BBox, b::BBox) (a.up[1] >= b.lo[1] && a.lo[1] <= b.up[1]) && (a.up[2] >= b.lo[2] && a.lo[2] <= b.up[2]) && (a.up[3] >= b.lo[3] && a.lo[3] <= b.up[3]) end # Contact detection between heterogeneous BVs - only needed when one BVH has exactly one leaf function iscontact(a::BSphere, b::BBox) # This is an edge case, used for broad-phase collision detection, so we simply take the # sphere's bounding box, as a full sphere-box contact detection is computationally heavy ab = BBox( (a.x[1] - a.r, a.x[2] - a.r, a.x[3] - a.r), (a.x[1] + a.r, a.x[2] + a.r, a.x[3] + a.r), ) iscontact(ab, b) end function iscontact(a::BBox, b::BSphere) iscontact(b, a) end
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
10753
""" $(TYPEDEF) Implicit bounding volume hierarchy constructed from an iterable of some geometric primitives' (e.g. triangles in a mesh) bounding volumes forming the [`ImplicitTree`](@ref) leaves. The leaves and merged nodes above them can have different types - e.g. `BSphere{Float64}` for leaves merged into larger `BBox{Float64}`. The initial geometric primitives are sorted according to their Morton-encoded coordinates; the unsigned integer type used for the Morton encoding can be chosen between `$(MortonUnsigned)`. Finally, the tree can be incompletely-built up to a given `built_level` and later start contact detection downwards from this level, e.g.: ``` Implicit tree from 5 bounding volumes - i.e. the real leaves Tree Level Nodes & Leaves Build Up Traverse Down 1 1 Ʌ | 2 2 3 | | 3 4 5 6 7v | | 4 8 9 10 11 12 13v 14v 15v | V -------Real------- ---Virtual--- ``` # Methods function BVH( bounding_volumes::AbstractVector{L}, node_type::Type{N}=L, morton_type::Type{U}=UInt, built_level::Integer=1; num_threads=Threads.nthreads(), ) where {L, N, U <: MortonUnsigned} # Fields - `tree::`[`ImplicitTree`](@ref)`{Int}` - `nodes::VN <: AbstractVector` - `leaves::VL <: AbstractVector` - `order::VO <: AbstractVector` - `built_level::Int` # Examples Simple usage with bounding spheres and default 64-bit types: ```jldoctest using ImplicitBVH using ImplicitBVH: BSphere # Generate some simple bounding spheres bounding_spheres = [ BSphere([0., 0., 0.], 0.5), BSphere([0., 0., 1.], 0.6), BSphere([0., 0., 2.], 0.5), BSphere([0., 0., 3.], 0.4), BSphere([0., 0., 4.], 0.6), ] # Build BVH bvh = BVH(bounding_spheres) # Traverse BVH for contact detection traversal = traverse(bvh) @show traversal.contacts; ; # output traversal.contacts = [(1, 2), (2, 3), (4, 5)] ``` Using `Float32` bounding spheres for leaves, `Float32` bounding boxes for nodes above, and `UInt32` Morton codes: ```jldoctest using ImplicitBVH using ImplicitBVH: BBox, BSphere # Generate some simple bounding spheres bounding_spheres = [ BSphere{Float32}([0., 0., 0.], 0.5), BSphere{Float32}([0., 0., 1.], 0.6), BSphere{Float32}([0., 0., 2.], 0.5), BSphere{Float32}([0., 0., 3.], 0.4), BSphere{Float32}([0., 0., 4.], 0.6), ] # Build BVH bvh = BVH(bounding_spheres, BBox{Float32}, UInt32) # Traverse BVH for contact detection traversal = traverse(bvh) @show traversal.contacts; ; # output traversal.contacts = [(1, 2), (2, 3), (4, 5)] ``` Build BVH up to level 2 and start traversing down from level 3, reusing the previous traversal cache: ```julia bvh = BVH(bounding_spheres, BBox{Float32}, UInt32, 2) traversal = traverse(bvh, 3, traversal) ``` """ struct BVH{VN <: AbstractVector, VL <: AbstractVector, VO <: AbstractVector} built_level::Int tree::ImplicitTree{Int} nodes::VN leaves::VL order::VO end # Custom pretty-printing function Base.show(io::IO, b::BVH{VN, VL, VO}) where {VN, VL, VO} print( io, """ BVH built_level: $(typeof(b.built_level)) $(b.built_level) tree: $(b.tree) nodes: $(VN)($(size(b.nodes))) leaves: $(VL)($(size(b.leaves))) order: $(VO)($(size(b.order))) """ ) end function BVH( bounding_volumes::AbstractVector{L}, node_type::Type{N}=L, morton_type::Type{U}=UInt, built_level=1; num_threads=Threads.nthreads(), ) where {L, N, U <: MortonUnsigned} # Ensure correctness @assert firstindex(bounding_volumes) == 1 "BVH vector types used must be 1-indexed" # Ensure efficiency isconcretetype(N) || @warn "node_type given as unsized type (e.g. BBox instead of \ BBox{Float64}) leading to non-inline vector storage" isconcretetype(L) || @warn "bounding_volumes given as unsized type (e.g. BBox instead of \ BBox{Float64}) leading to non-inline vector storage" # Pre-compute shape of the implicit tree numbv = length(bounding_volumes) tree = ImplicitTree{Int}(numbv) # Compute level up to which tree should be built if built_level isa Integer @assert 1 <= built_level <= tree.levels built_ilevel = Int(built_level) elseif built_level isa AbstractFloat @assert 0 <= built_level <= 1 built_ilevel = round(Int, tree.levels + (1 - tree.levels) * built_level) else throw(TypeError(:BVH, "built_level (the level to build BVH up to)", Union{Integer, AbstractFloat}, typeof(built_level))) end # Compute morton codes for the bounding volumes mortons = similar(bounding_volumes, morton_type) @inbounds morton_encode!(mortons, bounding_volumes, num_threads=num_threads) # Compute indices that sort codes along the Z-curve - closer objects have closer Morton codes # TODO: check parallel SyncSort or ThreadsX.QuickSort order = sortperm(mortons) # Pre-allocate vector of bounding volumes for the real nodes above the bottom level bvh_nodes = similar(bounding_volumes, N, tree.real_nodes - tree.real_leaves) # Aggregate bounding volumes up to root if tree.real_nodes >= 2 aggregate_oibvh!(bvh_nodes, bounding_volumes, tree, order, built_ilevel, num_threads) end BVH(built_ilevel, tree, bvh_nodes, bounding_volumes, order) end # Build ImplicitBVH nodes above the leaf-level from the bottom up, inplace function aggregate_oibvh!(bvh_nodes, bvh_leaves, tree, order, built_level, num_threads) # Special case: aggregate level above leaves - might have different node types aggregate_last_level!(bvh_nodes, bvh_leaves, tree, order, num_threads) level = tree.levels - 2 while level >= built_level aggregate_level!(bvh_nodes, level, tree, num_threads) level -= 1 end nothing end @inline function aggregate_last_level_range!( bvh_nodes, bvh_leaves, order, start_pos, num_nodes_next, irange, ) # The bvh_nodes are not sorted! Instead, we have the indices permutation in `order` @inbounds for i in irange[1]:irange[2] lchild_implicit = 2i - 1 rchild_implicit = 2i rchild_virtual = rchild_implicit > num_nodes_next lchild_index = order[lchild_implicit] if !rchild_virtual rchild_index = order[rchild_implicit] end # If using different node type than leaf type (e.g. BSphere leaves and BBox nodes) do # conversion; this conditional is optimised away at compile-time if eltype(bvh_nodes) === eltype(bvh_leaves) # If right child is virtual, set the parent BV to the left child one; otherwise merge if rchild_virtual bvh_nodes[start_pos - 1 + i] = bvh_leaves[lchild_index] else bvh_nodes[start_pos - 1 + i] = bvh_leaves[lchild_index] + bvh_leaves[rchild_index] end else if rchild_virtual bvh_nodes[start_pos - 1 + i] = eltype(bvh_nodes)(bvh_leaves[lchild_index]) else bvh_nodes[start_pos - 1 + i] = eltype(bvh_nodes)(bvh_leaves[lchild_index], bvh_leaves[rchild_index]) end end end nothing end @inline function aggregate_last_level!(bvh_nodes, bvh_leaves, tree, order, num_threads) # Memory index of first node on this level (i.e. first above leaf-level) level = tree.levels - 1 start_pos = memory_index(tree, pow2(level - 1)) # Number of real nodes on this level num_nodes = pow2(level - 1) - tree.virtual_leaves >> (tree.levels - level) # Merge all pairs of children below this level num_nodes_next = pow2(level) - tree.virtual_leaves >> (tree.levels - (level + 1)) # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_nodes, num_threads, 100) if tp.num_tasks == 1 @inbounds aggregate_last_level_range!( bvh_nodes, bvh_leaves, order, start_pos, num_nodes_next, (1, num_nodes) ) else tasks = Vector{Task}(undef, tp.num_tasks) for i in 1:tp.num_tasks @inbounds tasks[i] = Threads.@spawn aggregate_last_level_range!( bvh_nodes, bvh_leaves, order, start_pos, num_nodes_next, tp[i], ) end for i in 1:tp.num_tasks wait(tasks[i]) end end nothing end @inline function aggregate_level_range!( bvh_nodes, start_pos, start_pos_next, num_nodes_next, irange, ) @inbounds for i in irange[1]:irange[2] lchild_index = start_pos_next + 2i - 2 rchild_index = start_pos_next + 2i - 1 if rchild_index > start_pos_next + num_nodes_next - 1 # If right child is virtual, set the parent BV to the child one bvh_nodes[start_pos - 1 + i] = bvh_nodes[lchild_index] else # Merge children bounding volumes bvh_nodes[start_pos - 1 + i] = bvh_nodes[lchild_index] + bvh_nodes[rchild_index] end end nothing end @inline function aggregate_level!(bvh_nodes, level, tree, num_threads) # Memory index of first node on this level start_pos = memory_index(tree, pow2(level - 1)) # Number of real nodes on this level num_nodes = pow2(level - 1) - tree.virtual_leaves >> (tree.levels - level) # Merge all pairs of children below this level start_pos_next = memory_index(tree, pow2(level)) num_nodes_next = pow2(level) - tree.virtual_leaves >> (tree.levels - (level + 1)) # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_nodes, num_threads, 100) if tp.num_tasks == 1 @inbounds aggregate_level_range!( bvh_nodes, start_pos, start_pos_next, num_nodes_next, (1, num_nodes), ) else tasks = Vector{Task}(undef, tp.num_tasks) for i in 1:tp.num_tasks @inbounds tasks[i] = Threads.@spawn aggregate_level_range!( bvh_nodes, start_pos, start_pos_next, num_nodes_next, tp[i], ) end for i in 1:tp.num_tasks wait(tasks[i]) end end nothing end
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
4952
""" $(TYPEDEF) Implicit binary tree for `num_leaves` elements, where nodes are labelled according to a breadth-first search. # Methods ImplicitTree(num_leaves::Integer) ImplicitTree{T}(num_leaves::Integer) # Fields $(TYPEDFIELDS) # Examples ```julia julia> using ImplicitBVH # Given 5 geometric elements (e.g. bounding boxes) we construct the following implicit tree # having the 5 real leaves at implicit indices 8-12 plus 3 virtual leaves. # Nodes & Leaves Tree Level # 1 1 # 2 3 2 # 4 5 6 7v 3 # 8 9 10 11 12 13v 14v 15v 4 julia> tree = ImplicitTree(5) ImplicitTree{Int64} levels: Int64 4 real_leaves: Int64 5 real_nodes: Int64 11 virtual_leaves: Int64 3 virtual_nodes: Int64 4 # We can keep all tree nodes in a contiguous vector with no extra padding for the virtual # nodes by computing the real memory index of real nodes; e.g. real memory index of node 8 # skips node 7 which is virtual: julia> memory_index(tree, 8) 7 # We can get the range of indices of real nodes on a given level julia> level_indices(tree, 3) (4, 6) # And we can check if a node at a given implicit index is virtual julia> isvirtual(tree, 6) false julia> isvirtual(tree, 7) true ``` """ struct ImplicitTree{T <: Integer} "Number of levels in the tree." levels::T "Number of real leaves - i.e. the elements from which the tree was constructed." real_leaves::T "Total number of real nodes in tree." real_nodes::T "Number of virtual leaves needed at the bottom level to have a perfect binary tree." virtual_leaves::T "Total number of virtual nodes in tree needed for a complete binary tree." virtual_nodes::T end # Custom print function Base.print(io::IO, t::ImplicitTree{T}) where {T} print(io, "ImplicitTree{$T}(levels: $(t.levels), real_leaves: $(t.real_leaves))") end function ImplicitTree{T}(num_leaves::Integer) where {T <: Integer} @boundscheck if num_leaves < 1 throw(DomainError(num_leaves, "must have at least one geometry!")) end lr = num_leaves # number of real leaves levels = @inbounds ilog2(lr, RoundUp) + 1 # number of binary tree levels lv = 2^(levels - 1) - lr # number of virtual leaves nv = 2lv - count_ones(lv) # number of virtual nodes nr = 2lr - 1 + count_ones(lv) # number of real nodes ImplicitTree{T}(levels, lr, nr, lv, nv) end # Convenience constructors ImplicitTree(num_leaves::Integer) = ImplicitTree{typeof(num_leaves)}(num_leaves) """ memory_index(tree::ImplicitTree, implicit_index::Integer) Return actual memory index for a node at implicit index i in a perfect BFS-labelled tree. """ @inline function memory_index(tree::ImplicitTree, implicit_index::Integer) # This will be elided when @inbounds @boundscheck begin if !(1 <= implicit_index <= 2^tree.levels - 1) throw(BoundsError(tree, implicit_index)) end end # Level at which the implicit index is implicit_level = @inbounds ilog2(implicit_index, RoundDown) + 1 # Number of virtual nodes at level before virtual_nodes_level = tree.virtual_leaves >> (tree.levels - (implicit_level - 1)) # Total number of virtual nodes up to the level before virtual_nodes_before = 2 * virtual_nodes_level - count_ones(virtual_nodes_level) # Skipping the number of virtual_nodes we had before the implicit_index implicit_index - virtual_nodes_before end """ level_indices(tree::ImplicitTree, level::Integer) Return range Tuple{Int64, Int64} of memory indices of elements at `level`. """ @inline function level_indices(tree::ImplicitTree, level::Integer) # This will be elided when @inbounds @boundscheck begin if !(1 <= level <= tree.levels) throw(BoundsError(tree, level)) end end # Index of first element at this level start = @inbounds memory_index(tree, pow2(level - 1)) nreal = pow2(level - 1) - tree.virtual_leaves >> (tree.levels - level) stop = start + nreal - 1 start, stop end """ isvirtual(tree::ImplicitTree, implicit_index::Integer) Check if given `implicit_index` corresponds to a virtual node. """ @inline function isvirtual(tree::ImplicitTree, implicit_index::Integer) # This will be elided when @inbounds @boundscheck begin if !(1 <= implicit_index <= 2^tree.levels - 1) throw(BoundsError(tree, implicit_index)) end end # Level at which the implicit index is level = @inbounds ilog2(implicit_index, RoundDown) + 1 level_first = pow2(level - 1) nreal = level_first - tree.virtual_leaves >> (tree.levels - level) # If index is beyond last real node, it's virtual implicit_index - level_first + 1 > nreal end
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
6875
""" $(TYPEDEF) Acceptable unsigned integer types for Morton encoding: $(MortonUnsigned). """ const MortonUnsigned = Union{UInt16, UInt32, UInt64} """ morton_split3(v::UInt16) morton_split3(v::UInt32) morton_split3(v::UInt64) Shift a number's individual bits such that they have two zeros between them. """ @inline function morton_split3(v::UInt16) # Extract first 5 bits s = v & 0x001f s = (s | s << 8) & 0x100f s = (s | s << 4) & 0x10c3 s = (s | s << 2) & 0x1249 s end @inline function morton_split3(v::UInt32) # Extract first 10 bits s = v & 0x0000_03ff # Following StackOverflow discussion: https://stackoverflow.com/questions/18529057/ # produce-interleaving-bit-patterns-morton-keys-for-32-bit-64-bit-and-128bit s = (s | s << 16) & 0x30000ff s = (s | s << 8) & 0x0300f00f s = (s | s << 4) & 0x30c30c3 s = (s | s << 2) & 0x9249249 s end @inline function morton_split3(v::UInt64) # Extract first 21 bits s = v & 0x0_001f_ffff s = (s | s << 32) & 0x1f00000000ffff s = (s | s << 16) & 0x1f0000ff0000ff s = (s | s << 8) & 0x100f00f00f00f00f s = (s | s << 4) & 0x10c30c30c30c30c3 s = (s | s << 2) & 0x1249249249249249 s end """ morton_scaling(::Type{UInt16}) = 2^5 morton_scaling(::Type{UInt32}) = 2^10 morton_scaling(::Type{UInt64}) = 2^21 Exclusive maximum number possible to use for 3D Morton encoding for each type. """ morton_scaling(::Type{UInt16}) = 2^5 morton_scaling(::Type{UInt32}) = 2^10 morton_scaling(::Type{UInt64}) = 2^21 """ relative_precision(::Type{Float16}) = 1e-2 relative_precision(::Type{Float32}) = 1e-5 relative_precision(::Type{Float64}) = 1e-14 Relative precision value for floating-point types. """ relative_precision(::Type{Float16}) = Float16(1e-2) relative_precision(::Type{Float32}) = Float32(1e-5) relative_precision(::Type{Float64}) = Float64(1e-14) """ morton_encode_single(centre, mins, maxs, U::MortonUnsignedType=UInt32) Return Morton code for a single 3D position `centre` scaled uniformly between `mins` and `maxs`. Works transparently for SVector, Vector, etc. with eltype UInt16, UInt32 or UInt64. """ @inline function morton_encode_single(centre, mins, maxs, ::Type{U}=UInt) where {U <: MortonUnsigned} scaling = morton_scaling(U) m = zero(U) @inbounds for i in 1:3 scaled = (centre[i] - mins[i]) / (maxs[i] - mins[i]) # Scaling number between (0, 1) index = U(floor(scaled * scaling)) # Scaling to (0, morton_scaling) m += morton_split3(index) << (3 - i) # Shift into position - XYZXYZXYZ end m end function morton_encode_range!( mortons::AbstractVector{U}, bounding_volumes, mins, maxs, irange, ) where {U <: MortonUnsigned} @inbounds for i in irange[1]:irange[2] bv_center = center(bounding_volumes[i]) mortons[i] = morton_encode_single(bv_center, mins, maxs, U) end nothing end """ bounding_volumes_extrema(bounding_volumes) Compute exclusive lower and upper bounds in iterable of bounding volumes, e.g. Vector{BBox}. """ function bounding_volumes_extrema(bounding_volumes) xmin, ymin, zmin = center(bounding_volumes[1]) xmax, ymax, zmax = xmin, ymin, zmin @inbounds for i in 2:length(bounding_volumes) xc, yc, zc = center(bounding_volumes[i]) xc < xmin && (xmin = xc) yc < ymin && (ymin = yc) zc < zmin && (zmin = zc) xc > xmax && (xmax = xc) yc > ymax && (ymax = yc) zc > zmax && (zmax = zc) end # Expand extrema by float precision to ensure morton codes are exclusively bounded by them T = typeof(xmin) xmin = xmin - relative_precision(T) * abs(xmin) - floatmin(T) ymin = ymin - relative_precision(T) * abs(ymin) - floatmin(T) zmin = zmin - relative_precision(T) * abs(zmin) - floatmin(T) xmax = xmax + relative_precision(T) * abs(xmax) + floatmin(T) ymax = ymax + relative_precision(T) * abs(ymax) + floatmin(T) zmax = zmax + relative_precision(T) * abs(zmax) + floatmin(T) (xmin, ymin, zmin), (xmax, ymax, zmax) end """ morton_encode!(mortons::AbstractVector{U}, bounding_volumes) where {U <: MortonUnsigned} morton_encode!(mortons::AbstractVector{U}, bounding_volumes, mins, maxs) Encode each bounding volume into vector of corresponding Morton codes such that they uniformly cover the maximum Morton range given an unsigned integer type `U <: ` [`MortonUnsigned`](@ref). !!! warning The dimension-wise exclusive `mins` and `maxs` *must* be correct; if any bounding volume center is equal to, or beyond `mins` / `maxs`, the results will be silently incorrect. """ function morton_encode!( mortons::AbstractVector{U}, bounding_volumes::AbstractVector, mins, maxs; num_threads=Threads.nthreads(), ) where {U <: MortonUnsigned} # Bounds checking @assert firstindex(mortons) == firstindex(bounding_volumes) == 1 @assert length(mortons) == length(bounding_volumes) @assert length(mins) == length(maxs) == 3 # Trivial case length(bounding_volumes) == 0 && return nothing # Encode bounding volumes' centres across multiple threads using contiguous ranges tp = TaskPartitioner(length(bounding_volumes), num_threads, 1000) if tp.num_tasks == 1 morton_encode_range!( mortons, bounding_volumes, mins, maxs, (firstindex(bounding_volumes), lastindex(bounding_volumes)), ) else tasks = Vector{Task}(undef, tp.num_tasks) @inbounds for i in 1:tp.num_tasks tasks[i] = Threads.@spawn morton_encode_range!( mortons, bounding_volumes, mins, maxs, tp[i], ) end @inbounds for i in 1:tp.num_tasks wait(tasks[i]) end end nothing end function morton_encode!( mortons::AbstractVector{U}, bounding_volumes; num_threads=Threads.nthreads(), ) where {U <: MortonUnsigned} # Compute exclusive bounds [xmin, ymin, zmin], [xmax, ymax, zmax]. mins, maxs = bounding_volumes_extrema(bounding_volumes) morton_encode!(mortons, bounding_volumes, mins, maxs, num_threads=num_threads) nothing end """ morton_encode(bounding_volumes, ::Type{U}=UInt) where {U <: MortonUnsigned} Encode the centers of some `bounding_volumes` as Morton codes of type `U <: ` [`MortonUnsigned`](@ref). See [`morton_encode!`](@ref) for full details. """ function morton_encode( bounding_volumes, ::Type{U}=UInt; num_threads=Threads.nthreads(), ) where {U <: MortonUnsigned} # Pre-allocate vector of morton codes mortons = similar(bounding_volumes, U) morton_encode!(mortons, bounding_volumes, num_threads=num_threads) mortons end
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
2921
""" $(TYPEDEF) Partitioning `num_elems` elements / jobs over maximum `max_tasks` tasks with minimum `min_elems` elements per task. # Methods TaskPartitioner(num_elems, max_tasks=Threads.nthreads(), min_elems=1) # Fields $(TYPEDFIELDS) # Examples ```jldoctest using ImplicitBVH: TaskPartitioner # Divide 10 elements between 4 tasks tp = TaskPartitioner(10, 4) for i in 1:tp.num_tasks @show tp[i] end # output tp[i] = (1, 3) tp[i] = (4, 6) tp[i] = (7, 9) tp[i] = (10, 10) ``` ```jldoctest using ImplicitBVH: TaskPartitioner # Divide 20 elements between 6 tasks with minimum 5 elements per task. # Not all tasks will be required tp = TaskPartitioner(20, 6, 5) for i in 1:tp.num_tasks @show tp[i] end # output tp[i] = (1, 5) tp[i] = (6, 10) tp[i] = (11, 15) tp[i] = (16, 20) ``` """ struct TaskPartitioner num_elems::Int max_tasks::Int min_elems::Int num_tasks::Int # computed end function TaskPartitioner(num_elems, max_tasks=Threads.nthreads(), min_elems=1) # Number of tasks needed to have at least `min_nodes` per task num_tasks = num_elems ÷ max_tasks >= min_elems ? max_tasks : num_elems ÷ min_elems if num_tasks < 1 num_tasks = 1 end TaskPartitioner(num_elems, max_tasks, min_elems, num_tasks) end function Base.getindex(tp::TaskPartitioner, itask::Integer) @boundscheck 1 <= itask <= tp.num_tasks || throw(BoundsError(tp, itask)) # Compute element indices handled by this task per_task = (tp.num_elems + tp.num_tasks - 1) ÷ tp.num_tasks task_istart = (itask - 1) * per_task + 1 task_istop = min(itask * per_task, tp.num_elems) task_istart, task_istop end Base.firstindex(tp::TaskPartitioner) = 1 Base.lastindex(tp::TaskPartitioner) = tp.num_tasks Base.length(tp::TaskPartitioner) = tp.num_tasks # Fast ilog2 adapted from https://github.com/jlapeyre/ILog2.jl - thank you! # Included here directly to minimise dependencies and possible errors surface area const IntBits = Union{Int8, Int16, Int32, Int64, Int128, UInt8, UInt16, UInt32, UInt64, UInt128} ilog2(x, ::typeof(RoundUp)) = ispow2(x) ? ilog2(x) : ilog2(x) + 1 ilog2(x, ::typeof(RoundDown)) = ilog2(x) @generated function msbindex(::Type{T}) where {T <: Integer} sizeof(T) * 8 - 1 end @inline function ilog2(n::T) where {T <: IntBits} @boundscheck n > zero(T) || throw(DomainError(n)) msbindex(T) - leading_zeros(n) end # Specialised maths functions pow2(n::Integer) = 1 << n function dot3(x, y) x[1] * y[1] + x[2] * y[2] + x[3] * y[3] end function dist3sq(x, y) (x[1] - y[1]) * (x[1] - y[1]) + (x[2] - y[2]) * (x[2] - y[2]) + (x[3] - y[3]) * (x[3] - y[3]) end dist3(x, y) = sqrt(dist3sq(x, y)) minimum2(a, b) = a < b ? a : b minimum3(a, b, c) = a < b ? minimum2(a, c) : minimum2(b, c) maximum2(a, b) = a > b ? a : b maximum3(a, b, c) = a > b ? maximum2(a, c) : maximum2(b, c)
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
2526
""" $(TYPEDEF) Alias for a tuple of two indices representing e.g. a contacting pair. """ const IndexPair = Tuple{Int, Int} """ $(TYPEDEF) Collected BVH traversal `contacts` vector, some stats, plus the two buffers `cache1` and `cache2` which can be reused for future traversals to minimise memory allocations. # Fields - `start_level1::Int`: the level at which the single/pair-tree traversal started for the first BVH. - `start_level2::Int`: the level at which the pair-tree traversal started for the second BVH. - `num_checks::Int`: the total number of contact checks done. - `num_contacts::Int`: the number of contacts found. - `contacts::view(cache1, 1:num_contacts)`: the contacting pairs found, as a view into `cache1`. - `cache1::C1{IndexPair} <: AbstractVector`: first BVH traversal buffer. - `cache2::C2{IndexPair} <: AbstractVector`: second BVH traversal buffer. """ struct BVHTraversal{C1 <: AbstractVector, C2 <: AbstractVector} # Stats start_level1::Int start_level2::Int num_checks::Int # Data num_contacts::Int cache1::C1 cache2::C2 end # Constructor in the case of single-tree traversal (e.g. traverse(bvh)), when we only have a # single start_level function BVHTraversal( start_level::Int, num_checks::Int, num_contacts::Int, cache1::AbstractVector, cache2::AbstractVector, ) BVHTraversal(start_level, start_level, num_checks, num_contacts, cache1, cache2) end # Custom pretty-printing function Base.show(io::IO, t::BVHTraversal{C1, C2}) where {C1, C2} print( io, """ BVHTraversal start_level1: $(typeof(t.start_level1)) $(t.start_level1) start_level2: $(typeof(t.start_level2)) $(t.start_level2) num_checks: $(typeof(t.num_checks)) $(t.num_checks) num_contacts: $(typeof(t.num_contacts)) $(t.num_contacts) contacts: $(Base.typename(typeof(t.contacts)).wrapper){IndexPair}($(size(t.contacts))) cache1: $C1($(size(t.cache1))) cache2: $C2($(size(t.cache2))) """ ) end function Base.getproperty(bt::BVHTraversal, sym::Symbol) if sym === :contacts return @view bt.cache1[1:bt.num_contacts] else return getfield(bt, sym) end end Base.propertynames(::BVHTraversal) = (:start_level1, :start_level2, :num_checks, :contacts, :num_contacts, :cache1, :cache2) # Single BVH and BVH-BVH traversal include("traverse_single.jl") include("traverse_pair.jl")
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
32138
""" traverse( bvh1::BVH, bvh2::BVH, start_level1::Int=default_start_level(bvh1), start_level2::Int=default_start_level(bvh2), cache::Union{Nothing, BVHTraversal}=nothing; num_threads=Threads.nthreads(), )::BVHTraversal Return all the `bvh1` bounding volume leaves that are in contact with any in `bvh2`. The returned [`BVHTraversal`](@ref) also contains two contact buffers that can be reused on future traversals. # Examples ```jldoctest using ImplicitBVH using ImplicitBVH: BBox, BSphere # Generate some simple bounding spheres bounding_spheres1 = [ BSphere{Float32}([0., 0., 0.], 0.5), BSphere{Float32}([0., 0., 3.], 0.4), ] bounding_spheres2 = [ BSphere{Float32}([0., 0., 1.], 0.6), BSphere{Float32}([0., 0., 2.], 0.5), BSphere{Float32}([0., 0., 4.], 0.6), ] # Build BVHs bvh1 = BVH(bounding_spheres1, BBox{Float32}, UInt32) bvh2 = BVH(bounding_spheres2, BBox{Float32}, UInt32) # Traverse BVH for contact detection traversal = traverse(bvh1, bvh2, default_start_level(bvh1), default_start_level(bvh2)) # Reuse traversal buffers for future contact detection - possibly with different BVHs traversal = traverse(bvh1, bvh2, default_start_level(bvh1), default_start_level(bvh2), traversal) @show traversal.contacts; ; # output traversal.contacts = [(1, 1), (2, 3)] ``` """ function traverse( bvh1::BVH{V1, V2, V3}, bvh2::BVH{V1, V2, V3}, start_level1::Int=default_start_level(bvh1), start_level2::Int=default_start_level(bvh2), cache::Union{Nothing, BVHTraversal}=nothing; num_threads=Threads.nthreads(), ) where {V1, V2, V3} @boundscheck begin @assert bvh1.tree.levels >= start_level1 >= bvh1.built_level @assert bvh2.tree.levels >= start_level2 >= bvh2.built_level end # Explanation: say BVH1 has 10 levels, BVH2 has 8 levels; the last level has "leaves" (the # actual bounding volumes for contact detection), levels above have "nodes". Both BVHs are # aligned to start at level 1. We have two buffers, bvtt1 (src) and bvtt2 (dst); bvtt1 stores # the current level's pairs of BVs we need to check for contact. For each contacting pair of # BVs in bvtt1, we pair their children for checking contacts at the next level, which we write # into bvtt2. Then bvtt1 and bvtt2 are swapped, we advance to the next level, and repeat. # # A complicating factor is the fact that the two BVHs may have different heights. We then split # contact detection into 4 stages: first, we traverse both in sync - that is, at level 1 we have # in bvtt1=[(1, 1)] and we write into bvtt2=[(2, 2), (2, 3), (3, 2), (3, 3)] (if the root of # BVH1 is in contact with the root of BVH2). We continue at level 2, 3... until we reach level # 7, the level above BVH2 leaves. Now we only traverse BVH1, keeping BVH2's level fixed, and # doing node-node checks until we reach level 9 in BVH1; now both BVHs have reached the level # above leaves. We do another in-sync pairwise contact detection, this time having nodes in # bvtt1 (src) and writing possible contacts to check for leaves in bvtt2 (dst). Now we have # reached the leaf-level of both BVHs and we write all contacts found into the final contacts # vector. # Allocate and add all possible BVTT contact pairs to start with bvtt1, bvtt2, num_bvtt = initial_bvtt(bvh1, bvh2, start_level1, start_level2, cache) num_checks = num_bvtt # Compute node-node contacts while both BVHs are at node levels level1 = start_level1 level2 = start_level2 while level1 < bvh1.tree.levels - 1 && level2 < bvh2.tree.levels - 1 # We can have maximum 4 new checks per contact-pair; resize destination BVTT accordingly length(bvtt2) < 4 * num_bvtt && resize!(bvtt2, 4 * num_bvtt) # Check contacts in bvtt1 and add future checks in bvtt2 num_bvtt = traverse_nodes_pair!(bvh1, bvh2, bvtt1, bvtt2, num_bvtt, level1, level2, num_threads) num_checks += num_bvtt # Swap source and destination buffers for next iteration bvtt1, bvtt2 = bvtt2, bvtt1 level1 += 1 level2 += 1 end # Compute node-node contacts while only right BVH is at level above leaves while level1 < bvh1.tree.levels - 1 && level2 == bvh2.tree.levels - 1 # We can have maximum 2 new checks per contact-pair; resize destination BVTT accordingly length(bvtt2) < 2 * num_bvtt && resize!(bvtt2, 2 * num_bvtt) # Check contacts in bvtt1 and add future checks in bvtt2 num_bvtt = traverse_nodes_left!(bvh1, bvh2, bvtt1, bvtt2, num_bvtt, level1, level2, num_threads) num_checks += num_bvtt # Swap source and destination buffers for next iteration bvtt1, bvtt2 = bvtt2, bvtt1 level1 += 1 end # Compute node-node contacts while only left BVH is at level above leaves while level2 < bvh2.tree.levels - 1 && level1 == bvh1.tree.levels - 1 # We can have maximum 2 new checks per contact-pair; resize destination BVTT accordingly length(bvtt2) < 2 * num_bvtt && resize!(bvtt2, 2 * num_bvtt) # Check contacts in bvtt1 and add future checks in bvtt2 num_bvtt = traverse_nodes_right!(bvh1, bvh2, bvtt1, bvtt2, num_bvtt, level1, level2, num_threads) num_checks += num_bvtt # Swap source and destination buffers for next iteration bvtt1, bvtt2 = bvtt2, bvtt1 level2 += 1 end # Special case: if the right BVH is already at leaf level (i.e. it either had a single leaf or # start_level2 == bvh2.tree.levels) then we must do node-leaf checks down to both leaf levels while level2 == bvh2.tree.levels && level1 < bvh1.tree.levels # We can have maximum 2 new checks per contact-pair; resize destination BVTT accordingly length(bvtt2) < 2 * num_bvtt && resize!(bvtt2, 2 * num_bvtt) # Check contacts in bvtt1 and add future checks in bvtt2 num_bvtt = traverse_nodes_leaves_left!(bvh1, bvh2, bvtt1, bvtt2, num_bvtt, level1, num_threads) num_checks += num_bvtt # Swap source and destination buffers for next iteration bvtt1, bvtt2 = bvtt2, bvtt1 level1 += 1 end # Special case: if the left BVH is already at leaf level (i.e. it either had a single leaf or # start_level1 == bvh1.tree.levels) then we must do node-leaf checks down to both leaf levels while level1 == bvh1.tree.levels && level2 < bvh2.tree.levels # We can have maximum 2 new checks per contact-pair; resize destination BVTT accordingly length(bvtt2) < 2 * num_bvtt && resize!(bvtt2, 2 * num_bvtt) # Check contacts in bvtt1 and add future checks in bvtt2 num_bvtt = traverse_nodes_leaves_right!(bvh1, bvh2, bvtt1, bvtt2, num_bvtt, level2, num_threads) num_checks += num_bvtt # Swap source and destination buffers for next iteration bvtt1, bvtt2 = bvtt2, bvtt1 level2 += 1 end # Compute node-node contacts when both BVHs are at level above leaves if level1 == bvh1.tree.levels - 1 && level2 == bvh2.tree.levels - 1 # We can have maximum 4 new checks per contact-pair; resize destination BVTT accordingly length(bvtt2) < 4 * num_bvtt && resize!(bvtt2, 4 * num_bvtt) # Check contacts in bvtt1 and add future checks in bvtt2 num_bvtt = traverse_nodes_pair!(bvh1, bvh2, bvtt1, bvtt2, num_bvtt, level1, level2, num_threads) num_checks += num_bvtt # Swap source and destination buffers for next iteration bvtt1, bvtt2 = bvtt2, bvtt1 level1 += 1 level2 += 1 end # Arrived at final leaf level with both BVHs, now populating contact list length(bvtt2) < num_bvtt && resize!(bvtt2, num_bvtt) num_bvtt = traverse_leaves_pair!(bvh1, bvh2, bvtt1, bvtt2, num_bvtt, num_threads) # Return contact list and the other buffer as possible cache BVHTraversal(start_level1, start_level2, num_checks, num_bvtt, bvtt2, bvtt1) end function initial_bvtt(bvh1, bvh2, start_level1, start_level2, cache) # Generate all possible contact checks at the given start_level level_nodes1 = pow2(start_level1 - 1) level_nodes2 = pow2(start_level2 - 1) # Number of real nodes at the given start_level and number of checks we'll do num_real1 = level_nodes1 - bvh1.tree.virtual_leaves >> (bvh1.tree.levels - start_level1) num_real2 = level_nodes2 - bvh2.tree.virtual_leaves >> (bvh2.tree.levels - start_level2) level_checks = num_real1 * num_real2 # If we're not at leaf-level, allocate enough memory for next BVTT expansion if start_level1 == bvh1.tree.levels && start_level2 == bvh2.tree.levels initial_number = level_checks # Both at leaf level elseif start_level1 == bvh1.tree.levels || start_level2 == bvh2.tree.levels initial_number = 2 * level_checks # Only one at leaf level else initial_number = 4 * level_checks # Neither at leaf level end # Reuse cache if given if isnothing(cache) bvtt1 = similar(bvh1.nodes, IndexPair, initial_number) bvtt2 = similar(bvh1.nodes, IndexPair, initial_number) else bvtt1 = cache.cache1 bvtt2 = cache.cache2 length(bvtt1) < initial_number && resize!(bvtt1, initial_number) length(bvtt2) < initial_number && resize!(bvtt2, initial_number) end # Insert all checks at this level num_bvtt = 0 @inbounds for i in level_nodes1:level_nodes1 + num_real1 - 1 # Node-node pair checks for j in level_nodes2:level_nodes2 + num_real2 - 1 num_bvtt += 1 bvtt1[num_bvtt] = (i, j) end end bvtt1, bvtt2, num_bvtt end function traverse_nodes_pair!(bvh1, bvh2, src, dst, num_src, level1, level2, num_threads) # Traverse nodes when level is above leaves for both BVH1 and BVH2 # Compute number of virtual elements before this level to skip when computing the memory index virtual_nodes_level1 = bvh1.tree.virtual_leaves >> (bvh1.tree.levels - (level1 - 1)) virtual_nodes_before1 = 2 * virtual_nodes_level1 - count_ones(virtual_nodes_level1) virtual_nodes_level2 = bvh2.tree.virtual_leaves >> (bvh2.tree.levels - (level2 - 1)) virtual_nodes_before2 = 2 * virtual_nodes_level2 - count_ones(virtual_nodes_level2) # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_src, num_threads, 100) if tp.num_tasks == 1 num_dst = traverse_nodes_pair_range!( bvh1, bvh2, src, dst, nothing, virtual_nodes_before1, virtual_nodes_before2, (1, num_src), ) else # Keep track of tasks launched and number of elements written by each task in their unique # memory region. The unique region is equal to 4 dst elements per src element tasks = Vector{Task}(undef, tp.num_tasks) num_written = Vector{Int}(undef, tp.num_tasks) @inbounds for i in 1:tp.num_tasks istart, iend = tp[i] tasks[i] = Threads.@spawn traverse_nodes_pair_range!( bvh1, bvh2, src, view(dst, 4istart - 3:4iend), view(num_written, i), virtual_nodes_before1, virtual_nodes_before2, (istart, iend), ) end # As tasks finish sequentially, move the new written contacts into contiguous region num_dst = 0 @inbounds for i in 1:tp.num_tasks wait(tasks[i]) task_num_written = num_written[i] # Repack written contacts by the second, third thread, etc. if i > 1 istart, iend = tp[i] for j in 1:task_num_written dst[num_dst + j] = dst[4istart - 3 + j - 1] end end num_dst += task_num_written end end num_dst end function traverse_nodes_pair_range!( bvh1, bvh2, src, dst, num_written, num_skips1, num_skips2, irange, ) # Check src[irange[1]:irange[2]] and write to dst[1:num_dst]; dst should be given as a view num_dst = 0 # For each BVTT pair of nodes, check for contact @inbounds for i in irange[1]:irange[2] # Extract implicit indices of BVH nodes to test implicit1, implicit2 = src[i] node1 = bvh1.nodes[implicit1 - num_skips1] node2 = bvh2.nodes[implicit2 - num_skips2] # If the two nodes are touching, expand BVTT with new possible contacts - i.e. pair # the nodes' children if iscontact(node1, node2) # If a node's right child is virtual, don't add that check. Guaranteed to always have # at least one real child # BVH1 node's right child is virtual if isvirtual(bvh1.tree, 2 * implicit1 + 1) # BVH2 node's right child is virtual too if isvirtual(bvh2.tree, 2 * implicit2 + 1) dst[num_dst + 1] = (implicit1 * 2, implicit2 * 2) num_dst += 1 # Only BVH1 node's right child is virtual else dst[num_dst + 1] = (implicit1 * 2, implicit2 * 2) dst[num_dst + 2] = (implicit1 * 2, implicit2 * 2 + 1) num_dst += 2 end # Only BVH2 node's right child is virtual elseif isvirtual(bvh2.tree, 2 * implicit2 + 1) dst[num_dst + 1] = (implicit1 * 2, implicit2 * 2) dst[num_dst + 2] = (implicit1 * 2 + 1, implicit2 * 2) num_dst += 2 # All children are real else dst[num_dst + 1] = (implicit1 * 2, implicit2 * 2) dst[num_dst + 2] = (implicit1 * 2, implicit2 * 2 + 1) dst[num_dst + 3] = (implicit1 * 2 + 1, implicit2 * 2) dst[num_dst + 4] = (implicit1 * 2 + 1, implicit2 * 2 + 1) num_dst += 4 end end end # Known at compile-time; no return if called in multithreaded context if isnothing(num_written) return num_dst else num_written[] = num_dst return nothing end end function traverse_nodes_left!(bvh1, bvh2, src, dst, num_src, level1, level2, num_threads) # Traverse nodes when BVH2 is already one above leaf-level - i.e. only BVH1 is sprouted further # Compute number of virtual elements before this level to skip when computing the memory index virtual_nodes_level1 = bvh1.tree.virtual_leaves >> (bvh1.tree.levels - (level1 - 1)) virtual_nodes_before1 = 2 * virtual_nodes_level1 - count_ones(virtual_nodes_level1) virtual_nodes_level2 = bvh2.tree.virtual_leaves >> (bvh2.tree.levels - (level2 - 1)) virtual_nodes_before2 = 2 * virtual_nodes_level2 - count_ones(virtual_nodes_level2) # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_src, num_threads, 100) if tp.num_tasks == 1 num_dst = traverse_nodes_left_range!( bvh1, bvh2, src, dst, nothing, virtual_nodes_before1, virtual_nodes_before2, (1, num_src), ) else # Keep track of tasks launched and number of elements written by each task in their unique # memory region. The unique region is equal to 2 dst elements per src element tasks = Vector{Task}(undef, tp.num_tasks) num_written = Vector{Int}(undef, tp.num_tasks) @inbounds for i in 1:tp.num_tasks istart, iend = tp[i] tasks[i] = Threads.@spawn traverse_nodes_left_range!( bvh1, bvh2, src, view(dst, 2istart - 1:2iend), view(num_written, i), virtual_nodes_before1, virtual_nodes_before2, (istart, iend), ) end # As tasks finish sequentially, move the new written contacts into contiguous region num_dst = 0 @inbounds for i in 1:tp.num_tasks wait(tasks[i]) task_num_written = num_written[i] # Repack written contacts by the second, third thread, etc. if i > 1 istart, iend = tp[i] for j in 1:task_num_written dst[num_dst + j] = dst[2istart - 1 + j - 1] end end num_dst += task_num_written end end num_dst end function traverse_nodes_left_range!( bvh1, bvh2, src, dst, num_written, num_skips1, num_skips2, irange, ) # Check src[irange[1]:irange[2]] and write to dst[1:num_dst]; dst should be given as a view num_dst = 0 # For each BVTT pair of nodes, check for contact. Only expand BVTT for BVH1, as BVH2 is already # one above leaf level @inbounds for i in irange[1]:irange[2] # Extract implicit indices of BVH nodes to test implicit1, implicit2 = src[i] node1 = bvh1.nodes[implicit1 - num_skips1] node2 = bvh2.nodes[implicit2 - num_skips2] # If the two nodes are touching, expand BVTT with new possible contacts - i.e. pair # the nodes' children if iscontact(node1, node2) # If a node's right child is virtual, don't add that check. Guaranteed to always have # at least one real child # BVH1 node's right child is virtual if isvirtual(bvh1.tree, 2 * implicit1 + 1) dst[num_dst + 1] = (implicit1 * 2, implicit2) num_dst += 1 else dst[num_dst + 1] = (implicit1 * 2, implicit2) dst[num_dst + 2] = (implicit1 * 2 + 1, implicit2) num_dst += 2 end end end # Known at compile-time; no return if called in multithreaded context if isnothing(num_written) return num_dst else num_written[] = num_dst return nothing end end function traverse_nodes_right!(bvh1, bvh2, src, dst, num_src, level1, level2, num_threads) # Traverse nodes when BVH2 is already one above leaf-level - i.e. only BVH1 is sprouted further # Compute number of virtual elements before this level to skip when computing the memory index virtual_nodes_level1 = bvh1.tree.virtual_leaves >> (bvh1.tree.levels - (level1 - 1)) virtual_nodes_before1 = 2 * virtual_nodes_level1 - count_ones(virtual_nodes_level1) virtual_nodes_level2 = bvh2.tree.virtual_leaves >> (bvh2.tree.levels - (level2 - 1)) virtual_nodes_before2 = 2 * virtual_nodes_level2 - count_ones(virtual_nodes_level2) # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_src, num_threads, 100) if tp.num_tasks == 1 num_dst = traverse_nodes_right_range!( bvh1, bvh2, src, dst, nothing, virtual_nodes_before1, virtual_nodes_before2, (1, num_src), ) else # Keep track of tasks launched and number of elements written by each task in their unique # memory region. The unique region is equal to 2 dst elements per src element tasks = Vector{Task}(undef, tp.num_tasks) num_written = Vector{Int}(undef, tp.num_tasks) @inbounds for i in 1:tp.num_tasks istart, iend = tp[i] tasks[i] = Threads.@spawn traverse_nodes_right_range!( bvh1, bvh2, src, view(dst, 2istart - 1:2iend), view(num_written, i), virtual_nodes_before1, virtual_nodes_before2, (istart, iend), ) end # As tasks finish sequentially, move the new written contacts into contiguous region num_dst = 0 @inbounds for i in 1:tp.num_tasks wait(tasks[i]) task_num_written = num_written[i] # Repack written contacts by the second, third thread, etc. if i > 1 istart, iend = tp[i] for j in 1:task_num_written dst[num_dst + j] = dst[2istart - 1 + j - 1] end end num_dst += task_num_written end end num_dst end function traverse_nodes_right_range!( bvh1, bvh2, src, dst, num_written, num_skips1, num_skips2, irange, ) # Check src[irange[1]:irange[2]] and write to dst[1:num_dst]; dst should be given as a view num_dst = 0 # For each BVTT pair of nodes, check for contact. Only expand BVTT for BVH2, as BVH1 is already # one above leaf level @inbounds for i in irange[1]:irange[2] # Extract implicit indices of BVH nodes to test implicit1, implicit2 = src[i] node1 = bvh1.nodes[implicit1 - num_skips1] node2 = bvh2.nodes[implicit2 - num_skips2] # If the two nodes are touching, expand BVTT with new possible contacts - i.e. pair # the nodes' children if iscontact(node1, node2) # If a node's right child is virtual, don't add that check. Guaranteed to always have # at least one real child # BVH2 node's right child is virtual if isvirtual(bvh2.tree, 2 * implicit2 + 1) dst[num_dst + 1] = (implicit1, implicit2 * 2) num_dst += 1 else dst[num_dst + 1] = (implicit1, implicit2 * 2) dst[num_dst + 2] = (implicit1, implicit2 * 2 + 1) num_dst += 2 end end end # Known at compile-time; no return if called in multithreaded context if isnothing(num_written) return num_dst else num_written[] = num_dst return nothing end end function traverse_nodes_leaves_left!(bvh1, bvh2, src, dst, num_src, level1, num_threads) # Special case: BVH2 is at leaf level; only BVH1 is sprouted further with node-leaf checks # Compute number of virtual elements before this level to skip when computing the memory index virtual_nodes_level1 = bvh1.tree.virtual_leaves >> (bvh1.tree.levels - (level1 - 1)) virtual_nodes_before1 = 2 * virtual_nodes_level1 - count_ones(virtual_nodes_level1) # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_src, num_threads, 100) if tp.num_tasks == 1 num_dst = traverse_nodes_leaves_left_range!( bvh1, bvh2, src, dst, nothing, virtual_nodes_before1, (1, num_src), ) else # Keep track of tasks launched and number of elements written by each task in their unique # memory region. The unique region is equal to 2 dst elements per src element tasks = Vector{Task}(undef, tp.num_tasks) num_written = Vector{Int}(undef, tp.num_tasks) @inbounds for i in 1:tp.num_tasks istart, iend = tp[i] tasks[i] = Threads.@spawn traverse_nodes_leaves_left_range!( bvh1, bvh2, src, view(dst, 2istart - 1:2iend), view(num_written, i), virtual_nodes_before1, (istart, iend), ) end # As tasks finish sequentially, move the new written contacts into contiguous region num_dst = 0 @inbounds for i in 1:tp.num_tasks wait(tasks[i]) task_num_written = num_written[i] # Repack written contacts by the second, third thread, etc. if i > 1 istart, iend = tp[i] for j in 1:task_num_written dst[num_dst + j] = dst[2istart - 1 + j - 1] end end num_dst += task_num_written end end num_dst end function traverse_nodes_leaves_left_range!( bvh1, bvh2, src, dst, num_written, num_skips1, irange, ) # Check src[irange[1]:irange[2]] and write to dst[1:num_dst]; dst should be given as a view num_dst = 0 # Number of implicit indices above leaf-level num_above2 = pow2(bvh2.tree.levels - 1) - 1 # For each BVTT pair of nodes, check for contact. Only expand BVTT for BVH1, as BVH2 is already # at leaf level @inbounds for i in irange[1]:irange[2] # Extract implicit indices of BVH nodes to test implicit1, implicit2 = src[i] node1 = bvh1.nodes[implicit1 - num_skips1] iorder2 = bvh2.order[implicit2 - num_above2] leaf2 = bvh2.leaves[iorder2] # If the two nodes are touching, expand BVTT with new possible contacts - i.e. pair # the nodes' children if iscontact(node1, leaf2) # If a node's right child is virtual, don't add that check. Guaranteed to always have # at least one real child # BVH1 node's right child is virtual if isvirtual(bvh1.tree, 2 * implicit1 + 1) dst[num_dst + 1] = (implicit1 * 2, implicit2) num_dst += 1 else dst[num_dst + 1] = (implicit1 * 2, implicit2) dst[num_dst + 2] = (implicit1 * 2 + 1, implicit2) num_dst += 2 end end end # Known at compile-time; no return if called in multithreaded context if isnothing(num_written) return num_dst else num_written[] = num_dst return nothing end end function traverse_nodes_leaves_right!(bvh1, bvh2, src, dst, num_src, level2, num_threads) # Special case: BVH1 is at leaf level; only BVH2 is sprouted further with node-leaf checks # Compute number of virtual elements before this level to skip when computing the memory index virtual_nodes_level2 = bvh2.tree.virtual_leaves >> (bvh2.tree.levels - (level2 - 1)) virtual_nodes_before2 = 2 * virtual_nodes_level2 - count_ones(virtual_nodes_level2) # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_src, num_threads, 100) if tp.num_tasks == 1 num_dst = traverse_nodes_leaves_right_range!( bvh1, bvh2, src, dst, nothing, virtual_nodes_before2, (1, num_src), ) else # Keep track of tasks launched and number of elements written by each task in their unique # memory region. The unique region is equal to 2 dst elements per src element tasks = Vector{Task}(undef, tp.num_tasks) num_written = Vector{Int}(undef, tp.num_tasks) @inbounds for i in 1:tp.num_tasks istart, iend = tp[i] tasks[i] = Threads.@spawn traverse_nodes_leaves_right_range!( bvh1, bvh2, src, view(dst, 2istart - 1:2iend), view(num_written, i), virtual_nodes_before2, (istart, iend), ) end # As tasks finish sequentially, move the new written contacts into contiguous region num_dst = 0 @inbounds for i in 1:tp.num_tasks wait(tasks[i]) task_num_written = num_written[i] # Repack written contacts by the second, third thread, etc. if i > 1 istart, iend = tp[i] for j in 1:task_num_written dst[num_dst + j] = dst[2istart - 1 + j - 1] end end num_dst += task_num_written end end num_dst end function traverse_nodes_leaves_right_range!( bvh1, bvh2, src, dst, num_written, num_skips2, irange, ) # Check src[irange[1]:irange[2]] and write to dst[1:num_dst]; dst should be given as a view num_dst = 0 # Number of implicit indices above leaf-level num_above1 = pow2(bvh1.tree.levels - 1) - 1 # For each BVTT pair of nodes, check for contact. Only expand BVTT for BVH2, as BVH1 is already # at leaf level @inbounds for i in irange[1]:irange[2] # Extract implicit indices of BVH nodes to test implicit1, implicit2 = src[i] iorder1 = bvh1.order[implicit1 - num_above1] leaf1 = bvh1.leaves[iorder1] node2 = bvh2.nodes[implicit2 - num_skips2] # If the two nodes are touching, expand BVTT with new possible contacts - i.e. pair # the nodes' children if iscontact(leaf1, node2) # If a node's right child is virtual, don't add that check. Guaranteed to always have # at least one real child # BVH2 node's right child is virtual if isvirtual(bvh2.tree, 2 * implicit2 + 1) dst[num_dst + 1] = (implicit1, implicit2 * 2) num_dst += 1 else dst[num_dst + 1] = (implicit1, implicit2 * 2) dst[num_dst + 2] = (implicit1, implicit2 * 2 + 1) num_dst += 2 end end end # Known at compile-time; no return if called in multithreaded context if isnothing(num_written) return num_dst else num_written[] = num_dst return nothing end end function traverse_leaves_pair!(bvh1, bvh2, src, contacts, num_src, num_threads) # Traverse final level, only doing leaf-leaf checks # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_src, num_threads, 100) if tp.num_tasks == 1 num_contacts = traverse_leaves_pair_range!( bvh1, bvh2, src, view(contacts, :), nothing, (1, num_src), ) else num_contacts = 0 # Keep track of tasks launched and number of elements written by each task in their unique # memory region. The unique region is equal to 1 dst elements per src element tasks = Vector{Task}(undef, tp.num_tasks) num_written = Vector{Int}(undef, tp.num_tasks) @inbounds for i in 1:tp.num_tasks istart, iend = tp[i] tasks[i] = Threads.@spawn traverse_leaves_pair_range!( bvh1, bvh2, src, view(contacts, istart:iend), view(num_written, i), (istart, iend), ) end @inbounds for i in 1:tp.num_tasks wait(tasks[i]) task_num_written = num_written[i] # Repack written contacts by the second, third thread, etc. if i > 1 istart, iend = tp[i] for j in 1:task_num_written contacts[num_contacts + j] = contacts[istart + j - 1] end end num_contacts += task_num_written end end num_contacts end function traverse_leaves_pair_range!( bvh1, bvh2, src, contacts, num_written, irange ) # Check src[irange[1]:irange[2]] and write to dst[1:num_dst]; dst should be given as a view num_dst = 0 # Number of implicit indices above leaf-level num_above1 = pow2(bvh1.tree.levels - 1) - 1 num_above2 = pow2(bvh2.tree.levels - 1) - 1 # For each BVTT pair of nodes, check for contact @inbounds for i in irange[1]:irange[2] # Extract implicit indices of BVH leaves to test implicit1, implicit2 = src[i] iorder1 = bvh1.order[implicit1 - num_above1] iorder2 = bvh2.order[implicit2 - num_above2] leaf1 = bvh1.leaves[iorder1] leaf2 = bvh2.leaves[iorder2] # If two leaves are touching, save in contacts if iscontact(leaf1, leaf2) contacts[num_dst + 1] = (iorder1, iorder2) num_dst += 1 end end # Known at compile-time; no return if called in multithreaded context if isnothing(num_written) return num_dst else num_written[] = num_dst return nothing end end
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
12566
""" default_start_level(bvh::BVH)::Int default_start_level(num_leaves::Integer)::Int Compute the default start level when traversing a single BVH tree. """ function default_start_level(bvh::BVH) maximum2(bvh.tree.levels ÷ 2, bvh.built_level) end function default_start_level(num_leaves::Integer) # Compute the default start level from the number of leaves (geometries) only @boundscheck if num_leaves < 1 throw(DomainError(num_leaves, "must have at least one geometry!")) end levels = @inbounds ilog2(num_leaves, RoundUp) + 1 # number of binary tree levels maximum2(levels ÷ 2, 1) end """ traverse( bvh::BVH, start_level::Int=default_start_level(bvh), cache::Union{Nothing, BVHTraversal}=nothing; num_threads=Threads.nthreads(), )::BVHTraversal Traverse `bvh` downwards from `start_level`, returning all contacting bounding volume leaves. The returned [`BVHTraversal`](@ref) also contains two contact buffers that can be reused on future traversals. # Examples ```jldoctest using ImplicitBVH using ImplicitBVH: BBox, BSphere # Generate some simple bounding spheres bounding_spheres = [ BSphere{Float32}([0., 0., 0.], 0.5), BSphere{Float32}([0., 0., 1.], 0.6), BSphere{Float32}([0., 0., 2.], 0.5), BSphere{Float32}([0., 0., 3.], 0.4), BSphere{Float32}([0., 0., 4.], 0.6), ] # Build BVH bvh = BVH(bounding_spheres, BBox{Float32}, UInt32) # Traverse BVH for contact detection traversal = traverse(bvh, 2) # Reuse traversal buffers for future contact detection - possibly with different BVHs traversal = traverse(bvh, 2, traversal) @show traversal.contacts; ; # output traversal.contacts = [(1, 2), (2, 3), (4, 5)] ``` """ function traverse( bvh::BVH, start_level::Int, cache::Union{Nothing, BVHTraversal}=nothing; num_threads=Threads.nthreads(), ) @assert bvh.tree.levels >= start_level >= bvh.built_level # No contacts / traversal for a single node if bvh.tree.real_nodes <= 1 return BVHTraversal(start_level, 0, 0, similar(bvh.nodes, IndexPair, 0), similar(bvh.nodes, IndexPair, 0)) end # Allocate and add all possible BVTT contact pairs to start with bvtt1, bvtt2, num_bvtt = initial_bvtt(bvh, start_level, cache) num_checks = num_bvtt level = start_level while level < bvh.tree.levels # We can have maximum 4 new checks per contact-pair; resize destination BVTT accordingly length(bvtt2) < 4 * num_bvtt && resize!(bvtt2, 4 * 4 * num_bvtt) # Check contacts in bvtt1 and add future checks in bvtt2; only sprout self-checks before # second-to-last level as leaf self-checks are pointless self_checks = level < bvh.tree.levels - 1 num_bvtt = traverse_nodes!(bvh, bvtt1, bvtt2, num_bvtt, level, self_checks, num_threads) num_checks += num_bvtt # Swap source and destination buffers for next iteration bvtt1, bvtt2 = bvtt2, bvtt1 level += 1 end # Arrived at final leaf level, now populating contact list length(bvtt2) < num_bvtt && resize!(bvtt2, num_bvtt) num_bvtt = traverse_leaves!(bvh, bvtt1, bvtt2, num_bvtt, num_threads) # Return contact list and the other buffer as possible cache BVHTraversal(start_level, num_checks, num_bvtt, bvtt2, bvtt1) end # Needed for compiler disambiguation; user interface is the same as for a default argument function traverse(bvh::BVH) traverse(bvh, default_start_level(bvh), nothing) end function initial_bvtt(bvh, start_level, cache) # Generate all possible contact checks at the given start_level level_nodes = pow2(start_level - 1) level_checks = (level_nodes - 1) * level_nodes ÷ 2 + level_nodes # If we're not at leaf-level, allocate enough memory for next BVTT expansion initial_number = start_level == bvh.tree.levels ? level_checks : 4 * level_checks # Reuse cache if given if isnothing(cache) bvtt1 = similar(bvh.nodes, IndexPair, initial_number) bvtt2 = similar(bvh.nodes, IndexPair, initial_number) else bvtt1 = cache.cache1 bvtt2 = cache.cache2 length(bvtt1) < initial_number && resize!(bvtt1, initial_number) length(bvtt2) < initial_number && resize!(bvtt2, initial_number) end # Insert all checks at this level num_bvtt = 0 num_real = level_nodes - bvh.tree.virtual_leaves >> (bvh.tree.levels - start_level) @inbounds for i in level_nodes:level_nodes + num_real - 1 # Only insert self-checks if we still have nodes below us; leaf self-checks are not needed if start_level != bvh.tree.levels num_bvtt += 1 bvtt1[num_bvtt] = (i, i) end # Node-node pair checks for j in i + 1:level_nodes + num_real - 1 num_bvtt += 1 bvtt1[num_bvtt] = (i, j) end end bvtt1, bvtt2, num_bvtt end function traverse_nodes_range!( bvh, src, dst, num_written, num_skips, self_checks, irange, ) # Check src[irange[1]:irange[2]] and write to dst[1:num_dst]; dst should be given as a view num_dst = 0 # For each BVTT pair of nodes, check for contact @inbounds for i in irange[1]:irange[2] # Extract implicit indices of BVH nodes to test implicit1, implicit2 = src[i] # If self-check (1, 1), sprout children self-checks (2, 2) (3, 3) and pair children (2, 3) if implicit1 == implicit2 # If the right child is virtual, only add left child self-check if isvirtual(bvh.tree, 2 * implicit1 + 1) if self_checks dst[num_dst + 1] = (implicit1 * 2, implicit1 * 2) num_dst += 1 end else if self_checks dst[num_dst + 1] = (implicit1 * 2, implicit1 * 2) dst[num_dst + 2] = (implicit1 * 2, implicit1 * 2 + 1) dst[num_dst + 3] = (implicit1 * 2 + 1, implicit1 * 2 + 1) num_dst += 3 else dst[num_dst + 1] = (implicit1 * 2, implicit1 * 2 + 1) num_dst += 1 end end # Otherwise pair children of the two nodes else node1 = bvh.nodes[implicit1 - num_skips] node2 = bvh.nodes[implicit2 - num_skips] # If the two nodes are touching, expand BVTT with new possible contacts - i.e. pair # the nodes' children if iscontact(node1, node2) # If the right node's right child is virtual, don't add that check. Guaranteed to # always have node1 to the left of node2, hence its children will always be real if isvirtual(bvh.tree, 2 * implicit2 + 1) dst[num_dst + 1] = (implicit1 * 2, implicit2 * 2) dst[num_dst + 2] = (implicit1 * 2 + 1, implicit2 * 2) num_dst += 2 else dst[num_dst + 1] = (implicit1 * 2, implicit2 * 2) dst[num_dst + 2] = (implicit1 * 2, implicit2 * 2 + 1) dst[num_dst + 3] = (implicit1 * 2 + 1, implicit2 * 2) dst[num_dst + 4] = (implicit1 * 2 + 1, implicit2 * 2 + 1) num_dst += 4 end end end end # Known at compile-time; no return if called in multithreaded context if isnothing(num_written) return num_dst else num_written[] = num_dst return nothing end end function traverse_nodes!(bvh, src, dst, num_src, level, self_checks, num_threads) # Traverse levels above leaves => no contacts, only further BVTT sprouting # Compute number of virtual elements before this level to skip when computing the memory index virtual_nodes_level = bvh.tree.virtual_leaves >> (bvh.tree.levels - (level - 1)) virtual_nodes_before = 2 * virtual_nodes_level - count_ones(virtual_nodes_level) # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_src, num_threads, 100) if tp.num_tasks == 1 num_dst = traverse_nodes_range!( bvh, src, dst, nothing, virtual_nodes_before, self_checks, (1, num_src), ) else # Keep track of tasks launched and number of elements written by each task in their unique # memory region. The unique region is equal to 4 dst elements per src element tasks = Vector{Task}(undef, tp.num_tasks) num_written = Vector{Int}(undef, tp.num_tasks) @inbounds for i in 1:tp.num_tasks istart, iend = tp[i] tasks[i] = Threads.@spawn traverse_nodes_range!( bvh, src, view(dst, 4istart - 3:4iend), view(num_written, i), virtual_nodes_before, self_checks, (istart, iend), ) end # As tasks finish sequentially, move the new written contacts into contiguous region num_dst = 0 @inbounds for i in 1:tp.num_tasks wait(tasks[i]) task_num_written = num_written[i] # Repack written contacts by the second, third thread, etc. if i > 1 istart, iend = tp[i] for j in 1:task_num_written dst[num_dst + j] = dst[4istart - 3 + j - 1] end end num_dst += task_num_written end end num_dst end function traverse_leaves_range!( bvh, src, contacts, num_written, irange ) # Check src[irange[1]:irange[2]] and write to dst[1:num_dst]; dst should be given as a view num_dst = 0 # Number of implicit indices above leaf-level num_above = pow2(bvh.tree.levels - 1) - 1 # For each BVTT pair of nodes, check for contact @inbounds for i in irange[1]:irange[2] # Extract implicit indices of BVH leaves to test implicit1, implicit2 = src[i] iorder1 = bvh.order[implicit1 - num_above] iorder2 = bvh.order[implicit2 - num_above] leaf1 = bvh.leaves[iorder1] leaf2 = bvh.leaves[iorder2] # If two leaves are touching, save in contacts if iscontact(leaf1, leaf2) # While it's guaranteed that implicit1 < implicit2, the bvh.order may not be # ascending, so we add this comparison to output ordered contact indices contacts[num_dst + 1] = iorder1 < iorder2 ? (iorder1, iorder2) : (iorder2, iorder1) num_dst += 1 end end # Known at compile-time; no return if called in multithreaded context if isnothing(num_written) return num_dst else num_written[] = num_dst return nothing end end function traverse_leaves!(bvh, src, contacts, num_src, num_threads) # Traverse final level, only doing leaf-leaf checks # Split computation into contiguous ranges of minimum 100 elements each; if only single thread # is needed, inline call tp = TaskPartitioner(num_src, num_threads, 100) if tp.num_tasks == 1 num_contacts = traverse_leaves_range!( bvh, src, view(contacts, :), nothing, (1, num_src), ) else num_contacts = 0 # Keep track of tasks launched and number of elements written by each task in their unique # memory region. The unique region is equal to 1 dst elements per src element tasks = Vector{Task}(undef, tp.num_tasks) num_written = Vector{Int}(undef, tp.num_tasks) @inbounds for i in 1:tp.num_tasks istart, iend = tp[i] tasks[i] = Threads.@spawn traverse_leaves_range!( bvh, src, view(contacts, istart:iend), view(num_written, i), (istart, iend), ) end @inbounds for i in 1:tp.num_tasks wait(tasks[i]) task_num_written = num_written[i] # Repack written contacts by the second, third thread, etc. if i > 1 istart, iend = tp[i] for j in 1:task_num_written contacts[num_contacts + j] = contacts[istart + j - 1] end end num_contacts += task_num_written end end num_contacts end
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
code
27244
using ImplicitBVH using ImplicitBVH: BBox, BSphere using Test using Random using LinearAlgebra @testset "test_utilities" begin using ImplicitBVH: minimum2, minimum3, maximum2, maximum3, dot3, dist3sq, dist3 Random.seed!(42) for _ in 1:20 a, b, c = rand(), rand(), rand() @test minimum2(a, b) == minimum([a, b]) @test maximum2(a, b) == maximum([a, b]) @test minimum3(a, b, c) == minimum([a, b, c]) @test maximum3(a, b, c) == maximum([a, b, c]) end for _ in 1:20 x = (rand(), rand(), rand()) y = (rand(), rand(), rand()) @test dot3(x, y) ≈ dot(x, y) @test dist3sq(x, y) ≈ dot(x .- y, x .- y) @test dist3(x, y) ≈ sqrt(dot(x .- y, x .- y)) end end @testset "test_implicit_tree" begin # Perfect, filled tree # # Level Nodes # 1 1 # 2 2 3 # 3 4 5 6 7 # ------Real----- tree = ImplicitTree(4) @test tree.levels == 3 @test tree.real_leaves == 4 @test tree.virtual_leaves == 0 @test tree.real_nodes == 7 @test tree.virtual_nodes == 0 @test memory_index(tree, 1) == 1 @test memory_index(tree, 7) == 7 @test level_indices(tree, 1) == (1, 1) @test level_indices(tree, 2) == (2, 3) @test level_indices(tree, 3) == (4, 7) @test isvirtual(tree, 1) == false @test isvirtual(tree, 7) == false # Incomplete tree with virtual (v) nodes # # Level Nodes # 1 1 # 2 2 3 # 3 4 5 6 7v # 4 8 9 10 11 12 13 14v 15v # 5 16 17 18 19 20 21 22 23 24 25 26 27v 28v 29v 30v 31v # --------------------------Real----------------------------- -----------Virtual----------- tree = ImplicitTree(11) @test tree.levels == 5 @test tree.real_leaves == 11 @test tree.virtual_leaves == 5 @test tree.real_nodes == 23 @test tree.virtual_nodes == 8 @test memory_index(tree, 1) == 1 @test memory_index(tree, 8) == 7 @test memory_index(tree, 16) == 13 @test level_indices(tree, 1) == (1, 1) @test level_indices(tree, 3) == (4, 6) @test level_indices(tree, 5) == (13, 23) @test isvirtual(tree, 6) == false @test isvirtual(tree, 7) == true @test isvirtual(tree, 26) == false @test isvirtual(tree, 27) == true @test isvirtual(tree, 31) == true # Trees with different integer types @test ImplicitTree{Int32}(11).real_nodes isa Int32 @test ImplicitTree{UInt32}(11).real_nodes isa UInt32 end @testset "test_bsphere" begin Base.isapprox(a::NTuple{3, T}, b) where T = all(isapprox.(a, b)) # Planar equilateral triangle p1 = (0., 0., 0.) p2 = (1., 0., 0.) p3 = (cosd(60), sind(60), 0.) bs = BSphere{Float64}(p1, p2, p3) @test bs.x ≈ (p1 .+ p2 .+ p3) ./ 3. @test bs.r ≈ 1. / sqrt(3.) # Planar right triangle p1 = [0., 0., 0.] p2 = [0., 1., 0.] p3 = [0., 1., 1.] bs = BSphere{Float64}(p1, p2, p3) @test bs.x ≈ (0., 0.5, 0.5) @test bs.r ≈ 1. / sqrt(2.) # Points in straight line p1 = (0., 0., 0.) p2 = (1., 0., 0.) p3 = (2., 0., 0.) bs = BSphere{Float64}(p1, p2, p3) @test bs.x ≈ (1., 0., 0.) @test bs.r ≈ 1. # Other constructors BSphere{Float32}(p1, p2, p3) BSphere(p1, p2, p3) BSphere{Float32}([p1, p2, p3]) BSphere([p1, p2, p3]) BSphere(reshape([p1..., p2..., p3...], 3, 3)) # Merging two touching spheres a = BSphere((0., 0., 0.), 0.5) b = BSphere((1., 0., 0.), 0.5) c = a + b @test c.x ≈ (0.5, 0., 0.) @test c.r ≈ 1. # Merging when a is inside b a = BSphere((0.1, 0., 0.), 0.1) b = BSphere((0., 0., 0.), 0.5) c = a + b @test c.x ≈ b.x @test c.r ≈ b.r # Merging when b is inside a a = BSphere((0., 0., 0.), 0.5) b = BSphere((0.1, 0., 0.), 0.1) c = a + b @test c.x ≈ a.x @test c.r ≈ a.r # Merging for completely overlapping spheres a = BSphere((0., 0., 0.), 0.5) c = a + a @test c.x ≈ a.x @test c.r ≈ a.r a = BSphere((1e25, 1e25, 1e25), 0.5) c = a + a @test c.x ≈ a.x @test c.r ≈ a.r end @testset "test_bbox" begin # Cubically-placed points p1 = (0., 0., 0.) p2 = (1., 1., 0.) p3 = (1., 1., 1.) bb = BBox{Float64}(p1, p2, p3) @test bb.lo ≈ (0., 0., 0.) @test bb.up ≈ (1., 1., 1.) # Points in straight line p1 = [0., 0., 0.] p2 = [1., 0., 0.] p3 = [2., 0., 0.] bb = BBox{Float64}(p1, p2, p3) @test bb.lo ≈ (0., 0., 0.) @test bb.up ≈ (2., 0., 0.) # Other constructors BBox{Float32}(p1, p2, p3) BBox(p1, p2, p3) BBox{Float32}([p1, p2, p3]) BBox([p1, p2, p3]) BBox(reshape([p1..., p2..., p3...], 3, 3)) # Merging two touching boxes a = BBox((0., 0., 0.), (1., 1., 1.)) b = BBox((1., 0., 0.), (2., 1., 1.)) c = a + b @test c.lo ≈ (0., 0., 0.) @test c.up ≈ (2., 1., 1.) # Merging when a is inside b a = BBox((0.1, 0.1, 0.1), (0.2, 0.2, 0.2)) b = BBox((0., 0., 0.), (1., 1., 1.)) c = a + b @test c.lo ≈ b.lo @test c.up ≈ b.up # Merging when b is inside a a = BBox((0., 0., 0.), (1., 1., 1.)) b = BBox((0.1, 0.1, 0.1), (0.2, 0.2, 0.2)) c = a + b @test c.lo ≈ a.lo @test c.up ≈ a.up # Merging for completely overlapping boxes a = BBox((0., 0., 0.), (1., 1., 1.)) c = a + a @test c.lo ≈ a.lo @test c.up ≈ a.up a = BBox((1e-25, 1e-25, 1e-25), (1e25, 1e25, 1e25)) c = a + a @test c.lo ≈ a.lo @test c.up ≈ a.up end @testset "test_morton" begin # Single numbers x = UInt16(0b111) m = ImplicitBVH.morton_split3(x) @test m == 0b1001001 x = UInt32(0b111) m = ImplicitBVH.morton_split3(x) @test m == 0b1001001 x = UInt64(0b111) m = ImplicitBVH.morton_split3(x) @test m == 0b1001001 # Random bounding volumes Random.seed!(42) # Extrema computed at different precisions bv = map(BSphere{Float16}, [10 .* rand(3, 3) for _ in 1:100]) mins, maxs = ImplicitBVH.bounding_volumes_extrema(bv) @test all([ImplicitBVH.center(b)[1] > mins[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] > mins[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] > mins[3] for b in bv]) @test all([ImplicitBVH.center(b)[1] < maxs[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] < maxs[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] < maxs[3] for b in bv]) bv = map(BSphere{Float32}, [1000 .* rand(3, 3) for _ in 1:100]) mins, maxs = ImplicitBVH.bounding_volumes_extrema(bv) @test all([ImplicitBVH.center(b)[1] > mins[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] > mins[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] > mins[3] for b in bv]) @test all([ImplicitBVH.center(b)[1] < maxs[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] < maxs[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] < maxs[3] for b in bv]) bv = map(BSphere{Float64}, [1000 .* rand(3, 3) for _ in 1:100]) mins, maxs = ImplicitBVH.bounding_volumes_extrema(bv) @test all([ImplicitBVH.center(b)[1] > mins[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] > mins[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] > mins[3] for b in bv]) @test all([ImplicitBVH.center(b)[1] < maxs[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] < maxs[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] < maxs[3] for b in bv]) # Extrema computed for degenerate inputs bv = [BSphere((0., 0., 0.), 1.)] mins, maxs = ImplicitBVH.bounding_volumes_extrema(bv) @test all([ImplicitBVH.center(b)[1] > mins[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] > mins[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] > mins[3] for b in bv]) @test all([ImplicitBVH.center(b)[1] < maxs[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] < maxs[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] < maxs[3] for b in bv]) bv = [BSphere((1000., 0., 0.), 1.), BSphere((1000., 0., 0.), 1.)] mins, maxs = ImplicitBVH.bounding_volumes_extrema(bv) @test all([ImplicitBVH.center(b)[1] > mins[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] > mins[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] > mins[3] for b in bv]) @test all([ImplicitBVH.center(b)[1] < maxs[1] for b in bv]) @test all([ImplicitBVH.center(b)[2] < maxs[2] for b in bv]) @test all([ImplicitBVH.center(b)[3] < maxs[3] for b in bv]) # Different morton code sizes bv = map(BSphere, [rand(3, 3) for _ in 1:10]) ImplicitBVH.morton_encode(bv, UInt16) ImplicitBVH.morton_encode(bv, UInt32) ImplicitBVH.morton_encode(bv, UInt64) ImplicitBVH.morton_encode(bv) bv = map(BBox, [rand(3, 3) for _ in 1:10]) ImplicitBVH.morton_encode(bv, UInt16) ImplicitBVH.morton_encode(bv, UInt32) ImplicitBVH.morton_encode(bv, UInt64) ImplicitBVH.morton_encode(bv) bv = map(BSphere{Float16}, [rand(3, 3) for _ in 1:10]) ImplicitBVH.morton_encode(bv, UInt16) ImplicitBVH.morton_encode(bv, UInt32) # ImplicitBVH.morton_encode(bv, UInt64) # Range of UInt64 is too high compared to Float16 # ImplicitBVH.morton_encode(bv) bv = map(BBox{Float16}, [rand(3, 3) for _ in 1:10]) ImplicitBVH.morton_encode(bv, UInt16) ImplicitBVH.morton_encode(bv, UInt32) # ImplicitBVH.morton_encode(bv, UInt64) # Range of UInt64 is too high compared to Float16 # ImplicitBVH.morton_encode(bv) bv = map(BSphere{Float32}, [rand(3, 3) for _ in 1:10]) ImplicitBVH.morton_encode(bv, UInt16) ImplicitBVH.morton_encode(bv, UInt32) ImplicitBVH.morton_encode(bv, UInt64) ImplicitBVH.morton_encode(bv) bv = map(BBox{Float32}, [rand(3, 3) for _ in 1:10]) ImplicitBVH.morton_encode(bv, UInt16) ImplicitBVH.morton_encode(bv, UInt32) ImplicitBVH.morton_encode(bv, UInt64) ImplicitBVH.morton_encode(bv) # Degenerate inputs a = BSphere((0., 0., 0.), 0.5) b = BSphere((1., 0., 0.), 0.1) ImplicitBVH.morton_encode([a, b], UInt32) ImplicitBVH.morton_encode([a, a], UInt32) ImplicitBVH.morton_encode([a], UInt32) end @testset "bvh_single_bsphere_small_ordered" begin # Simple, ordered bounding spheres traversal test bvs = [ BSphere([0., 0, 0], 0.5), BSphere([0., 0, 1], 0.6), BSphere([0., 0, 2], 0.5), BSphere([0., 0, 3], 0.4), BSphere([0., 0, 4], 0.6), ] # Build the following ImplicitBVH from 5 bounding volumes: # # Nodes & Leaves Tree Level # 1 1 # 2 3 2 # 4 5 6 7v 3 # 8 9 10 11 12 13v 14v 15v 4 bvh = BVH(bvs) @test length(bvh.nodes) == 6 # Test the default start levels @test default_start_level(bvh) == default_start_level(length(bvs)) # Level 3 @test bvh.nodes[4].x ≈ (bvs[1] + bvs[2]).x # First two BVs are paired @test bvh.nodes[5].x ≈ (bvs[3] + bvs[4]).x # Next two BVs are paired @test bvh.nodes[6].x ≈ bvs[5].x # Last BV has no pair # Level 2 @test bvh.nodes[2].x ≈ ((bvs[1] + bvs[2]) + (bvs[3] + bvs[4])).x @test bvh.nodes[3].x ≈ bvs[5].x # Root @test bvh.nodes[1].x ≈ ((bvs[1] + bvs[2]) + (bvs[3] + bvs[4]) + bvs[5]).x # Find contacting pairs traversal = traverse(bvh) @test length(traversal.contacts) == 3 @test (4, 5) in traversal.contacts @test (1, 2) in traversal.contacts @test (2, 3) in traversal.contacts # Build the same BVH with BBox nodes leaf = BBox{Float64} bvh = BVH(bvs, leaf) @test length(bvh.nodes) == 6 # Level 3 center = ImplicitBVH.center @test center(bvh.nodes[4]) ≈ center(leaf(bvs[1], bvs[2])) # First two BVs are paired @test center(bvh.nodes[5]) ≈ center(leaf(bvs[3], bvs[4])) # Next two BVs are paired @test center(bvh.nodes[6]) ≈ center(bvs[5]) # Last BV has no pair # Level 2 @test center(bvh.nodes[2]) ≈ center(leaf(bvs[1], bvs[2]) + leaf(bvs[3], bvs[4])) @test center(bvh.nodes[3]) ≈ center(bvs[5]) # Root @test center(bvh.nodes[1]) ≈ center(leaf(bvs[1], bvs[2]) + leaf(bvs[3], bvs[4]) + leaf(bvs[5])) # Find contacting pairs traversal = traverse(bvh) @test length(traversal.contacts) == 3 @test (4, 5) in traversal.contacts @test (1, 2) in traversal.contacts @test (2, 3) in traversal.contacts end @testset "bvh_single_bbox_small_ordered" begin # Simple, ordered bounding box traversal test bvs = [ BBox(BSphere([0., 0, 0], 0.5)), BBox(BSphere([0., 0, 1], 0.6)), BBox(BSphere([0., 0, 2], 0.5)), BBox(BSphere([0., 0, 3], 0.4)), BBox(BSphere([0., 0, 4], 0.6)), ] # Build the following ImplicitBVH from 5 bounding volumes: # # Nodes & Leaves Tree Level # 1 1 # 2 3 2 # 4 5 6 7v 3 # 8 9 10 11 12 13v 14v 15v 4 bvh = BVH(bvs) @test length(bvh.nodes) == 6 # Test the default start levels @test default_start_level(bvh) == default_start_level(length(bvs)) # Level 3 center = ImplicitBVH.center @test center(bvh.nodes[4]) ≈ center(bvs[1] + bvs[2]) # First two BVs are paired @test center(bvh.nodes[5]) ≈ center(bvs[3] + bvs[4]) # Next two BVs are paired @test center(bvh.nodes[6]) ≈ center(bvs[5]) # Last BV has no pair # Level 2 @test center(bvh.nodes[2]) ≈ center((bvs[1] + bvs[2]) + (bvs[3] + bvs[4])) @test center(bvh.nodes[3]) ≈ center(bvs[5]) # Root @test center(bvh.nodes[1]) ≈ center((bvs[1] + bvs[2]) + (bvs[3] + bvs[4]) + bvs[5]) # Find contacting pairs traversal = traverse(bvh) @test length(traversal.contacts) == 3 @test (4, 5) in traversal.contacts @test (1, 2) in traversal.contacts @test (2, 3) in traversal.contacts end @testset "bvh_single_bsphere_small_unordered" begin # Bounding spheres traversal test with unordered spheres bvs = [ BSphere([0., 0, 1], 0.6), BSphere([0., 0, 2], 0.5), BSphere([0., 0, 0], 0.5), BSphere([0., 0, 4], 0.6), BSphere([0., 0, 3], 0.4), ] # Build the following ImplicitBVH from 5 bounding volumes: # # Nodes & Leaves Tree Level # 1 1 # 2 3 2 # 4 5 6 7v 3 # 8 9 10 11 12 13v 14v 15v 4 bvh = BVH(bvs) @test length(bvh.nodes) == 6 # Test the default start levels @test default_start_level(bvh) == default_start_level(length(bvs)) # Level 3 @test bvh.nodes[4].x ≈ (bvs[3] + bvs[1]).x # First two BVs are paired @test bvh.nodes[5].x ≈ (bvs[2] + bvs[5]).x # Next two BVs are paired @test bvh.nodes[6].x ≈ bvs[4].x # Last BV has no pair # Level 2 @test bvh.nodes[2].x ≈ ((bvs[3] + bvs[1]) + (bvs[2] + bvs[5])).x @test bvh.nodes[3].x ≈ bvs[4].x # Root @test bvh.nodes[1].x ≈ ((bvs[3] + bvs[1]) + (bvs[2] + bvs[5]) + bvs[4]).x # Find contacting pairs traversal = traverse(bvh) @test length(traversal.contacts) == 3 @test (4, 5) in traversal.contacts @test (1, 3) in traversal.contacts @test (1, 2) in traversal.contacts # Build the same BVH with BBox nodes leaf = BBox{Float64} bvh = BVH(bvs, leaf) @test length(bvh.nodes) == 6 # Level 3 center = ImplicitBVH.center @test center(bvh.nodes[4]) ≈ center(leaf(bvs[3], bvs[1])) # First two BVs are paired @test center(bvh.nodes[5]) ≈ center(leaf(bvs[2], bvs[5])) # Next two BVs are paired @test center(bvh.nodes[6]) ≈ center(bvs[4]) # Last BV has no pair # Level 2 @test center(bvh.nodes[2]) ≈ center(leaf(bvs[3], bvs[1]) + leaf(bvs[2], bvs[5])) @test center(bvh.nodes[3]) ≈ center(bvs[4]) # Root @test center(bvh.nodes[1]) ≈ center(leaf(bvs[3], bvs[1]) + leaf(bvs[2], bvs[5]) + leaf(bvs[4])) # Find contacting pairs traversal = traverse(bvh) @test length(traversal.contacts) == 3 @test (4, 5) in traversal.contacts @test (1, 3) in traversal.contacts @test (1, 2) in traversal.contacts end @testset "bvh_single_bbox_small_unordered" begin # Bounding spheres traversal test with unordered spheres bvs = [ BBox(BSphere([0., 0, 1], 0.6)), BBox(BSphere([0., 0, 2], 0.5)), BBox(BSphere([0., 0, 0], 0.5)), BBox(BSphere([0., 0, 4], 0.6)), BBox(BSphere([0., 0, 3], 0.4)), ] # Build the following ImplicitBVH from 5 bounding volumes: # # Nodes & Leaves Tree Level # 1 1 # 2 3 2 # 4 5 6 7v 3 # 8 9 10 11 12 13v 14v 15v 4 bvh = BVH(bvs) @test length(bvh.nodes) == 6 # Test the default start levels @test default_start_level(bvh) == default_start_level(length(bvs)) # Level 3 center = ImplicitBVH.center @test center(bvh.nodes[4]) ≈ center(bvs[3] + bvs[1]) # First two BVs are paired @test center(bvh.nodes[5]) ≈ center(bvs[2] + bvs[5]) # Next two BVs are paired @test center(bvh.nodes[6]) ≈ center(bvs[4]) # Last BV has no pair # Level 2 @test center(bvh.nodes[2]) ≈ center((bvs[3] + bvs[1]) + (bvs[2] + bvs[5])) @test center(bvh.nodes[3]) ≈ center(bvs[4]) # Root @test center(bvh.nodes[1]) ≈ center((bvs[3] + bvs[1]) + (bvs[2] + bvs[5]) + bvs[4]) # Find contacting pairs traversal = traverse(bvh) @test length(traversal.contacts) == 3 @test (4, 5) in traversal.contacts @test (1, 3) in traversal.contacts @test (1, 2) in traversal.contacts end @testset "bvh_single_randomised" begin # Random bounding volumes of different densities; BSphere leaves, BSphere nodes Random.seed!(42) for num_entities in 1:11:200 # Test different starting levels tree = ImplicitTree(num_entities) for start_level in 1:tree.levels bvs = map(BSphere, [6 * rand(3) .+ rand(3, 3) for _ in 1:num_entities]) # Brute force contact detection brute_contacts = ImplicitBVH.IndexPair[] for i in 1:length(bvs) for j in i + 1:length(bvs) if ImplicitBVH.iscontact(bvs[i], bvs[j]) push!(brute_contacts, (i, j)) end end end # ImplicitBVH-based contact detection bvh = BVH(bvs) traversal = traverse(bvh, start_level) bvh_contacts = traversal.contacts # Test the default start levels @test default_start_level(bvh) == default_start_level(length(bvs)) # Ensure ImplicitBVH finds same contacts as checking all possible pairs @test length(brute_contacts) == length(bvh_contacts) @test all(brute_contact in bvh_contacts for brute_contact in brute_contacts) end end # Random bounding volumes of different densities; BSphere leaves, BBox nodes Random.seed!(42) for num_entities in 1:11:200 # Test different starting levels tree = ImplicitTree(num_entities) for start_level in 1:tree.levels bvs = map(BSphere, [6 * rand(3) .+ rand(3, 3) for _ in 1:num_entities]) # Brute force contact detection brute_contacts = ImplicitBVH.IndexPair[] for i in 1:length(bvs) for j in i + 1:length(bvs) if ImplicitBVH.iscontact(bvs[i], bvs[j]) push!(brute_contacts, (i, j)) end end end # ImplicitBVH-based contact detection bvh = BVH(bvs, BBox{Float64}) traversal = traverse(bvh, start_level) bvh_contacts = traversal.contacts # Test the default start levels @test default_start_level(bvh) == default_start_level(length(bvs)) # Ensure ImplicitBVH finds same contacts as checking all possible pairs @test length(brute_contacts) == length(bvh_contacts) @test all(brute_contact in bvh_contacts for brute_contact in brute_contacts) end end # Testing different settings Random.seed!(42) bvs = map(BSphere, [6 * rand(3) .+ rand(3, 3) for _ in 1:100]) bvh = BVH(bvs) traversal = traverse(bvh) BVH(bvs, BSphere{Float64}) BVH(bvs, BBox{Float64}) BVH(bvs, BBox{Float64}, UInt32) BVH(bvs, BBox{Float64}, UInt32, 3) BVH(bvs, BBox{Float64}, UInt32, 0.0) BVH(bvs, BBox{Float64}, UInt32, 0.5) BVH(bvs, BBox{Float64}, UInt32, 1.0) traverse(bvh, 3) traverse(bvh, 3, traversal) end @testset "bvh_pair_equivalent_randomised" begin # Random bounding volumes of different densities; BSphere leaves, BSphere nodes Random.seed!(42) for num_entities in 1:11:200 # Test different starting levels tree = ImplicitTree(num_entities) for start_level1 in 1:tree.levels, start_level2 in 1:tree.levels bvs = map(BSphere, [6 * rand(3) .+ rand(3, 3) for _ in 1:num_entities]) bvh = BVH(bvs) # Test the default start levels @test default_start_level(bvh) == default_start_level(length(bvs)) # First traverse the BVH normally, then as if we had two different BVHs contacts1 = traverse(bvh, start_level1).contacts contacts2 = traverse(bvh, bvh, start_level1, start_level2).contacts # The second one should have the same contacts as contacts1, plus contacts between the # same BVs and reverse order; e.g. if contacts1=[(1, 2), (2, 3)], then # contacts2=[(1, 1), (2, 2), (3, 3), (1, 2), (2, 1), (2, 3), (3, 2)]. Check this. @test all((i, i) in contacts2 for i in 1:num_entities) contacts2 = [(i, j) for (i, j) in contacts2 if i != j] @test all((j, i) in contacts2 for (i, j) in contacts2) contacts2 = [(i, j) for (i, j) in contacts2 if i < j] sort!(contacts1) sort!(contacts2) @test contacts1 == contacts2 end end # Random bounding volumes of different densities; BSphere leaves, BBox nodes Random.seed!(42) for num_entities in 1:11:200 # Test different starting levels tree = ImplicitTree(num_entities) for start_level1 in 1:tree.levels, start_level2 in 1:tree.levels bvs = map(BSphere, [6 * rand(3) .+ rand(3, 3) for _ in 1:num_entities]) bvh = BVH(bvs, BBox{Float64}) # Test the default start levels @test default_start_level(bvh) == default_start_level(length(bvs)) # First traverse the BVH normally, then as if we had two different BVHs contacts1 = traverse(bvh, start_level1).contacts contacts2 = traverse(bvh, bvh, start_level1, start_level2).contacts # The second one should have the same contacts as contacts1, plus contacts between the # same BVs and reverse order; e.g. if contacts1=[(1, 2), (2, 3)], then # contacts2=[(1, 1), (2, 2), (3, 3), (1, 2), (2, 1), (2, 3), (3, 2)]. Check this. @test all((i, i) in contacts2 for i in 1:num_entities) contacts2 = [(i, j) for (i, j) in contacts2 if i != j] @test all((j, i) in contacts2 for (i, j) in contacts2) contacts2 = [(i, j) for (i, j) in contacts2 if i < j] sort!(contacts1) sort!(contacts2) @test contacts1 == contacts2 end end end @testset "bvh_pair_randomised" begin # Random bounding volumes of different densities; BSphere leaves, BSphere nodes Random.seed!(42) for num_entities1 in 1:21:200, num_entities2 in 1:21:200 # Test different starting levels tree1 = ImplicitTree(num_entities1) tree2 = ImplicitTree(num_entities2) for start_level1 in 1:tree1.levels, start_level2 in 1:tree2.levels bvs1 = map(BSphere, [6 * rand(3) .+ rand(3, 3) for _ in 1:num_entities1]) bvs2 = map(BSphere, [6 * rand(3) .+ rand(3, 3) for _ in 1:num_entities2]) # Brute force contact detection brute_contacts = ImplicitBVH.IndexPair[] for i in 1:length(bvs1) for j in 1:length(bvs2) if ImplicitBVH.iscontact(bvs1[i], bvs2[j]) push!(brute_contacts, (i, j)) end end end # ImplicitBVH-based contact detection bvh1 = BVH(bvs1) bvh2 = BVH(bvs2) traversal = traverse(bvh1, bvh2, start_level1, start_level2) bvh_contacts = traversal.contacts # Ensure ImplicitBVH finds same contacts as checking all possible pairs @test length(brute_contacts) == length(bvh_contacts) @test all(brute_contact in bvh_contacts for brute_contact in brute_contacts) end end # Random bounding volumes of different densities; BSphere leaves, BBox nodes Random.seed!(42) for num_entities1 in 1:21:200, num_entities2 in 1:21:200 # Test different starting levels tree1 = ImplicitTree(num_entities1) tree2 = ImplicitTree(num_entities2) min_levels = tree1.levels < tree2.levels ? tree1.levels : tree2.levels for start_level in 1:min_levels - 1 bvs1 = map(BSphere, [6 * rand(3) .+ rand(3, 3) for _ in 1:num_entities1]) bvs2 = map(BSphere, [6 * rand(3) .+ rand(3, 3) for _ in 1:num_entities2]) # Brute force contact detection brute_contacts = ImplicitBVH.IndexPair[] for i in 1:length(bvs1) for j in 1:length(bvs2) if ImplicitBVH.iscontact(bvs1[i], bvs2[j]) push!(brute_contacts, (i, j)) end end end # ImplicitBVH-based contact detection bvh1 = BVH(bvs1, BBox{Float64}) bvh2 = BVH(bvs2, BBox{Float64}) traversal = traverse(bvh1, bvh2, start_level) bvh_contacts = traversal.contacts # Ensure ImplicitBVH finds same contacts as checking all possible pairs @test length(brute_contacts) == length(bvh_contacts) @test all(brute_contact in bvh_contacts for brute_contact in brute_contacts) end end end
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
docs
6309
[![ImplicitBVH](https://github.com/StellaOrg/ImplicitBVH.jl/blob/main/docs/src/static/bunny.png?raw=true)](https://stellaorg.github.io/ImplicitBVH.jl/) [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://stellaorg.github.io/ImplicitBVH.jl/stable) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://stellaorg.github.io/ImplicitBVH.jl/dev) # ImplicitBVH.jl *High-Performance Parallel Bounding Volume Hierarchy for Collision Detection* It uses an implicit bounding volume hierarchy constructed from an iterable of some geometric primitives' (e.g. triangles in a mesh) bounding volumes forming the `ImplicitTree` leaves. The leaves and merged nodes above them can have different types - e.g. `BSphere{Float64}` leaves merged into larger `BBox{Float64}`. The initial geometric primitives are sorted according to their Morton-encoded coordinates; the unsigned integer type used for the Morton encoding can be chosen between `UInt16`, `UInt32` and `UInt64`. Finally, the tree can be incompletely-built up to a given `built_level` and later start contact detection downwards from this level. ## Examples Simple usage with bounding spheres and default 64-bit types: ```julia using ImplicitBVH using ImplicitBVH: BBox, BSphere # Generate some simple bounding spheres bounding_spheres = [ BSphere([0., 0., 0.], 0.5), BSphere([0., 0., 1.], 0.6), BSphere([0., 0., 2.], 0.5), BSphere([0., 0., 3.], 0.4), BSphere([0., 0., 4.], 0.6), ] # Build BVH bvh = BVH(bounding_spheres) # Traverse BVH for contact detection traversal = traverse(bvh) @show traversal.contacts # output traversal.contacts = [(1, 2), (2, 3), (4, 5)] ``` Using `Float32` bounding spheres for leaves, `Float32` bounding boxes for nodes above, and `UInt32` Morton codes: ```julia using ImplicitBVH using ImplicitBVH: BBox, BSphere # Generate some simple bounding spheres bounding_spheres = [ BSphere{Float32}([0., 0., 0.], 0.5), BSphere{Float32}([0., 0., 1.], 0.6), BSphere{Float32}([0., 0., 2.], 0.5), BSphere{Float32}([0., 0., 3.], 0.4), BSphere{Float32}([0., 0., 4.], 0.6), ] # Build BVH bvh = BVH(bounding_spheres, BBox{Float32}, UInt32) # Traverse BVH for contact detection traversal = traverse(bvh) @show traversal.contacts # output traversal.contacts = [(1, 2), (2, 3), (4, 5)] ``` Build BVH up to level 2 and start traversing down from level 3, reusing the previous traversal cache: ```julia bvh = BVH(bounding_spheres, BBox{Float32}, UInt32, 2) traversal = traverse(bvh, 3, traversal) ``` Compute contacts between two different BVH trees (e.g. two different robotic parts): ```julia using ImplicitBVH using ImplicitBVH: BBox, BSphere # Generate some simple bounding spheres (will be BVH leaves) bounding_spheres1 = [ BSphere{Float32}([0., 0., 0.], 0.5), BSphere{Float32}([0., 0., 3.], 0.4), ] bounding_spheres2 = [ BSphere{Float32}([0., 0., 1.], 0.6), BSphere{Float32}([0., 0., 2.], 0.5), BSphere{Float32}([0., 0., 4.], 0.6), ] # Build BVHs using bounding boxes for nodes bvh1 = BVH(bounding_spheres1, BBox{Float32}, UInt32) bvh2 = BVH(bounding_spheres2, BBox{Float32}, UInt32) # Traverse BVH for contact detection traversal = traverse( bvh1, bvh2, default_start_level(bvh1), default_start_level(bvh2), # previous_traversal_cache, # num_threads=4, ) ``` Check out the `benchmark` folder for an example traversing an STL model. # Implicit Bounding Volume Hierarchy The main idea behind the ImplicitBVH is the use of an implicit perfect binary tree constructed from some bounding volumes. If we had, say, 5 objects to construct the BVH from, it would form an incomplete binary tree as below: ``` Implicit tree from 5 bounding volumes - i.e. the real leaves: Tree Level Nodes & Leaves Build Up Traverse Down 1 1 Ʌ | 2 2 3 | | 3 4 5 6 7v | | 4 8 9 10 11 12 13v 14v 15v | V -------Real------- ---Virtual--- ``` We do not need to store the "virtual" nodes in memory; rather, we can compute the number of virtual nodes we need to skip to get to a given node index, following the fantastic ideas from [1]. # Performance As contact detection is one of the most computationally-intensive parts of physical simulation and computer vision applications, this implementation has been optimised for maximum performance and scalability: - Computing bounding volumes is optimised for triangles, e.g. constructing 249,882 `BSphere{Float64}` on a single thread takes 4.47 ms on my Mac M1. The construction itself has zero allocations; all computation can be done in parallel in user code. - Building a complete bounding volume hierarchy from the 249,882 triangles of [`xyzrgb_dragon.obj`](https://github.com/alecjacobson/common-3d-test-models/blob/master/data/xyzrgb_dragon.obj) takes 11.83 ms single-threaded. The sorting step is the bottleneck, so multi-threading the Morton encoding and BVH up-building does not significantly improve the runtime; waiting on a multi-threaded sorter. - Traversing the same 249,882 `BSphere{Float64}` for the triangles (aggregated into `BBox{Float64}` parents) takes 136.38 ms single-threaded and 43.16 ms with 4 threads, at 79% strong scaling. Only fundamental Julia types are used - e.g. `struct`, `Tuple`, `UInt`, `Float64` - which can be straightforwardly inlined, unrolled and fused by the compiler. These types are also straightforward to transpile to accelerators via [`KernelAbstractions.jl`](https://github.com/JuliaGPU/KernelAbstractions.jl) such as `CUDA`, `AMDGPU`, `oneAPI`, `Apple Metal`. # Roadmap - Use `KernelAbstractions.jl` kernels to build and traverse the BVH; I think we just need a performant KA `sort!` function, the rest is straightforward. # References The implicit tree formulation (genius idea!) which forms the core of the BVH structure originally appeared in the following paper: > [1] Chitalu FM, Dubach C, Komura T. Binary Ostensibly‐Implicit Trees for Fast Collision Detection. InComputer Graphics Forum 2020 May (Vol. 39, No. 2, pp. 509-521). # License `ImplicitBVH.jl` is MIT-licensed. Enjoy.
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
docs
684
# Running Benchmarks / Examples First, download the [`xyzrgb_dragon.obj`](https://github.com/alecjacobson/common-3d-test-models/blob/master/data/xyzrgb_dragon.obj) into this directory. You can run the following benchmarks, which then generate [PProf](https://github.com/JuliaPerf/PProf.jl) profiling archives: ```bash bvh_build.jl => bvh_build.pb.gz bvh_contact.jl => bvh_contact.pb.gz bvh_volumes.jl => bvh_volumes.pb.gz morton.jl => morton.pb.gz ``` You can open each profile using the `view_profile.jl` script. Finally, you can plot the bounding boxes around a given mesh via [GLMakie](https://docs.makie.org/stable/) using the `plotting.jl` script.
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
docs
145
# Bounding Volumes ```@docs ImplicitBVH.BBox ImplicitBVH.BSphere ``` ## Query Functions ```@docs ImplicitBVH.iscontact ImplicitBVH.center ```
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
docs
87
# Implicit Binary Tree ```@docs ImplicitTree memory_index level_indices isvirtual ```
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
docs
171
# ImplicitBVH.jl Documentation ## BVH Construction & Traversal ```@docs BVH traverse BVHTraversal default_start_level ImplicitBVH.IndexPair ``` ## Index ```@index ```
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
docs
267
# Morton Encoding ```@docs ImplicitBVH.MortonUnsigned ImplicitBVH.morton_encode ImplicitBVH.morton_encode! ImplicitBVH.morton_encode_single ImplicitBVH.morton_scaling ImplicitBVH.morton_split3 ImplicitBVH.bounding_volumes_extrema ImplicitBVH.relative_precision ```
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.4.1
cd2e6d23b1e666909b10821a69313e32193a8d11
docs
54
# Utilities ```@docs ImplicitBVH.TaskPartitioner ```
ImplicitBVH
https://github.com/StellaOrg/ImplicitBVH.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
403
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE __precompile__() module BoundingSphere if VERSION < v"0.7-" else using Random using LinearAlgebra using Statistics: middle end include("api.jl") include("boundary.jl") include("geometry.jl") include("welzl.jl") include("ritter.jl") include("util.jl") end # module
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
1849
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE export boundingsphere export WelzlMTF export WelzlPivot export Ritter abstract type BoundingSphereAlg end """ WelzlMTF() Welzl algorithm with move to front heuristic. See Algorithm I in https://people.inf.ethz.ch/gaertner/subdir/texts/own_work/esa99_final.pdf. In almost all situations it is better to use [`WelzlPivot`](@ref) instead. ## Pros * Fast for small examples ## Cons * Prone to numerical stability issues """ struct WelzlMTF <: BoundingSphereAlg end """ WelzlPivot(;max_iterations=1000) Welzl algorithm with pivoting. See Algorithm II in https://people.inf.ethz.ch/gaertner/subdir/texts/own_work/esa99_final.pdf. ## Pros * Fast ## Cons * In very rare cases can be numerically instable """ struct WelzlPivot <: BoundingSphereAlg max_iterations::Int end function WelzlPivot(;max_iterations=1000) WelzlPivot(max_iterations) end """ center, radius = boundingsphere(pts [, algorithm=WelzlPivot()]) Compute the smallest sphere that contains each point in `pts`. # Arguments * pts: A list of points. Points should be vectors with floating point entries. * algorithm: An optional algorithm to do the computation. See names(BoundingSphere) to get """ function boundingsphere end function boundingsphere!(pts, alg::WelzlMTF=WelzlMTF()) bdry = create_boundary_device(pts, alg) ball, support_count = welzl!(pts, bdry, alg) r = radius(ball) c = center(ball) c, r end function boundingsphere!(pts, alg::BoundingSphereAlg) bdry = create_boundary_device(pts, alg) ball = welzl!(pts, bdry, alg) r = radius(ball) c = center(ball) c, r end @noinline function boundingsphere(pts, alg::BoundingSphereAlg=WelzlMTF()) boundingsphere!(copy(pts), alg) end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
3516
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE struct ProjectorStack{P <: AbstractVector} # matrix that is decomposed into Σ v_i ⊗ v_i* for # an orthonormal system v_i vs::Vector{P} end function Base.push!(p::ProjectorStack, v) @assert norm(v) ≈ 1 push!(p.vs, v) p end function Base.pop!(p::ProjectorStack) pop!(p.vs) p end function Base.:*(p::ProjectorStack, v::AbstractVector) ret = zero(v) for vi in p.vs ret = ret + vi*dot(vi, v) end ret end """ BoundaryDevice Finds unique spheres determined by prescribed affine independent boundary points. In the welzl algorithm this problem needs to be solved in series, where points are pushed and popped from to the boundary. Subtypes must implement the following interface: * push_if_stable!(device, pt)::Bool : * pop!(device): Remove last point from the boundary. * get_ball(device)::SqBall : Get the last ball from the device. * length(device)::Int : Get the current count of boundary points * ismaxlength(device)::Bool: Check if there are dim+1 boundary points in the device """ abstract type BoundaryDevice end Base.isempty(b::BoundaryDevice) = length(b) == 0 """ GaertnerBdry BoundaryDevice that corresponds to M_B in Section 4 of Gaertners paper. See also: [BoundaryDevice](@ref) """ mutable struct GaertnerBdry{P<:AbstractVector, F<:AbstractFloat} <: BoundaryDevice centers::Vector{P} square_radii::Vector{F} # projection onto of affine space spanned by points # shifted such that first point becomes origin projector::ProjectorStack{P} empty_center::P # center of ball spanned by empty boundary end function create_boundary_device(pts, alg) P = eltype(pts) F = eltype(P) projector = ProjectorStack(P[]) centers = P[] square_radii = F[] empty_center = F(NaN)*first(pts) GaertnerBdry(centers, square_radii, projector, empty_center) end function Base.length(b::GaertnerBdry) @assert length(b.centers) == length(b.square_radii) return length(b.centers) end function push_if_stable!(b::GaertnerBdry, pt) if isempty(b) push!(b.square_radii, zero(eltype(pt))) push!(b.centers, pt) dim = length(pt) return true end q0 = first(b.centers) center = b.centers[end] C = center - q0 r2 = b.square_radii[end] Qm = pt - q0 M = b.projector Qm_bar = M*Qm residue = Qm - Qm_bar e = sqdist(Qm, C) - r2 z = 2*sqnorm(residue) # TODO should we use norm(residue) instead of z here? # seems more intuitive, OTOH z is used in the paper tol = eps(eltype(pt)) * max(r2, one(r2)) @assert !isnan(tol) isstable = abs(z) > tol if isstable center_new = center + (e/z) * residue r2new = r2 + (e^2)/(2z) push!(b.projector, residue / norm(residue)) push!(b.centers, center_new) push!(b.square_radii, r2new) end isstable end function Base.pop!(b::GaertnerBdry) n = length(b) pop!(b.centers) pop!(b.square_radii) if n >= 2 pop!(b.projector) end b end function get_ball(b::GaertnerBdry) if isempty(b) c = b.empty_center r2 = zero(eltype(c)) else c = b.centers[end] r2 = b.square_radii[end] end SqBall(c,r2) end function ismaxlength(b::GaertnerBdry) dim = length(b.empty_center) length(b) == dim + 1 end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
717
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE struct SqBall{P,F} center::P sqradius::F end function isinside(pt, ball::SqBall; atol=0, rtol=0) r2 = sqdist(pt, center(ball)) R2 = sqradius(ball) r2 <= R2 || isapprox(r2, R2;atol=atol^2,rtol=rtol^2) end function allinside(pts, ball; kw...) for pt in pts isinside(pt, ball; kw...) || return false end true end center(b::SqBall) = b.center radius(b::SqBall) = sqrt(b.sqradius) sqradius(b::SqBall) = b.sqradius dist(p1,p2) = norm(p1-p2) sqdist(p1::AbstractVector, p2::AbstractVector) = sqnorm(p1-p2) sqdist(x,y) = sqdist(y,x) sqnorm(p) = sum(abs2,p)
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
1056
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE """ Ritter() ## Pros * extremly fast * simple ## Cons * Very inaccurate. """ struct Ritter <: BoundingSphereAlg end function max_distance_point(pts, pt1) pt_best = first(pts) d2_best = sqdist(pt_best, pt1) for pt in pts d2 = sqdist(pt, pt1) if d2 > d2_best pt_best = pt d2_best = d2 end end pt_best end function sqsphere_two_points(pt1,pt2) c = map(middle, pt1, pt2) r2 = sqdist(pt1, pt2) / 4 c, r2 end @noinline function ritter(pts) pt1 = first(pts) pt2 = max_distance_point(pts, pt1) c, r2 = sqsphere_two_points(pt1, pt2) for pt in pts if sqdist(pt, c) > r2 direction = (c - pt) / norm(c - pt) r = sqrt(r2) pt_op = c + direction * r c,r2 = sqsphere_two_points(pt, pt_op) end end r = sqrt(r2) c, r end boundingsphere(pts, alg::Ritter) = ritter(pts)
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
505
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE function prefix(pts, i) inds = eachindex(pts) index = first(inds) : i view(pts, index) end function move_to_front!(pts, i) @assert i in eachindex(pts) pt = pts[i] for j in eachindex(pts) qt = pts[j] pts[j] = pt pt = qt j == i && break end pts end function leq_approx(x,y;kw...) x < y || isapprox(x,y;kw...) end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
2027
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE function welzl!(pts, bdry::BoundaryDevice, alg::WelzlMTF) bdry_len = length(bdry) support_count = 0 ball = get_ball(bdry) if ismaxlength(bdry) support_count = 0 return ball, support_count end for i in eachindex(pts) pt = pts[i] if !isinside(pt, ball) pts_i = prefix(pts, i-1) isstable = push_if_stable!(bdry, pt) if isstable ball, s = welzl!(pts_i, bdry, alg) @assert isinside(pt, ball, rtol=1e-2, atol=1e-10) pop!(bdry) move_to_front!(pts, i) support_count = s + 1 end end end @assert bdry_len == length(bdry) ball, support_count end function find_max_excess(ball, pts, k1) T = eltype(first(pts)) e_max = T(-Inf) k_max = k1 -1 for k in k1:length(pts) pt = pts[k] e = sqdist(pt, center(ball)) - sqradius(ball) if e > e_max e_max = e k_max = k end end e_max, k_max end function welzl!(pts, bdry, alg::WelzlPivot) t = 1 alg_inner = WelzlMTF() @assert isempty(bdry) ball, s = welzl!(prefix(pts,t), bdry, alg_inner) for i in 1:alg.max_iterations @assert s <= t e, k = find_max_excess(ball, pts, t+1) P = eltype(pts) F = eltype(P) if e > eps(F) # TODO should this be a parameter of the algorithm? @assert t < k pt = pts[k] push_if_stable!(bdry, pt) ball_new, s_new = welzl!(prefix(pts,s), bdry, alg_inner) # @assert isinside(pt, ball_new, rtol=1e-6) pop!(bdry) @assert isempty(bdry) move_to_front!(pts,k) ball = ball_new t = s + 1 s = s_new + 1 else return ball end end return ball end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
3941
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE bernoulli(p) = rand() <= p function poisson(lambda) k = 0 p = exp(-lambda) s = p x = rand() while x > s k += 1 p = p * lambda / k s += p end k end struct Householder{T} <: AbstractMatrix{T} v::Vector{T} end function Base.size(h::Householder) l = length(h.v) l,l end function Base.getindex(h::Householder, i, j) I[i,j] - 2*h.v[i]*h.v[j] end function random_householder(dim) v = randn(dim) normalize!(v) Householder(v) end function random_orthogonal(dim) ret = if dim == 1 [(-1.)^bernoulli(0.5)] else dim1 = dim - 1 m = random_householder(dim) rot1 = random_orthogonal(dim1) m * [rot1 zeros(dim1, 1); zeros(1, dim1) 1] end @assert ret * ret' ≈ Matrix(I,dim,dim) ret end function random_embedding(dim_target, dim_src) inc = Matrix(I,dim_target, dim_src) rot = random_orthogonal(dim_target) M = SMatrix{dim_target, dim_src} M(rot * inc) end function create_ball_points(npoints, dim_src; codim = poisson(0.3), p_boundary=1, p_rep=1/sqrt(npoints), p_shuffle=0.5, ) dim_target = dim_src + codim @assert dim_src <= dim_target @assert 0 <= p_boundary <= 1 @assert 0 <= p_rep <= 1 @assert 0 <= p_shuffle <= 1 F = Float64 P = SVector{dim_src, F} pts = P[] center = randn(dim_src) R = 10*rand() ball = MB.SqBall(center, R^2) while length(pts) < npoints dir = normalize!(randn(dim_src)) r = if bernoulli(p_boundary) R else R*rand() end pt = center + r*dir while true push!(pts, pt) bernoulli(p_rep) || break (length(pts) == npoints) && break end end bernoulli(p_shuffle) && shuffle!(pts) @assert length(pts) == npoints @assert eltype(pts) == P if dim_target > dim_src embedding = random_embedding(dim_target, dim_src) center = embedding * center pts = map(pt -> embedding*pt, pts) ball = MB.SqBall(center, R^2) end make_ball_containing_pts(ball, pts) end function make_ball_containing_pts(ball, pts) R2 = ball.sqradius center = ball.center for pt in pts R2pt = MB.sqdist(pt, center) if R2pt > R2 @assert R2pt ≈ R2 R2 = R2pt end end MB.SqBall(center, R2), pts end function random_test(alg, npoints, dim; rtol_inside=nothing, atol_inside=nothing, rtol_radius=nothing, allow_broken::Bool=false, kw...) ball_ref, pts = create_ball_points(npoints, dim; kw...) @assert MB.allinside(pts, ball_ref) P = eltype(pts) F = eltype(P) c, r = boundingsphere(pts, alg) ball = MB.SqBall(c, r^2) r_ref = MB.radius(ball_ref) if rtol_radius == nothing rtol_radius = sqrt(eps(max(r, r_ref))) end issmall = r <= r_ref || isapprox(r, r_ref; rtol=rtol_radius) if allow_broken && !issmall @test_broken issmall else @test issmall end if rtol_inside == nothing rtol_inside = 1e-6 end if atol_inside == nothing atol_inside = 100eps(F) end contains_all_points = MB.allinside(pts, ball, rtol=rtol_inside, atol=atol_inside) if allow_broken && !contains_all_points @test_broken contains_all_points # pts = map(pt -> map(BigFloat,pt), pts) # @show length(pts) # @show length(first(pts)) # @show ball_ref # @show pts # @show ball else @test contains_all_points end end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
654
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE using BoundingSphere const MB = BoundingSphere using BenchmarkTools using StaticArrays for (dim, npoints) in [ (2, 100), (3,1000) ] seed!(42) pts = [@SVector(randn(3)) for _ in 1:npoints] for A in subtypes(MB.BoundingSphereAlg) alg = A() println("Running $alg on $npoints points of dimension $dim") trial = @benchmark boundingsphere($pts, $alg) show(stdout, MIME"text/plain"(), trial) println() end end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
564
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE using BoundingSphere const MB = BoundingSphere using StaticArrays if VERSION < v"0.7-" using Base.Test const stdout = STDOUT seed!(x) = srand(x) else using Random using Random: seed! using LinearAlgebra using Test using InteractiveUtils: subtypes end include("helpers.jl") include("test_broken.jl") include("test_util.jl") include("test_welzl.jl") include("test_degenerate_examples.jl") include("perf.jl")
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
1275
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE @testset "6 points 2d" begin pts = [ [-2.740694122152086187327313382411375641822814941406250000000000000000000000000000, 8.010609127471919777008224627934396266937255859375000000000000000000000000000000], [-7.875078087682085836718215432483702898025512695312500000000000000000000000000000e-02, 8.253169461411594909350242232903838157653808593750000000000000000000000000000000], [-5.281301381389667426446976605802774429321289062500000000000000000000000000000000, 6.407720312422610753344542899867519736289978027343750000000000000000000000000000], [3.279069514617182434790265688207000494003295898437500000000000000000000000000000, -2.195389590186907824431727931369096040725708007812500000000000000000000000000000], [3.279069514617182434790265688207000494003295898437500000000000000000000000000000, -2.195389590186907824431727931369096040725708007812500000000000000000000000000000]] c,r = boundingsphere(pts, WelzlPivot()) ball = MB.SqBall(c, r^2) @test MB.allinside(pts, ball, atol=10) @test_broken MB.allinside(pts, ball, rtol=1e-1) @test_broken MB.allinside(pts, ball, rtol=1e-6) end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
1876
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE @testset "2 points 2d" begin ball_ref = MB.SqBall{Array{Float64,1},Float64}([1.79979, -0.419288], 38.387992027461046) pts = StaticArrays.SArray{Tuple{2},Float64,1,2}[[0.379453, 0.65952], [1.29807, 1.06029], [1.66662, -0.225889]] c,r = boundingsphere(pts, WelzlPivot()) ball = MB.SqBall(c, r^2) @test MB.allinside(pts, ball, rtol=1e-1) @test MB.allinside(pts, ball, rtol=1e-6) # not sure if WelzlMTF should give a good result c,r = boundingsphere(pts, WelzlMTF()) ball = MB.SqBall(c, r^2) @test MB.allinside(pts, ball, rtol=1e-1) @test MB.allinside(pts, ball, rtol=1e-6) end @testset "2 points 1d" begin x = -5. y = x + 10*eps(Float64) pts = [[x], [y]] c,r = boundingsphere(pts, WelzlPivot()) ball = MB.SqBall(c, r^2) @test MB.allinside(pts, ball, atol=100eps(Float64)) # not sure if WelzlMTF should give a good result @test_broken boundingsphere(pts, WelzlMTF()) # ball = MB.SqBall(c, r^2) # @test_broken MB.allinside(pts, ball, rtol=1e-1) # @test_broken MB.allinside(pts, ball, rtol=1e-6) end @testset "3 points 3d" begin ball_ref = MB.SqBall{Array{Float64,1},Float64}([1.05415, -2.52996, -0.584979], 20.953846606252085) pts = StaticArrays.SArray{Tuple{3},Float64,1,3}[[1.18024, 0.0853978, -3.01374], [0.20966, -3.69213, 3.76129], [4.51103, -0.881877, 1.92254]] c,r = boundingsphere(pts, WelzlPivot()) ball = MB.SqBall(c, r^2) @test MB.allinside(pts, ball, rtol=1e-1) @test MB.allinside(pts, ball, rtol=1e-6) # not sure if WelzlMTF should give a good result c,r = boundingsphere(pts, WelzlMTF()) ball = MB.SqBall(c, r^2) @test MB.allinside(pts, ball, rtol=1e-1) @test MB.allinside(pts, ball, rtol=1e-6) end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
966
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE @testset "prefix" begin @test MB.prefix(["a", "b", "c", "d"], 0) == [] @test MB.prefix(["a", "b", "c", "d"], 1) == ["a"] @test MB.prefix(["a", "b", "c", "d"], 2) == ["a","b"] # mut data = [1,2,3] p = MB.prefix(data, 1) p[1] = 42 @test data == [42,2,3] end @testset "move_to_front!" begin pts_initial = ["a", "b", "c", "d"] pts = deepcopy(pts_initial) MB.move_to_front!(pts, 1) @test pts == pts_initial pts = deepcopy(pts_initial) MB.move_to_front!(pts, 2) @test pts == ["b", "a", "c", "d"] pts = deepcopy(pts_initial) MB.move_to_front!(pts, 4) @test pts == ["d", "a", "b", "c"] end @testset "isinside" begin @test MB.isinside([0.], MB.SqBall([0.], 0.)) @test !MB.isinside([0.], MB.SqBall([NaN], 0.)) @test !MB.isinside([0.], MB.SqBall([0.], NaN)) end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
code
5017
# This file is a part of JuliaFEM. # License is MIT: see https://github.com/JuliaFEM/BoundingSphere.jl/blob/master/LICENSE using StaticArrays @testset "Generic type support" begin inputs = [] pts_template = [[-1,0],[1,0],[0,-1],[0,1]] for F in subtypes(AbstractFloat) F == Float16 && continue # Float16 fires assertions for V in [Vector{F}, SVector{2,F}] pts::Vector{V} = map(V, pts_template) push!(inputs, pts) end end for A in subtypes(MB.BoundingSphereAlg) for pts in inputs alg = A() c, r = boundingsphere(pts, alg) P = eltype(pts) F = eltype(P) @test typeof(c) == P @test typeof(r) == F @inferred boundingsphere(pts, alg) @test norm(c) < sqrt(eps(F)) @test r ≈ 1 end end end @testset "support_count" begin alg = WelzlMTF() a = @SVector [0.] b = @SVector [1.] c = @SVector [2.] pts = [a] bdry = MB.create_boundary_device(pts, alg) ball, support_count = MB.welzl!(pts, bdry, alg) @test isempty(bdry) @test support_count == 1 pts = [a,b] bdry = MB.create_boundary_device(pts, alg) ball, support_count = MB.welzl!(pts, bdry, alg) @test isempty(bdry) @test support_count == 2 pts = [a,b,c] bdry = MB.create_boundary_device(pts, alg) ball, support_count = MB.welzl!(pts, bdry, alg) @test isempty(bdry) @test support_count == 2 @test Set(pts[1:support_count]) == Set([a,c]) vals = randn(10) V = SVector{1, Float64} pts = map(V, vals) v1, v2 = map(V, extrema(vals)) bdry = MB.create_boundary_device(pts, alg) ball, support_count = MB.welzl!(pts, bdry, alg) @test isempty(bdry) @test support_count == 2 @test Set(pts[1:support_count]) == Set([v1,v2]) end @testset "random support_count" begin seed!(42) alg = WelzlMTF() for dim in 1:10, npoints in 1:20 ball, pts = create_ball_points(dim, npoints, p_rep=0, p_boundary=0) bdry = MB.create_boundary_device(pts, alg) ball, support_count = MB.welzl!(pts, bdry, alg) @test isempty(bdry) # support set suffices pts2 = pts[1:support_count] c, r = boundingsphere(pts2, alg) @test MB.center(ball) ≈ c @test MB.radius(ball) ≈ r # support set is not too large pts3 = copy(pts2) if length(pts3) > 1 index = rand(1:length(pts3)) deleteat!(pts3, index) c, r = boundingsphere(pts3, alg) @test r < MB.radius(ball) end end end @testset "random Ritter" begin seed!(42) for dim in 1:5 for npoints in 1:100 random_test(Ritter(), npoints, dim, rtol_radius=0.3, allow_broken=false ) end end end @testset "random WelzlPivot" begin @testset "random WelzlPivot small" begin seed!(42) alg = WelzlPivot() for dim in 1:3 for npoints in 1:10 random_test(alg, npoints, dim, allow_broken=false, codim=0) end end end @testset "non degenerate" begin seed!(42) alg = WelzlPivot() for dim in 1:10 for npoints in 1:100 random_test(alg, npoints, dim, p_boundary=0, p_rep=0, codim=0, allow_broken=false) end end end @testset "nasty" begin seed!(42) alg = WelzlPivot() for _ in 1:1 for dim in 1:10 for npoints in 1:100 random_test(alg, npoints, dim, p_rep=1/sqrt(npoints), p_boundary=0.5, allow_broken=true) random_test(alg, npoints, dim, p_rep=1/sqrt(npoints), p_boundary=1, allow_broken=true) random_test(alg, npoints, dim, p_rep=0, p_boundary=0, allow_broken=true) random_test(alg, npoints, dim, allow_broken=true) random_test(alg, npoints, dim, codim=poisson(3), allow_broken=true) end end end end end @testset "random WelzlMTF" begin seed!(42) for dim in 1:10, npoints in 1:20 random_test(WelzlMTF(), npoints, dim, codim=0, p_rep=0, p_boundary=0, allow_broken=false) end end
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.2.0
9f45d48e55111126a87a8aea1ddffe9ac2e3fbc3
docs
2450
# BoundingSphere [![][gitter-img]][gitter-url] [![][travis-img]][travis-url] [![][pkg-0.6-img]][pkg-0.6-url] [![][pkg-0.7-img]][pkg-0.7-url] [![][coveralls-img]][coveralls-url] [![][docs-stable-img]][docs-stable-url] [![][docs-latest-img]][docs-latest-url] [![][issues-img]][issues-url] [![][appveyor-img]][appveyor-url] Package contains algorithms to calculate smallest enclosing sphere for a given set of points in N dimensions. BoundingSphere.jl is a complete rewrite from scratch of [Miniball.jl](https://github.com/JuliaFEM/Miniball.jl). See [Miniball.jl issue #28](https://github.com/JuliaFEM/Miniball.jl/issues/28). ## Usage ```julia using BoundingSphere pts = [randn(3) for _ in 1:10] center, radius = boundingsphere(pts) using StaticArrays pts = [@SVector(randn(3)) for _ in 1:10] # use static arrays for performance algorithm = Ritter() # fast but inaccurate center, radius = boundingsphere(pts, algorithm) # customize algorithm ``` [gitter-img]: https://badges.gitter.im/Join%20Chat.svg [gitter-url]: https://gitter.im/JuliaFEM/JuliaFEM.jl [contrib-url]: https://juliafem.github.io/BoundingSphere.jl/latest/man/contributing/ [discourse-tag-url]: https://discourse.julialang.org/tags/boundingsphere [docs-latest-img]: https://img.shields.io/badge/docs-latest-blue.svg [docs-latest-url]: https://juliafem.github.io/BoundingSphere.jl/latest [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://juliafem.github.io/BoundingSphere.jl/stable [travis-img]: https://travis-ci.org/JuliaFEM/BoundingSphere.jl.svg?branch=master [travis-url]: https://travis-ci.org/JuliaFEM/BoundingSphere.jl [coveralls-img]: https://coveralls.io/repos/github/JuliaFEM/BoundingSphere.jl/badge.svg?branch=master [coveralls-url]: https://coveralls.io/github/JuliaFEM/BoundingSphere.jl?branch=master [issues-img]: https://img.shields.io/github/issues/JuliaFEM/BoundingSphere.jl.svg [issues-url]: https://github.com/JuliaFEM/BoundingSphere.jl/issues [pkg-0.6-img]: http://pkg.julialang.org/badges/BoundingSphere_0.6.svg [pkg-0.6-url]: http://pkg.julialang.org/?pkg=BoundingSphere&ver=0.6 [pkg-0.7-img]: http://pkg.julialang.org/badges/BoundingSphere_0.7.svg [pkg-0.7-url]: http://pkg.julialang.org/?pkg=BoundingSphere&ver=0.7 [appveyor-img]: https://ci.appveyor.com/api/projects/status/s1vk9v0sxbmr2pen/branch/master?svg=true [appveyor-url]: https://ci.appveyor.com/project/JuliaFEM/boundingsphere-jl/branch/master
BoundingSphere
https://github.com/JuliaFEM/BoundingSphere.jl.git
[ "MIT" ]
0.7.0
56dddf9619ef896307031c8c0515e4f7ad1da0b1
code
1263
## Bench pricer function using FinancialToolbox, BenchmarkTools, ForwardDiff, ReverseDiff, Zygote, TaylorSeries suite = BenchmarkGroup() S0 = 100.0; K = 100.0; r = 0.01; T = 1.0; sigma = 0.2; d = 0.01; price = blsprice(S0, K, r, T, sigma, d); inputs = [S0, K, r, T, price, d]; output = similar(inputs); suite["evaluation"] = @benchmarkable blsimpv($S0, $K, $r, $T, $price, $d) suite["forward"] = @benchmarkable @views ForwardDiff.gradient!(output, x -> blsimpv(x[1], x[2], x[3], x[4], x[5], x[6]), $inputs); suite["ReverseDiff"] = @benchmarkable @views ReverseDiff.gradient(x -> blsimpv(x[1], x[2], x[3], x[4], x[5], x[6]), $inputs); cfg = ReverseDiff.GradientConfig(similar(inputs)) f_tape = ReverseDiff.compile(ReverseDiff.GradientTape(x -> blsimpv(x[1], x[2], x[3], x[4], x[5], x[6]), inputs, cfg)) suite["ReverseDiff compiled"] = @benchmarkable ReverseDiff.gradient!($output, $f_tape, $inputs); suite["Zygote"] = @benchmarkable Zygote.gradient(blsimpv, $S0, $K, $r, $T, $price, $d); spot_taylor = taylor_expand(identity, S0, order = 22) price_taylor = blsprice(spot_taylor, K, r, T, sigma, d); suite["taylor_series"] = @benchmarkable blsimpv($spot_taylor, $K, $r, $T, $price_taylor, $d); SUITE["implied volatility"] = suite # tune!(suite) # @show run(suite)
FinancialToolbox
https://github.com/rcalxrc08/FinancialToolbox.jl.git
[ "MIT" ]
0.7.0
56dddf9619ef896307031c8c0515e4f7ad1da0b1
code
1492
## Bench pricer function using FinancialToolbox, BenchmarkTools, ForwardDiff, ReverseDiff, Zygote, TaylorSeries S0 = 100.0; K = 100.0; r = 0.01; T = 1.0; sigma = 0.2; d = 0.01; inputs = [S0, K, r, T, sigma, d]; suite = BenchmarkGroup() suite["standard"] = @benchmarkable blsprice(S0, K, r, T, sigma, d); output = similar(inputs); suite["forwarddiff"] = @benchmarkable @views ForwardDiff.gradient!(output, x -> blsprice(x[1], x[2], x[3], x[4], x[5], x[6]), $inputs); suite["reversediff"] = @benchmarkable @views ReverseDiff.gradient(x -> blsprice(x[1], x[2], x[3], x[4], x[5], x[6]), $inputs); cfg = ReverseDiff.GradientConfig(similar(inputs)) f_tape = ReverseDiff.compile(ReverseDiff.GradientTape(x -> blsprice(x[1], x[2], x[3], x[4], x[5], x[6]), inputs, cfg)) suite["reversediff compiled"] = @benchmarkable ReverseDiff.gradient!($output, $f_tape, $inputs); # suite["implied volatility forward"] = @benchmarkable ReverseDiff.gradient(x->blsprice(x...),inputs); # suite["implied volatility forward"] = @benchmarkable @views Zygote.gradient(x -> blsprice(x[1], x[2], x[3], x[4], x[5], x[6]), inputs); suite["zygote"] = @benchmarkable Zygote.gradient(blsprice, $S0, $K, $r, $T, $sigma, $d); # suite["implied volatility forward"] = @benchmarkable Zygote.gradient(x->blsprice(x...),inputs); spot_taylor = taylor_expand(identity, S0, order = 22) suite["taylor_series"] = @benchmarkable blsprice($spot_taylor, $K, $r, $T, $sigma, $d); SUITE["Pricer"] = suite # tune!(suite) # @show run(suite)
FinancialToolbox
https://github.com/rcalxrc08/FinancialToolbox.jl.git
[ "MIT" ]
0.7.0
56dddf9619ef896307031c8c0515e4f7ad1da0b1
code
1154
## Bench pricer function using FinancialToolbox, BenchmarkTools, ForwardDiff, ReverseDiff, Zygote, TaylorSeries S0 = 100.0; K = 100.0; r = 0.01; T = 1.0; sigma = 0.2; d = 0.01; inputs = [S0, K, r, T, sigma, d]; suite = BenchmarkGroup() suite["standard"] = @benchmarkable blsvega($S0, $K, $r, $T, $sigma, $d); output = similar(inputs); suite["forwarddiff"] = @benchmarkable @views ForwardDiff.gradient!(output, x -> blsvega(x[1], x[2], x[3], x[4], x[5], x[6]), $inputs); suite["reversediff"] = @benchmarkable @views ReverseDiff.gradient(x -> blsvega(x[1], x[2], x[3], x[4], x[5], x[6]), $inputs); cfg = ReverseDiff.GradientConfig(similar(inputs)) f_tape = ReverseDiff.compile(ReverseDiff.GradientTape(x -> blsvega(x[1], x[2], x[3], x[4], x[5], x[6]), inputs, cfg)) suite["reversediff compiled"] = @benchmarkable ReverseDiff.gradient!($output, $f_tape, $inputs); suite["zygote"] = @benchmarkable @views Zygote.gradient(blsvega, $S0, $K, $r, $T, $sigma, $d); spot_taylor = taylor_expand(identity, S0, order = 22) suite["taylor_series"] = @benchmarkable blsvega($spot_taylor, $K, $r, $T, $sigma, $d); SUITE["Vega"] = suite # tune!(suite) # @show run(suite)
FinancialToolbox
https://github.com/rcalxrc08/FinancialToolbox.jl.git
[ "MIT" ]
0.7.0
56dddf9619ef896307031c8c0515e4f7ad1da0b1
code
933
using BenchmarkTools using Random const SUITE = BenchmarkGroup() include("bench_pricer.jl") include("bench_vega.jl") include("bench_impv.jl") # SUITE["utf8"] = BenchmarkGroup(["string", "unicode"]) # teststr = String(join(rand(MersenneTwister(1), 'a':'d', 10^4))) # SUITE["utf8"]["replace"] = @benchmarkable replace($teststr, "a" => "b") # SUITE["utf8"]["join"] = @benchmarkable join($teststr, $teststr) # SUITE["utf8"]["plots"] = BenchmarkGroup() # SUITE["trigonometry"] = BenchmarkGroup(["math", "triangles"]) # SUITE["trigonometry"]["circular"] = BenchmarkGroup() # for f in (sin, cos, tan) # for x in (0.0, pi) # SUITE["trigonometry"]["circular"][string(f), x] = @benchmarkable ($f)($x) # end # end # SUITE["trigonometry"]["hyperbolic"] = BenchmarkGroup() # for f in (sin, cos, tan) # for x in (0.0, pi) # SUITE["trigonometry"]["hyperbolic"][string(f), x] = @benchmarkable ($f)($x) # end # end
FinancialToolbox
https://github.com/rcalxrc08/FinancialToolbox.jl.git