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
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
561
""" Mustache [Mustache](https://github.com/jverzani/Mustache.jl) is a templating package for `Julia` based on [Mustache.js](http://mustache.github.io/). [ [Docs](https://jverzani.github.io/Mustache.jl/dev/) ] """ module Mustache if isdefined(Base, :Experimental) && isdefined(Base.Experimental, Symbol("@optlevel")) @eval Base.Experimental.@optlevel 1 end using Tables include("utils.jl") include("tokens.jl") include("context.jl") include("writer.jl") include("parse.jl") include("render.jl") export @mt_str, @jmt_str, render, render_from_file end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
5604
## context ## A context stores objects where named values are looked up. mutable struct Context view ## of what? a Dict, Module, CompositeKind, DataFrame.parent. parent ## a context or nothing _cache::Dict end function Context(view, parent=nothing) d = Dict() d["."] = isa(view, AnIndex) ? view.value : view Context(view, parent, d) end ## used by renderTokens function ctx_push(ctx::Context, view) Context(view, ctx) ## add context as a parent end function ctx_pop(ctx::Context) ctx.parent end # we have some rules here # * Each part of a dotted name should resolve only against its parent. # * Any falsey value prior to the last part of the name should yield ''. # * The first part of a dotted name should resolve as any other name. function lookup_dotted(ctx::Context, dotted) for key in split(dotted, ".") nctx = lookup(Context(ctx.view), key) falsy(nctx) && return nothing ctx = Context(nctx, ctx) end ctx.view end # look up key in context function lookup(ctx::Context, key) if haskey(ctx._cache, key) return ctx._cache[key] end # use global lookup down global_lookup = false if startswith(key, "~") global_lookup = true key = replace(key, r"^~" => "") end # begin context = ctx value = nothing while context !== nothing value′ = nothing ## does name have a .? We first check if it is a key, then use lookup_dotted value′ = lookup_in_view(context.view, stripWhitespace(key)) if value′ === nothing && occursin(r"\.", key) value′ = lookup_dotted(context, key) if value′ == nothing ## do something with "." ## we use .[ind] to refer to value in parent of given index; m = match(r"^\.\[(.*)\]$", key) if m !== nothing idx = first(m.captures) idx == nothing && throw(ArgumentError("XXX")) vals = context.parent.view # this has limited support for indices: "end", or a number, but no # arithmetic, such as `end-1`. ## This is for an iterable; rather than ## limit the type, we let non-iterables error. if true # isa(vals, AbstractVector) || isa(vals, Tuple) # supports getindex(v, i)? if idx == "end" value′ = AnIndex(-1, vals[end]) else ind = Base.parse(Int, idx) value′ = AnIndex(ind, string(vals[ind])) end end else !global_lookup && break end end end if value′ !== nothing value = value′ !global_lookup && break end context = context.parent end ## cache ctx._cache[key] = value return(value) end ## Lookup value in an object by key ## This of course varies based on the view. ## After checking several specific types, if view is Tables compatible ## this will return "column" corresponding to the key function lookup_in_view(view, key) val = _lookup_in_view(view, key) !falsy(val) && return val if Tables.istable(view) isempty(Tables.rows(view)) && return nothing sch = Tables.schema(Tables.rows(view)) falsy(sch) && return nothing k = normalize(key) if k ∈ sch.names return [row[k] for row ∈ Tables.rows(view)] end # elseif is_dataframe(view) # if occursin(r"^:", key) key = key[2:end] end # key = Symbol(key) # out = nothing # if haskey(view, key) # out = view[1, key] ## first element only # end # out else __lookup_in_view(view, key) end end # look up key in view, return `nothing` if not found function _lookup_in_view(view::AbstractDict, key) get(view, normalize(key), nothing) end # support legacy use of `first` and `second` as variable names # referring to piece, otherwise look up value function _lookup_in_view(view::Pair, key) ## is it a symbol? key == "first" && return view.first key == "second" && return view.second view.first == normalize(key) ? view.second : nothing end function _lookup_in_view(view::NamedTuple, key) key′ = normalize(key) haskey(view, key′) && return getindex(view, key′) return nothing end function _lookup_in_view(view::Module, key) hasmatch = false re = Regex("^$key\$") for i in names(view, all=true) if occursin(re, string(i)) hasmatch = true break end end out = nothing if hasmatch out = getfield(view, Symbol(key)) ## view.key end out end _lookup_in_view(view, key) = nothing ## Default lookup is likely not great, function __lookup_in_view(view, key) k = normalize(key) k′ = Symbol(k) # check propertyname, then fieldnames if k in propertynames(view) getproperty(view, k) elseif k′ in propertynames(view) getproperty(view, k′) else nms = fieldnames(typeof(view)) # we match on symbol or string for fieldname if isa(k, Symbol) has_match = k in nms else has_match = Symbol(k) in nms end out = nothing if has_match out = getfield(view, Symbol(k)) ## view.key end out end end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
6559
## Main function to parse a template This works in several steps: each ## character parsed into a token, the tokens are squashed, then ## nested, then rendered. """ Mustache.parse(template, tags = ("{{", "}}")) Parse a template into tokens. * `template`: a string containing a template * `tags`: the tags used to indicate a variable. Adding interior braces (`{`,`}`) around the variable will prevent HTML escaping. (That is for the default tags, `{{{varname}}}` is used; for tags like `("<<",">>")` then `<<{varname}>>` is used.) # Extended The template interprets tags in different ways. The string macro `mt` is used below to both `parse` (on construction) and `render` (when called). ## Variable substitution. Like basic string interpolation, variable substitution can be performed using a non-prefixed tag: ```jldoctest mustache julia> using Mustache julia> a = mt"Some {{:variable}}."; julia> a(; variable="pig") "Some pig." julia> a = mt"Cut: {{{:scissors}}}"; julia> a(; scissors = "8< ... >8") "Cut: 8< ... >8" ``` Both using a symbol, as the values to substitute are passed through keyword arguments. The latter uses triple braces to inhibit the escaping of HTML entities. Tags can be given special meanings through prefixes. For example, to avoid the HTML escaping an `&` can be used: ```jldoctest mustache julia> a = mt"Cut: {{&:scissors}}"; julia> a(; scissors = "8< ... >8") "Cut: 8< ... >8" ``` ## Sections Tags can create "sections" which can be used to conditionally include text, apply a function to text, or iterate over the values passed to `render`. ### Include text To include text, the `#` prefix can open a section followed by a `/` to close the section: ```jldoctest mustache julia> a = mt"I see a {{#:ghost}}ghost{{/:ghost}}"; julia> a(; ghost=true) "I see a ghost" julia> a(; ghost=false) "I see a " ``` The latter is to illustrate that if the variable does not exist or is "falsy", the section text will not display. The `^` prefix shows text when the variable is not present. ```jldoctest mustache julia> a = mt"I see {{#:ghost}}a ghost{{/:ghost}}{{^:ghost}}nothing{{/:ghost}}"; julia> a(; ghost=false) "I see nothing" ``` ### Apply a function to the text If the variable refers to a function, it will be applied to the text within the section: ```jldoctest mustache julia> a = mt"{{#:fn}}How many letters{{/:fn}}"; julia> a(; fn=length) "16" ``` The use of the prefix `!` will first render the text in the section, then apply the function: ```jldoctest mustache julia> a = mt"The word '{{:variable}}' has {{|:fn}}{{:variable}}{{/:fn}} letters."; julia> a(; variable="length", fn=length) "The word 'length' has 6 letters." ``` ### Iterate over values If the variable in a section is an iterable container, the values will be iterated over. `Tables.jl` compatible values are iterated in a row by row manner, such as this view, which is a tuple of named tuples: ```jldoctest mustache julia> a = mt"{{#:data}}x={{:x}}, y={{:y}} ... {{/:data}}"; julia> a(; data=((x=1,y=2), (x=2, y=4))) "x=1, y=2 ... x=2, y=4 ... " ``` Iterables like vectors, tuples, or ranges -- which have no named values -- can have their values referenced by a `{{.}}` tag: ```jldoctest mustache julia> a = mt"{{#:countdown}}{{.}} ... {{/:countdown}} blastoff"; julia> a(; countdown = 5:-1:1) "5 ... 4 ... 3 ... 2 ... 1 ... blastoff" ``` ## Partials Partials allow substitution. The use of the tag prefix `>` includes either a file or a string and renders it accordingly: ```jldoctest mustache julia> a = mt"{{>:partial}}"; julia> a(; partial="variable is {{:variable}}", variable=42) "variable is 42" ``` The use of the tag prefix `<` just includes the partial (a file in this case) without rendering. ## Comments Using the tag-prefix `!` will comment out the text: ```jldoctest mustache julia> a = mt"{{! ignore this comment}}This is rendered"; julia> a() "This is rendered" ``` Multi-lne comments are permitted. """ function parse(template, tags = ("{{", "}}")) tokens = make_tokens(template, tags) out = nestTokens(tokens) MustacheTokens(out) end """ mt"string" String macro to parse tokens from a string. See [`parse`](@ref). """ macro mt_str(s) parse(s) end """ jmt"string" String macro that interpolates values escaped by dollar signs, then parses strings. Note: modified from a macro in [HypertextLiteral](https://github.com/clarkevans/HypertextLiteral.jl/blob/master/src/macros.jl). Example: ``` x = 1 toks = jmt"\$(2x) by {{:a}}" toks(; a=2) # "2 by 2" ``` """ macro jmt_str(expr::String) # Essentially this is an ad-hoc scanner of the string, splitting # it by `$` to find interpolated parts and delegating the hard work # to `Meta.parse`, treating everything else as a literal string. args = Any[] start = idx = 1 strlen = length(expr) while true idx = findnext(isequal('$'), expr, start) if idx == nothing push!(args, expr[start:strlen]) break end push!(args, expr[start:idx-1]) start = idx + 1 (nest, tail) = Meta.parse(expr, start; greedy=false) if nest == nothing throw("missing interpolation expression") end if !(expr[start] == '(' || nest isa Symbol) throw(DomainError(nest, "interpolations must be symbols or parenthesized")) end if Meta.isexpr(nest, :(=)) throw(DomainError(nest, "assignments are not permitted in an interpolation")) end if nest isa String # this is an interpolated string literal nest = Expr(:string, nest) end push!(args, nest) start = tail end quote Mustache.parse(string($(map(esc, args)...))) end end ## Dict for storing parsed templates TEMPLATES = Dict{AbstractString, MustacheTokens}() """ Mustache.load(filepath, args...) Load file specified through `filepath` and return the compiled tokens. Tokens are memoized for efficiency, Additional arguments are passed to `Mustache.parse` (for adjusting the tags). """ function load(filepath, args...) isfile(filepath) || throw(ArgumentError("File $filepath not found")) key = string(mtime(filepath)) * filepath * string(hash(args)) haskey(TEMPLATES,key) && return TEMPLATES[key] open(filepath) do s global tpl = parse(read(s, String), args...) end TEMPLATES[key] = tpl tpl end # old names. To be deprecated? const template_from_file = load
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
2513
""" render([io], tokens, view) render([io], tokens; kwargs...) (tokens::MustacheTokens)([io]; kwargs...) Render a set of tokens with a view, using optional `io` object to print or store. ## Arguments * `io::IO`: Optional `IO` object. * `tokens`: Either Mustache tokens, or a string to parse into tokens * `view`: A view provides a context to look up unresolved symbols demarcated by mustache braces. A view may be specified by a dictionary, a module, a composite type, a vector, a named tuple, a data frame, a `Tables` object, or keyword arguments. !!! note The `render` method is currently exported, but this export may be deprecated in the future. """ function render(io::IO, tokens::MustacheTokens, view) _writer = Writer() render(io, _writer, tokens, view) end function render(io::IO, tokens::MustacheTokens; kwargs...) render(io, tokens, Dict(kwargs...)) end render(tokens::MustacheTokens, view) = sprint(io -> render(io, tokens, view)) render(tokens::MustacheTokens; kwargs...) = sprint(io -> render(io, tokens; kwargs...)) ## make MustacheTokens callable for kwargs... function (m::MustacheTokens)(io::IO, args...; kwargs...) if length(args) == 1 render(io, m, first(args)) else render(io, m; kwargs...) end end (m::MustacheTokens)(args...; kwargs...) = sprint(io -> m(io, args...; kwargs...)) ## Exported call without first parsing tokens via mt"literal" ## ## @param template a string containing the template for expansion ## @param view a Dict, Module, CompositeType, DataFrame holding variables for expansion function render(io::IO, template::AbstractString, view; tags= ("{{", "}}")) return render(io, parse(template, tags), view) end function render(io::IO, template::AbstractString; kwargs...) return render(io, parse(template); kwargs...) end render(template::AbstractString, view; tags=("{{", "}}")) = sprint(io -> render(io, template, view, tags=tags)) render(template::AbstractString; kwargs...) = sprint(io -> render(io, template; kwargs...)) # Exported, but should be deprecated.... """ render_from_file(filepath, view) render_from_file(filepath; kwargs...) Renders a template from `filepath` and `view`. !!! note This function simply combines `Mustache.render` and `Mustache.load` and may be deprecated in the future. """ render_from_file(filepath, view) = render(Mustache.load(filepath), view) render_from_file(filepath::AbstractString; kwargs...) = render(Mustache.load(filepath); kwargs...)
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
22372
# XXX # * if the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration # * If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object. # Token types abstract type Token end mutable struct TextToken <: Token _type::String value::String end mutable struct TagToken <: Token _type::String value::String ltag::String rtag::String indent::String TagToken(_type, value, ltag, rtag, indent="") = new(_type, value, ltag, rtag, indent) end mutable struct SectionToken <: Token _type::String value::String ltag::String rtag::String collector::Vector SectionToken(_type, value, ltag, rtag) = new(_type, value, ltag, rtag, Any[]) end mutable struct BooleanToken <: Token _type::String value::String ltag::String rtag::String collector::Vector BooleanToken(_type, value, ltag, rtag) = new(_type, value, ltag, rtag, Any[]) end mutable struct MustacheTokens tokens::Vector{Token} end MustacheTokens() = MustacheTokens(Token[]) Base.length(tokens::MustacheTokens) = length(tokens.tokens) Base.lastindex(tokens::MustacheTokens) = lastindex(tokens.tokens) Base.getindex(tokens::MustacheTokens, ind) = getindex(tokens.tokens, ind) Base.pop!(tokens::MustacheTokens) = pop!(tokens.tokens) function Base.push!(tokens::MustacheTokens, token::Token) # squash if possible if length(tokens) == 0 push!(tokens.tokens, token) return end lastToken = tokens[end] if !falsy(lastToken) && lastToken._type == "text" == token._type lastToken.value *= token.value else push!(tokens.tokens, token) end end struct AnIndex ind::Int value::String end Base.string(ind::AnIndex) = string(ind.value) Base.iterate(I::AnIndex, st=nothing) = st === nothing ? (I.ind, nothing) : nothing ### We copy some functions from Tokenize function peekchar(io::Base.GenericIOBuffer) if !io.readable || io.ptr > io.size return '∅' end ch, _ = readutf(io) return ch end # this implementation is copied from Tokenize, @inline function utf8_trailing(i) if i < 193 return 0 elseif i < 225 return 1 elseif i < 241 return 2 elseif i < 249 return 3 elseif i < 253 return 4 else return 5 end end const utf8_offset = [0x00000000 0x00003080 0x000e2080 0x03c82080 0xfa082080 0x82082080] function readutf(io, offset = 0) ch = convert(UInt8, io.data[io.ptr + offset]) if ch < 0x80 return convert(Char, ch), 0 end trailing = utf8_trailing(ch + 1) c::UInt32 = 0 for j = 1:trailing c += ch c <<= 6 ch = convert(UInt8, io.data[io.ptr + j + offset]) end c += ch c -= utf8_offset[trailing + 1] return convert(Char, c), trailing end #### ## this is modified from dpeekchar in Tokenize function peekaheadmatch(io::IO, m=['{','{']) if !io.readable || io.ptr > io.size return false end i,N = 1, length(m) ch1, trailing = readutf(io) ch1 != m[1] && return false offset = 0 while true i == N && return true i += 1 offset += trailing + 1 if io.ptr + offset > io.size return false end chn, trailing = readutf(io, offset) chn != m[i] && return false end return false end # ...{{.... -> (..., {{....) function scan_until!(io, tags, firstline) out = IOBuffer() while !end_of_road(io) if peekaheadmatch(io, tags) val = String(take!(out)) close(out) return val, firstline else c = read(io, Char) firstline = firstline && !(c== '\n') print(out, c) end end val = String(take!(out)) close(out) return val, firstline end # skip over tags function scan_past!(io, tags = ('{','{')) for i in 1:length(tags) t = read(io, Char) end end # end of io stream function end_of_road(io) !io.readable && return true io.ptr > io.size && return true return false end # strip whitespace at head of io stream WHITESPACE = (' ', '\t', '\r') function popfirst!_whitespace(io) while !end_of_road(io) c::Char = peekchar(io) !(c in WHITESPACE) && break read(io, Char) end end # is tag possibly standalone # check the left side # XXX This could be part of scan_until! # then we could avoid regular expressions here function is_l_standalone(txt, firstline) if firstline occursin(r"^ *$", txt) else out = occursin(r"\n *$", txt) out end end # check the last side function is_r_standalone(io) end_of_road(io) && return true offset = 0 ch::Char, trailing::Int = readutf(io) while true ch == '\n' && return true !(ch in WHITESPACE) && return false offset += trailing + 1 io.ptr + offset > io.size && return true ch, trailing = readutf(io, offset) end return false end ## Make the initial set of tokens before nesting function make_tokens(template, tags) ltag, rtag = tags ltags = collect(ltag) rtags = collect(rtag) sections = MustacheTokens() tokens = MustacheTokens() firstline = true io = IOBuffer(template) while !end_of_road(io) # we have # ...text... {{ tag }} ...rest... # each lap makes token of ...text... and {{tag}} leaving ...rest... b0 = 0 text_value, firstline = scan_until!(io, ltags, firstline) b1 = position(io) if end_of_road(io) token = TextToken("text", text_value) push!(tokens, token) return tokens end scan_past!(io, ltags) text_token = TextToken("text", text_value) # grab tag token t0 = position(io) token_value, firstline = scan_until!(io, rtags, firstline) t1 = position(io) if end_of_road(io) throw(ArgumentError("tag not closed: $token_value $ltag $rtag")) end scan_past!(io, rtags) # what kinda tag did we get? token_value = stripWhitespace(token_value) _type = token_value[1:1] if _type in ("#", "^", "/", ">", "<", "!", "|", "=", "{", "&", "@") # type is first, we peel it off, also strip trailing = and }, # as necessary token_value = stripWhitespace(token_value[2:(end-(_type == "="))]) if _type == "{" #strip "}" if present in token, and if not io if token_value[end]=='}' token_value = token_value[1:end-1] else c = peekchar(io) c == '}' && read(io, Char) end end if _type == "=" tag_token = TagToken("=", token_value, ltag, rtag) ts = String.(split(token_value, r"[ \t]+")) length(ts) != 2 && throw(ArgumentError("Change of delimiter must be a pair. Identified: $ts")) ltag, rtag = ts ltags, rtags = collect(ltag), collect(rtag) elseif _type == ">" # get indentation if firstline && occursin(r"^\h*$", text_value) m = match(r"^(\h*)$", text_value) else m = match(r"\n([\s\t\h]*)$", text_value) end indent = m == nothing ? "" : m.captures[1] tag_token = TagToken(_type, token_value, ltag, rtag, indent==nothing ? "" : indent) elseif _type in ("#", "^", "|") tag_token = SectionToken(_type, token_value, ltag, rtag) elseif _type in ("@",) tag_token = BooleanToken(_type, token_value, ltag, rtag) else tag_token = TagToken(_type, token_value, ltag, rtag) end else token_value = stripWhitespace(token_value) tag_token = TagToken("name", token_value, ltag, rtag) end if tag_token._type == "name" firstline = false end # are we standalone? # yes if firstline and all whitespace # yes if !firstline and match \nwhitespace # AND # match rest with space[EOF,\n] standalone = is_r_standalone(io) && is_l_standalone(text_value, firstline) firstline = false if standalone && _type in ("!", "^", "/", "#", "<", ">", "|", "=") # we strip text_value back to \n or beginning text_token.value = replace(text_token.value, r" *$" => "") # strip whitespace at outset of io and "\n" popfirst!_whitespace(io) if !end_of_road(io) read(io, Char) # will be \n firstline = true end end push!(tokens, text_token) push!(tokens, tag_token) # account for matching/nested sections if _type == "#" || _type == "^" || _type == "|" || _type == "@" push!(sections, tag_token) elseif _type == "/" ## section nestinng if length(sections) == 0 throw(ArgumentError("Unopened section $token_value at $t0")) end openSection = pop!(sections) if openSection.value != token_value throw(ArgumentError("Unclosed section: " * openSection.value * " at $t0")) end end end if length(sections) > 0 openSection = pop!(sections) throw(ArgumentError("Unclosed section " * string(openSection.value))) end return(tokens) end ## Forms the given array of `tokens` into a nested tree structure where ## tokens that represent a section have two additional items: 1) an array of ## all tokens that appear in that section and 2) the index in the original ## template that represents the end of that section. function nestTokens(tokens) tree = Array{Any}(undef, 0) collector = tree sections = MustacheTokens() #Array{Any}(undef, 0) for i ∈ 1:length(tokens) token = tokens[i] ## a {{#name}}...{{/name}} will iterate over name ## a {{^name}}...{{/name}} does ... if we have no name ## start nesting if token._type == "^" || token._type == "#" || token._type == "|" || token._type == "@" push!(sections, token) push!(collector, token) token.collector = Array{Any}(undef, 0) collector = token.collector elseif token._type == "/" section = pop!(sections) if length(sections) > 0 push!(sections[end].collector, token) collector = sections[end].collector else collector = tree end else push!(collector, token) end end return(tree) end ## In lambdas with section this is used to go from the tokens to an unevaluated string ## This might have issues with space being trimmed function toString(tokens) io = IOBuffer() for token in tokens write(io, _toString(Val{Symbol(token._type)}(), token)) end out = String(take!(io)) close(io) out end _toString(::Val{:name}, t) = t.ltag * t.value * t.rtag _toString(::Val{:text}, t) = t.value _toString(::Val{Symbol("^")}, t) = t.ltag * "^" * t.value * t.rtag _toString(::Val{Symbol("|")}, t) = t.ltag * "|" * t.value * t.rtag _toString(::Val{Symbol("/")}, t) = t.ltag * "/" * t.value * t.rtag _toString(::Val{Symbol(">")}, t) = t.ltag * ">" * t.value * t.rtag _toString(::Val{Symbol("<")}, t) = t.ltag * "<" * t.value * t.rtag _toString(::Val{Symbol("&")}, t) = t.ltag * "&" * t.value * t.rtag _toString(::Val{Symbol("{")}, t) = t.ltag * "{" * t.value * t.rtag _toString(::Val{Symbol("=")}, t) = "" function _toString(::Val{Symbol("#")}, t) out = t.ltag * "#" * t.value * t.rtag if !isempty(t.collector) out *= toString(t.collector) end out end ## ---------------------------------------------------- # render tokens with values given in context function renderTokensByValue(value, io, token, writer, context, template, args...) inverted = token._type == "^" if (inverted && falsy(value)) _renderTokensByValue(value, io, token, writer, context, template, args...) elseif Tables.istable(value) isempty(Tables.rows(value)) && return nothing rows = Tables.rows(value) for row in rows renderTokens(io, token.collector, writer, ctx_push(context, row), template, args...) end elseif !falsy(value) _renderTokensByValue(value, io, token, writer, context, template, args...) else nothing # value == nothing end end ## Helper function for dispatch based on value in renderTokens function _renderTokensByValue(value::AbstractDict, io, token, writer, context, template, args...) renderTokens(io, token.collector, writer, ctx_push(context, value), template, args...) end function _renderTokensByValue(value::Union{AbstractArray, Tuple}, io, token, writer, context, template, args...) inverted = token._type == "^" if (inverted && falsy(value)) renderTokens(io, token.collector, writer, ctx_push(context, ""), template, args...) else n = length(value) for (i,v) in enumerate(value) renderTokens(io, token.collector, writer, ctx_push(context, v), template, (i,n)) end end end ## what to do with an index value `.[ind]`? ## We have `.[ind]` being of a leaf type (values are not pushed onto a Context) so of simple usage function _renderTokensByValue(value::AnIndex, io, token, writer, context, template, idx=(0,0)) idx_match = (value.ind == idx[1]) || (value.ind==-1 && idx[1] == idx[2]) if token._type == "#" || token._type == "|" # print if match if idx_match renderTokens(io, token.collector, writer, context, template, idx) end elseif token._type == "^" # print if *not* a match if !idx_match renderTokens(io, token.collector, writer, context, template, idx) end else renderTokens(io, token.collector, writer, ctx_push(context, value.value), template) end end function _renderTokensByValue(value::Function, io, token, writer, context, template, args...) ## function get's passed # When the value is a callable # object, such as a function or lambda, the object will # be invoked and passed the block of text. The text # passed is the literal block, unrendered. {{tags}} will # not have been expanded - the lambda should do that on # its own. In this way you can implement filters or # caching. # out = (value())(token.collector, render) if token._type == "name" push_task_local_storage(context.view) out = render(string(value()), context.view) elseif token._type == "|" # pass evaluated values view = context.parent.view push_task_local_storage(view) sec_value = render(MustacheTokens(token.collector), view) out = render(string(value(sec_value)), view) else ## How to get raw section value? ## desc: Lambdas used for sections should receive the raw section string. ## Lambdas used for sections should parse with the current delimiters. sec_value = toString(token.collector) view = context.parent.view if isa(value, Function) ## Supposed to be called value(sec_value, render+context) but ## we call render(value(sec_value), context) push_task_local_storage(view) tags = (token.ltag, token.rtag) _render = x -> render(parse(x, tags), view) out = try value(sec_value, _render) catch err value(sec_value) end else out = value end # ensure tags are used out = render(parse(string(out), (token.ltag, token.rtag)), view) end write(io, out) end function _renderTokensByValue(value::Any, io, token, writer, context, template, args...) inverted = token._type == "^" if (inverted && falsy(value)) || !falsy(value) renderTokens(io, token.collector, writer, context, template) end end ## Low-level function that renders the given `tokens` using the given `writer` ## and `context`. The `template` string is only needed for templates that use ## higher-order sections to extract the portion of the original template that ## was contained in that section. function renderTokens(io, tokens, writer, context, template, idx=(0,0)) for i in 1:length(tokens) token = tokens[i] tokenValue = token.value if token._type == "#" || token._type == "|" ## iterate over value if Dict, Array or DataFrame, ## or display conditionally value = lookup(context, tokenValue) ctx = isa(value, AnIndex) ? context : Context(value, context) renderTokensByValue(value, io, token, writer, ctx, template, idx) # if !isa(value, AnIndex) # context = Context(value, context) # end # renderTokensByValue(value, io, token, writer, context, template, idx) # if !isa(value, AnIndex) # context = ctx_pop(context) # end elseif token._type == "^" ## display if falsy, unlike # value = lookup(context, tokenValue) if !isa(value, AnIndex) ctx = Context(value, context) if falsy(value) renderTokensByValue(value, io, token, writer, ctx, template, idx) end else # for indices falsy test is performed in # _renderTokensByValue(value::AnIndex,...) renderTokensByValue(value, io, token, writer, context, template, idx) end elseif token._type == ">" ## partials: desc: Each line of the partial should be indented before rendering. fname = stripWhitespace(tokenValue) value = lookup(context, tokenValue) tpl_string = "" if isfile(fname) found_partial = true indent = token.indent buf = IOBuffer() for (rowno, l) in enumerate(eachline(fname, keep=true)) # we don't strip indent from first line, so we don't indent that print(buf, rowno > 0 ? indent : "", l) end tpl_string = String(take!(buf)) else value = lookup(context, fname) if !falsy(value) indent = token.indent slashn = "" # don't indent if last \n if occursin(r"\n$", value) value = chomp(value) slashn = "\n" end buf = IOBuffer() l = split(value, r"[\n]") print(buf, indent*join(l, "\n"*indent)) tpl_string = String(take!(buf)) * slashn close(buf) end end if tpl_string != "" ## Delimiters set in a parent template should not affect a partial. ## Delimiters set in a partial should not affect the parent template. tpl = parse(tpl_string, ("{{", "}}")) ## Issue 82, what context to pass along to the partial ## this makes "scope" of partial just the immediate value, not ## the parent renderTokens(io, tpl, writer, Context(context.view,nothing), template,idx) else # can't find partial. Issue #83 requests signal, but this doesn't # seem to match spec. Signal would go here. end elseif token._type == "<" ## partials without parse fname = stripWhitespace(tokenValue) if isfile(fname) print(io, open(x -> read(x, String), fname)) else @warn("File $fname not found") end elseif token._type == "&" value = lookup(context, tokenValue) if !falsy(value) ## desc: A lambda's return value should parse with the default delimiters. ## parse(value()) ensures that if isa(value, Function) push_task_local_storage(context.view) val = render(parse(string(value())), context.view) else val = value end print(io, val) end elseif token._type == "{" value = lookup(context, tokenValue) if !falsy(value) if isa(value, Function) push_task_local_storage(context.view) val = render(parse(string(value())), context.view) else val = value end print(io, val) end elseif token._type == "@" value = lookup(context, tokenValue) if !falsy(value) print(io, render(MustacheTokens(token.collector), value)) end elseif token._type == "name" value = lookup(context, tokenValue) if !falsy(value) if isa(value, Function) push_task_local_storage(context.view) val = render(string(value()), context.view) else val = value end print(io, escape_html(val)) end elseif token._type == "text" print(io, string(tokenValue)) end end end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
2659
## regular expressions to use whiteRe = r"\s*" spaceRe = r"\s+" nonSpaceRe = r"\S" eqRe = r"\s*=" curlyRe = r"\s*\}" # # section # ^ inversion # / close section # > partials # { dont' escape # & unescape a variable # = set delimiters {{=<% %>=}} will set delimiters to <% %> # ! comments # | lamdda "section" with *evaluated* value tagRe = r"^[#^/<>{&=!|]" function asRegex(txt) for i in ("[","]") txt = replace(txt, Regex("\\$i") => "\\$i") end for i in ("(", ")", "{","}", "|") txt = replace(txt, Regex("[$i]") => "[$i]") end Regex(txt) end isWhitespace(x) = occursin(whiteRe, x) function stripWhitespace(x) y = replace(x, r"^\s+" => "") replace(y, r"\s+$" => "") end ## this is for falsy value ## Falsy is true if x is false, 0 length, "", ... falsy(x::Bool) = !x falsy(x::Array) = isempty(x) || all(falsy, x) falsy(x::AbstractString) = x == "" falsy(x::Nothing) = true falsy(x::Missing) = true #falsy(x) = (x == nothing) || false # default function falsy(x) Tables.istable(x) && isempty(Tables.rows(x)) && return true x == nothing && return true false end ## escape_html with entities entityMap = [("&", "&amp;"), ("<", "&lt;"), (">", "&gt;"), ("'", "&#39;"), ("\"", "&quot;"), ("/", "&#x2F;")] function escape_html(x) y = string(x) for (k,v) in entityMap y = replace(y, k => v) end y end ## Make these work function escapeRe(string) replace(string, r"[\-\[\]{}()*+?.,\\\^$|#\s]" => "\\\$&"); end function escapeTags(tags) [Regex(escapeRe(tags[1]) * "\\s*"), Regex("\\s*" * escapeRe(tags[2]))] end # key may be string or a ":symbol" function normalize(key) if occursin(r"^:", key) key = key[2:end] key = Symbol(key) end return key end # means to push values into scope of function through # magic `this` variable, ala JavaScript # user in function has # `this = Mustache.get_this()` # then `this.prop` should get value or nothing struct This{T} __v__::T end # get function Base.getproperty(this::This, key::Symbol) key == :__v__ && return getfield(this, :__v__) get(this.__v__, key, nothing) end # push to task local storage to evaluate function function push_task_local_storage(view) task_local_storage(:__this__,This(view)) end get_this() = get(task_local_storage(), :__this__, This(())) ## heuristic to avoid loading DataFrames ## Once `Tables.jl` support for DataFrames is available, this can be dropped is_dataframe(x) = !isa(x, Dict) && !isa(x, Module) &&!isa(x, Array) && occursin(r"DataFrame", string(typeof(x)))
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
1323
## writer mutable struct Writer _cache::Dict _partialCache::Dict _loadPartial ## Function or nothing end Writer() = Writer(Dict(), Dict(), nothing) function clearCache(w::Writer) w._cache=Dict() w._partialCache=Dict() end function compile(io::IO, w::Writer, template, tags) # if haskey(w._cache, template) # return(w._cache[template]) # end ## tokens = parse(template, tags) tokens = template compileTokens(io, w, tokens.tokens, template) # w._cache[template] = compileTokens(io, w, tokens.tokens, template) # return(w._cache[template]) end function compilePartial(w::Writer, name, template, tags) fn = sprint(io -> compile(io, w, template, tags)) w._partialCache[name] = fn fn end function getPartial(w::Writer, name) ## didn't do loadPartial, as not sure where template is # if !haskey(w._partialCache, name) && is(w._loadPartial, Function) # compilePartial(w, w._partialCache[name] end function compileTokens(io, w::Writer, tokens, template) ## return a function function f(w::Writer, view) # no partials renderTokens(io, tokens, w, Context(view), template) # io in closure end return(f) end function render(io::IO, w::Writer, template, view) f = compile(io, w, template, ["{{", "}}"]) f(w, view) end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
10244
using Mustache using Test tpl = mt"a:{{x}} b:{{{y}}}" x, y = "ex", "why" d = Dict("x"=>"ex", "y"=>"why") mutable struct ThrowAway x y end struct Issue123 range end @test render(tpl, Main) == "a:ex b:why" @test render(tpl, d) == "a:ex b:why" @test render(tpl, ThrowAway(x,y)) == "a:ex b:why" ## triple quoted tpl = mt"""a:{{x}} b:{{y}}""" @test render(tpl, Main) == "a:ex b:why" @test render(tpl, d) == "a:ex b:why" @test render(tpl, ThrowAway(x,y)) == "a:ex b:why" ## conditional tpl = "{{#b}}this doesn't show{{/b}}{{#a}}this does show{{/a}}" @test render(tpl, Dict("a" => 1)) == "this does show" ## dict using symbols d = Dict(:a => x, :b => y) tpl = "a:{{:a}} b:{{:b}}" @test render(tpl, d) == "a:ex b:why" ## keyword args @test render(tpl, a="ex", b="why") == "a:ex b:why" ## unicode module TMP α = 1 β = 2 end @test render("{{α}} + 1 = {{β}}", TMP) == "1 + 1 = 2" @test render("{{:β}}", β=2) == "2" @test render("α - {{:β}}", β=2) == "α - 2" @test render("{{:α}}", α="β") == "β" ## {{.}} test tpl = mt"{{#:vec}}{{.}} {{/:vec}}" @test render(tpl, vec=[1,2,3]) == "1 2 3 " ## test of function, see http://mustache.github.io/mustache.5.html (Lambdas) tpl = mt"""{{#wrapped}} {{name}} is awesome. {{/wrapped}} """ d = Dict("name" => "Willy", "wrapped" => (txt, r) -> "<b>" * r(txt) * "</b>") @test Mustache.render(tpl, d) == "<b>Willy is awesome.\n</b>" # this shouldn't be "Willy", rather "{{name}}" d = Dict("name" => "Willy", "wrapped" => (txt) -> "<b>" * txt * "</b>") @test Mustache.render(tpl, d) == "<b>Willy is awesome.\n</b>" ## Test of using Dict in {{#}}/{{/}} things tpl = mt"{{#:d}}{{x}} and {{y}}{{/:d}}" d = Dict(); d["x"] = "salt"; d["y"] = "pepper" @test Mustache.render(tpl, d=d) == "salt and pepper" ## Added a new tag "|" for applying a function to a section tpl = """{{|lambda}}{{value}}{{/lambda}} dollars.""" d = Dict("value"=>"1.23456789", "lambda"=>(txt) -> "<b>" * string(round(parse(Float64, txt), digits=2)) * "</b>") @test Mustache.render(tpl, d) == "<b>1.23</b> dollars." tpl = """{{|lambda}}key{{/lambda}} dollars.""" d = Dict("lambda" => (txt) -> begin d = Dict("key" => "value") d[txt] end ) @test Mustache.render(tpl, d) == "value dollars." ## test nested section with filtering lambda tpl = """ {{#lambda}} {{#iterable}} {{#iterable2}} {{.}} {{/iterable2}} {{/iterable}} {{/lambda}} """ d = Dict("iterable"=>Dict("iterable2"=>["a","b","c"]), "lambda"=>(txt) -> "XXX $txt XXX") expected = "XXX a\nb\nc\n XXX" @test Mustache.render(tpl, d) == expected ## If the value of a section key is a function, it is called with the section's literal block of text, un-rendered, as its first argument. The second argument is a special rendering function that uses the current view as its view argument. It is called in the context of the current view object. tpl = mt"{{#:bold}}Hi {{:name}}.{{/:bold}}" function bold(text, render) this = Mustache.get_this() "<b>" * render(text) * "</b>" * this.xtra end expected = "<b>Hi Tater.</b>Hi Willy." @test Mustache.render(tpl; name="Tater", bold=bold, xtra = "Hi Willy.") == expected ## if the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration. tpl = mt"{{#:beatles}} * {{:name}} {{/:beatles}}" function name() this = Mustache.get_this() this.first * " " * this.last end beatles = [(first="John", last="Lennon"), (first="Paul", last="McCartney")] expected = "* John Lennon\n* Paul McCartney\n" @test tpl(; beatles=beatles, name=name) == expected ## Test with Named Tuples as a view tpl = "{{#:NT}}{{:a}} and {{:b}}{{/:NT}}" expected = "eh and bee" @test Mustache.render(tpl, NT=(a="eh", b="bee")) == expected expected = "eh and " @test Mustache.render(tpl, NT=(a="eh",)) == expected ## Test with a Table interface nt = (a="eh", b="bee", c="see") rt = [nt, nt, nt] # Tables.istable(rt) == true expected = "eh and bee"^3 @test Mustache.render(tpl, NT=rt) == expected ## test load filepath = joinpath(@__DIR__, "test.tpl") expected = "Testing 1, 2, 3..." @test render(Mustache.load(filepath), (one="1", two="2", three="3")) == expected @test render(Mustache.load(filepath), one="1", two="2", three="3") == expected filepath = joinpath(@__DIR__, "test-sections-lf.tpl") tokens = Mustache.load(filepath) @test Mustache.render(tokens, Dict("a"=>Dict("x"=>111,),)) == """ 111\n""" @test Mustache.render(tokens, Dict("y"=>222,)) == " 222\n" filepath = joinpath(@__DIR__, "test-sections-crlf.tpl") tokens = Mustache.load(filepath) @test Mustache.render(tokens, Dict("a"=>Dict("x"=>111,),)) == " 111\r\n" @test Mustache.render(tokens, Dict("y"=>222,)) == " 222\r\n" ## Test of MustacheTokens being callable tpl = mt"""Hello {{:name}}""" @test tpl(name="world") == "Hello world" # using kwargs... @test tpl((name="world",)) == "Hello world" # using arg @testset "closed issues" begin ## issue #51 inverted section @test Mustache.render("""{{^repos}}No repos :({{/repos}}""", Dict("repos" => [])) == "No repos :(" @test Mustache.render("{{^repos}}foo{{/repos}}",Dict("repos" => [Dict("name" => "repo name")])) == "" ## Issue #80 with 0 as falsy tpl = "this is {{:zero}}" @test render(tpl, zero=0) == "this is 0" ## Issue 88 template = "{{#:vec}}{{.}}{{^.[end]}},{{/.[end]}}{{/:vec}}"; @test render(template, vec=["a", "b", "c"]) == "a,b,c" @test render(template, vec=fill("a", 3)) == "a,a,a" ## Issue 91 handle istable without a schema. (Is getfield a general enough solution?) tpl = "{{#list}}{{ item }} {{/list}}" v = Dict("list" => Any[Dict("item" => "one"),Dict("item" => "two")]) @test Mustache.render(tpl, v) == "one two " ## Issue 99 expose tags tpl = "<<#list>><< item >> <</list>>" v = Dict("list" => Any[Dict("item" => "one"),Dict("item" => "two")]) @test Mustache.render(tpl, v, tags=("<<", ">>")) == "one two " tpl = "[[#list]][[ item ]] [[/list]]" @test Mustache.render(tpl, v, tags=("[[", "]]")) == "one two " ## Issue 104, bad nesting (needed to pop context) tpl1 = mt""" {{#nested.vec}} {{.}} {{/nested.vec}} {{nested.foo}} """ tpl2 = mt""" {{#nested}} {{#vec}} {{.}} {{/vec}} {{foo}} {{/nested}} {{nested.foo}} """ data2 = Dict("nested" => Dict("vec" => [1,2], "foo" => "bar")) @test Mustache.render(tpl1, data2) == "1\n2\nbar\n" @test Mustache.render(tpl2, data2) == "1\n2\nbar\nbar\n" ## Issue 114 Combine custom tags with no HTML escaping @test Mustache.render("\$[[{JL_VERSION_MATRIX}]]", Dict("JL_VERSION_MATRIX"=>"&"), tags=("\$[[","]]")) == "&" ## Issue fixed by PR #122 tpl = """ {{#:vec}}{{#.[1]}}<bold>{{.}}</bold>{{/.[1]}}{{^.[1]}}{{.}} {{/.[1]}}{{/:vec}} """ @test Mustache.render(tpl, vec = ["A1", "B2", "C3"]) == "<bold>A1</bold>B2 C3 \n" ## tpl = mt""" <input type="range" {{@:range}} min="{{start}}" step="{{step}}" max="{{stop}}" {{/:range}}> """ @test render(tpl, Issue123(1:2:3)) == "<input type=\"range\" min=\"1\" step=\"2\" max=\"3\" >\n" ## Issue 124 regression test" tpl = mt""" {{^dims}}<input type="text" value="">{{/dims}} {{#dims}}<textarea {{#.[1]}}cols="{{.}}"{{/.[1]}} {{#.[2]}}rows="{{.}}"{{/.[2]}}></textarea>{{/dims}} """ @test render(tpl, Dict("dims"=>missing)) == "<input type=\"text\" value=\"\">\n\n" @test render(tpl, Dict("dims"=>["1", "2"])) == "\n<textarea cols=\"1\" ></textarea><textarea rows=\"2\"></textarea>\n" @test render(tpl, Dict("dims"=>("1", "2"))) == "\n<textarea cols=\"1\" ></textarea><textarea rows=\"2\"></textarea>\n" @test render(tpl, Dict("dims"=>(1, 2))) == "\n<textarea cols=\"1\" ></textarea><textarea rows=\"2\"></textarea>\n" @test render(tpl, Dict("dims"=>1:2)) == "\n<textarea cols=\"1\" ></textarea><textarea rows=\"2\"></textarea>\n" ## issue 128 global versus local d = Dict(:two=>Dict(:x=>3), :x=>2) tpl = mt""" {{#:one}} {{#:two}} {{:x}} {{/:two}} {{/:one}} """ @test render(tpl, one=d) == "3\n" tpl = mt""" {{#:one}} {{#:two}} {{~:x}} {{/:two}} {{/:one}} """ @test render(tpl, one=d) == "2\n" @test render(tpl, one=d, x=1) == "1\n" ## Issue #133 triple brace with } tpl = raw"\includegraphics{<<{:filename}>>}" tokens = Mustache.parse(tpl, ("<<",">>")) @test render(tokens, filename="XXX") == raw"\includegraphics{XXX}" # alternative is to use `&` to avoid escaping @test render(raw"\includegraphics{<<&:filename>>}", (filename="XXX",), #render(string, view;tags=...) tags=("<<",">>")) == raw"\includegraphics{XXX}" ## jmt macro x = 1 tpl = jmt"$(2x) by {{:a}}" @test tpl(a=2) == "2 by 2" ## Issue #139 -- mishandling of tables data with partials A = [Dict("a" => "eh", "b" => "bee"), Dict("a" => "ah", "b" => "buh")] tpl = mt"{{#:A}}Pronounce a as {{>:d}} and b as {{b}}. {{/:A}}" out1 = render(tpl, A=A, d="*{{a}}*") A = [Dict(:a => "eh", :b => "bee"), Dict(:a => "ah", :b => "buh")] tpl = mt"{{#:A}}Pronounce a as {{>:d}} and b as {{:b}}. {{/:A}}" out2 = render(tpl, A=A, d="*{{:a}}*") A = [(a = "eh", b = "bee"), (a = "ah", b = "buh")] tpl = mt"{{#:A}}Pronounce a as {{>:d}} and b as {{:b}}. {{/:A}}" out3 = render(tpl, A=A, d="*{{:a}}*") @test out1 == out2 == out3 ## lookup in Tables compatible data ## find column tpl = mt"{{#:vec}}{{.}} {{/:vec}}" A = [(vec=1, a=2), (vec=2, a=3), (vec=3, a=4)] @test render(tpl, A) == "1 2 3 " ## Issue #143 look up key before checking for dotted @test render("Hello, {{ values.name }}!", Dict("values.name"=>"world")) == "Hello, world!" ## Issue 156 function calls with other tags tpla = """ <<#:vec>> - <<{name}>> - <<#:uppercase>><<{name}>><</:uppercase>> <</:vec>> """ tplb = """ {{#:vec}} - {{{name}}} - {{#:uppercase}}{{{name}}}{{/:uppercase}} {{/:vec}} """ vec = [Dict("name" => x) for x in ("a", "b")] _uppercase(str, render) = uppercase(render(str)) a = Mustache.render(Mustache.parse(tpla, ("<<", ">>")); vec=vec, uppercase=_uppercase) b = Mustache.render(Mustache.parse(tplb); vec=vec, uppercase=_uppercase) @test a == b end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
617
## Data frame test ## not run by default. Too time consuming and relies on external pacakgs using Mustache, DataFrames using Test using Printf # simple usage tpl = mt""" {{:TITLE}} {{#:D}} {{:english}} <--> {{:spanish}} {{/:D}} """ d = DataFrame(english=["hello", "good bye"], spanish=["hola", "adios"]) @test render(tpl, TITLE="translate", D=d) == "translate\nhello <--> hola\ngood bye <--> adios\n" ## Issue with data frames as keyword arguments tpl = """ {{#:fred}}{{:a}}--{{:b}}{{/:fred}} {{:barney}} """ d = DataFrame(a=[1,2,3], b=[3,2,1]) @test render(tpl, fred=d, barney="123") == "1--32--23--1\n123\n"
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
2060
## Some simple tests of the package using Mustache mtrender = render tpl = mt"the value of x is {{x}} and that of y is {{y}}" ## a dict out = mtrender(tpl, Dict("x"=>1, "y"=>2)) println(out) ## A module x = 1; y = "two" mtrender(tpl, Main) ## a CompositeKind mutable struct ThrowAway x y end mtrender(tpl, ThrowAway("ex","why")) ## a more useful CompositeKind using Distributions tpl = mt"Beta distribution with alpha={{alpha}}, beta={{beta}}" mtrender(tpl, Beta(1, 2)) ## conditional text using Mustache tpl = "{{#b}}this doesn't show{{/b}}{{#a}}this does show{{/a}}" mtrender(tpl, Dict("a" => 1)) ## We can iterate over data frames. Handy for making tables using Mustache using DataFrames ## SHow values in Main in a web page _names = Array(String, 0) _summaries = Array(String, 0) m = Main for s in sort(map(string, names(m))) v = Symbol(s) if isdefined(m,v) push!(_names, s) push!(_summaries, summary(eval(m,v))) end end using DataFrames d = DataFrame(names = _names, summs = _summaries) tpl = " <html> <head> <title>{{Title}}</title> </head> <body> <table> <tr><th>name</th><th>summary</th></tr> {{#d}} <tr><td>{{names}}</td><td>{{summs}}</td></tr> {{/d}} </body> </html> "; out = mtrender(tpl, {"Title" => "A quick table", "d" => d}) ## show in browser (on Mac) f = tempname() io = open("$f.html", "w") print(io, out) close(io) run(`open $f.html`) ## A dict using symbols d = { :a => 1, :b => 2} tpl = "symbol {{:a}} and {{:b}}" mtrender(tpl, d) ## array of Dicts using Mustache A = [Dict("a" => "eh", "b" => "bee"), Dict("a" => "ah", "b" => "buh")] ## Contrast to data frame: # D = DataFrame(quote # a = ["eh", "ah"] # b = ["bee", "buh"] # end); tpl = mt"{{#A}} pronounce a as {{a}} and b as {{b}}.{{/A}}" mtrender(tpl, Dict("A" => A)) ## use .[ind] to index within a vector: tpl = mt"{{#:vec}}{{.[1]}}{{/:vec}}" # just first one mtrender(tpl, vec=["A1","B2","C3"]) tpl = mt"{{#:vec}}{{.}}{{^.[end]}}, {{/.[end]}}{{/:vec}}" # serial commas mtrender(tpl, vec=["A1","B2","C3"])
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
1618
using Mustache function test_data(str, iter) [Dict(str => x) for x in iter] end failing_template = mt"{{#report}}[{{#times1}}{{x}},{{/times1}}],[{{#times2}}{{y}},{{/times2}}]{{/report}}" test_func = () -> render(failing_template, Dict("report" => [ Dict("times1" => test_data("x", 1:4), "times2" => test_data("y",4:8))])) res = test_func() @assert res == "[1,2,3,4,],[4,5,6,7,8,]" failing_template = mt"{{#report}}[{{#times1}}{{x}},[{{#times2}}{{y}},{{/times2}}],{{/times1}}]{{/report}}" test_func = () -> render(failing_template, Dict("report" => [Dict("times1" => test_data("x", 1:3), "times2" => test_data("y",4:8))])) res = test_func() @assert res == "[1,[4,5,6,7,8,],2,[4,5,6,7,8,],3,[4,5,6,7,8,],]" failing_template = mt"{{#report}}{{/report}}[{{#times1}}{{x}},[{{#times2}}{{x}},{{/times2}}],{{/times1}}]" test_func = () -> render(failing_template, Dict("report" => [], "times1" => test_data("x", 1:3), "times2" => test_data("x", 4:8))) res = test_func() @assert res == "[1,[4,5,6,7,8,],2,[4,5,6,7,8,],3,[4,5,6,7,8,],]" ## issue #31 -- nested sections mutable struct Location lat::Float64 lon::Float64 end mutable struct Thing location::Location name::AbstractString end x = [Thing(Location(1.,2.), "name"), Thing(Location(3.,4.), "nombre")] tpl = """ {{#:x}} {{#.}} {{#location}} {{lat}}--{{lon}} {{/location}} {{name}} {{/.}} {{/:x}} """ Mustache.render(tpl, x=x) == "\n\n\n1.0--2.0\n\nname\n\n\n\n\n3.0--4.0\n\nnombre\n\n\n"
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
2992
## This downloads and populates the spec test files using Mustache using YAML using Test ghub = "https://raw.githubusercontent.com/mustache/spec/72233f3ffda9e33915fd3022d0a9ebbcce265acd/specs/{{:spec}}.yml" specs = ["comments", "delimiters", "interpolation", "inverted", "partials", "sections"#, #"~lambdas" ] D = Dict() for spec in specs nm = Mustache.render(ghub, spec=spec) D[spec] = YAML.load_file(download(nm)) end function write_spec_file(fname) io = open("spec_$fname.jl","w") println(io, """ using Mustache using Test """) x = D[fname] println(io, "@testset \" $fname \" begin\n") for (i,t) in enumerate(x["tests"]) tpl = t["template"] tpl = replace(tpl, "\\" => "\\\\") tpl = replace(tpl, r"\"" => "\\\"") data = t["data"] desc = t["desc"] if haskey(t, "partials") for (k,v) in t["partials"] data[k] = v end end val = try Mustache.render(t["template"], data) catch err "Failed" end expected = t["expected"] expected_ = replace(expected, "\\" => "\\\\") expected_ = replace(expected_, r"\"" => "\\\"") expected_ = "\"\"\"" * expected_ * "\"\"\"" println(io, "\n\t## $desc") print(io, "tpl = \"\"\"") print(io, tpl) println(io, "\"\"\"\n") println(io, "\t@test Mustache.render(tpl, $data) == $expected_") println("") end println(io, "end\n\n") close(io) end for spec in specs write_spec_file(spec) end # partials are different, as they refer to an external file # this should clean up temp files, but we don't run as part of test suite # test 7 fails, but I think that one is wrong using Test function test_partials() for spec in specs for (i,t) in enumerate(D[spec]["tests"]) if haskey(t, "partials") println("""Test $spec / $i""") d = t["data"] partial = t["partials"] for (k,v) in partial io = open(k, "w") write(io, v) close(io) end tpl = t["template"] expected = t["expected"] out = Mustache.render(tpl, d) val = out == expected if val @test val else val = replace(out, r"\n"=>"") == replace(expected, r"\n"=>"") if val println("""$(t["desc"]): newline issue ...""") @test val else println("""$(t["desc"]): FAILED:\n $out != $expected""") end end for (k,v) in partial rm(k) end end end end end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
1756
using Mustache using Test tpl = mt"a:{{x}} b:{{{y}}}" x, y = "ex", "why" d = Dict("x"=>"ex", "y"=>"why") mutable struct ThrowAway x y end @test render(tpl, Main) == "a:ex b:why" @test render(tpl, d) == "a:ex b:why" @test render(tpl, ThrowAway(x,y)) == "a:ex b:why" ## triple quoted tpl = mt"""a:{{x}} b:{{y}}""" @test render(tpl, Main) == "a:ex b:why" @test render(tpl, d) == "a:ex b:why" @test render(tpl, ThrowAway(x,y)) == "a:ex b:why" ## conditional tpl = "{{#b}}this doesn't show{{/b}}{{#a}}this does show{{/a}}" @test render(tpl, Dict("a" => 1)) == "this does show" ## dict using symbols d = Dict(:a => x, :b => y) tpl = "a:{{:a}} b:{{:b}}" @test render(tpl, d) == "a:ex b:why" ## keyword args @test render(tpl, a="ex", b="why") == "a:ex b:why" ## unicode module TMP α = 1 β = 2 end @test render("{{α}} + 1 = {{β}}", TMP) == "1 + 1 = 2" @test render("{{:β}}", β=2) == "2" @test render("α - {{:β}}", β=2) == "α - 2" @test render("{{:α}}", α="β") == "β" ## {{.}} test tpl = mt"{{#:vec}}{{.}} {{/:vec}}" @test render(tpl, vec=[1,2,3]) == "1 2 3 " ## test of function, see http://mustache.github.io/mustache.5.html (Lambdas) tpl = mt"""{{#wrapped}} {{name}} is awesome. {{/wrapped}} """ d = Dict() d["name"] = "Willy" d["wrapped"] = function() function(text, render) "<b>" * render(text) * "</b>" end end @test Mustache.render(tpl, d) == "<b>\n Willy is awesome.\n</b>\n" #?? extra \n?? ## Test of using Dict in {{#}}/{{/}} things tpl = mt"{{#:d}}{{x}} and {{y}}{{/:d}}" d = Dict(); d["x"] = "salt"; d["y"] = "pepper" @test Mustache.render(tpl, d=d) == "salt and pepper" ## issue #51 inverted section @test Mustache.render("""{{^repos}}No repos :({{/repos}}""", Dict("repos" => [])) == "No repos :("
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
339
include("Mustache_test.jl") include("multiple_nested_sections.jl") include("test_index.jl") #include("data-frame-test.jl") # spec tests include("spec_comments.jl") include("spec_delimiters.jl") include("spec_interpolation.jl") include("spec_inverted.jl") include("spec_partials.jl") include("spec_sections.jl") include("spec_lambdas.jl")
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
1945
using Mustache using Test @testset " comments " begin ## Comment blocks should be removed from the template. tpl = """12345{{! Comment Block! }}67890""" @test Mustache.render(tpl, Dict{Any,Any}()) == """1234567890""" ## Multiline comments should be permitted. tpl = """12345{{! This is a multi-line comment... }}67890 """ @test Mustache.render(tpl, Dict{Any,Any}()) == """1234567890 """ ## All standalone comment lines should be removed. tpl = """Begin. {{! Comment Block! }} End. """ @test Mustache.render(tpl, Dict{Any,Any}()) == """Begin. End. """ ## All standalone comment lines should be removed. tpl = """Begin. {{! Indented Comment Block! }} End. """ @test Mustache.render(tpl, Dict{Any,Any}()) == """Begin. End. """ ## "\r\n" should be considered a newline for standalone tags. tpl = """| {{! Standalone Comment }} |""" @test Mustache.render(tpl, Dict{Any,Any}()) == """| |""" ## Standalone tags should not require a newline to precede them. tpl = """ {{! I'm Still Standalone }} !""" @test Mustache.render(tpl, Dict{Any,Any}()) == """!""" ## Standalone tags should not require a newline to follow them. tpl = """! {{! I'm Still Standalone }}""" @test Mustache.render(tpl, Dict{Any,Any}()) == """! """ ## All standalone comment lines should be removed. tpl = """Begin. {{! Something's going on here... }} End. """ @test Mustache.render(tpl, Dict{Any,Any}()) == """Begin. End. """ ## All standalone comment lines should be removed. tpl = """Begin. {{!s Something's going on here... }} End. """ @test Mustache.render(tpl, Dict{Any,Any}()) == """Begin. End. """ ## Inline comments should not strip whitespace tpl = """ 12 {{! 34 }} """ @test Mustache.render(tpl, Dict{Any,Any}()) == """ 12 """ ## Comment removal should preserve surrounding whitespace. tpl = """12345 {{! Comment Block! }} 67890""" @test Mustache.render(tpl, Dict{Any,Any}()) == """12345 67890""" end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
2855
using Mustache using Test @testset " delimiters " begin ## The equals sign (used on both sides) should permit delimiter changes. tpl = """{{=<% %>=}}(<%text%>)""" @test Mustache.render(tpl, Dict{Any,Any}("text"=>"Hey!")) == """(Hey!)""" ## Characters with special meaning regexen should be valid delimiters. tpl = """({{=[ ]=}}[text])""" @test Mustache.render(tpl, Dict{Any,Any}("text"=>"It worked!")) == """(It worked!)""" ## Delimiters set outside sections should persist. tpl = """[ {{#section}} {{data}} |data| {{/section}} {{= | | =}} |#section| {{data}} |data| |/section| ] """ @test Mustache.render(tpl, Dict{Any,Any}("section"=>true,"data"=>"I got interpolated.")) == """[ I got interpolated. |data| {{data}} I got interpolated. ] """ ## Delimiters set outside inverted sections should persist. tpl = """[ {{^section}} {{data}} |data| {{/section}} {{= | | =}} |^section| {{data}} |data| |/section| ] """ @test Mustache.render(tpl, Dict{Any,Any}("section"=>false,"data"=>"I got interpolated.")) == """[ I got interpolated. |data| {{data}} I got interpolated. ] """ ## Delimiters set in a parent template should not affect a partial. tpl = """[ {{>include}} ] {{= | | =}} [ |>include| ] """ @test Mustache.render(tpl, Dict{Any,Any}("value"=>"yes","include"=>".{{value}}.")) == """[ .yes. ] [ .yes. ] """ ## Delimiters set in a partial should not affect the parent template. tpl = """[ {{>include}} ] [ .{{value}}. .|value|. ] """ @test Mustache.render(tpl, Dict{Any,Any}("value"=>"yes","include"=>".{{value}}. {{= | | =}} .|value|.")) == """[ .yes. .yes. ] [ .yes. .|value|. ] """ ## Surrounding whitespace should be left untouched. tpl = """| {{=@ @=}} |""" @test Mustache.render(tpl, Dict{Any,Any}()) == """| |""" ## Whitespace should be left untouched. tpl = """ | {{=@ @=}} """ @test Mustache.render(tpl, Dict{Any,Any}()) == """ | """ ## Standalone lines should be removed from the template. tpl = """Begin. {{=@ @=}} End. """ @test Mustache.render(tpl, Dict{Any,Any}()) == """Begin. End. """ ## Indented standalone lines should be removed from the template. tpl = """Begin. {{=@ @=}} End. """ @test Mustache.render(tpl, Dict{Any,Any}()) == """Begin. End. """ ## "\r\n" should be considered a newline for standalone tags. tpl = """| {{= @ @ =}} |""" @test Mustache.render(tpl, Dict{Any,Any}()) == """| |""" ## Standalone tags should not require a newline to precede them. tpl = """ {{=@ @=}} =""" @test Mustache.render(tpl, Dict{Any,Any}()) == """=""" ## Standalone tags should not require a newline to follow them. tpl = """= {{=@ @=}}""" @test Mustache.render(tpl, Dict{Any,Any}()) == """= """ ## Superfluous in-tag whitespace should be ignored. tpl = """|{{= @ @ =}}|""" @test Mustache.render(tpl, Dict{Any,Any}()) == """||""" end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
6479
using Mustache using Test @testset " interpolation " begin ## Mustache-free templates should render as-is. tpl = """Hello from {Mustache}! """ @test Mustache.render(tpl, Dict{Any,Any}()) == """Hello from {Mustache}! """ ## Unadorned tags should interpolate content into the template. tpl = """Hello, {{subject}}! """ @test Mustache.render(tpl, Dict{Any,Any}("subject"=>"world")) == """Hello, world! """ ## Basic interpolation should be HTML escaped. tpl = """These characters should be HTML escaped: {{forbidden}} """ @test Mustache.render(tpl, Dict{Any,Any}("forbidden"=>"& \" < >")) == """These characters should be HTML escaped: &amp; &quot; &lt; &gt; """ ## Triple mustaches should interpolate without HTML escaping. tpl = """These characters should not be HTML escaped: {{{forbidden}}} """ @test Mustache.render(tpl, Dict{Any,Any}("forbidden"=>"& \" < >")) == """These characters should not be HTML escaped: & \" < > """ ## Ampersand should interpolate without HTML escaping. tpl = """These characters should not be HTML escaped: {{&forbidden}} """ @test Mustache.render(tpl, Dict{Any,Any}("forbidden"=>"& \" < >")) == """These characters should not be HTML escaped: & \" < > """ ## Integers should interpolate seamlessly. tpl = """\"{{mph}} miles an hour!\"""" @test Mustache.render(tpl, Dict{Any,Any}("mph"=>85)) == """\"85 miles an hour!\"""" ## Integers should interpolate seamlessly. tpl = """\"{{{mph}}} miles an hour!\"""" @test Mustache.render(tpl, Dict{Any,Any}("mph"=>85)) == """\"85 miles an hour!\"""" ## Integers should interpolate seamlessly. tpl = """\"{{&mph}} miles an hour!\"""" @test Mustache.render(tpl, Dict{Any,Any}("mph"=>85)) == """\"85 miles an hour!\"""" ## Decimals should interpolate seamlessly with proper significance. tpl = """\"{{power}} jiggawatts!\"""" @test Mustache.render(tpl, Dict{Any,Any}("power"=>1.21)) == """\"1.21 jiggawatts!\"""" ## Decimals should interpolate seamlessly with proper significance. tpl = """\"{{{power}}} jiggawatts!\"""" @test Mustache.render(tpl, Dict{Any,Any}("power"=>1.21)) == """\"1.21 jiggawatts!\"""" ## Decimals should interpolate seamlessly with proper significance. tpl = """\"{{&power}} jiggawatts!\"""" @test Mustache.render(tpl, Dict{Any,Any}("power"=>1.21)) == """\"1.21 jiggawatts!\"""" ## Failed context lookups should default to empty strings. tpl = """I ({{cannot}}) be seen!""" @test Mustache.render(tpl, Dict{Any,Any}()) == """I () be seen!""" ## Failed context lookups should default to empty strings. tpl = """I ({{{cannot}}}) be seen!""" @test Mustache.render(tpl, Dict{Any,Any}()) == """I () be seen!""" ## Failed context lookups should default to empty strings. tpl = """I ({{&cannot}}) be seen!""" @test Mustache.render(tpl, Dict{Any,Any}()) == """I () be seen!""" ## Dotted names should be considered a form of shorthand for sections. tpl = """\"{{person.name}}\" == \"{{#person}}{{name}}{{/person}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("person"=>Dict{Any,Any}("name"=>"Joe"))) == """\"Joe\" == \"Joe\"""" ## Dotted names should be considered a form of shorthand for sections. tpl = """\"{{{person.name}}}\" == \"{{#person}}{{{name}}}{{/person}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("person"=>Dict{Any,Any}("name"=>"Joe"))) == """\"Joe\" == \"Joe\"""" ## Dotted names should be considered a form of shorthand for sections. tpl = """\"{{&person.name}}\" == \"{{#person}}{{&name}}{{/person}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("person"=>Dict{Any,Any}("name"=>"Joe"))) == """\"Joe\" == \"Joe\"""" ## Dotted names should be functional to any level of nesting. tpl = """\"{{a.b.c.d.e.name}}\" == \"Phil\"""" @test Mustache.render(tpl, Dict{Any,Any}("a"=>Dict{Any,Any}("b"=>Dict{Any,Any}("c"=>Dict{Any,Any}("d"=>Dict{Any,Any}("e"=>Dict{Any,Any}("name"=>"Phil"))))))) == """\"Phil\" == \"Phil\"""" ## Any falsey value prior to the last part of the name should yield ''. tpl = """\"{{a.b.c}}\" == \"\"""" @test Mustache.render(tpl, Dict{Any,Any}("a"=>Dict{Any,Any}())) == """\"\" == \"\"""" ## Each part of a dotted name should resolve only against its parent. tpl = """\"{{a.b.c.name}}\" == \"\"""" @test Mustache.render(tpl, Dict{Any,Any}("c"=>Dict{Any,Any}("name"=>"Jim"),"a"=>Dict{Any,Any}("b"=>Dict{Any,Any}()))) == """\"\" == \"\"""" ## The first part of a dotted name should resolve as any other name. tpl = """\"{{#a}}{{b.c.d.e.name}}{{/a}}\" == \"Phil\"""" @test Mustache.render(tpl, Dict{Any,Any}("b"=>Dict{Any,Any}("c"=>Dict{Any,Any}("d"=>Dict{Any,Any}("e"=>Dict{Any,Any}("name"=>"Wrong")))),"a"=>Dict{Any,Any}("b"=>Dict{Any,Any}("c"=>Dict{Any,Any}("d"=>Dict{Any,Any}("e"=>Dict{Any,Any}("name"=>"Phil"))))))) == """\"Phil\" == \"Phil\"""" ## Dotted names should be resolved against former resolutions. tpl = """{{#a}}{{b.c}}{{/a}}""" @test Mustache.render(tpl, Dict{Any,Any}("b"=>Dict{Any,Any}("c"=>"ERROR"),"a"=>Dict{Any,Any}("b"=>Dict{Any,Any}()))) == """""" ## Interpolation should not alter surrounding whitespace. tpl = """| {{string}} |""" @test Mustache.render(tpl, Dict{Any,Any}("string"=>"---")) == """| --- |""" ## Interpolation should not alter surrounding whitespace. tpl = """| {{{string}}} |""" @test Mustache.render(tpl, Dict{Any,Any}("string"=>"---")) == """| --- |""" ## Interpolation should not alter surrounding whitespace. tpl = """| {{&string}} |""" @test Mustache.render(tpl, Dict{Any,Any}("string"=>"---")) == """| --- |""" ## Standalone interpolation should not alter surrounding whitespace. tpl = """ {{string}} """ @test Mustache.render(tpl, Dict{Any,Any}("string"=>"---")) == """ --- """ ## Standalone interpolation should not alter surrounding whitespace. tpl = """ {{{string}}} """ @test Mustache.render(tpl, Dict{Any,Any}("string"=>"---")) == """ --- """ ## Standalone interpolation should not alter surrounding whitespace. tpl = """ {{&string}} """ @test Mustache.render(tpl, Dict{Any,Any}("string"=>"---")) == """ --- """ ## Superfluous in-tag whitespace should be ignored. tpl = """|{{ string }}|""" @test Mustache.render(tpl, Dict{Any,Any}("string"=>"---")) == """|---|""" ## Superfluous in-tag whitespace should be ignored. tpl = """|{{{ string }}}|""" @test Mustache.render(tpl, Dict{Any,Any}("string"=>"---")) == """|---|""" ## Superfluous in-tag whitespace should be ignored. tpl = """|{{& string }}|""" @test Mustache.render(tpl, Dict{Any,Any}("string"=>"---")) == """|---|""" end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
4698
using Mustache using Test @testset " inverted " begin ## Falsey sections should have their contents rendered. tpl = """\"{{^boolean}}This should be rendered.{{/boolean}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """\"This should be rendered.\"""" ## Truthy sections should have their contents omitted. tpl = """\"{{^boolean}}This should not be rendered.{{/boolean}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """\"\"""" ## Objects and hashes should behave like truthy values. tpl = """\"{{^context}}Hi {{name}}.{{/context}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("context"=>Dict{Any,Any}("name"=>"Joe"))) == """\"\"""" ## Lists should behave like truthy values. tpl = """\"{{^list}}{{n}}{{/list}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("list"=>Dict{Any,Any}[Dict("n"=>1), Dict("n"=>2), Dict("n"=>3)])) == """\"\"""" ## Empty lists should behave like falsey values. tpl = """\"{{^list}}Yay lists!{{/list}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("list"=>Any[])) == """\"Yay lists!\"""" ## Multiple inverted sections per template should be permitted. tpl = """{{^bool}} * first {{/bool}} * {{two}} {{^bool}} * third {{/bool}} """ @test Mustache.render(tpl, Dict{Any,Any}("two"=>"second","bool"=>false)) == """* first * second * third """ ## Nested falsey sections should have their contents rendered. tpl = """| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |""" @test Mustache.render(tpl, Dict{Any,Any}("bool"=>false)) == """| A B C D E |""" ## Nested truthy sections should be omitted. tpl = """| A {{^bool}}B {{^bool}}C{{/bool}} D{{/bool}} E |""" @test Mustache.render(tpl, Dict{Any,Any}("bool"=>true)) == """| A E |""" ## Failed context lookups should be considered falsey. tpl = """[{{^missing}}Cannot find key 'missing'!{{/missing}}]""" @test Mustache.render(tpl, Dict{Any,Any}()) == """[Cannot find key 'missing'!]""" ## Dotted names should be valid for Inverted Section tags. tpl = """\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"\"""" @test Mustache.render(tpl, Dict{Any,Any}("a"=>Dict{Any,Any}("b"=>Dict{Any,Any}("c"=>true)))) == """\"\" == \"\"""" ## Dotted names should be valid for Inverted Section tags. tpl = """\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\"""" @test Mustache.render(tpl, Dict{Any,Any}("a"=>Dict{Any,Any}("b"=>Dict{Any,Any}("c"=>false)))) == """\"Not Here\" == \"Not Here\"""" ## Dotted names that cannot be resolved should be considered falsey. tpl = """\"{{^a.b.c}}Not Here{{/a.b.c}}\" == \"Not Here\"""" @test Mustache.render(tpl, Dict{Any,Any}("a"=>Dict{Any,Any}())) == """\"Not Here\" == \"Not Here\"""" ## Inverted sections should not alter surrounding whitespace. tpl = """ | {{^boolean}} | {{/boolean}} | """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """ | | | """ ## Inverted should not alter internal whitespace. tpl = """ | {{^boolean}} {{! Important Whitespace }} {{/boolean}} | """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == " | \n |\n" #""" |\\s # | #""" ## Single-line sections should not alter surrounding whitespace. tpl = """ {{^boolean}}NO{{/boolean}} {{^boolean}}WAY{{/boolean}} """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """ NO WAY """ ## Standalone lines should be removed from the template. tpl = """| This Is {{^boolean}} | {{/boolean}} | A Line """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """| This Is | | A Line """ ## Standalone indented lines should be removed from the template. tpl = """| This Is {{^boolean}} | {{/boolean}} | A Line """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """| This Is | | A Line """ ## "\r\n" should be considered a newline for standalone tags. tpl = """| {{^boolean}} {{/boolean}} |""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """| |""" ## Standalone tags should not require a newline to precede them. tpl = """ {{^boolean}} ^{{/boolean}} /""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """^ /""" ## Standalone tags should not require a newline to follow them. tpl = """^{{^boolean}} / {{/boolean}}""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """^ / """ ## Superfluous in-tag whitespace should be ignored. tpl = """|{{^ boolean }}={{/ boolean }}|""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """|=|""" ## Inverted section should not affect following render. tpl = """|{{^ boolean }}={{/ boolean }} {{ following.subfield }}|""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false, "following"=>Dict("subfield"=>1))) == """|= 1|""" end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
8424
using Mustache using Test mutable struct CallableFunction <: Function calls::Int end (F::CallableFunction)() = (F.calls += 1; string(F.calls)) @testset " lambdas " begin # overview: | # Lambdas are a special-cased data type for use in interpolations and # sections. # When used as the data value for an Interpolation tag, the lambda MUST be # treatable as an arity 0 function, and invoked as such. The returned value # MUST be rendered against the default delimiters, then interpolated in place # of the lambda. # When used as the data value for a Section tag, the lambda MUST be treatable # as an arity 1 function, and invoked as such (passing a String containing the # unprocessed section contents). The returned value MUST be rendered against # the current delimiters, then interpolated in place of the section. # tests: # - name: Interpolation # desc: A lambda's return value should be interpolated. # data: # lambda: !code # ruby: 'proc { "world" }' # perl: 'sub { "world" }' # js: 'function() { return "world" }' # php: 'return "world";' # python: 'lambda: "world"' # clojure: '(fn [] "world")' # template: "Hello, {{lambda}}!" # expected: "Hello, world!" template = "Hello, {{lambda}}!" expected = "Hello, world!" data = Dict("lambda"=> () -> "world") @test Mustache.render(template, data) == expected # - name: Interpolation - Expansion # desc: A lambda's return value should be parsed. # data: # planet: "world" # lambda: !code # ruby: 'proc { "{{planet}}" }' # perl: 'sub { "{{planet}}" }' # js: 'function() { return "{{planet}}" }' # php: 'return "{{planet}}";' # python: 'lambda: "{{planet}}"' # clojure: '(fn [] "{{planet}}")' # template: "Hello, {{lambda}}!" # expected: "Hello, world!" template = "Hello, {{lambda}}!" expected = "Hello, world!" data = Dict("lambda" => () -> "{{planet}}", "planet" => "world") @test Mustache.render(template, data) == expected # - name: Interpolation - Alternate Delimiters # desc: A lambda's return value should parse with the default delimiters. # data: # planet: "world" # lambda: !code # ruby: 'proc { "|planet| => {{planet}}" }' # perl: 'sub { "|planet| => {{planet}}" }' # js: 'function() { return "|planet| => {{planet}}" }' # php: 'return "|planet| => {{planet}}";' # python: 'lambda: "|planet| => {{planet}}"' # clojure: '(fn [] "|planet| => {{planet}}")' # template: "{{= | | =}}\nHello, (|&lambda|)!" # expected: "Hello, (|planet| => world)!" template = "{{= | | =}}\nHello, (|&lambda|)!" expected = "Hello, (|planet| => world)!" data = Dict("planet"=>"world", "lambda"=> () -> "|planet| => {{planet}}") @test Mustache.render(template, data) == expected # - name: Interpolation - Multiple Calls # desc: Interpolated lambdas should not be cached. # data: # lambda: !code # ruby: 'proc { $calls ||= 0; $calls += 1 }' # perl: 'sub { no strict; $calls += 1 }' # js: 'function() { return (g=(function(){return this})()).calls=(g.calls||0)+1 }' # php: 'global $calls; return ++$calls;' # python: 'lambda: globals().update(calls=globals().get("calls",0)+1) or calls' # clojure: '(def g (atom 0)) (fn [] (swap! g inc))' # template: '{{lambda}} == {{{lambda}}} == {{lambda}}' # expected: '1 == 2 == 3' template = "{{lambda}} == {{{lambda}}} == {{lambda}}" expected = "1 == 2 == 3" data = Dict("lambda" => CallableFunction(0)) @test Mustache.render(template, data) == expected # - name: Escaping # desc: Lambda results should be appropriately escaped. # data: # lambda: !code # ruby: 'proc { ">" }' # perl: 'sub { ">" }' # js: 'function() { return ">" }' # php: 'return ">";' # python: 'lambda: ">"' # clojure: '(fn [] ">")' # template: "<{{lambda}}{{{lambda}}}" # expected: "<&gt;>" template = "<{{lambda}}{{{lambda}}}" expected = "<&gt;>" data = Dict("lambda" => () -> ">") @test Mustache.render(template, data) == expected # - name: Section # desc: Lambdas used for sections should receive the raw section string. # data: # x: 'Error!' # lambda: !code # ruby: 'proc { |text| text == "{{x}}" ? "yes" : "no" }' # perl: 'sub { $_[0] eq "{{x}}" ? "yes" : "no" }' # js: 'function(txt) { return (txt == "{{x}}" ? "yes" : "no") }' # php: 'return ($text == "{{x}}") ? "yes" : "no";' # python: 'lambda text: text == "{{x}}" and "yes" or "no"' # clojure: '(fn [text] (if (= text "{{x}}") "yes" "no"))' # template: "<{{#lambda}}{{x}}{{/lambda}}>" # expected: "<yes>" template = "<{{#lambda}}{{x}}{{/lambda}}>" expected = "<yes>" data = Dict("x" => "Error!", "lambda" => (txt) -> txt == "{{x}}" ? "yes" : "no") @test Mustache.render(template, data) == expected # - name: Section - Expansion # desc: Lambdas used for sections should have their results parsed. # data: # planet: "Earth" # lambda: !code # ruby: 'proc { |text| "#{text}{{planet}}#{text}" }' # perl: 'sub { $_[0] . "{{planet}}" . $_[0] }' # js: 'function(txt) { return txt + "{{planet}}" + txt }' # php: 'return $text . "{{planet}}" . $text;' # python: 'lambda text: "%s{{planet}}%s" % (text, text)' # clojure: '(fn [text] (str text "{{planet}}" text))' # template: "<{{#lambda}}-{{/lambda}}>" # expected: "<-Earth->" template = "<{{#lambda}}-{{/lambda}}>" expected = "<-Earth->" data = Dict("planet"=> "Earth", "lambda" => (txt) -> txt * "{{planet}}" * txt) @test Mustache.render(template, data) == expected # - name: Section - Alternate Delimiters # desc: Lambdas used for sections should parse with the current delimiters. # data: # planet: "Earth" # lambda: !code # ruby: 'proc { |text| "#{text}{{planet}} => |planet|#{text}" }' # perl: 'sub { $_[0] . "{{planet}} => |planet|" . $_[0] }' # js: 'function(txt) { return txt + "{{planet}} => |planet|" + txt }' # php: 'return $text . "{{planet}} => |planet|" . $text;' # python: 'lambda text: "%s{{planet}} => |planet|%s" % (text, text)' # clojure: '(fn [text] (str text "{{planet}} => |planet|" text))' # template: "{{= | | =}}<|#lambda|-|/lambda|>" # expected: "<-{{planet}} => Earth->" template = "{{= | | =}}<|#lambda|-|/lambda|>" expected = "<-{{planet}} => Earth->" data = Dict("planet"=>"Earth", "lambda"=> (txt) -> txt * "{{planet}} => |planet|" * txt) @test Mustache.render(template, data) == expected # - name: Section - Multiple Calls # desc: Lambdas used for sections should not be cached. # data: # lambda: !code # ruby: 'proc { |text| "__#{text}__" }' # perl: 'sub { "__" . $_[0] . "__" }' # js: 'function(txt) { return "__" + txt + "__" }' # php: 'return "__" . $text . "__";' # python: 'lambda text: "__%s__" % (text)' # clojure: '(fn [text] (str "__" text "__"))' # template: '{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}' # expected: '__FILE__ != __LINE__' template = "{{#lambda}}FILE{{/lambda}} != {{#lambda}}LINE{{/lambda}}" expected = "__FILE__ != __LINE__" data = Dict("lambda" => (txt) -> "__" * txt * "__") @test Mustache.render(template, data) == expected # - name: Inverted Section # desc: Lambdas used for inverted sections should be considered truthy. # data: # static: 'static' # lambda: !code # ruby: 'proc { |text| false }' # perl: 'sub { 0 }' # js: 'function(txt) { return false }' # php: 'return false;' # python: 'lambda text: 0' # clojure: '(fn [text] false)' # template: "<{{^lambda}}{{static}}{{/lambda}}>" # expected: "<>" template = "<{{^lambda}}{{static}}{{/lambda}}>" expected = "<>" data = Dict("static" => "static", "lambda" => (txt) -> false) @test Mustache.render(template, data) == expected end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
2174
using Mustache using Test @testset " partials " begin ## The greater-than operator should expand to the named partial. tpl = """\"{{>text}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("text"=>"from partial")) == """\"from partial\"""" ## The empty string should be used when the named partial is not found. tpl = """\"{{>text}}\"""" @test Mustache.render(tpl, Dict{Any,Any}()) == """\"\"""" ## The greater-than operator should operate within the current context. tpl = """\"{{>partial}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("partial"=>"*{{text}}*","text"=>"content")) == """\"*content*\"""" ## The greater-than operator should properly recurse. tpl = """{{>node}}""" @test Mustache.render(tpl, Dict{Any,Any}("nodes"=>Dict{Any,Any}[Dict("nodes"=>Any[],"content"=>"Y")],"content"=>"X","node"=>"{{content}}<{{#nodes}}{{>node}}{{/nodes}}>")) == """X<Y<>>""" ## The greater-than operator should not alter surrounding whitespace. tpl = """| {{>partial}} |""" @test Mustache.render(tpl, Dict{Any,Any}("partial"=>"\t|\t")) == """| | |""" ## Whitespace should be left untouched. tpl = """ {{data}} {{> partial}} """ @test Mustache.render(tpl, Dict{Any,Any}("partial"=>">\n>","data"=>"|")) == """ | > > """ ## "\r\n" should be considered a newline for standalone tags. tpl = """| {{>partial}} |""" @test Mustache.render(tpl, Dict{Any,Any}("partial"=>">")) == """| >|""" ## Standalone tags should not require a newline to precede them. tpl = """ {{>partial}} >""" @test_skip Mustache.render(tpl, Dict{Any,Any}("partial"=>">\n>")) == """ > >>""" ## Standalone tags should not require a newline to follow them. tpl = """> {{>partial}}""" @test Mustache.render(tpl, Dict{Any,Any}("partial"=>">\n>")) == """> > >""" ## Each line of the partial should be indented before rendering. tpl = """\\ {{>partial}} / """ @test Mustache.render(tpl, Dict{Any,Any}("partial"=>"|\n{{{content}}}\n|\n","content"=>"<\n->")) == """\\ | < -> | / """ ## Superfluous in-tag whitespace should be ignored. tpl = """|{{> partial }}|""" @test Mustache.render(tpl, Dict{Any,Any}("partial"=>"[]","boolean"=>true)) == """|[]|""" end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
6043
using Mustache using Test @testset " sections " begin ## Truthy sections should have their contents rendered. tpl = """\"{{#boolean}}This should be rendered.{{/boolean}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """\"This should be rendered.\"""" ## Falsey sections should have their contents omitted. tpl = """\"{{#boolean}}This should not be rendered.{{/boolean}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>false)) == """\"\"""" ## Objects and hashes should be pushed onto the context stack. tpl = """\"{{#context}}Hi {{name}}.{{/context}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("context"=>Dict{Any,Any}("name"=>"Joe"))) == """\"Hi Joe.\"""" ## All elements on the context stack should be accessible. tpl = """{{#a}} {{one}} {{#b}} {{one}}{{two}}{{one}} {{#c}} {{one}}{{two}}{{three}}{{two}}{{one}} {{#d}} {{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}} {{#e}} {{one}}{{two}}{{three}}{{four}}{{five}}{{four}}{{three}}{{two}}{{one}} {{/e}} {{one}}{{two}}{{three}}{{four}}{{three}}{{two}}{{one}} {{/d}} {{one}}{{two}}{{three}}{{two}}{{one}} {{/c}} {{one}}{{two}}{{one}} {{/b}} {{one}} {{/a}} """ @test Mustache.render(tpl, Dict{Any,Any}("c"=>Dict{Any,Any}("three"=>3),"e"=>Dict{Any,Any}("five"=>5),"b"=>Dict{Any,Any}("two"=>2),"a"=>Dict{Any,Any}("one"=>1),"d"=>Dict{Any,Any}("four"=>4))) == """1 121 12321 1234321 123454321 1234321 12321 121 1 """ ## Lists should be iterated; list items should visit the context stack. tpl = """\"{{#list}}{{item}}{{/list}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("list"=>Dict{Any,Any}[Dict("item"=>1), Dict("item"=>2), Dict("item"=>3)])) == """\"123\"""" ## Empty lists should behave like falsey values. tpl = """\"{{#list}}Yay lists!{{/list}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("list"=>Any[])) == """\"\"""" ## Multiple sections per template should be permitted. tpl = """{{#bool}} * first {{/bool}} * {{two}} {{#bool}} * third {{/bool}} """ @test Mustache.render(tpl, Dict{Any,Any}("two"=>"second","bool"=>true)) == """* first * second * third """ ## Nested truthy sections should have their contents rendered. tpl = """| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |""" @test Mustache.render(tpl, Dict{Any,Any}("bool"=>true)) == """| A B C D E |""" ## Nested falsey sections should be omitted. tpl = """| A {{#bool}}B {{#bool}}C{{/bool}} D{{/bool}} E |""" @test Mustache.render(tpl, Dict{Any,Any}("bool"=>false)) == """| A E |""" ## Failed context lookups should be considered falsey. tpl = """[{{#missing}}Found key 'missing'!{{/missing}}]""" @test Mustache.render(tpl, Dict{Any,Any}()) == """[]""" ## Implicit iterators should directly interpolate strings. tpl = """\"{{#list}}({{.}}){{/list}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("list"=>["a", "b", "c", "d", "e"])) == """\"(a)(b)(c)(d)(e)\"""" ## Implicit iterators should cast integers to strings and interpolate. tpl = """\"{{#list}}({{.}}){{/list}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("list"=>[1, 2, 3, 4, 5])) == """\"(1)(2)(3)(4)(5)\"""" ## Implicit iterators should cast decimals to strings and interpolate. tpl = """\"{{#list}}({{.}}){{/list}}\"""" @test Mustache.render(tpl, Dict{Any,Any}("list"=>[1.1, 2.2, 3.3, 4.4, 5.5])) == """\"(1.1)(2.2)(3.3)(4.4)(5.5)\"""" ## Dotted names should be valid for Section tags. tpl = """\"{{#a.b.c}}Here{{/a.b.c}}\" == \"Here\"""" @test Mustache.render(tpl, Dict{Any,Any}("a"=>Dict{Any,Any}("b"=>Dict{Any,Any}("c"=>true)))) == """\"Here\" == \"Here\"""" ## Dotted names should be valid for Section tags. tpl = """\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\"""" @test Mustache.render(tpl, Dict{Any,Any}("a"=>Dict{Any,Any}("b"=>Dict{Any,Any}("c"=>false)))) == """\"\" == \"\"""" ## Dotted names that cannot be resolved should be considered falsey. tpl = """\"{{#a.b.c}}Here{{/a.b.c}}\" == \"\"""" @test Mustache.render(tpl, Dict{Any,Any}("a"=>Dict{Any,Any}())) == """\"\" == \"\"""" ## Sections should not alter surrounding whitespace. tpl = """ | {{#boolean}} | {{/boolean}} | """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """ | | | """ ## Sections should not alter internal whitespace. tpl = """ | {{#boolean}} {{! Important Whitespace }} {{/boolean}} | """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """ | | """ ## Single-line sections should not alter surrounding whitespace. tpl = """ {{#boolean}}YES{{/boolean}} {{#boolean}}GOOD{{/boolean}} """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """ YES GOOD """ ## Standalone lines should be removed from the template. tpl = """| This Is {{#boolean}} | {{/boolean}} | A Line """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """| This Is | | A Line """ ## Indented standalone lines should be removed from the template. tpl = """| This Is {{#boolean}} | {{/boolean}} | A Line """ @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """| This Is | | A Line """ ## "\r\n" should be considered a newline for standalone tags. tpl = """| {{#boolean}} {{/boolean}} |""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """| |""" ## Standalone tags should not require a newline to precede them. tpl = """ {{#boolean}} #{{/boolean}} /""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """# /""" ## Standalone tags should not require a newline to follow them. tpl = """#{{#boolean}} / {{/boolean}}""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """# / """ ## Superfluous in-tag whitespace should be ignored. tpl = """|{{# boolean }}={{/ boolean }}|""" @test Mustache.render(tpl, Dict{Any,Any}("boolean"=>true)) == """|=|""" ## Nested object fields should be accessible via global lookup tpl = """|{{# inner }}{{ field.subfield }}{{/ inner }} {{# inner }}{{ ~field.subfield }}{{/ inner }}|""" @test Mustache.render(tpl, Dict{Any,Any}("inner"=>Dict("field"=>Dict("subfield"=>1)),"field"=>Dict("subfield"=>2))) == """|1 2|""" end
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
code
359
## Experimental syntax for indexing within vectors: using Test ## use # to include tpl = mt"{{#:vec}}{{#.[1]}}{{.}}{{/.[1]}}{{/:vec}}" out = Mustache.render(tpl, vec=["A1","B2","C3"]) @test out == "A1" ## use ^ to exclude tpl = mt"{{#:vec}}{{.}}{{^.[end]}}, {{/.[end]}}{{/:vec}}" out = Mustache.render(tpl, vec=["A1","B2","C3"]) @test out == "A1, B2, C3"
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
docs
806
# Mustache [![Docs](https://img.shields.io/badge/docs-dev-blue.svg)](https://jverzani.github.io/Mustache.jl/dev) [![Build Status](https://github.com/jverzani/Mustache.jl/workflows/CI/badge.svg)](https://github.com/jverzani/Mustache.jl/actions) [![codecov](https://codecov.io/gh/jverzani/Mustache.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/jverzani/Mustache.jl) [{{ mustache }}](http://mustache.github.io/) is ... a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. This package ports over the [mustache.js](https://github.com/janl/mustache.js) implementation for use in [Julia](http://julialang.org). All credit should go there. All bugs are my own.
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.0.20
3b2db451a872b20519ebb0cec759d3d81a1c6bcb
docs
18935
# Mustache.jl Documentation for [Mustache.jl](https://github.com/jverzani/Mustache.jl). ## Examples Following the main [documentation](http://mustache.github.io/mustache.5.html) for `Mustache.js` we have a "typical Mustache template" defined by: ```julia using Mustache tpl = mt""" Hello {{name}} You have just won {{value}} dollars! {{#in_ca}} Well, {{taxed_value}} dollars, after taxes. {{/in_ca}} """ ``` The values with braces (mustaches on their side) are looked up in a view, such as a dictionary or module. For example, ```julia d = Dict( "name" => "Chris", "value" => 10000, "taxed_value" => 10000 - (10000 * 0.4), "in_ca" => true) Mustache.render(tpl, d) ``` Yielding ``` Hello Chris You have just won 10000 dollars! Well, 6000.0 dollars, after taxes. ``` The `render` function pieces things together. Like `print`, the first argument is for an optional `IO` instance. In the above example, where one is not provided, a string is returned. The flow is * a template is parsed into tokens by `Mustache.parse`. This can be called directly, indirectly through the non-standard string literal `mt`, or when loading a file with `Mustache.load`. The templates use tags comprised of matching mustaches (`{}`), either two or three, to indicate a value to be substituted for. These tags may be adjusted when `parse` is called. * The tokens and a view are `render`ed. The `render` function takes tokens as its second argument. If this argument is a string, `parse` is called internally. The `render` function than reassambles the template, substituting values, as appropriate, from the "view" passed to it and writes the output to the specified `io` argument. There are only 4 exports: `mt` and `jmt`, string literals to specify a template, `render`, and `render_from_file`. The view used to provide values to substitute into the template can be specified in a variety of ways. The above example used a dictionary. A Module may also be used, such as `Main`: ```julia name, value, taxed_value, in_ca = "Christine", 10000, 10000 - (10000 * 0.4), false Mustache.render(tpl, Main) |> print ``` Which yields: ``` Hello Christine You have just won 10000 dollars! ``` Further, keyword arguments can be used when the variables in the templates are symbols: ```julia goes_together = mt"{{{:x}}} and {{{:y}}}." Mustache.render(goes_together, x="Salt", y="pepper") Mustache.render(goes_together, x="Bread", y="butter") ``` `Tokens` objects are functors; keyword arguments can also be passed to a `Tokens` object directly (bypassing the use of `render`): ```julia goes_together = mt"{{{:x}}} and {{{:y}}}." goes_together(x="Fish", y="chips") ``` Similarly, a named tuple may be used as a view. As well, one can use Composite Kinds. This may make writing `show` methods easier: ```julia using Distributions tpl = "Beta distribution with alpha={{α}}, beta={{β}}" Mustache.render(tpl, Beta(1, 2)) ``` gives ``` "Beta distribution with alpha=1.0, beta=2.0" ``` ### Rendering The `render` function combines tokens and a view to fill in the template. The basic call is `render([io::IO], tokens, view)`, however there are variants: * `render(tokens; kwargs...)` * `render(string, view)` (`string` is parsed into tokens) * `render(string; kwargs...)` Finally, tokens are callable, so there are these variants to call `render`: * `tokens([io::IO], view)` * `tokens([io::IO]; kwargs...)` ### Views Views are used to hold values for the templates variables. There are many possible objects that can be used for views: * a dictionary * a named tuple * keyword arguments to `render` * a module For templates which iterate over a variable, these can be * a `Tables.jl` compatible object with row iteration support (e.g., A `DataFrame`, a tuple of named tuples, ...) * a vector or tuple (in which case "`.`" is used to match ### Templates and tokens A template is parsed into tokens. The `render` function combines the tokens with the view to create the output. * Parsing is done at compile time, if the `mt` string literal is used to define the template. If re-using a template, this is encouraged, as it will be more performant. * If string interpolation is desired prior to the parsing into tokens, the `jmt` string literal can be used. * As well, a string can be used to define a template. When `parse` is called, the string will be parsed into tokens. This is the flow if `render` is called on a string (and not tokens). ### Variables Tags representing variables for substitution have the form `{{varname}}`, `{{:symbol}}`, or their triple-braced versions `{{{varname}}}` or `{{{:symbol}}}`. The `varname` version will match variables in a view such as a dictionary or a module. The `:symbol` version will match variables passed in via named tuple or keyword arguments. ```julia b = "be" Mustache.render(mt"a {{b}} c", Main) # "a be c" Mustache.render(mt"a {{:b}} c", b="bee") # "a bee c" Mustache.render(mt"a {{:b}} c", (b="bee", c="sea")) # "a bee c" ``` The triple brace prevents HTML substitution for entities such as `<`. The following are escaped when only double braces are used: "&", "<", ">", "'", "\", and "/". ```julia Mustache.render(mt"a {{:b}} c", b = "%< bee >%") # "a %&lt; bee &gt;% c" Mustache.render(mt"a {{{:b}}} c", b = "%< bee >%") # "a %< bee >% c" ``` If different tags are specified to `parse`, say `<<` or `>>`, then `<<{` and `}>>` indicate the prevention of substitution. ```julia tokens = Mustache.parse("a <<:b>> c", ("<<", ">>")) Mustache.render(tokens, b = "%< B >%") # a %&lt; B &gt;% c" tokens = Mustache.parse("a <<{:b}>> c", ("<<", ">>")) Mustache.render(tokens, b = "%< B >%") # "a %< B >% c" ``` If the variable refers to a function, the value will be the result of calling the function with no arguments passed in. ```julia Mustache.render(mt"a {{:b}} c", b = () -> "Bea") # "a Bea c" ``` ```julia using Dates Mustache.render(mt"Written in the year {{:yr}}."; yr = year∘now) # "Written in the year 2023." ``` ### Sections In the main example, the template included: ``` {{#in_ca}} Well, {{taxed_value}} dollars, after taxes. {{/in_ca}} ``` Tags beginning with `#varname` and closed with `/varname` create "sections." These have different behaviors depending on the value of the variable. When the variable is not a function or a container the part between them is used only if the variable is defined and not "falsy:" ```julia a = mt"{{#:b}}Hi{{/:b}}"; a(; b=true) # "Hi" a(; c=true) # "" a(; b=false) # "" also, as `b` is "falsy" (e.g., false, nothing, "") ``` If the variable name refers to a function that function will be passed the unevaluated string within the section, as expected by the Mustache specification: ```julia Mustache.render("{{#:a}}one{{/:a}}", a=length) # "3" ``` The specification has been widened to accept functions of two arguments, the string and a render function: ```julia tpl = mt"{{#:bold}}Hi {{:name}}.{{/:bold}}" function bold(text, render) "<b>" * render(text) * "</b>" end tpl(; name="Tater", bold=bold) # "<b>Hi Tater.</b>" ``` If the tag "|" is used, the section value will be rendered first, an enhancement to the specification. ```julia fmt(txt) = "<b>" * string(round(parse(Float64, txt), digits=2)) * "</b>"; tpl = """{{|:lambda}}{{:value}}{{/:lambda}} dollars."""; Mustache.render(tpl, value=1.23456789, lambda=fmt) # "<b>1.23</b> dollars." ``` (Without the `|` in the tag, an error, `ERROR: ArgumentError: cannot parse "{{:value}}" as Float64`, will be thrown.) ### Inverted Related, if the tag begins with `^varname` and ends with `/varname` the text between these tags is included only if the variable is *not* defined or is `falsy`. ### Iteration If the section variable, `{{#varname}}`, binds to an iterable collection, then the text in the section is repeated for each item in the collection with the view used for the context of the template given by the item. This is useful for collections of named objects, such as DataFrames (where the collection is comprised of rows) or arrays of dictionaries. For `Tables.jl` objects the rows are iterated over. For data frames, the variable names are specified as symbols or strings. Here is a template for making a web page: ```julia tpl = mt""" <html> <head> <title>{{:TITLE}}</title> </head> <body> <table> <tr><th>name</th><th>summary</th></tr> {{#:D}} <tr><td>{{:names}}</td><td>{{:summs}}</td></tr> {{/:D}} </body> </html> """ ``` This can be used to generate a web page for `varinfo`-like values: ```julia _names = String[] _summaries = String[] for s in sort(map(string, names(Main))) v = Symbol(s) if isdefined(Main,v) push!(_names, s) push!(_summaries, summary(eval(v))) end end using DataFrames d = DataFrame(names=_names, summs=_summaries) out = Mustache.render(tpl, TITLE="A quick table", D=d) print(out) ``` This can be compared to using an array of `Dict`s, convenient if you have data by the row: ```julia A = [Dict("a" => "eh", "b" => "bee"), Dict("a" => "ah", "b" => "buh")] tpl = mt"{{#:A}}Pronounce a as {{a}} and b as {{b}}. {{/:A}}" Mustache.render(tpl, A=A) |> print ``` yielding ``` Pronounce a as eh and b as bee. Pronounce a as ah and b as buh. ``` The same approach can be made to make a LaTeX table from a data frame: ```julia function df_to_table(df, label="label", caption="caption") fmt = repeat("c", size(df,2)) header = join(string.(names(df)), " & ") row = join(["{{:$x}}" for x in map(string, names(df))], " & ") tpl=""" \\begin{table} \\centering \\begin{tabular}{$fmt} $header\\\\ {{#:DF}} $row\\\\ {{/:DF}} \\end{tabular} \\caption{$caption} \\label{tab:$label} \\end{table} """ Mustache.render(tpl, DF=df) end ``` In the above, a string is used above -- and not a `mt` macro -- so that string interpolation can happen. The `jmt_str` string macro allows for substitution, so the above template could also have been more simply written as: ```julia function df_to_table(df, label="label", caption="caption") fmt = repeat("c", size(df,2)) header = join(string.(names(df)), " & ") row = join(["{{:$x}}" for x in map(string, names(df))], " & ") tpl = jmt""" \begin{table} \centering \begin{tabular}{$fmt} $header\\ {{#:DF}} $row\\ {{/:DF}} \end{tabular} \caption{$caption} \label{tab:$label} \end{table} """ Mustache.render(tpl, DF=df) end ``` #### Iterating over vectors Though it isn't part of the Mustache specification, when iterating over an unnamed vector or tuple, `Mustache.jl uses` `{{.}}` to refer to the item: ```julia tpl = mt"{{#:vec}}{{.}} {{/:vec}}" Mustache.render(tpl, vec = ["A1", "B2", "C3"]) # "A1 B2 C3 " ``` Note the extra space after `C3`. There is also *limited* support for indexing with the iteration of a vector that allows one to treat the last element differently. The syntax `.[ind]` refers to the value `vec[ind]`. (There is no support for the usual arithmetic on indices.) To print commas one can use this pattern: ```julia tpl = mt"{{#:vec}}{{.}}{{^.[end]}}, {{/.[end]}}{{/:vec}}" Mustache.render(tpl, vec = ["A1", "B2", "C3"]) # "A1, B2, C3" ``` To put the first value in bold, but no others, say: ```julia tpl = mt""" {{#:vec}} {{#.[1]}}<bold>{{.}}</bold>{{/.[1]}} {{^.[1]}}{{.}}{{/.[1]}} {{/:vec}} """ Mustache.render(tpl, vec = ["A1", "B2", "C3"]) # basically "<bold>A1</bold>B2 C3" ``` This was inspired by [this](http://stackoverflow.com/questions/11147373/only-show-the-first-item-in-list-using-mustache) question, but the syntax chosen was more Julian. This syntax -- as implemented for now -- does not allow for iteration. That is constructs like `{{#.[1]}}` don't introduce iteration, but only offer a conditional check. ### Iterating when the value of a section variable is a function From the Mustache documentation, consider the template ```julia tpl = mt"{{#:beatles}} * {{:name}} {{/:beatles}}" ``` when `beatles` is a vector of named tuples (or some other `Tables.jl` object) and `name` is a function. When iterating over `beatles`, `name` can reference the rows of the `beatles` object by name. In `JavaScript`, this is done with `this.XXX`. In `Julia`, the values are stored in the `task_local_storage` object (with symbols as keys) allowing the access. The `Mustache.get_this` function allows `JavaScript`-like usage: ```julia function name() this = Mustache.get_this() this.first * " " * this.last end beatles = [(first="John", last="Lennon"), (first="Paul", last="McCartney")] tpl(; beatles, name) # "* John Lennon\n* Paul McCartney\n" ``` ### Conditional checking without iteration The section tag, `#`, check for existence; pushes the object into the view; and then iterates over the object. For cases where iteration is not desirable; the tag type `@` can be used. Compare these: ```julia julia> struct RANGE range end julia> tpl = mt""" <input type="range" {{@:range}} min="{{start}}" step="{{step}}" max="{{stop}}" {{/:range}}> """; julia> Mustache.render(tpl, RANGE(1:1:2)) "<input type=\"range\" min=\"1\" step=\"1\" max=\"2\" >\n" julia> tpl = mt""" <input type="range" {{#:range}} min="{{start}}" step="{{step}}" max="{{stop}}" {{/:range}}> """; julia> Mustache.render(tpl, RANGE(1:1:2)) # iterates over Range.range "<input type=\"range\" min=\"1\" step=\"1\" max=\"2\" min=\"1\" step=\"1\" max=\"2\" >\n" ``` ### Non-eager finding of values A view might have more than one variable bound to a symbol. The first one found is replaced in the template *unless* the variable is prefaced with `~`. This example illustrates: ```julia d = Dict(:two=>Dict(:x=>3), :x=>2) tpl = mt""" {{#:one}} {{#:two}} {{~:x}} {{/:two}} {{/:one}} """ Mustache.render(tpl, one=d) # "2\n" Mustache.render(tpl, one=d, x=1) # "1\n" ``` Were `{{:x}}` used, the value `3` would have been found within the dictionary `Dict(:x=>3)`; however, the presence of `{{~:x}}` is an instruction to keep looking up in the specified view to find other values, and use the last one found to substitute in. (This is hinted at in [this issue](https://github.com/janl/mustache.js/issues/399)) ### Partials Partials are used to include partial templates into a template. Partials begin with a greater than sign, like `{{> box.tpl }}`. In this example, the file `box.tpl` is opened and inserted into the template, then populated. A full path may be specified. They also inherit the calling context. In this way you may want to think of partials as includes, imports, template expansion, nested templates, or subtemplates, even though those aren't literally the case here. The partial specified by `{{< box.tpl }}` is not parsed, rather included as is into the file. This can be faster. The variable can be a filename, as indicated above, or if not a variable. For example ```julia julia> tpl = """\"{{>partial}}\"""" "\"{{>partial}}\"" julia> Mustache.render(tpl, Dict("partial"=>"*{{text}}*","text"=>"content")) "\"*content*\"" ``` ### Summary of tags To summarize the different tags marking a variable: * `{{variable}}` does substitution of the value held in `variable` in the current view; escapes HTML characters * `{{{variable}}}` does substitution of the value held in `variable` in the current view; does not escape HTML characters. The outer pair of mustache braces can be adjusted using `Mustache.parse`. * `{{&variable}}` is an alternative syntax for triple braces (useful with custom braces) * `{{~variable}}` does substitution of the value held in `variable` in the outmost view * `{{#variable}}` depending on the type of variable, does the following: - if `variable` is not a functions container and is not absent or `nothing` will use the text between the matching tags, marked with `{{/variable}}`; otherwise that text will be skipped. (Like an `if/end` block.) - if `variable` is a function, it will be applied to contents of the section. Use of `|` instead of `#` will instruct the rendering of the contents before applying the function. The spec allows for a function to have signature `(x, render)` where `render` is used internally to convert. This implementation allows rendering when `(x)` is the single argument. - if `variable` is a `Tables.jl` compatible object (row wise, with named rows), will iterate over the values, pushing the named tuple to be the top-most view for the part of the template up to `{{\variable}}`. - if `variable` is a vector or tuple -- for the part of the template up to `{{\variable}}` -- will iterate over the values. Use `{{.}}` to refer to the (unnamed) values. The values `.[end]` and `.[i]`, for a numeric literal, will refer to values in the vector or tuple. * `{{^variable}}`/`{{.variable}}` tags will show the values when `variable` is not defined, or is `nothing`. * `{{>partial}}` will include the partial value into the template, filling in the template using the current view. The partial can be a variable or a filename (checked with `isfile`). * `{{<partial}}` directly include partial value into template without filling in with the current view. * `{{!comment}}` comments begin with a bang, `!` ## Alternatives `Julia` provides some alternatives to this package which are better suited for many jobs: * For simple substitution inside a string there is string [interpolation](https://docs.julialang.org/en/latest/manual/strings/). * For piecing together pieces of text either the `string` function or string concatenation (the `*` operator) are useful. (Also an `IOBuffer` is useful for larger tasks of this type.) * For formatting numbers and text, the [Formatting.jl](https://github.com/JuliaLang/Formatting.jl) package, the [Format](https://github.com/JuliaString/Format.jl) package, and the [StringLiterals](https://github.com/JuliaString/StringLiterals.jl) package are available. * The [HypertextLiteral](https://github.com/MechanicalRabbit/HypertextLiteral.jl) package is useful when interpolating HTML, SVG, or SGML tagged content. ## Differences from Mustache.js This project deviates from Mustache.js in a few significant ways: * Julia structures are used, not JavaScript objects. As illustrated, one can use Dicts, Modules, DataFrames, functions, ... * In the Mustache spec, when lambdas are used as section names, the function is passed the unevaluated section: ```julia template = "<{{#lambda}}{{x}}{{/lambda}}>" data = Dict("x" => "Error!", "lambda" => (txt) -> txt == "{{x}}" ? "yes" : "no") Mustache.render(template, data) ## "<yes>", as txt == "{{x}}" ``` The tag "|" is similar to the section tag "#", but will receive the *evaluated* section: ```julia template = "<{{|lambda}}{{x}}{{/lambda}}>" data = Dict("x" => "Error!", "lambda" => (txt) -> txt == "{{x}}" ? "yes" : "no") Mustache.render(template, data) ## "<no>", as "Error!" != "{{x}}" ``` ## API ```@autodocs Modules = [Mustache] ```
Mustache
https://github.com/jverzani/Mustache.jl.git
[ "MIT" ]
1.1.0
13cad02cb3224ad0810ce364b785e81812d6cf02
code
984
module PlotReferenceImages local_path(args...) = normpath(@__DIR__, "..", args...) """ reference_file(backend::Symbol, i::Int, version::String) Find the latest version of the reference image file for the reference image `i` and the backend `be`. This returns a path to the file in the folder of the latest version. If no file is found, a path pointing to the file of the folder specified by `version` is returned. """ function reference_file(backend, i, version) refdir = local_path("Plots", string(backend)) fn = "ref$i.png" versions = sort(VersionNumber.(readdir(refdir)), rev = true) reffn = joinpath(refdir, string(version), fn) for v in versions tmpfn = joinpath(refdir, string(v), fn) if isfile(tmpfn) reffn = tmpfn break end end return reffn end reference_path(backend, version) = local_path("Plots", string(backend), string(version)) export reference_file, reference_path end # module
PlotReferenceImages
https://github.com/JuliaPlots/PlotReferenceImages.jl.git
[ "MIT" ]
1.1.0
13cad02cb3224ad0810ce364b785e81812d6cf02
code
174
using Test, PlotReferenceImages @testset "PlotReferenceImages" begin @test !isdir(reference_path(:notabackend, v"1")) @test isfile(reference_file(:gr, 1, v"1")) end
PlotReferenceImages
https://github.com/JuliaPlots/PlotReferenceImages.jl.git
[ "MIT" ]
1.1.0
13cad02cb3224ad0810ce364b785e81812d6cf02
docs
2109
# PlotReferenceImages [![Build Status](https://travis-ci.org/JuliaPlots/PlotReferenceImages.jl.svg?branch=master)](https://travis-ci.org/JuliaPlots/PlotReferenceImages.jl) This package serves two purposes. It holds the reference images for the [Plots.jl](https://github.com/JuliaPlots/Plots.jl) test suite and it provides utilities to generate the images for the [Plots.jl documentation](http://docs.juliaplots.org/latest/) at [PlotDocs.jl](https://github.com/JuliaPlots/PlotDocs.jl) ## Installation To update test reference images for Plots.jl you can develop this package with: ```julia julia> ] pkg> dev https://github.com/JuliaPlots/PlotReferenceImages.jl.git ``` ## Usage Plots test images can be updated with the Plots test suite: ```julia julia> ] pkg> test Plots ``` If reference images differ from the previously saved images, a window opens showing both versions. Check carefully if the changes are expected and an improvement. In that case agree to overwrite the old image. Otherwise it would be great if you could open an issue on Plots.jl, submit a PR with a fix for the regression or update the PR you are currently working on. After updating all the images, make sure that all tests pass, `git add` the new files, commit and submit a PR. --- You can update the images for a specific backend in the backends section of the Plots documentation with: ```julia using PlotReferenceImages generate_reference_images(sym) ``` Currently `sym ∈ (:gr, :pyplot, :plotlyjs, :pgfplots)` is supported. To update only a single image you can do: ```julia generate_reference_image(sym, i::Int) ``` To update the Plots documentaion images run: ```julia using PlotReferenceImages generate_doc_images() ``` This takes some time. So if you only want to update a specific image, run: ```julia generate_doc_image(id::String) ``` Possible values for `id` can be found in the keys of `PlotReferenceImages.DOC_IMAGE_FILES`. If you are satisfied with the new images, commit and submit a PR. ## Contributing Any help to make these processes less complicated or automate them is very much appreciated.
PlotReferenceImages
https://github.com/JuliaPlots/PlotReferenceImages.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
2191
using .Threads, LoopVectorization, ThreadPools, ThreadPinning using LIKWID function _blocked(A, blockid) ilo, ihi, jlo, jhi = A.loop_limits[blockid] data = @views A.blocks[blockid] @turbo for j in jlo:jhi for i in ilo:ihi data[i, j] = i * j + 0.25( data[i-2, j] + data[i-1, j] + data[i+2, j] + data[i+1, j] + data[i, j] + data[i, j-2] + data[i, j-1] + data[i, j+2] + data[i, j+1]) end end end function blocked_version(A) @sync for tid in 1:nthreads() @tspawnat tid _blocked(A, tid) end end function tturbo_version(data::AbstractArray{T,N}, nhalo) where {T, N} ilo = first(axes(data, 1)) + nhalo ihi = last(axes(data, 1)) - nhalo jlo = first(axes(data, 2)) + nhalo jhi = last(axes(data, 2)) - nhalo @tturbo for j in jlo:jhi for i in ilo:ihi data[i, j] = i * j + 0.25( data[i-2, j] + data[i-1, j] + data[i+2, j] + data[i+1, j] + data[i, j] + data[i, j-2] + data[i, j-1] + data[i, j+2] + data[i, j+1]) end end end function compare_tturbo_v_blocked(A_blocked, A_tturbo) println("Running benchmark") println("-----------------") tturbo_version(A_flat, nhalo) blocked_version(A_block) global t_elaps = 0. max_iter = 10 for iter in 1:max_iter global t_elaps += @elapsed tturbo_version(A_tturbo, nhalo) end t_tturbo = t_elaps / max_iter global t_elaps = 0. for iter in 1:max_iter global t_elaps += @elapsed blocked_version(A_blocked) end t_blocked = t_elaps / max_iter @show nthreads() @show t_blocked t_tturbo @show t_tturbo / t_blocked println("-----------------") println() end pinthreads(:compact) use_numa = true ni = 5000 nj = 5000 nhalo = 4 T = Float64 A_block = BlockHaloArray((ni, nj), nhalo, nthreads(); use_numa=use_numa, T=T); A_flat = rand(T, ni + 2nhalo, nj + 2nhalo); compare_tturbo_v_blocked(A_block, A_flat) metrics, events = @perfmon "FLOPS_DP" tturbo_version(A_flat, nhalo); metrics, events = @perfmon "FLOPS_DP" blocked_version(A_block); nothing
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
1173
using CairoMakie using CSV function strong_scaling(P, N) S = 1 - P 1 / (S + (P / N)) end f = CSV.File("deluge_results.csv") max_nthreads = maximum(f.nthreads) fig = Figure() ax = Axis(fig[1, 1], title="Strong Scaling", xlabel="Threads", ylabel="Speedup (vs 1 thread)", ) lines!(ax, 1:max_nthreads, 1:max_nthreads, label="Linear Scaling", color=:black) lines!(ax, 1:max_nthreads, strong_scaling.(0.99, 1:max_nthreads), label="99% Parallel", color=:green, linestyle=:dash) lines!(ax, f.nthreads, first(f.t_block_ns) ./ f.t_block_ns, label="BlockHaloArray") lines!(ax, f.nthreads, first(f.t_flat_ns) ./ f.t_flat_ns, label="@tturbo") ax2 = Axis(fig[2, 1], title="Runtime vs Threads", xlabel="Threads", ylabel="Runtime[s]") ax3 = Axis(fig[2, 1], yaxisposition=:right, ylabel="@tturbo / BlockHaloArray") hidespines!(ax3) hidexdecorations!(ax3) lines!(ax2, f.nthreads, f.t_block_ns, label="BlockHaloArray") lines!(ax2, f.nthreads, f.t_flat_ns, label="@tturbo") lines!(ax3, f.nthreads, f.t_flat_ns ./ f.t_block_ns, color=:black) lines!(ax2, [NaN], [NaN], label="speedup", color=:black) fig[1, 2] = Legend(fig, ax,) fig[2, 2] = Legend(fig, ax2,) fig
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
186
# import Pkg # Pkg.activate("..") include("stencils.jl") recon = MUSCLReconstruction(MinMod()) nhalo = 2 run_stencil_benchmark(recon, nhalo, Float64, "stencil_2nd_order_results.csv")
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
176
# import Pkg # Pkg.activate("..") include("stencils.jl") recon = MLP5Reconstruction() nhalo = 3 run_stencil_benchmark(recon, nhalo, Float64, "stencil_5th_order_results.csv")
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
22688
using .Threads using ThreadPinning: pinthreads using BlockHaloArrays using BlockHaloArrays: @tspawnat using LoopVectorization using TimerOutputs abstract type AbstractReconstructionScheme end abstract type AbstractMUSCLReconstruction <: AbstractReconstructionScheme end abstract type AbstractLimiter end const to = TimerOutput() const global L = 1 const global R = 2 const global SMALL_NUM = 1e-30 struct MinMod <: AbstractLimiter end @inline limit(::MinMod, r) = max(0, min(r, 1)) struct VanLeer <: AbstractLimiter end @inline limit(::VanLeer, r) = (r + abs(r)) / (1 + abs(r)) struct SuperBee <: AbstractLimiter end @inline limit(::SuperBee, r) = max(0, min(2r, 1), min(r, 2)) struct MUSCLReconstruction{L<:AbstractLimiter} <: AbstractMUSCLReconstruction limiter::L end struct MLP5Reconstruction <: AbstractMUSCLReconstruction end function reconstruct_with_blocks!(RS::MUSCLReconstruction, U, i_edge, j_edge, blockid) # i_edge & j_edge holds the i+1/2 & j+1/2 L and R values # these limits must be the no-halo versions. If the true array size is (10,10) with # 2 halo cells, the limits must be ilo, ihi = 3, 8 and jlo, jhi = 3, 8 ilo, ihi, jlo, jhi = first(U).loop_limits[blockid] ϵ = eps(Float64) for (ϕ̄, ϕ_recon) in zip(U, i_edge) # (ρ, u, v, p) @turbo for j = jlo:jhi for i = ilo-1:ihi ϕ̄ᵢⱼ = ϕ̄[blockid][i, j] ϕ̄ᵢ₊₁ⱼ = ϕ̄[blockid][i+1, j] Δ_minus_half = ϕ̄ᵢⱼ - ϕ̄[blockid][i-1, j] Δ_plus_half = ϕ̄ᵢ₊₁ⱼ - ϕ̄ᵢⱼ Δ_plus_three_half = ϕ̄[blockid][i+2, j] - ϕ̄ᵢ₊₁ⱼ # Machine epsilon checks Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + 1e-30) rR = Δ_plus_half / (Δ_plus_three_half + 1e-30) lim_L = limit(RS.limiter, rL) lim_R = limit(RS.limiter, rR) ϕ_recon[blockid][1, i, j] = ϕ̄ᵢⱼ + 0.5lim_L * Δ_minus_half ϕ_recon[blockid][2, i, j] = ϕ̄ᵢ₊₁ⱼ - 0.5lim_R * Δ_plus_three_half end end end for (ϕ̄, ϕ_recon) in zip(U, j_edge) # (ρ, u, v, p) @turbo for j = jlo-1:jhi for i = ilo:ihi ϕ̄ᵢⱼ = ϕ̄[blockid][i, j] ϕ̄ᵢⱼ₊₁ = ϕ̄[blockid][i, j+1] Δ_minus_half = ϕ̄ᵢⱼ - ϕ̄[blockid][i, j-1] Δ_plus_half = ϕ̄ᵢⱼ₊₁ - ϕ̄ᵢⱼ Δ_plus_three_half = ϕ̄[blockid][i, j+2] - ϕ̄ᵢⱼ₊₁ # Machine epsilon checks Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + 1e-30) rR = Δ_plus_half / (Δ_plus_three_half + 1e-30) lim_L = limit(RS.limiter, rL) lim_R = limit(RS.limiter, rR) ϕ_recon[blockid][1, i, j] = ϕ̄ᵢⱼ + 0.5lim_L * Δ_minus_half ϕ_recon[blockid][2, i, j] = ϕ̄ᵢⱼ₊₁ - 0.5lim_R * Δ_plus_three_half end end end return nothing end function reconstruct_flat!(RS::MUSCLReconstruction, U, i_edge, j_edge, looplimits) # i_edge & j_edge holds the i+1/2 & j+1/2 L and R values # these limits must be the no-halo versions. If the true array size is (10,10) with # 2 halo cells, the limits must be ilo, ihi = 3, 8 and jlo, jhi = 3, 8 ilo, ihi, jlo, jhi = looplimits # @show ilo, ihi, jlo, jhi ϵ = eps(Float64) for (ϕ̄, ϕ_recon) in zip(U, i_edge) # (ρ, u, v, p) @tturbo for j = jlo:jhi for i = ilo-1:ihi ϕ̄ᵢⱼ = ϕ̄[i, j] ϕ̄ᵢ₊₁ⱼ = ϕ̄[i+1, j] Δ_minus_half = ϕ̄ᵢⱼ - ϕ̄[i-1, j] Δ_plus_half = ϕ̄ᵢ₊₁ⱼ - ϕ̄ᵢⱼ Δ_plus_three_half = ϕ̄[i+2, j] - ϕ̄ᵢ₊₁ⱼ # Machine epsilon checks Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + 1e-30) rR = Δ_plus_half / (Δ_plus_three_half + 1e-30) lim_L = limit(RS.limiter, rL) lim_R = limit(RS.limiter, rR) ϕ_recon[1, i, j] = ϕ̄ᵢⱼ + 0.5lim_L * Δ_minus_half ϕ_recon[2, i, j] = ϕ̄ᵢ₊₁ⱼ - 0.5lim_R * Δ_plus_three_half end end end for (ϕ̄, ϕ_recon) in zip(U, j_edge) # (ρ, u, v, p) @tturbo for j = jlo-1:jhi for i = ilo:ihi ϕ̄ᵢⱼ = ϕ̄[i, j] ϕ̄ᵢⱼ₊₁ = ϕ̄[i, j+1] Δ_minus_half = ϕ̄ᵢⱼ - ϕ̄[i, j-1] Δ_plus_half = ϕ̄ᵢⱼ₊₁ - ϕ̄ᵢⱼ Δ_plus_three_half = ϕ̄[i, j+2] - ϕ̄ᵢⱼ₊₁ # Machine epsilon checks Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + 1e-30) rR = Δ_plus_half / (Δ_plus_three_half + 1e-30) lim_L = limit(RS.limiter, rL) lim_R = limit(RS.limiter, rR) ϕ_recon[1, i, j] = ϕ̄ᵢⱼ + 0.5lim_L * Δ_minus_half ϕ_recon[2, i, j] = ϕ̄ᵢⱼ₊₁ - 0.5lim_R * Δ_plus_three_half end end end return nothing end function reconstruct_with_blocks!(::MLP5Reconstruction, U, i_edge, j_edge, blockid, ϵ=eps(Float64)) # i_edge & j_edge holds the i+1/2 & j+1/2 L and R values # these limits must be the no-halo versions. If the true array size is (10,10) with # 2 halo cells, the limits must be ilo, ihi = 3, 8 and jlo, jhi = 3, 8 ilo, ihi, jlo, jhi = first(U).loop_limits[blockid] for (ϕ̄, ϕ_recon) in zip(U, i_edge) # (ρ, u, v, p) @turbo for j = jlo:jhi for i = ilo-1:ihi Δ_minus_half = ϕ̄[blockid][i, j] - ϕ̄[blockid][i-1, j] Δ_plus_three_half = ϕ̄[blockid][i+2, j] - ϕ̄[blockid][i+1, j] Δ_plus_half = ϕ̄[blockid][i+1, j] - ϕ̄[blockid][i, j] Δ_plus_five_half = ϕ̄[blockid][i+3, j] - ϕ̄[blockid][i+2, j] Δ_minus_three_half = ϕ̄[blockid][i-1, j] - ϕ̄[blockid][i-2, j] Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_minus_three_half = Δ_minus_three_half * (abs(Δ_minus_three_half) >= ϵ) Δ_plus_five_half = Δ_plus_five_half * (abs(Δ_plus_five_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + SMALL_NUM) rL_m1 = Δ_minus_half / (Δ_minus_three_half + SMALL_NUM) rL_p1 = Δ_plus_three_half / (Δ_plus_half + SMALL_NUM) rR = Δ_minus_half / (Δ_plus_half + SMALL_NUM) rR_p1 = Δ_plus_half / (Δ_plus_three_half + SMALL_NUM) rR_p2 = Δ_plus_three_half / (Δ_plus_five_half + SMALL_NUM) β_L = ((-2 / (rL_m1 + SMALL_NUM)) + 11.0 + 24rL - 3rL * rL_p1) / 30.0 β_R = ((-2 / (rR_p2 + SMALL_NUM)) + 11.0 + 24rR_p1 - 3rR_p1 * rR) / 30.0 tanθ_ij = abs(ϕ̄[blockid][i, j+1] - ϕ̄[blockid][i, j-1]) / (abs(ϕ̄[blockid][i+1, j] - ϕ̄[blockid][i-1, j]) + SMALL_NUM) tanθ_ij_p1 = abs(ϕ̄[blockid][i+1, j+1] - ϕ̄[blockid][i+1, j-1]) / (abs(ϕ̄[blockid][i+2, j] - ϕ̄[blockid][i, j]) + SMALL_NUM) α_L, α_R = get_alpha(rL, rR_p1, tanθ_ij, tanθ_ij_p1) ϕ_recon[blockid][1, i, j] = ϕ̄[blockid][i, j] + 0.5max(0, min(α_L * rL, α_L, β_L)) * Δ_minus_half ϕ_recon[blockid][2, i, j] = ϕ̄[blockid][i+1, j] - 0.5max(0, min(α_R * rR_p1, α_R, β_R)) * Δ_plus_three_half end end end for (ϕ̄, ϕ_recon) in zip(U, j_edge) # (ρ, u, v, p) @turbo for j = jlo-1:jhi for i = ilo:ihi Δ_minus_half = ϕ̄[blockid][i, j] - ϕ̄[blockid][i, j-1] Δ_plus_three_half = ϕ̄[blockid][i, j+2] - ϕ̄[blockid][i, j+1] Δ_plus_half = ϕ̄[blockid][i, j+1] - ϕ̄[blockid][i, j] Δ_minus_three_half = ϕ̄[blockid][i, j-1] - ϕ̄[blockid][i, j-2] Δ_plus_five_half = ϕ̄[blockid][i, j+3] - ϕ̄[blockid][i, j+3] Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_minus_three_half = Δ_minus_three_half * (abs(Δ_minus_three_half) >= ϵ) Δ_plus_five_half = Δ_plus_five_half * (abs(Δ_plus_five_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + SMALL_NUM) rL_m1 = Δ_minus_half / (Δ_minus_three_half + SMALL_NUM) rL_p1 = Δ_plus_three_half / (Δ_plus_half + SMALL_NUM) rR = Δ_minus_half / (Δ_plus_half + SMALL_NUM) rR_p1 = Δ_plus_half / (Δ_plus_three_half + SMALL_NUM) rR_p2 = Δ_plus_three_half / (Δ_plus_five_half + SMALL_NUM) β_L = ((-2 / (rL_m1 + SMALL_NUM)) + 11.0 + 24rL - 3rL * rL_p1) / 30.0 β_R = ((-2 / (rR_p2 + SMALL_NUM)) + 11.0 + 24rR_p1 - 3rR_p1 * rR) / 30.0 tanθ_ij = abs(ϕ̄[blockid][i+1, j] - ϕ̄[blockid][i-1, j]) / (abs(ϕ̄[blockid][i, j+1] - ϕ̄[blockid][i, j-1]) + SMALL_NUM) tanθ_ij_p1 = abs(ϕ̄[blockid][i+1, j+1] - ϕ̄[blockid][i-1, j+1]) / (abs(ϕ̄[blockid][i, j+2] - ϕ̄[blockid][i, j]) + SMALL_NUM) α_L, α_R = get_alpha(rL, rR_p1, tanθ_ij, tanθ_ij_p1) ϕ_recon[blockid][1, i, j] = ϕ̄[blockid][i, j] + 0.5max(0, min(α_L * rL, α_L, β_L)) * Δ_minus_half ϕ_recon[blockid][2, i, j] = ϕ̄[blockid][i, j+1] - 0.5max(0, min(α_R * rR_p1, α_R, β_R)) * Δ_plus_three_half end end end return nothing end function reconstruct_with_blocks_v2!(::MLP5Reconstruction, U, i_edge, j_edge, blockid, ϵ=eps(Float64)) # i_edge & j_edge holds the i+1/2 & j+1/2 L and R values # these limits must be the no-halo versions. If the true array size is (10,10) with # 2 halo cells, the limits must be ilo, ihi = 3, 8 and jlo, jhi = 3, 8 limits = Tuple(first(U).loop_limits[blockid]) for (ϕ̄, ϕ_recon_i, ϕ_recon_j) in zip(U, i_edge, j_edge) # (ρ, u, v, p) A = @views ϕ̄[blockid] ϕ_recon_i_edge = @views ϕ_recon_i[blockid] ϕ_recon_j_edge = @views ϕ_recon_j[blockid] reconstruct_mlp5!(A, ϕ_recon_i_edge, ϕ_recon_j_edge, limits, ϵ) end return nothing end function reconstruct_mlp5!(A, i_edge, j_edge, limits::NTuple{4, Int}, ϵ=eps(Float64)) # i_edge & j_edge holds the i+1/2 & j+1/2 L and R values # these limits must be the no-halo versions. If the true array size is (10,10) with # 2 halo cells, the limits must be ilo, ihi = 3, 8 and jlo, jhi = 3, 8 ilo, ihi, jlo, jhi = limits @turbo for j = jlo:jhi for i = ilo-1:ihi Δ_minus_half = A[i, j] - A[i-1, j] Δ_plus_three_half = A[i+2, j] - A[i+1, j] Δ_plus_half = A[i+1, j] - A[i, j] Δ_plus_five_half = A[i+3, j] - A[i+2, j] Δ_minus_three_half = A[i-1, j] - A[i-2, j] Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_minus_three_half = Δ_minus_three_half * (abs(Δ_minus_three_half) >= ϵ) Δ_plus_five_half = Δ_plus_five_half * (abs(Δ_plus_five_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + SMALL_NUM) rL_m1 = Δ_minus_half / (Δ_minus_three_half + SMALL_NUM) rL_p1 = Δ_plus_three_half / (Δ_plus_half + SMALL_NUM) rR = Δ_minus_half / (Δ_plus_half + SMALL_NUM) rR_p1 = Δ_plus_half / (Δ_plus_three_half + SMALL_NUM) rR_p2 = Δ_plus_three_half / (Δ_plus_five_half + SMALL_NUM) β_L = ((-2 / (rL_m1 + SMALL_NUM)) + 11.0 + 24rL - 3rL * rL_p1) / 30.0 β_R = ((-2 / (rR_p2 + SMALL_NUM)) + 11.0 + 24rR_p1 - 3rR_p1 * rR) / 30.0 tanθ_ij = abs(A[i, j+1] - A[i, j-1]) / (abs(A[i+1, j] - A[i-1, j]) + SMALL_NUM) tanθ_ij_p1 = abs(A[i+1, j+1] - A[i+1, j-1]) / (abs(A[i+2, j] - A[i, j]) + SMALL_NUM) α_L, α_R = get_alpha(rL, rR_p1, tanθ_ij, tanθ_ij_p1) i_edge[1, i, j] = A[i, j] + 0.5max(0, min(α_L * rL, α_L, β_L)) * Δ_minus_half i_edge[2, i, j] = A[i+1, j] - 0.5max(0, min(α_R * rR_p1, α_R, β_R)) * Δ_plus_three_half end end @turbo for j = jlo-1:jhi for i = ilo:ihi Δ_minus_half = A[i, j] - A[i, j-1] Δ_plus_three_half = A[i, j+2] - A[i, j+1] Δ_plus_half = A[i, j+1] - A[i, j] Δ_minus_three_half = A[i, j-1] - A[i, j-2] Δ_plus_five_half = A[i, j+3] - A[i, j+3] Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_minus_three_half = Δ_minus_three_half * (abs(Δ_minus_three_half) >= ϵ) Δ_plus_five_half = Δ_plus_five_half * (abs(Δ_plus_five_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + SMALL_NUM) rL_m1 = Δ_minus_half / (Δ_minus_three_half + SMALL_NUM) rL_p1 = Δ_plus_three_half / (Δ_plus_half + SMALL_NUM) rR = Δ_minus_half / (Δ_plus_half + SMALL_NUM) rR_p1 = Δ_plus_half / (Δ_plus_three_half + SMALL_NUM) rR_p2 = Δ_plus_three_half / (Δ_plus_five_half + SMALL_NUM) β_L = ((-2 / (rL_m1 + SMALL_NUM)) + 11.0 + 24rL - 3rL * rL_p1) / 30.0 β_R = ((-2 / (rR_p2 + SMALL_NUM)) + 11.0 + 24rR_p1 - 3rR_p1 * rR) / 30.0 tanθ_ij = abs(A[i+1, j] - A[i-1, j]) / (abs(A[i, j+1] - A[i, j-1]) + SMALL_NUM) tanθ_ij_p1 = abs(A[i+1, j+1] - A[i-1, j+1]) / (abs(A[i, j+2] - A[i, j]) + SMALL_NUM) α_L, α_R = get_alpha(rL, rR_p1, tanθ_ij, tanθ_ij_p1) j_edge[1, i, j] = A[i, j] + 0.5max(0, min(α_L * rL, α_L, β_L)) * Δ_minus_half j_edge[2, i, j] = A[i, j+1] - 0.5max(0, min(α_R * rR_p1, α_R, β_R)) * Δ_plus_three_half end end return nothing end function reconstruct_flat!(::MLP5Reconstruction, U, i_edge, j_edge, looplimits, ϵ=eps(Float64)) # i_edge & j_edge holds the i+1/2 & j+1/2 L and R values # these limits must be the no-halo versions. If the true array size is (10,10) with # 2 halo cells, the limits must be ilo, ihi = 3, 8 and jlo, jhi = 3, 8 ilo, ihi, jlo, jhi = looplimits for (ϕ̄, ϕ_recon) in zip(U, i_edge) # (ρ, u, v, p) @tturbo for j = jlo:jhi for i = ilo-1:ihi Δ_minus_half = ϕ̄[i, j] - ϕ̄[i-1, j] Δ_plus_three_half = ϕ̄[i+2, j] - ϕ̄[i+1, j] Δ_plus_half = ϕ̄[i+1, j] - ϕ̄[i, j] Δ_plus_five_half = ϕ̄[i+3, j] - ϕ̄[i+2, j] Δ_minus_three_half = ϕ̄[i-1, j] - ϕ̄[i-2, j] Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_minus_three_half = Δ_minus_three_half * (abs(Δ_minus_three_half) >= ϵ) Δ_plus_five_half = Δ_plus_five_half * (abs(Δ_plus_five_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + SMALL_NUM) rL_m1 = Δ_minus_half / (Δ_minus_three_half + SMALL_NUM) rL_p1 = Δ_plus_three_half / (Δ_plus_half + SMALL_NUM) rR = Δ_minus_half / (Δ_plus_half + SMALL_NUM) rR_p1 = Δ_plus_half / (Δ_plus_three_half + SMALL_NUM) rR_p2 = Δ_plus_three_half / (Δ_plus_five_half + SMALL_NUM) β_L = ((-2 / (rL_m1 + SMALL_NUM)) + 11.0 + 24rL - 3rL * rL_p1) / 30.0 β_R = ((-2 / (rR_p2 + SMALL_NUM)) + 11.0 + 24rR_p1 - 3rR_p1 * rR) / 30.0 tanθ_ij = abs(ϕ̄[i, j+1] - ϕ̄[i, j-1]) / (abs(ϕ̄[i+1, j] - ϕ̄[i-1, j]) + SMALL_NUM) tanθ_ij_p1 = abs(ϕ̄[i+1, j+1] - ϕ̄[i+1, j-1]) / (abs(ϕ̄[i+2, j] - ϕ̄[i, j]) + SMALL_NUM) α_L, α_R = get_alpha(rL, rR_p1, tanθ_ij, tanθ_ij_p1) ϕ_recon[1, i, j] = ϕ̄[i, j] + 0.5max(0, min(α_L * rL, α_L, β_L)) * Δ_minus_half ϕ_recon[2, i, j] = ϕ̄[i+1, j] - 0.5max(0, min(α_R * rR_p1, α_R, β_R)) * Δ_plus_three_half end end end for (ϕ̄, ϕ_recon) in zip(U, j_edge) # (ρ, u, v, p) @tturbo for j = jlo-1:jhi for i = ilo:ihi Δ_minus_half = ϕ̄[i, j] - ϕ̄[i, j-1] Δ_plus_three_half = ϕ̄[i, j+2] - ϕ̄[i, j+1] Δ_plus_half = ϕ̄[i, j+1] - ϕ̄[i, j] Δ_minus_three_half = ϕ̄[i, j-1] - ϕ̄[i, j-2] Δ_plus_five_half = ϕ̄[i, j+3] - ϕ̄[i, j+3] Δ_minus_half = Δ_minus_half * (abs(Δ_minus_half) >= ϵ) Δ_plus_three_half = Δ_plus_three_half * (abs(Δ_plus_three_half) >= ϵ) Δ_plus_half = Δ_plus_half * (abs(Δ_plus_half) >= ϵ) Δ_minus_three_half = Δ_minus_three_half * (abs(Δ_minus_three_half) >= ϵ) Δ_plus_five_half = Δ_plus_five_half * (abs(Δ_plus_five_half) >= ϵ) rL = Δ_plus_half / (Δ_minus_half + SMALL_NUM) rL_m1 = Δ_minus_half / (Δ_minus_three_half + SMALL_NUM) rL_p1 = Δ_plus_three_half / (Δ_plus_half + SMALL_NUM) rR = Δ_minus_half / (Δ_plus_half + SMALL_NUM) rR_p1 = Δ_plus_half / (Δ_plus_three_half + SMALL_NUM) rR_p2 = Δ_plus_three_half / (Δ_plus_five_half + SMALL_NUM) β_L = ((-2 / (rL_m1 + SMALL_NUM)) + 11.0 + 24rL - 3rL * rL_p1) / 30.0 β_R = ((-2 / (rR_p2 + SMALL_NUM)) + 11.0 + 24rR_p1 - 3rR_p1 * rR) / 30.0 tanθ_ij = abs(ϕ̄[i+1, j] - ϕ̄[i-1, j]) / (abs(ϕ̄[i, j+1] - ϕ̄[i, j-1]) + SMALL_NUM) tanθ_ij_p1 = abs(ϕ̄[i+1, j+1] - ϕ̄[i-1, j+1]) / (abs(ϕ̄[i, j+2] - ϕ̄[i, j]) + SMALL_NUM) α_L, α_R = get_alpha(rL, rR_p1, tanθ_ij, tanθ_ij_p1) ϕ_recon[1, i, j] = ϕ̄[i, j] + 0.5max(0, min(α_L * rL, α_L, β_L)) * Δ_minus_half ϕ_recon[2, i, j] = ϕ̄[i, j+1] - 0.5max(0, min(α_R * rR_p1, α_R, β_R)) * Δ_plus_three_half end end end return nothing end @inline function get_alpha(rL, rR_p1, tanθ_ij, tanθ_ij_p1) α_L_term = ((2max(1, rL) * (1 + max(0, (tanθ_ij_p1 / (rR_p1 + SMALL_NUM))))) / (1 + tanθ_ij)) α_R_term = ((2max(1, rR_p1) * (1 + max(0, (tanθ_ij / (rL + SMALL_NUM))))) / (1 + tanθ_ij_p1)) # This is the g(x) = max(1, min(2, alpha)) function α_L = max(1, min(2, α_L_term)) α_R = max(1, min(2, α_R_term)) return α_L, α_R end function run_stencil_benchmark(recon, nhalo, T, results_file) @show nthreads() pinthreads(:compact) dims = (512, 1024) .* 10 nblocks = nthreads() @show dims @show T # ------------------------------------------------------------------------------------- # Block version # ------------------------------------------------------------------------------------- ρ_flat = rand(T, dims...) u_flat = rand(T, dims...) v_flat = rand(T, dims...) p_flat = rand(T, dims...) U = (ρ=BlockHaloArray(ρ_flat, nhalo, nblocks), u=BlockHaloArray(u_flat, nhalo, nblocks), v=BlockHaloArray(v_flat, nhalo, nblocks), p=BlockHaloArray(p_flat, nhalo, nblocks)) edgedims = (2, dims...) halodims = (2, 3) i_edges = (ρ=BlockHaloArray(zeros(T, edgedims...), halodims, nhalo, nblocks), u=BlockHaloArray(zeros(T, edgedims...), halodims, nhalo, nblocks), v=BlockHaloArray(zeros(T, edgedims...), halodims, nhalo, nblocks), p=BlockHaloArray(zeros(T, edgedims...), halodims, nhalo, nblocks)) j_edges = deepcopy(i_edges) # cache it reconstruct_with_blocks!(recon, U, i_edges, j_edges, 1) max_iter = 10 for _ in 1:max_iter @timeit to "reconstruct_with_blocks!" begin @sync for thread_id in 1:nblocks @tspawnat thread_id reconstruct_with_blocks!(recon, U, i_edges, j_edges, thread_id) end end end # cache it reconstruct_with_blocks_v2!(recon, U, i_edges, j_edges, 1) max_iter = 10 for _ in 1:max_iter @timeit to "reconstruct_with_blocks_v2!" begin @sync for thread_id in 1:nblocks @tspawnat thread_id reconstruct_with_blocks_v2!(recon, U, i_edges, j_edges, thread_id) end end end # ------------------------------------------------------------------------------------- # Flat version # ------------------------------------------------------------------------------------- ρ_edge_flat = zeros(T, edgedims) u_edge_flat = zeros(T, edgedims) v_edge_flat = zeros(T, edgedims) p_edge_flat = zeros(T, edgedims) U_flat = (ρ=ρ_flat, u=u_flat, v=v_flat, p=p_flat) i_edges_flat = (ρ=ρ_edge_flat, u=u_edge_flat, v=v_edge_flat, p=p_edge_flat) j_edges_flat = deepcopy(i_edges_flat) ilo = first(axes(U_flat.ρ, 1)) + nhalo jlo = first(axes(U_flat.ρ, 2)) + nhalo ihi = last(axes(U_flat.ρ, 1)) - nhalo jhi = last(axes(U_flat.ρ, 2)) - nhalo looplimits = (ilo, ihi, jlo, jhi) # cache it reconstruct_flat!(recon, U_flat, i_edges_flat, j_edges_flat, looplimits) for _ in 1:max_iter @timeit to "reconstruct_flat!" begin reconstruct_flat!(recon, U_flat, i_edges_flat, j_edges_flat, looplimits) end end show(to) println() t_flat = TimerOutputs.time(to["reconstruct_flat!"]) t_block = TimerOutputs.time(to["reconstruct_with_blocks!"]) println("t_flat / t_block = $(t_flat / t_block)") open(results_file, "a") do io println(io, "$(nthreads()),$t_flat,$t_block") end nothing end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
885
using Documenter, BlockHaloArrays DocMeta.setdocmeta!(BlockHaloArrays, :DocTestSetup, :(using BlockHaloArrays); recursive=true) makedocs( source = "src", build = "build", clean = true, doctest = true, repo = "https://github.com/smillerc/BlockHaloArrays.jl", highlightsig = true, format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true" ), expandfirst = [], modules = [BlockHaloArrays], pages = [ "BlockHaloArrays.jl" => "index.md", # "Examples" => example_md_files, "Reference" => [ # "MPIHaloArray" => "mpihaloarray.md", # "Topology" => "topology.md", "API" => "api.md" ] ], sitename = "BlockHaloArrays.jl" ) deploydocs(repo = "github.com/smillerc/BlockHaloArrays.jl.git", branch = "gh-pages", devbranch = "main",)
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
14424
module BlockHaloArrays using Base.Threads, Base.Iterators, LinearAlgebra import Base.eltype, Base.size, Base.axes, Base.copy! import Base.eachindex, Base.first, Base.firstindex, Base.last, Base.lastindex using NumaAllocators using EllipsisNotation using OffsetArrays export BlockHaloArray export flatten, repartition!, updatehalo!, updateblockhalo! export globalindices, nblocks export domainview export onboundary export donorview, haloview export blockindex, localindex export @tspawnat abstract type AbstractBlockHaloArray end """ A blocked array structure that stores thread-specific data in blocks. This facilitates a micro domain-decompisition for shared-memory applications. Each thread operates on it's own block of data. This provides better performance scaling than multi-threaded loops # Fields - `blocks::Vector{AA}`: - `block_layout::NTuple{D,Int}`: number of blocks along each dimension - `global_blockranges::Array{NTuple{D,UnitRange{Int}},D}`: Indexing/ranges of each block from the global perspective - `nhalo::Int`: Number of halo regions, e.g. 2 entries along each dimension - `loop_limits::Vector{Vector{Int}}`: Looping limits for convienence e.g. `[ilo,ihi,jlo,jhi]` - `globaldims::NTuple{D,Int}`: Dimensions of the array if it were a simple `Array{T,D}`, e.g. `(20,20)` """ struct BlockHaloArray{NB,T,N,NH,NBL,AA<:Array{T,N},SA,NL} <: AbstractBlockHaloArray blocks::NTuple{NB,AA} block_layout::NTuple{NBL,Int} halodims::NTuple{NH,Int} global_blockranges::Vector{NTuple{N,UnitRange{Int}}} nhalo::Int loop_limits::NTuple{NB, NTuple{NL, Int}} globaldims::NTuple{N,Int} neighbor_blocks::Vector{Dict{Symbol,Int}} # private vars _cummulative_blocksize_per_dim::OffsetVector{Vector{Int64},Vector{Vector{Int64}}} _linear_indices::LinearIndices{NBL,NTuple{NBL,Base.OneTo{Int}}} _donor_views::Vector{Dict{Symbol,SA}} _halo_views::Vector{Dict{Symbol,SA}} end """ An MPI-aware BlockHaloArray. The only difference between this and the plain `BlockHaloArray` is the addition of send/receive buffers that help MPI communication. # Fields - `blocks::Vector{AA}`: - `block_layout::NTuple{D,Int}`: number of blocks along each dimension - `global_blockranges::Array{NTuple{D,UnitRange{Int}},D}`: Indexing/ranges of each block from the global perspective - `nhalo::Int`: Number of halo regions, e.g. 2 entries along each dimension - `loop_limits::Vector{Vector{Int}}`: Looping limits for convienence e.g. `[ilo,ihi,jlo,jhi]` - `globaldims::NTuple{D,Int}`: Dimensions of the array if it were a simple `Array{T,D}`, e.g. `(20,20)` - `_global_halo_send_buf::Vector{Array{T,D}}`: Buffers used to send across MPI ranks - `_global_halo_recv_buf::Vector{Array{T,D}}`: Buffers used to receive across MPI ranks """ struct MPIBlockHaloArray{T,N,NH,NBL,AA<:Array{T,N}} <: AbstractBlockHaloArray blocks::Vector{AA} block_layout::NTuple{NBL,Int} halodims::NTuple{NH,Int} global_blockranges::Vector{NTuple{N,UnitRange{Int}}} nhalo::Int loop_limits::NTuple{NBL, NTuple{4, Int}} globaldims::NTuple{N,Int} neighbor_blocks::Vector{Dict{Symbol,Int}} _global_halo_send_buf::Vector{Array{T,NH}} _global_halo_recv_buf::Vector{Array{T,NH}} end include("spawn.jl") include("partitioning.jl") include("halo_exchange.jl") include("indexing.jl") """ Construct a BlockHaloArray # Arguments - `dims::NTuple{N,Int}`: Array dimensions - `nhalo::Integer`: Number of halo entries (equal in all dimensions) # Keyword Arguments - `nblocks::Integer`: Number of blocks to divide the array into; default is nthreads() - `T`:: Array number type; default is Float64 """ function BlockHaloArray(dims::NTuple{N,Int}, halodims::NTuple{N2,Int}, nhalo::Integer, nblocks=Base.Threads.nthreads(); T=Float64, use_numa=true, tile_dims=nothing) where {N,N2} alldims = Tuple(1:length(dims)) non_halo_dims = Tuple([i for (i, v) in enumerate(dims) if !(i in halodims)]) for dim in halodims if !(dim in alldims) error("Invalid halo dimension: $(dim) not in any of the array axes $alldims") end end if !isempty(non_halo_dims) if !(all(non_halo_dims .< halodims)) error("The axes for halo exchange must be the outmost-most of the array: halodims=$halodims, non-halo dims=$non_halo_dims") end end if any(halodims .> length(dims)) error("Some (or all) of the given halo_dims $(halodims) are incompatible with the dimensionality of the given array A") end mismatched_blocks = false if nblocks > Threads.nthreads() @warn "nblocks ($nblocks) > nthreads ($(nthreads()))" mismatched_blocks = true end blocks = Vector{Array{T,N}}(undef, nblocks) halo_only_sizes = Tuple([v for (i, v) in enumerate(dims) if i in halodims]) if tile_dims === nothing tile_dims = block_layout(nblocks, length(halodims)) |> Tuple else if prod(tile_dims) != nblocks error("Invalid tile_dims; the number of blocks is not consistent") end end halo_only_dims = Tuple([v for (i, v) in enumerate(dims) if i in halodims]) nhalodims = length(halo_only_dims) non_halo_dim_sizes = Tuple([v for (i, v) in enumerate(dims) if !(i in halodims)]) if halodims == Tuple(1:length(dims)) block_ranges = get_block_ranges(dims, tile_dims) else block_ranges_halo_only = get_block_ranges(halo_only_dims, tile_dims) block_ranges = update_block_ranges_with_non_halo_dims(block_ranges_halo_only, dims, halodims) end block_sizes = [collect(flatten(size.(block))) for block in block_ranges] # this is the cumulative block size along each dimension, indexed via [tile_dimension][1:blocks_in_tile_dim] cummulative_blocksize_per_dim = OffsetArray( cumsum.(collect(split_count.(dims[[i for i in halodims]], tile_dims))), UnitRange(first(halodims), last(halodims)) ) LI = LinearIndices(tile_dims) # used to convert the cartesian block id into the linear one (for the get/set index methods) # pad the dimensions that will include halo regions for block in block_sizes for i in eachindex(block) if i in halodims block[i] += 2nhalo end end end for threadid in eachindex(blocks) # allocate on the thread's numa node if use_numa try threadid_to_numa_mapping = map_threadid_to_numa() numa_id = threadid_to_numa_mapping[threadid] blocks[threadid] = Array{T}(numa(numa_id), block_sizes[threadid]...) catch # if threadid == firstindex(blocks) # @warn "Unable to allocate blocks on the thread-local NUMA node" # end blocks[threadid] = Array{T}(undef, block_sizes[threadid]...) end else blocks[threadid] = Array{T}(undef, block_sizes[threadid]...) end end loop_limits = Vector{Vector{Int}}(undef, nblocks) for i in eachindex(loop_limits) loop_limits[i] = [(first(ax) + nhalo, last(ax) - nhalo) for ax in axes(blocks[i])] |> flatten |> collect end loop_lims = Tuple(Tuple.(loop_limits)) neighbors = get_neighbor_blocks(tile_dims) # Pass undef'ed vector to the constructor, since the views # need to be done _after_ the type is created. _halo_views = gen_halo_views(blocks, nhalo, halodims) HaloViewTypes = typeof(first(_halo_views)[:ilo]) halo_views = Vector{Dict{Symbol, HaloViewTypes}}(undef, nblocks) _donor_views = gen_donor_views(blocks, nhalo, halodims) DonorViewTypes = typeof(first(_donor_views)[:ilo]) donor_views = Vector{Dict{Symbol, DonorViewTypes}}(undef, nblocks) A = BlockHaloArray(tuple(blocks...), tile_dims, halodims, vec(block_ranges), nhalo, loop_lims, dims, neighbors, cummulative_blocksize_per_dim, LI, donor_views, halo_views) # Get the halo reciever and domain donor views of each block. # These views are used during the halo sync process halo_views = gen_halo_views(A) donor_views = gen_donor_views(A) for i in eachindex(A.blocks) A._halo_views[i] = halo_views[i] A._donor_views[i] = donor_views[i] end # # testing NUMA first-touch policy if !mismatched_blocks if use_numa @sync for tid in 1:nblocks @tspawnat tid fill!(A.blocks[tid], 0) end end else for tid in 1:nblocks fill!(A.blocks[tid], 0) end end return A end function BlockHaloArray(A::AbstractArray{T,N}, nhalo::Integer, nblocks=Base.Threads.nthreads(); use_numa=true, tile_dims=nothing) where {T,N} halodims = Tuple(1:length(size(A))) BlockHaloArray(A, halodims, nhalo, nblocks; use_numa=use_numa, tile_dims=tile_dims) end """ Construct a BlockHaloArray from a normal Array """ function BlockHaloArray(A::AbstractArray{T,N}, halodims::NTuple{N2,Integer}, nhalo::Integer, nblocks=Base.Threads.nthreads(); use_numa=true, tile_dims=nothing) where {T,N,N2} dims = size(A) A_blocked = BlockHaloArray(dims, halodims, nhalo, nblocks; T=T, use_numa=use_numa, tile_dims=tile_dims) block_ranges = A_blocked.global_blockranges for tid in LinearIndices(block_ranges) domain_view = domainview(A_blocked, tid) A_view = view(A, block_ranges[tid]...) copy!(domain_view, A_view) end return A_blocked end function BlockHaloArray(dims::NTuple{N,Int}, nhalo::Integer, nblocks=Base.Threads.nthreads(); T=Float64, use_numa=true, tile_dims=nothing) where {N} halodims = Tuple(1:length(dims)) BlockHaloArray(dims, halodims, nhalo, nblocks; T=T, use_numa=use_numa, tile_dims=tile_dims) end """Create a dictionary mapping the threadid to the NUMA node.""" function map_threadid_to_numa() buf = [] for (id, node) in enumerate(cpuids_per_numa()) for tid in node push!(buf, (tid + 1, id - 1)) # +/- 1 is due to difference in 0 and 1-based indexing with lscpu end end Dict(buf) end eltype(A::AbstractBlockHaloArray) = eltype(first(A.blocks)) size(A::AbstractBlockHaloArray) = A.globaldims size(A::AbstractBlockHaloArray, dim) = size.(A.blocks, dim) axes(A::AbstractBlockHaloArray) = axes.(A.blocks) axes(A::AbstractBlockHaloArray, dim) = axes.(A.blocks, dim) first(A::AbstractBlockHaloArray) = first(A.blocks) firstindex(A::AbstractBlockHaloArray) = firstindex(A.blocks) last(A::AbstractBlockHaloArray) = last(A.blocks) lastindex(A::AbstractBlockHaloArray) = lastindex(A.blocks) eachindex(A::AbstractBlockHaloArray) = eachindex(A.blocks) nblocks(A::AbstractBlockHaloArray) = length(A.blocks) """ Determine if the block is on the boundary # Arguments - `A::AbstractBlockHaloArray`: The array in question - `blockid::Integer`: The id of the block. This is normally associated with the thread id - `boundary::Symbol`: Which boundary are we checking for? Examples include :ilo, :jhi, etc... """ function onboundary(A::AbstractBlockHaloArray, blockid::Integer, boundary::Symbol) try if A.neighbor_blocks[blockid][boundary] < 0 return true else return false end catch return false end end """ domainview(A::BlockHaloArray, blockid) -> SubArray Get the SubArray view of the domain region of a block in the BlockHaloArray. """ function domainview(A::BlockHaloArray, blockid::Integer, offset) if blockid < 1 || blockid > nblocks(A) error("Invalid blockid, must be 1 <= blockid <= $(nblocks(A))") end if offset > A.nhalo error("offset must be <= nhalo") end if offset < 0 error("offset must be > 0") end function f(i, halodims, offset) if i in halodims return offset else return 0 end end idx_offset = ntuple(i -> f(i, A.halodims, offset), length(A.globaldims)) _, _, lo_dom_start, _ = lo_indices(A.blocks[blockid], A.nhalo, A.halodims) _, hi_dom_end, _, _ = hi_indices(A.blocks[blockid], A.nhalo, A.halodims) lo_dom_start = lo_dom_start .- idx_offset hi_dom_end = hi_dom_end .+ idx_offset idx_range = UnitRange.(lo_dom_start, hi_dom_end) return @views A.blocks[blockid][.., idx_range...] end domainview(A::BlockHaloArray, blockid::Integer) = domainview(A, blockid, 0) """Get the halo region at a particular location, e.g. `:ilo` for block `blockid`""" haloview(A::BlockHaloArray, blockid::Integer, location::Symbol) = A._halo_views[blockid][location] """Get the domain donor region at a particular location, e.g. `:ilo` for block `blockid`""" donorview(A::BlockHaloArray, blockid::Integer, location::Symbol) = A._donor_views[blockid][location] """ copy!(dst, src) -> dst Copy from an AbstractArray into a BlockHaloArray. The global dimensions of the BlockHaloArray must be the same as the AbstractArray """ function copy!(BHA::BlockHaloArray, AA::AbstractArray) if eltype(AA) != eltype(BHA) @warn "Mismatched AbstractArray and BlockHaloArray eltypes" end if size(AA) != BHA.globaldims error("Mismatched array dimensions: BlockHaloArray.globaldims $(BHA.globaldims) != size(AbstractArray) $(size(AA))") end @sync for block_id in 1:nblocks(BHA) @tspawnat block_id _array_to_block!(BHA, AA, block_id) end end function _array_to_block!(BHA::BlockHaloArray, AA::AbstractArray, block_id::Int) dv = domainview(BHA, block_id) av = view(AA, BHA.global_blockranges[block_id]...) copy!(dv, av) # update the block end """ copy!(dst, src) -> dst Copy from a BlockHaloArray into an AbstractArray. The global dimensions of the BlockHaloArray must be the same as the AbstractArray """ function copy!(AA::AbstractArray, BHA::BlockHaloArray) if size(AA) != BHA.globaldims error("Mismatched array dimensions: BlockHaloArray.globaldims $(BHA.globaldims) != size(AbstractArray) $(size(AA))") end @sync for block_id in 1:nblocks(BHA) @tspawnat block_id _block_to_array!(AA, BHA, block_id) end end function _block_to_array!(AA::AbstractArray, BHA::BlockHaloArray, block_id::Int) dv = domainview(BHA, block_id) av = view(AA, BHA.global_blockranges[block_id]...) copy!(av, dv) # update the abstract array end end # module
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
31879
const halo_1d_exchange_map = Dict(:ilo => :ihi, :ihi => :ilo) const halo_2d_exchange_map = Dict( :ilo => :ihi, :ihi => :ilo, :jlo => :jhi, :jhi => :jlo, :ilojlo => :ihijhi, :ihijlo => :ilojhi, :ihijhi => :ilojlo, :ilojhi => :ihijlo ) const halo_3d_exchange_map = Dict( :ilo => :ihi, :ihi => :ilo, :jlo => :jhi, :jhi => :jlo, :klo => :khi, :khi => :klo, :ilojlo => :ihijhi, :ihijlo => :ilojhi, :ilojhi => :ihijlo, :ihijhi => :ilojlo, :ilokhi => :ihiklo, :iloklo => :ihikhi, :ihikhi => :iloklo, :ihiklo => :ilokhi, :jhikhi => :jloklo, :jlokhi => :jhiklo, :jhiklo => :jlokhi, :jloklo => :jhikhi, :ilojhikhi => :ihijloklo, :ihijhikhi => :ilojloklo, :ilojlokhi => :ihijhiklo, :ihijlokhi => :ilojhiklo, :ilojhiklo => :ihijlokhi, :ihijhiklo => :ilojlokhi, :ilojloklo => :ihijhikhi, :ihijloklo => :ilojhikhi, ) const hmap = (halo_1d_exchange_map, halo_2d_exchange_map, halo_3d_exchange_map) """1D halo exchange mapping, e.g. donor => reciever block ID""" function halo_exchange_map(::NTuple{1,Int}) return Dict(:ilo => :ihi, :ihi => :ilo) end """2D halo exchange mapping, e.g. donor => reciever block ID""" function halo_exchange_map(::NTuple{2,Int}) return Dict(:ilo => :ihi, :ihi => :ilo, :jlo => :jhi, :jhi => :jlo, :ilojlo => :ihijhi, :ihijlo => :ilojhi, :ihijhi => :ilojlo, :ilojhi => :ihijlo) end """3D halo exchange mapping, e.g. donor => reciever block ID""" function halo_exchange_map(::NTuple{3,Int}) return Dict( :ilo => :ihi, :ihi => :ilo, :jlo => :jhi, :jhi => :jlo, :klo => :khi, :khi => :klo, :ilojlo => :ihijhi, :ihijlo => :ilojhi, :ilojhi => :ihijlo, :ihijhi => :ilojlo, :ilokhi => :ihiklo, :iloklo => :ihikhi, :ihikhi => :iloklo, :ihiklo => :ilokhi, :jhikhi => :jloklo, :jlokhi => :jhiklo, :jhiklo => :jlokhi, :jloklo => :jhikhi, :ilojhikhi => :ihijloklo, :ihijhikhi => :ilojloklo, :ilojlokhi => :ihijhiklo, :ihijlokhi => :ilojhiklo, :ilojhiklo => :ihijlokhi, :ihijhiklo => :ilojlokhi, :ilojloklo => :ihijhikhi, :ihijloklo => :ilojhikhi, ) end """ domain_donor_ranges(block, nhal, halodims::NTuple{1, Int}) -> Dict Get the 1D ranges for each donor region in the doman that sends data to neighbor block halo regions """ function domain_donor_ranges(block, nhalo, halodims::NTuple{1,Int}) # domn == domain area _, _, lo_domn_start, lo_domn_end = lo_indices(block, nhalo) hi_domn_start, hi_domn_end, _, _ = hi_indices(block, nhalo) ilo_domn_start = [v for (i, v) in enumerate(lo_domn_start) if i in halodims] |> first ilo_domn_end = [v for (i, v) in enumerate(lo_domn_end) if i in halodims] |> first ihi_domn_start = [v for (i, v) in enumerate(hi_domn_start) if i in halodims] |> first ihi_domn_end = [v for (i, v) in enumerate(hi_domn_end) if i in halodims] |> first # key -> neighbor id, value -> array index ranges return Dict( :ilo => (ilo_domn_start:ilo_domn_end,), :ihi => (ihi_domn_start:ihi_domn_end,), ) end """ domain_donor_ranges(block, nhal, halodims::NTuple{2, Int}) -> Dict Get the 2D ranges for each donor region in the doman that sends data to neighbor block halo regions """ function domain_donor_ranges(block, nhalo, halodims::NTuple{2,Int}) # domn == domain area _, _, lo_domn_start, lo_domn_end = lo_indices(block, nhalo) hi_domn_start, hi_domn_end, _, _ = hi_indices(block, nhalo) ilo_domn_start, jlo_domn_start = [v for (i, v) in enumerate(lo_domn_start) if i in halodims] ilo_domn_end, jlo_domn_end = [v for (i, v) in enumerate(lo_domn_end) if i in halodims] ihi_domn_start, jhi_domn_start = [v for (i, v) in enumerate(hi_domn_start) if i in halodims] ihi_domn_end, jhi_domn_end = [v for (i, v) in enumerate(hi_domn_end) if i in halodims] # key -> neighbor id, value -> array index ranges return Dict( :ilo => (ilo_domn_start:ilo_domn_end, jlo_domn_start:jhi_domn_end), :jlo => (ilo_domn_start:ihi_domn_end, jlo_domn_start:jlo_domn_end), :ihi => (ihi_domn_start:ihi_domn_end, jlo_domn_start:jhi_domn_end), :jhi => (ilo_domn_start:ihi_domn_end, jhi_domn_start:jhi_domn_end), :ilojlo => (ilo_domn_start:ilo_domn_end, jlo_domn_start:jlo_domn_end), :ihijlo => (ihi_domn_start:ihi_domn_end, jlo_domn_start:jlo_domn_end), :ilojhi => (ilo_domn_start:ilo_domn_end, jhi_domn_start:jhi_domn_end), :ihijhi => (ihi_domn_start:ihi_domn_end, jhi_domn_start:jhi_domn_end), ) end """ domain_donor_ranges(block, nhal, halodims::NTuple{3, Int}) -> Dict Get the 3D ranges for each donor region in the doman that sends data to neighbor block halo regions """ function domain_donor_ranges(block, nhalo, halodims::NTuple{3,Int}) # dom == domain area _, _, lo_dom_start, lo_dom_end = lo_indices(block, nhalo) hi_dom_start, hi_dom_end, _, _ = hi_indices(block, nhalo) ilo_dom_start, jlo_dom_start, klo_dom_start = [v for (i, v) in enumerate(lo_dom_start) if i in halodims] ilo_dom_end, jlo_dom_end, klo_dom_end = [v for (i, v) in enumerate(lo_dom_end) if i in halodims] ihi_dom_start, jhi_dom_start, khi_dom_start = [v for (i, v) in enumerate(hi_dom_start) if i in halodims] ihi_dom_end, jhi_dom_end, khi_dom_end = [v for (i, v) in enumerate(hi_dom_end) if i in halodims] # key -> neighbor id, value -> array index ranges return Dict( :ilo => (ilo_dom_start:ilo_dom_end, jlo_dom_start:jhi_dom_end, klo_dom_start:khi_dom_end), :ihi => (ihi_dom_start:ihi_dom_end, jlo_dom_start:jhi_dom_end, klo_dom_start:khi_dom_end), :jlo => (ilo_dom_start:ihi_dom_end, jlo_dom_start:jlo_dom_end, klo_dom_start:khi_dom_end), :jhi => (ilo_dom_start:ihi_dom_end, jlo_dom_start:jlo_dom_end, klo_dom_start:khi_dom_end), :klo => (ilo_dom_start:ihi_dom_end, jlo_dom_start:jhi_dom_end, klo_dom_start:klo_dom_end), :khi => (ilo_dom_start:ihi_dom_end, jlo_dom_start:jhi_dom_end, khi_dom_start:khi_dom_end), :ilojlo => (ilo_dom_start:ilo_dom_end, jlo_dom_start:jlo_dom_end, klo_dom_start:khi_dom_end), :ihijlo => (ihi_dom_start:ihi_dom_end, jlo_dom_start:jlo_dom_end, klo_dom_start:khi_dom_end), :ilojhi => (ilo_dom_start:ilo_dom_end, jhi_dom_start:jhi_dom_end, klo_dom_start:khi_dom_end), :ihijhi => (ihi_dom_start:ihi_dom_end, jhi_dom_start:jhi_dom_end, klo_dom_start:khi_dom_end), :ilokhi => (ilo_dom_start:ilo_dom_end, jlo_dom_start:jhi_dom_end, khi_dom_start:khi_dom_end), :iloklo => (ilo_dom_start:ilo_dom_end, jlo_dom_start:jhi_dom_end, klo_dom_start:klo_dom_end), :ihikhi => (ihi_dom_start:ihi_dom_end, jlo_dom_start:jhi_dom_end, khi_dom_start:khi_dom_end), :ihiklo => (ihi_dom_start:ihi_dom_end, jlo_dom_start:jhi_dom_end, klo_dom_start:klo_dom_end), :jhikhi => (ilo_dom_start:ihi_dom_end, jhi_dom_start:jhi_dom_end, khi_dom_start:khi_dom_end), :jlokhi => (ilo_dom_start:ihi_dom_end, jlo_dom_start:jlo_dom_end, khi_dom_start:khi_dom_end), :jhiklo => (ilo_dom_start:ihi_dom_end, jhi_dom_start:jhi_dom_end, klo_dom_start:klo_dom_end), :jloklo => (ilo_dom_start:ihi_dom_end, jlo_dom_start:jlo_dom_end, klo_dom_start:klo_dom_end), :ilojhikhi => (ilo_dom_start:ilo_dom_end, jhi_dom_start:jhi_dom_end, khi_dom_start:khi_dom_end), :ihijhikhi => (ihi_dom_start:ihi_dom_end, jhi_dom_start:jhi_dom_end, khi_dom_start:khi_dom_end), :ilojlokhi => (ilo_dom_start:ilo_dom_end, jlo_dom_start:jlo_dom_end, khi_dom_start:khi_dom_end), :ihijlokhi => (ihi_dom_start:ihi_dom_end, jlo_dom_start:jlo_dom_end, khi_dom_start:khi_dom_end), :ilojhiklo => (ilo_dom_start:ilo_dom_end, jhi_dom_start:jhi_dom_end, klo_dom_start:klo_dom_end), :ihijhiklo => (ihi_dom_start:ihi_dom_end, jhi_dom_start:jhi_dom_end, klo_dom_start:klo_dom_end), :ilojloklo => (ilo_dom_start:ilo_dom_end, jlo_dom_start:jlo_dom_end, klo_dom_start:klo_dom_end), :ihijloklo => (ihi_dom_start:ihi_dom_end, jlo_dom_start:jlo_dom_end, klo_dom_start:klo_dom_end), ) end """ halo_reciever_ranges(block, nhalo, halodims::NTuple{1, Int}) -> Dict Get the 1D ranges for each halo region that recieves data from neighbor blocks """ function halo_reciever_ranges(block, nhalo, halodims::NTuple{1,Int}) # domn == domain area lo_halo_start, lo_halo_end, _, _ = lo_indices(block, nhalo) _, _, hi_halo_start, hi_halo_end = hi_indices(block, nhalo) ilo_halo_start = [v for (i, v) in enumerate(lo_halo_start) if i in halodims] |> first ilo_halo_end = [v for (i, v) in enumerate(lo_halo_end) if i in halodims] |> first ihi_halo_start = [v for (i, v) in enumerate(hi_halo_start) if i in halodims] |> first ihi_halo_end = [v for (i, v) in enumerate(hi_halo_end) if i in halodims] |> first # key -> neighbor id, value -> array index ranges return Dict( :ilo => (ilo_halo_start:ilo_halo_end,), :ihi => (ihi_halo_start:ihi_halo_end,), ) end """ halo_reciever_ranges(block, nhalo, halodims::NTuple{2, Int}) -> Dict Get the 2D ranges for each halo region that recieves data from neighbor blocks """ function halo_reciever_ranges(block, nhalo, halodims::NTuple{2,Int}) # domn == domain area lo_halo_start, lo_halo_end, lo_domn_start, _ = lo_indices(block, nhalo) _, hi_domn_end, hi_halo_start, hi_halo_end = hi_indices(block, nhalo) ilo_halo_start, jlo_halo_start = [v for (i, v) in enumerate(lo_halo_start) if i in halodims] ilo_halo_end, jlo_halo_end = [v for (i, v) in enumerate(lo_halo_end) if i in halodims] ilo_domn_start, jlo_domn_start = [v for (i, v) in enumerate(lo_domn_start) if i in halodims] ihi_domn_end, jhi_domn_end = [v for (i, v) in enumerate(hi_domn_end) if i in halodims] ihi_halo_start, jhi_halo_start = [v for (i, v) in enumerate(hi_halo_start) if i in halodims] ihi_halo_end, jhi_halo_end = [v for (i, v) in enumerate(hi_halo_end) if i in halodims] # key -> neighbor id, value -> array index ranges return Dict( :ilo => (ilo_halo_start:ilo_halo_end, jlo_domn_start:jhi_domn_end), :ihi => (ihi_halo_start:ihi_halo_end, jlo_domn_start:jhi_domn_end), :jlo => (ilo_domn_start:ihi_domn_end, jlo_halo_start:jlo_halo_end), :jhi => (ilo_domn_start:ihi_domn_end, jhi_halo_start:jhi_halo_end), :ilojlo => (ilo_halo_start:ilo_halo_end, jlo_halo_start:jlo_halo_end), :ilojhi => (ilo_halo_start:ilo_halo_end, jhi_halo_start:jhi_halo_end), :ihijlo => (ihi_halo_start:ihi_halo_end, jlo_halo_start:jlo_halo_end), :ihijhi => (ihi_halo_start:ihi_halo_end, jhi_halo_start:jhi_halo_end), ) end """ halo_reciever_ranges(block, nhalo, halodims::NTuple{3, Int}) -> Dict Get the 3D ranges for each halo region that recieves data from neighbor blocks """ function halo_reciever_ranges(block, nhalo, halodims::NTuple{3,Int}) # domn == domain area lo_halo_start, lo_halo_end, lo_domn_start, _ = lo_indices(block, nhalo) _, hi_domn_end, hi_halo_start, hi_halo_end = hi_indices(block, nhalo) ilo_halo_start, jlo_halo_start, klo_halo_start = [v for (i, v) in enumerate(lo_halo_start) if i in halodims] ilo_halo_end, jlo_halo_end, klo_halo_end = [v for (i, v) in enumerate(lo_halo_end) if i in halodims] ilo_domn_start, jlo_domn_start, klo_domn_start = [v for (i, v) in enumerate(lo_domn_start) if i in halodims] ihi_domn_end, jhi_domn_end, khi_domn_end = [v for (i, v) in enumerate(hi_domn_end) if i in halodims] ihi_halo_start, jhi_halo_start, khi_halo_start = [v for (i, v) in enumerate(hi_halo_start) if i in halodims] ihi_halo_end, jhi_halo_end, khi_halo_end = [v for (i, v) in enumerate(hi_halo_end) if i in halodims] # key -> neighbor id, value -> array index ranges return Dict( :ilo => (ilo_halo_start:ilo_halo_end, jlo_domn_start:jhi_domn_end, klo_domn_start:khi_domn_end), :ihi => (ihi_halo_start:ihi_halo_end, jlo_domn_start:jhi_domn_end, klo_domn_start:khi_domn_end), :jlo => (ilo_domn_start:ihi_domn_end, jlo_halo_start:jlo_halo_end, klo_domn_start:khi_domn_end), :jhi => (ilo_domn_start:ihi_domn_end, jhi_halo_start:jhi_halo_end, klo_domn_start:khi_domn_end), :klo => (ilo_domn_start:ihi_domn_end, jlo_domn_start:jhi_domn_end, klo_halo_start:klo_halo_end), :khi => (ilo_domn_start:ihi_domn_end, jlo_domn_start:jhi_domn_end, khi_halo_start:khi_halo_end), :ihijhi => (ihi_halo_start:ihi_halo_end, jhi_halo_start:jhi_halo_end, klo_domn_start:khi_domn_end), :ihijlo => (ihi_halo_start:ihi_halo_end, jlo_halo_start:jlo_halo_end, klo_domn_start:khi_domn_end), :ilojhi => (ilo_halo_start:ilo_halo_end, jhi_halo_start:jhi_halo_end, klo_domn_start:khi_domn_end), :ilojlo => (ilo_halo_start:ilo_halo_end, jlo_halo_start:jlo_halo_end, klo_domn_start:khi_domn_end), :ihikhi => (ihi_halo_start:ihi_halo_end, jlo_domn_start:jhi_domn_end, khi_halo_start:khi_halo_end), :ihiklo => (ihi_halo_start:ihi_halo_end, jlo_domn_start:jhi_domn_end, klo_halo_start:klo_halo_end), :iloklo => (ilo_halo_start:ilo_halo_end, jlo_domn_start:jhi_domn_end, klo_halo_start:klo_halo_end), :ilokhi => (ilo_halo_start:ilo_halo_end, jlo_domn_start:jhi_domn_end, khi_halo_start:khi_halo_end), :jloklo => (ilo_domn_start:ihi_domn_end, jlo_halo_start:jlo_halo_end, klo_halo_start:klo_halo_end), :jhikhi => (ilo_domn_start:ihi_domn_end, jhi_halo_start:jhi_halo_end, khi_halo_start:khi_halo_end), :jhiklo => (ilo_domn_start:ihi_domn_end, jhi_halo_start:jhi_halo_end, klo_halo_start:klo_halo_end), :jlokhi => (ilo_domn_start:ihi_domn_end, jlo_halo_start:jlo_halo_end, khi_halo_start:khi_halo_end), :ihijloklo => (ihi_halo_start:ihi_halo_end, jlo_halo_start:jlo_halo_end, klo_halo_start:klo_halo_end), :ilojhiklo => (ilo_halo_start:ilo_halo_end, jhi_halo_start:jhi_halo_end, klo_halo_start:klo_halo_end), :ilojloklo => (ilo_halo_start:ilo_halo_end, jlo_halo_start:jlo_halo_end, klo_halo_start:klo_halo_end), :ihijhiklo => (ihi_halo_start:ihi_halo_end, jhi_halo_start:jhi_halo_end, klo_halo_start:klo_halo_end), :ihijlokhi => (ihi_halo_start:ihi_halo_end, jlo_halo_start:jlo_halo_end, khi_halo_start:khi_halo_end), :ilojhikhi => (ilo_halo_start:ilo_halo_end, jhi_halo_start:jhi_halo_end, khi_halo_start:khi_halo_end), :ilojlokhi => (ilo_halo_start:ilo_halo_end, jlo_halo_start:jlo_halo_end, khi_halo_start:khi_halo_end), :ihijhikhi => (ihi_halo_start:ihi_halo_end, jhi_halo_start:jhi_halo_end, khi_halo_start:khi_halo_end), ) end """ updatehalo!(A, include_periodic_bc=false) Synchronize the halo regions within each block. This spawns tasks so that each thread/block copies from it's neighbor block's domain into the current block's halo region. # Arguments - `A`: `BlockHaloArray` - `include_periodic_bc`: Update the halo regions that are on periodic boundaries """ function updatehalo!(A::BlockHaloArray, include_periodic_bc) @sync for tid in eachindex(A.blocks) @tspawnat tid updateblockhalo!(A, tid, include_periodic_bc) end end function updatehalo!(A::BlockHaloArray) @sync for tid in eachindex(A.blocks) @tspawnat tid updateblockhalo!(A, tid) end end @inline function valid_neighbor(id::Integer) if id > 0 return true else return false end end """ updateblockhalo!(A::BlockHaloArray, block_id::Integer, include_periodic_bc=false) Copy data from the neighbor block into the current block's halo region # Arguments - `A`: `BlockHaloArray` - `block_id::Integer`: Block index - `include_periodic_bc`: Update the halo regions that are on periodic boundaries """ updateblockhalo!(A, current_block_id) = updateblockhalo!(A, current_block_id, false) function updateblockhalo!(A::BlockHaloArray{NB,T,N,NH,NBL,AA,SA,Y}, current_block_id::Integer, include_periodic_bc::Bool) where {NB,T,N,NH,NBL,AA,SA,Y} exchange_map = hmap[NH] for (dom_id, halo_id) in exchange_map neighbor_block_id = A.neighbor_blocks[current_block_id][halo_id] # The convention is that periodic neighbors block ids are < 0 as a hint to the # user and code. if include_periodic_bc neighbor_block_id = abs(neighbor_block_id) end if valid_neighbor(neighbor_block_id) copy!( A._halo_views[current_block_id][halo_id], A._donor_views[neighbor_block_id][dom_id] ) # copy donor -> halo # for idx in eachindex(A._halo_views[current_block_id][halo_id]) # A._halo_views[current_block_id][halo_id][idx] = A._donor_views[neighbor_block_id][dom_id][idx] # end end end return nothing end """Get the upper indices for an array `A` given a number of halo entries `nhalo`""" function hi_indices(A, nhalo) hmod = 1 .* (nhalo .== 0) hi_halo_end = last.(axes(A)) hi_halo_start = hi_halo_end .- nhalo .+ 1 .- hmod hi_domn_end = hi_halo_start .- 1 .+ hmod hi_domn_start = hi_domn_end .- nhalo .+ 1 .- hmod return (hi_domn_start, hi_domn_end, hi_halo_start, hi_halo_end) end """Get the upper indices for an array `A` given a number of halo entries `nhalo`. This version properly accounts for non-halo dimensions""" function hi_indices(A::AbstractArray{T,N}, nhalo, halodims) where {N,T} function f(i, halodims, nhalo) if i in halodims return nhalo else return 0 end end halo_tuple = ntuple(i -> f(i, halodims, nhalo), Val(N)) hi_indices(A, halo_tuple) end """Get the lower indices for an array `A` given a number of halo entries `nhalo`""" function lo_indices(A, nhalo) lmod = 1 .* (nhalo .== 0) lo_halo_start = first.(axes(A)) lo_halo_end = lo_halo_start .+ nhalo .- 1 .+ lmod lo_domn_start = lo_halo_end .+ 1 .- lmod lo_domn_end = lo_domn_start .+ nhalo .- 1 .+ lmod return (lo_halo_start, lo_halo_end, lo_domn_start, lo_domn_end) end """Get the lower indices for an array `A` given a number of halo entries `nhalo`. This version properly accounts for non-halo dimensions""" function lo_indices(A::AbstractArray{T,N}, nhalo, halodims) where {N,T} function f(i, halodims, nhalo) if i in halodims return nhalo else return 0 end end halo_tuple = ntuple(i -> f(i, halodims, nhalo), Val(N)) lo_indices(A, halo_tuple) end """Get the neighbor block id's for a 1D decomposition""" function get_neighbor_blocks_no_periodic(tile_dims::NTuple{1,Integer}) nblocks = prod(tile_dims) nneighbors = 2 CI = CartesianIndices(tile_dims) LI = LinearIndices(tile_dims) block_neighbors = Vector{Dict{Symbol,Int}}(undef, nblocks) neighbor_block_sym = [:ilo, :ihi] for i in LI # set up the block neighbors based on cartesian indexing neighbor_indices = [(i - 1), (i + 1)] block_neighbor_set = Vector{Tuple{Symbol,Int}}(undef, nneighbors) # if the index is out of bounds, it's invalid. # Otherwise, save the 1D index of the block # that is the proper neighbor for (neighbor_id, idx) in enumerate(neighbor_indices) neighbor_symbol = neighbor_block_sym[neighbor_id] valid_neighbor = checkbounds(Bool, CI, idx...) if valid_neighbor neighbor_block = LI[idx...] else neighbor_block = -1 end block_neighbor_set[neighbor_id] = (neighbor_symbol, neighbor_block) end block_neighbors[i] = Dict(block_neighbor_set) end return block_neighbors end """Get the neighbor block id's for a 2D decomposition""" function get_neighbor_blocks_no_periodic(tile_dims::NTuple{2,Integer}) nblocks = prod(tile_dims) nneighbors = 8 CI = CartesianIndices(tile_dims) LI = LinearIndices(tile_dims) block_neighbors = Vector{Dict{Symbol,Int}}(undef, nblocks) neighbor_block_sym = [:ilojlo, :jlo, :ihijlo, :ihi, :ihijhi, :jhi, :ilojhi, :ilo] for block_idx in CI i, j = Tuple(block_idx) # set up the block neighbors based on cartesian indexing neighbor_indices = [ (i - 1, j - 1), (i, j - 1), (i + 1, j - 1), (i + 1, j), (i + 1, j + 1), (i, j + 1), (i - 1, j + 1), (i - 1, j) ] block_neighbor_set = Vector{Tuple{Symbol,Int}}(undef, nneighbors) # if the index is out of bounds, it's invalid. Otherwise, save the 1D index of the block # that is the proper neighbor for (neighbor_id, idx) in enumerate(neighbor_indices) neighbor_symbol = neighbor_block_sym[neighbor_id] valid_neighbor = checkbounds(Bool, CI, idx...) if valid_neighbor neighbor_block = LI[idx...] else neighbor_block = -1 end block_neighbor_set[neighbor_id] = (neighbor_symbol, neighbor_block) end block_neighbors[LI[i, j]] = Dict(block_neighbor_set) # e.g. (:ilo => 4, :jhi => ...), where 4 is the ilo neighbor end return block_neighbors end """Get the neighbor block id's for a 3D decomposition""" function get_neighbor_blocks_no_periodic(tile_dims::NTuple{3,Integer}) nblocks = prod(tile_dims) nneighbors = 3^length(tile_dims) - 1 CI = CartesianIndices(tile_dims) LI = LinearIndices(tile_dims) block_neighbors = Vector{Dict{Symbol,Int}}(undef, nblocks) neighbor_block_sym = [ :ihi, :ihijhi, :ihijhikhi, :ihijhiklo, :ihijlo, :ihijlokhi, :ihijloklo, :ihikhi, :ihiklo, :ilo, :ilojhi, :ilojhikhi, :ilojhiklo, :ilojlo, :ilojlokhi, :ilojloklo, :ilokhi, :iloklo, :jhi, :jhikhi, :jhiklo, :jlo, :jlokhi, :jloklo, :khi, :klo, ] for block_idx in CI i, j, k = Tuple(block_idx) # set up the block neighbors based on cartesian indexing neighbor_indices = [ (i + 1, j, k), (i + 1, j + 1, k), (i + 1, j + 1, k + 1), (i + 1, j + 1, k - 1), (i + 1, j - 1, k), (i + 1, j - 1, k + 1), (i + 1, j - 1, k - 1), (i + 1, j, k + 1), (i + 1, j, k - 1), (i - 1, j, k), (i - 1, j + 1, k), (i - 1, j + 1, k + 1), (i - 1, j + 1, k - 1), (i - 1, j - 1, k), (i - 1, j - 1, k + 1), (i - 1, j - 1, k - 1), (i - 1, j, k + 1), (i - 1, j, k - 1), (i, j + 1, k), (i, j + 1, k + 1), (i, j + 1, k - 1), (i, j - 1, k), (i, j - 1, k + 1), (i, j - 1, k - 1), (i, j, k + 1), (i, j, k - 1), ] block_neighbor_set = Vector{Tuple{Symbol,Int}}(undef, nneighbors) # if the index is out of bounds, it's invalid. # Otherwise, save the 1D index of the block # that is the proper neighbor for (neighbor_id, idx) in enumerate(neighbor_indices) neighbor_symbol = neighbor_block_sym[neighbor_id] valid_neighbor = checkbounds(Bool, CI, idx...) if valid_neighbor neighbor_block = LI[idx...] else neighbor_block = -1 end block_neighbor_set[neighbor_id] = (neighbor_symbol, neighbor_block) end block_neighbors[LI[i, j, k]] = Dict(block_neighbor_set) end return block_neighbors end """Get the neighbor block id's for a 1D decomposition (with periodic edges)""" function get_neighbor_blocks(tile_dims::NTuple{1,Integer}) nblocks = prod(tile_dims) nneighbors = 2 CI = CartesianIndices(tile_dims) LI = LinearIndices(tile_dims) block_neighbors = Vector{Dict{Symbol,Int}}(undef, nblocks) neighbor_block_sym = [:ilo, :ihi] for i in LI # set up the block neighbors based on cartesian indexing neighbor_indices = [[i - 1], [i + 1]] block_neighbor_set = Vector{Tuple{Symbol,Int}}(undef, nneighbors) # if the index is out of bounds, it's invalid. # Otherwise, save the 1D index of the block # that is the proper neighbor for (neighbor_id, idx) in enumerate(neighbor_indices) periodic = false neighbor_symbol = neighbor_block_sym[neighbor_id] for (i, dim) in enumerate(idx) if dim < 1 periodic = true idx[i] = tile_dims[i] elseif dim > tile_dims[i] periodic = true idx[i] = 1 end end neighbor_block = LI[CI[idx...]] if periodic neighbor_block *= -1 end block_neighbor_set[neighbor_id] = (neighbor_symbol, neighbor_block) end block_neighbors[i] = Dict(block_neighbor_set) end return block_neighbors end """Get the neighbor block id's for a 2D decomposition (with periodic edges)""" function get_neighbor_blocks(tile_dims::NTuple{2,Integer}) nblocks = prod(tile_dims) nneighbors = 8 CI = CartesianIndices(tile_dims) LI = LinearIndices(tile_dims) block_neighbors = Vector{Dict{Symbol,Int}}(undef, nblocks) neighbor_block_sym = [:ilojlo, :jlo, :ihijlo, :ihi, :ihijhi, :jhi, :ilojhi, :ilo] for block_idx in CI i, j = Tuple(block_idx) # set up the block neighbors based on cartesian indexing neighbor_indices = [ [i - 1, j - 1], [i, j - 1], [i + 1, j - 1], [i + 1, j], [i + 1, j + 1], [i, j + 1], [i - 1, j + 1], [i - 1, j] ] block_neighbor_set = Vector{Tuple{Symbol,Int}}(undef, nneighbors) for (neighbor_id, idx) in enumerate(neighbor_indices) periodic = false neighbor_symbol = neighbor_block_sym[neighbor_id] for (i, dim) in enumerate(idx) if dim < 1 periodic = true idx[i] = tile_dims[i] elseif dim > tile_dims[i] periodic = true idx[i] = 1 end end neighbor_block = LI[CI[idx...]] if periodic neighbor_block *= -1 end block_neighbor_set[neighbor_id] = (neighbor_symbol, neighbor_block) end block_neighbors[LI[i, j]] = Dict(block_neighbor_set) # e.g. (:ilo => 4, :jhi => ...), where 4 is the ilo neighbor end return block_neighbors end """Get the neighbor block id's for a 3D decomposition (with periodic edges)""" function get_neighbor_blocks(tile_dims::NTuple{3,Integer}) nblocks = prod(tile_dims) nneighbors = 3^length(tile_dims) - 1 CI = CartesianIndices(tile_dims) LI = LinearIndices(tile_dims) block_neighbors = Vector{Dict{Symbol,Int}}(undef, nblocks) neighbor_block_sym = [ :ihi, :ihijhi, :ihijhikhi, :ihijhiklo, :ihijlo, :ihijlokhi, :ihijloklo, :ihikhi, :ihiklo, :ilo, :ilojhi, :ilojhikhi, :ilojhiklo, :ilojlo, :ilojlokhi, :ilojloklo, :ilokhi, :iloklo, :jhi, :jhikhi, :jhiklo, :jlo, :jlokhi, :jloklo, :khi, :klo, ] for block_idx in CI i, j, k = Tuple(block_idx) # set up the block neighbors based on cartesian indexing neighbor_indices = [ [i + 1, j, k], [i + 1, j + 1, k], [i + 1, j + 1, k + 1], [i + 1, j + 1, k - 1], [i + 1, j - 1, k], [i + 1, j - 1, k + 1], [i + 1, j - 1, k - 1], [i + 1, j, k + 1], [i + 1, j, k - 1], [i - 1, j, k], [i - 1, j + 1, k], [i - 1, j + 1, k + 1], [i - 1, j + 1, k - 1], [i - 1, j - 1, k], [i - 1, j - 1, k + 1], [i - 1, j - 1, k - 1], [i - 1, j, k + 1], [i - 1, j, k - 1], [i, j + 1, k], [i, j + 1, k + 1], [i, j + 1, k - 1], [i, j - 1, k], [i, j - 1, k + 1], [i, j - 1, k - 1], [i, j, k + 1], [i, j, k - 1], ] block_neighbor_set = Vector{Tuple{Symbol,Int}}(undef, nneighbors) # if the index is out of bounds, it's invalid. # Otherwise, save the 1D index of the block # that is the proper neighbor for (neighbor_id, idx) in enumerate(neighbor_indices) periodic = false neighbor_symbol = neighbor_block_sym[neighbor_id] for (i, dim) in enumerate(idx) if dim < 1 periodic = true idx[i] = tile_dims[i] elseif dim > tile_dims[i] periodic = true idx[i] = 1 end end neighbor_block = LI[CI[idx...]] if periodic neighbor_block *= -1 end block_neighbor_set[neighbor_id] = (neighbor_symbol, neighbor_block) end block_neighbors[LI[i, j, k]] = Dict(block_neighbor_set) end return block_neighbors end """ Generate the SubArray views of each halo region in `A::BlockHaloArray` that "reciever" views. These are the regions updated in the halo exchange copy/update. """ function gen_halo_views(A) blk_halo_views = Vector{Dict{Symbol,SubArray}}(undef, nblocks(A)) for blk_i in eachindex(A.blocks) halo_reciever = halo_reciever_ranges(A.blocks[blk_i], A.nhalo, A.halodims) blk_halo_views[blk_i] = Dict( k => @view A.blocks[blk_i][.., halo_reciever[k]...] for k in keys(halo_reciever) ) end blk_halo_views end function gen_halo_views(blocks, nhalo, halodims) blk_halo_views = Vector{Dict{Symbol,SubArray}}(undef, length(blocks)) for blk_i in eachindex(blocks) halo_reciever = halo_reciever_ranges(blocks[blk_i], nhalo, halodims) blk_halo_views[blk_i] = Dict( k => @view blocks[blk_i][.., halo_reciever[k]...] for k in keys(halo_reciever) ) end blk_halo_views end """ Generate the SubArray views of each domain region in `A::BlockHaloArray` that are called "donor" views. These are the regions copied from in the halo exchange copy/update. """ function gen_donor_views(A) blk_donor_views = Vector{Dict{Symbol,SubArray}}(undef, nblocks(A)) for blk_i in eachindex(A.blocks) donor = domain_donor_ranges(A.blocks[blk_i], A.nhalo, A.halodims) blk_donor_views[blk_i] = Dict( k => @view A.blocks[blk_i][.., donor[k]...] for k in keys(donor) ) end blk_donor_views end function gen_donor_views(blocks, nhalo, halodims) blk_donor_views = Vector{Dict{Symbol,SubArray}}(undef, length(blocks)) for blk_i in eachindex(blocks) donor = domain_donor_ranges(blocks[blk_i], nhalo, halodims) blk_donor_views[blk_i] = Dict( k => @view blocks[blk_i][.., donor[k]...] for k in keys(donor) ) end blk_donor_views end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
5173
""" Get the cartesian block index within the block layout. For example, in a (2,3) block tiling scheme, based on a given global index `global_i`, and the dimension-specific cummulative `block_sizes`, find the 2D index. The `dim` argument is used to ignore dimensions that are not include in the `halodims`. """ function get_block_idx(global_i, block_sizes, dim, halodims) block_i = 1 if !(dim in halodims) return 0 end for (i, val) in enumerate(block_sizes[dim]) if global_i <= val block_i = i - 1 break end end return block_i + 1 end """For a given single dimension, find the block-local index""" function _get_single_dim_local_index(global_i, block_i, nhalo, block_size) if block_i == 1 return global_i + nhalo else dblock = block_size[block_i] - block_size[block_i-1] return global_i - dblock + nhalo end end """ Get the block-local index based on the given global index. The `block_i` value is the dimension-specific block cartesian index. Dimensions not included in the `halodims` are a special case where the global index is the same as the local index. """ function get_local_idx(global_idx, block_i, nhalo, block_sizes, dim, halodims) if !(dim in halodims) return global_idx[dim] else hdim = dim - (length(global_idx) - length(halodims)) li = _get_single_dim_local_index(global_idx[dim], block_i[hdim], nhalo, block_sizes[dim]) return li end end """ Overload the getindex, or [], method for a BlockHaloArray. This is a 'flat' iterator of sorts, since the actual data within the BlockHaloArray is a series of separate blocks. Iterating through the array in this manner will be slower due to the additional arithmetic need to find the global to local index conversion for each block. """ function Base.getindex(A::BlockHaloArray, global_idx::Vararg{Int, N}) where {N} block_idx = ntuple(i -> get_block_idx(global_idx[A.halodims[i]], A._cummulative_blocksize_per_dim, A.halodims[i], A.halodims), length(A.halodims)) local_idx = ntuple(i -> get_local_idx(global_idx, block_idx, A.nhalo, A._cummulative_blocksize_per_dim, i, A.halodims), length(A.globaldims)) block_id::Int = A._linear_indices[block_idx...] return A.blocks[block_id][local_idx...] end function Base.getindex(A::BlockHaloArray, block_idx::Int) if block_idx > nblocks(A) @error("Attempting to access a block out-of-bounds") end return A.blocks[block_idx] end """ Get the scalar block index give a global index tuple """ function blockindex(A::BlockHaloArray, global_idx::NTuple{N,Int}) where {N} block_idx = ntuple(i -> get_block_idx(global_idx[A.halodims[i]], A._cummulative_blocksize_per_dim, A.halodims[i], A.halodims), length(A.halodims)) return A._linear_indices[block_idx...] end """ Get the block-local indices give a global index tuple """ function localindex(A::BlockHaloArray, global_idx::NTuple{N,Int}) where {N} block_idx = blockindex(A, global_idx) local_idx = ntuple(i -> get_local_idx(global_idx, block_idx, A.nhalo, A._cummulative_blocksize_per_dim, i, A.halodims), length(A.globaldims)) return local_idx end """ Overload the setindex, or A[I] = ... , method for a BlockHaloArray. This is a 'flat' iterator of sorts, since the actual data within the BlockHaloArray is a series of separate blocks. Iterating through the array in this manner will be slower due to the additional arithmetic needed to find the global to local index conversion for each block. """ function Base.setindex!(A::BlockHaloArray, v, global_idx::Vararg{Int, N}) where {N} block_idx = ntuple(i -> get_block_idx(global_idx[A.halodims[i]], A._cummulative_blocksize_per_dim, A.halodims[i], A.halodims), length(A.halodims)) local_idx = ntuple(i -> get_local_idx(global_idx, block_idx, A.nhalo, A._cummulative_blocksize_per_dim, i, A.halodims), length(A.globaldims)) block_id::Int = A._linear_indices[block_idx...] setindex!(A.blocks[block_id], v, local_idx...) end function Base.setindex!(A::BlockHaloArray, v, block_idx::Int) setindex!(A.blocks, v, block_idx) end """ globalindices(A::BlockHaloArray, block_index, local_indices) -> global_indices Given a block index and local coordinates, return the global indices # Example ``` julia> globalindices(A, 2, (3, 4)) -> (8, 10) ``` """ function globalindices(A::BlockHaloArray, block_index::Integer, local_indices) get_idx(idx, b_range, nhalo) = b_range[idx - nhalo] block_range = @views A.global_blockranges[block_index] return get_idx.(local_indices, block_range, A.nhalo) end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
6386
import Base.Iterators.flatten """ block_layout(nblocks, N) Determine the block layout based on the number of total blocks `nblocks` and the dimensionality `N` of the domain # Arguments - `nblocks::Integer` - `N::Integer` """ function block_layout(nblocks::Integer, N::Integer) @assert (1 <= N <= 3) "Invalid dimensionality of the domain: $N" if N == 1 return [nblocks] elseif N == 2 return _block_layout_2d(nblocks) elseif N == 3 return _block_layout_3d(nblocks) end end """ split_count(N::Integer, n::Integer) Return a vector of `n` integers which are approximately equally sized and sum to `N`. This borrows from https://juliaparallel.org/MPI.jl/latest/examples/06-scatterv/ """ function split_count(N::Integer, n::Integer) q, r = divrem(N, n) return [i <= r ? q + 1 : q for i = 1:n] end """Return all common denominators of n""" function denominators(n::Integer) denominators = Vector{Int}(undef, 0) for i in 1:n if mod(n, i) == 0 push!(denominators, i) end end return denominators end """Find the optimal block layout in 2D given total number of tiles `n`""" function _block_layout_2d(n) # find all common denominators of the total number of images denoms = denominators(n) # find all combinations of common denominators # whose product equals the total number of images dim1 = Vector{Int}(undef, 0) dim2 = Vector{Int}(undef, 0) for j in eachindex(denoms) for i in eachindex(denoms) if denoms[i] * denoms[j] == n push!(dim1, denoms[i]) push!(dim2, denoms[j]) end end end # pick the set of common denominators with the minimal norm # between two elements -- rectangle closest to a square n_tiles = [dim1[1], dim2[1]] for i in 2:length(dim1) n1 = norm([dim1[i], dim2[i]] .- sqrt(n)) n2 = norm(n_tiles .- sqrt(n)) if n1 < n2 n_tiles = [dim1[i], dim2[i]] end end return n_tiles end """Find the optimal block layout in 3D given total number of tiles `n`""" function _block_layout_3d(n) # find all common denominators of the total number of images denoms = denominators(n) # find all combinations of common denominators # whose product equals the total number of images dim1 = Vector{Int}(undef, 0) dim2 = Vector{Int}(undef, 0) dim3 = Vector{Int}(undef, 0) for k in eachindex(denoms) for j in eachindex(denoms) for i in eachindex(denoms) if denoms[i] * denoms[j] * denoms[k] == n push!(dim1, denoms[i]) push!(dim2, denoms[j]) push!(dim3, denoms[k]) end end end end # pick the set of common denominators with the minimal norm # between two elements -- rectangle closest to a square n_tiles = [dim1[1], dim2[1], dim3[1]] for i in 2:length(dim1) n1 = norm([dim1[i], dim2[i], dim3[i]] .- sqrt(n)) n2 = norm(n_tiles .- sqrt(n)) if n1 < n2 n_tiles = [dim1[i], dim2[i], dim3[i]] end end return n_tiles end """ get_block_ranges(dims::NTuple{N, Int}, nblocks::Integer) -> Array{NTuple{ndims,UnitRange{Int}}} Get the ranges of each block (in the global space) # Arguments - `dims::NTuple{N, Int}`: Dimensions of the flat array to split into blocks - `nblocks::Integer`: Number of total blocks """ function get_block_ranges(dims::NTuple{N,Int}, tile_dims) where {N} ndims = length(dims) block_sizes = split_count.(dims, collect(tile_dims)) end_idx = cumsum.(block_sizes) start_idx = copy(end_idx) for i in eachindex(end_idx) start_idx[i] = end_idx[i] - block_sizes[i] .+ 1 end blks = Array{NTuple{ndims,UnitRange{Int}}}(undef, tile_dims) for block_I in CartesianIndices(tile_dims) blks[block_I] = [start_idx[dim][x]:end_idx[dim][x] for (dim, x) in enumerate(Tuple(block_I))] |> Tuple end blks end """ update_block_ranges_with_non_halo_dims(block_ranges, axes_sizes, halo_dims) Update the ranges in each block to include the non-halo dimensions """ function update_block_ranges_with_non_halo_dims(block_ranges, axes_sizes, halo_dims) new_ranges = Array{NTuple{length(axes_sizes), UnitRange{Int}}}(undef, size(block_ranges)) non_halo_dim_sizes = Tuple([v for (i, v) in enumerate(axes_sizes) if !(i in halo_dims)]) for I in CartesianIndices(block_ranges) block = block_ranges[I] |> collect non_halo_ranges = UnitRange.(1, non_halo_dim_sizes) |> collect new_range = append!(non_halo_ranges, block) new_ranges[I] = Tuple(new_range) end new_ranges end """ repartition(A::AbstractBlockHaloArray, nblocks) -> BlockHaloArray Repartition the BlockHaloArray into a different block layout """ function repartition!(A::AbstractBlockHaloArray, nblocks::Integer) if nblocks == 1 @warn "Trying to repartition!() into 1 block is prohibited" return A elseif nblocks == length(A.blocks) @warn "New block layout is the same as the original" return A end Aflat = flatten(A) return BlockHaloArray(Aflat, A.nhalo, nblocks) end """ flatten(A::AbstractBlockHaloArray) -> Array Return a flattened version of a BlockHaloArray. This is a copy, since a view of the current block structure isn't possible. """ function flatten(A::AbstractBlockHaloArray) A_flat = zeros(eltype(A), A.globaldims) block_ranges = A.global_blockranges for tid in LinearIndices(block_ranges) domain_indices = UnitRange.((axes(A.blocks[tid]) .|> first) .+ A.nhalo, (axes(A.blocks[tid]) .|> last) .- A.nhalo) domain_view = view(A.blocks[tid], domain_indices...) A_flat_view = view(A_flat, block_ranges[tid]...) copy!(A_flat_view, domain_view) end return A_flat end function globalsize(A::AbstractBlockHaloArray, nohalo=true) ndims = length(size(first(A.blocks))) global_dims = zeros(Int, ndims) for block in A.blocks for dim in 1:ndims global_dims[dim] += size(block, dim) end end if nohalo global_dims .-= length(A.blocks) * ndims * A.nhalo end global_dims |> Tuple end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
1188
""" @tspawnat tid -> task Mimics `Base.Threads.@spawn`, but assigns the task to thread `tid` (with `sticky = true`). # Example ```julia julia> t = @tspawnat 4 Threads.threadid() Task (runnable) @0x0000000010743c70 julia> fetch(t) 4 ``` """ macro tspawnat(thrdid, expr) # Copied/modified from ThreadPools.jl/ThreadPinning.jl with the change task.sticky = false -> true # https://github.com/tro3/ThreadPools.jl/blob/c2c99a260277c918e2a9289819106dd38625f418/src/macros.jl#L244 letargs = Base._lift_one_interp!(expr) thunk = esc(:(() -> ($expr))) var = esc(Base.sync_varname) tid = esc(thrdid) quote check_threads($tid) let $(letargs...) local task = Task($thunk) task.sticky = true ccall(:jl_set_task_tid, Cvoid, (Any, Cint), task, $tid - 1) if $(Expr(:islocal, var)) put!($var, task) end schedule(task) task end end end function check_threads(tid, n_threads=Base.Threads.nthreads()::Int) if tid < 1 || tid > n_threads throw(AssertionError("@tspawnat invalid thread id (must be between 1 and nthreads)")) end end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
814
using TestItemRunner @run_package_tests # @testitem "Flat index testing" begin # dims = (4, 50, 50) # global_idx = (1, 26, 26) # halodims = (2, 3) # A = BlockHaloArray(dims, halodims, 2, 2) # block_idx = ntuple(i -> # BlockHaloArrays.get_block_idx(global_idx[A.halodims[i]], # A._cummulative_blocksize_per_dim, # A.halodims[i], # A.halodims), # length(A.halodims)) # local_idx = ntuple(i -> # BlockHaloArrays.get_local_idx(global_idx, # block_idx, # A.nhalo, # A._cummulative_blocksize_per_dim, # i, # A.halodims), # length(A.globaldims)) # @test block_idx == (2, 1) # @test local_idx == (1, 3, 28) # end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
244
using .Threads using BlockHaloArrays using EllipsisNotation using BlockHaloArrays: @tspawnat using Test # using JET # using TestItems, TestItemRunner function init(A, thread_id) dom = domainview(A, thread_id) fill!(dom, thread_id) end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
2118
@testitem "Copy Constructor" begin dims = (50, 50) nhalo = 2 nblocks = 6 B = rand(dims...) A = BlockHaloArray(B, nhalo, nblocks) end @testitem "Check tile dims" begin dims = (60, 10) nhalo = 2 nblocks = 6 tiledims = (3,3) # mismatched partitioning @test_throws ErrorException("Invalid tile_dims; the number of blocks is not consistent") BlockHaloArray(dims, nhalo, nblocks; tile_dims = tiledims) end @testitem "Provide tile dims" begin dims = (60, 10) nhalo = 2 nblocks = 6 tiledims = (6,1) A = BlockHaloArray(dims, nhalo, nblocks; tile_dims = tiledims) @test A.block_layout == tiledims @test A.global_blockranges[1] == (1:10, 1:10) @test A.global_blockranges[2] == (11:20, 1:10) @test A.global_blockranges[3] == (21:30, 1:10) @test A.global_blockranges[4] == (31:40, 1:10) @test A.global_blockranges[5] == (41:50, 1:10) @test A.global_blockranges[6] == (51:60, 1:10) for block in eachindex(A.blocks) @test size(A[block]) == (14, 14) # 10 + 2nhalo end end @testitem "2D Halo, 2D Array, Different Types" begin include("common.jl") dims = (50, 50) nhalo = 2 nblocks = 6 for T in [ Int16, Int32, Int64, Int128, Float16, Float32, Float64, ComplexF64 ] A = BlockHaloArray(dims, nhalo, nblocks; T=T) @test eltype(A) == T end end @testitem "2D Array, 1D halo dims" begin dims = (10, 20) halodims = (2,) nhalo = 2 nblocks = 4 A = BlockHaloArray(dims, nhalo, nblocks) end @testitem "2D Array, 2D halo dims" begin dims = (10, 20) nhalo = 2 nblocks = 4 A = BlockHaloArray(dims, nhalo, nblocks) @show A.global_blockranges @show A.block_layout @show typeof(A) end @testitem "3D Array, 1D halo dims" begin dims = (10, 20, 30) halodims = (2,) nhalo = 2 nblocks = 4 A = BlockHaloArray(dims, nhalo, nblocks) end @testitem "3D Array, 2D halo dims" begin dims = (10, 20, 30) halodims = (2, 3) nhalo = 2 nblocks = 4 A = BlockHaloArray(dims, nhalo, nblocks) end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
10484
@testitem "2D Halo, 2D Array" begin include("common.jl") dims = (50, 50) nhalo = 2 n_blocks = 6 A = BlockHaloArray(dims, nhalo, n_blocks; T=Int64) @test length(A.blocks) == n_blocks @test A.block_layout == (3, 2) # for a (3,2) block layout, here are the block id's # # *---* *---* *---* # | 4 | | 5 | | 6 | # j *---* *---* *---* # *---* *---* *---* # | 1 | | 2 | | 3 | # *---* *---* *---* # i # negative IDs mean it crosses over the domain boundaries, e.g. periodic blk_neighbor = [ Dict(:ilo => -3, :ihi => 2, :jlo => -4, :jhi => 4, :ilojhi => -6, :ihijhi => 5, :ilojlo => -6, :ihijlo => -5), # 1 Dict(:ilo => 1, :ihi => 3, :jlo => -5, :jhi => 5, :ilojhi => 4, :ihijhi => 6, :ilojlo => -4, :ihijlo => -6), # 2 Dict(:ilo => 2, :ihi => -1, :jlo => -6, :jhi => 6, :ilojhi => 5, :ihijhi => -4, :ilojlo => -5, :ihijlo => -4), # 3 Dict(:ilo => -6, :ihi => 5, :jlo => 1, :jhi => -1, :ilojhi => -3, :ihijhi => -2, :ilojlo => -3, :ihijlo => 2), # 4 Dict(:ilo => 4, :ihi => 6, :jlo => 2, :jhi => -2, :ilojhi => -1, :ihijhi => -3, :ilojlo => 1, :ihijlo => 3), # 5 Dict(:ilo => 5, :ihi => -4, :jlo => 3, :jhi => -3, :ilojhi => -2, :ihijhi => -1, :ilojlo => 2, :ihijlo => -1), # 6 ] for blockid in 1:n_blocks for key in keys(first(blk_neighbor)) @test A.neighbor_blocks[blockid][key] == blk_neighbor[blockid][key] end end @sync for tid in 1:n_blocks @tspawnat tid init(A, tid) end include_periodic_bc = true updatehalo!(A, include_periodic_bc) @show @allocated updatehalo!(A, include_periodic_bc) @show @allocated updatehalo!(A, true) @show @allocated updatehalo!(A, false) @show @allocated updatehalo!(A) @show @allocated updateblockhalo!(A, 1, true) @show @allocated updateblockhalo!(A, 1, false) for blockid in 1:n_blocks dv = domainview(A, blockid) @test all(dv .== blockid) end for blockid in 1:n_blocks hi_domn_start, hi_domn_end, hi_halo_start, hi_halo_end = BlockHaloArrays.hi_indices(A.blocks[blockid], A.nhalo) lo_halo_start, lo_halo_end, lo_domn_start, lo_domn_end = BlockHaloArrays.lo_indices(A.blocks[blockid], A.nhalo) ihi_domn_start, jhi_domn_start = hi_domn_start ihi_domn_end, jhi_domn_end = hi_domn_end ihi_halo_start, jhi_halo_start = hi_halo_start ihi_halo_end, jhi_halo_end = hi_halo_end ilo_halo_start, jlo_halo_start = lo_halo_start ilo_halo_end, jlo_halo_end = lo_halo_end ilo_domn_start, jlo_domn_start = lo_domn_start ilo_domn_end, jlo_domn_end = lo_domn_end current_block = A.blocks[blockid] ilo = A.neighbor_blocks[blockid][:ilo] |> Float64 |> abs ihi = A.neighbor_blocks[blockid][:ihi] |> Float64 |> abs jlo = A.neighbor_blocks[blockid][:jlo] |> Float64 |> abs jhi = A.neighbor_blocks[blockid][:jhi] |> Float64 |> abs @test all(current_block[ilo_halo_start:ilo_halo_end, jlo_domn_start:jhi_domn_end] .== ilo) @test all(current_block[ihi_halo_start:ihi_halo_end, jlo_domn_start:jhi_domn_end] .== ihi) @test all(current_block[ilo_domn_start:ihi_domn_end, jlo_halo_start:jlo_halo_end] .== jlo) @test all(current_block[ilo_domn_start:ihi_domn_end, jhi_halo_start:jhi_halo_end] .== jhi) end end @testitem "2D Halo, 3D Array" begin include("common.jl") dims = (4, 30, 20) halodims = (2, 3) nhalo = 2 n_blocks = 6 A = BlockHaloArray(dims, halodims, nhalo, n_blocks; T=Int64) @test length(A.blocks) == n_blocks @test A.block_layout == (3, 2) # for a (3,2) block layout, here are the block id's # # *---* *---* *---* # | 4 | | 5 | | 6 | # j *---* *---* *---* # *---* *---* *---* # | 1 | | 2 | | 3 | # *---* *---* *---* # i # negative IDs mean it crosses over the domain boundaries, e.g. periodic blk_neighbor = [ Dict(:ilo => -3, :ihi => 2, :jlo => -4, :jhi => 4, :ilojhi => -6, :ihijhi => 5, :ilojlo => -6, :ihijlo => -5), # 1 Dict(:ilo => 1, :ihi => 3, :jlo => -5, :jhi => 5, :ilojhi => 4, :ihijhi => 6, :ilojlo => -4, :ihijlo => -6), # 2 Dict(:ilo => 2, :ihi => -1, :jlo => -6, :jhi => 6, :ilojhi => 5, :ihijhi => -4, :ilojlo => -5, :ihijlo => -4), # 3 Dict(:ilo => -6, :ihi => 5, :jlo => 1, :jhi => -1, :ilojhi => -3, :ihijhi => -2, :ilojlo => -3, :ihijlo => 2), # 4 Dict(:ilo => 4, :ihi => 6, :jlo => 2, :jhi => -2, :ilojhi => -1, :ihijhi => -3, :ilojlo => 1, :ihijlo => 3), # 5 Dict(:ilo => 5, :ihi => -4, :jlo => 3, :jhi => -3, :ilojhi => -2, :ihijhi => -1, :ilojlo => 2, :ihijlo => -1), # 6 ] for blockid in 1:n_blocks for key in keys(first(blk_neighbor)) @test A.neighbor_blocks[blockid][key] == blk_neighbor[blockid][key] end end @sync for tid in 1:n_blocks @tspawnat tid init(A, tid) end for blockid in 1:n_blocks dv = domainview(A, blockid) @test all(dv .== blockid) end include_periodic_bc = true updatehalo!(A, include_periodic_bc) for blockid in 1:n_blocks hi_domn_start, hi_domn_end, hi_halo_start, hi_halo_end = BlockHaloArrays.hi_indices(A.blocks[blockid], A.nhalo, A.halodims) lo_halo_start, lo_halo_end, lo_domn_start, lo_domn_end = BlockHaloArrays.lo_indices(A.blocks[blockid], A.nhalo, A.halodims) _, ihi_domn_start, jhi_domn_start = hi_domn_start _, ihi_domn_end, jhi_domn_end = hi_domn_end _, ihi_halo_start, jhi_halo_start = hi_halo_start _, ihi_halo_end, jhi_halo_end = hi_halo_end _, ilo_halo_start, jlo_halo_start = lo_halo_start _, ilo_halo_end, jlo_halo_end = lo_halo_end _, ilo_domn_start, jlo_domn_start = lo_domn_start _, ilo_domn_end, jlo_domn_end = lo_domn_end current_block = A.blocks[blockid] ilo = A.neighbor_blocks[blockid][:ilo] |> Float64 |> abs ihi = A.neighbor_blocks[blockid][:ihi] |> Float64 |> abs jlo = A.neighbor_blocks[blockid][:jlo] |> Float64 |> abs jhi = A.neighbor_blocks[blockid][:jhi] |> Float64 |> abs @test all(current_block[:, ilo_halo_start:ilo_halo_end, jlo_domn_start:jhi_domn_end] .== ilo) @test all(current_block[:, ihi_halo_start:ihi_halo_end, jlo_domn_start:jhi_domn_end] .== ihi) @test all(current_block[:, ilo_domn_start:ihi_domn_end, jlo_halo_start:jlo_halo_end] .== jlo) @test all(current_block[:, ilo_domn_start:ihi_domn_end, jhi_halo_start:jhi_halo_end] .== jhi) end end @testitem "1D Array, 1D halo dims" begin include("common.jl") dims = (20,) nhalo = 2 n_blocks = 4 A = BlockHaloArray(dims, nhalo, n_blocks; T=Int32) @test A.neighbor_blocks[1][:ilo] == -4 @test A.neighbor_blocks[1][:ihi] == 2 @test A.neighbor_blocks[2][:ilo] == 1 @test A.neighbor_blocks[2][:ihi] == 3 @test A.neighbor_blocks[3][:ilo] == 2 @test A.neighbor_blocks[3][:ihi] == 4 @test A.neighbor_blocks[4][:ilo] == 3 @test A.neighbor_blocks[4][:ihi] == -1 @sync for tid in 1:n_blocks @tspawnat tid init(A, tid) end include_periodic_bc = true updatehalo!(A, include_periodic_bc) for blockid in 1:n_blocks hi_domn_start, hi_domn_end, hi_halo_start, hi_halo_end = BlockHaloArrays.hi_indices(A.blocks[blockid], A.nhalo) lo_halo_start, lo_halo_end, lo_domn_start, lo_domn_end = BlockHaloArrays.lo_indices(A.blocks[blockid], A.nhalo) ihi_halo_start = first(hi_halo_start) ihi_halo_end = first(hi_halo_end) ilo_halo_start = first(lo_halo_start) ilo_halo_end = first(lo_halo_end) current_block = A.blocks[blockid] ilo = A.neighbor_blocks[blockid][:ilo] |> Float64 |> abs ihi = A.neighbor_blocks[blockid][:ihi] |> Float64 |> abs @test all(current_block[ilo_halo_start:ilo_halo_end] .== ilo) @test all(current_block[ihi_halo_start:ihi_halo_end] .== ihi) end end @testitem "3D Array, 3D halo dims" begin include("common.jl") dims = (10, 20, 30) nhalo = 2 n_blocks = 6 A = BlockHaloArray(dims, nhalo, n_blocks; T=Float64) @sync for tid in 1:n_blocks @tspawnat tid init(A, tid) end include_periodic_bc = true updatehalo!(A, include_periodic_bc) for blockid in 1:n_blocks hi_domn_start, hi_domn_end, hi_halo_start, hi_halo_end = BlockHaloArrays.hi_indices(A.blocks[blockid], A.nhalo) lo_halo_start, lo_halo_end, lo_domn_start, lo_domn_end = BlockHaloArrays.lo_indices(A.blocks[blockid], A.nhalo) ihi_domn_start, jhi_domn_start, khi_domn_start = hi_domn_start ihi_domn_end, jhi_domn_end, khi_domn_end = hi_domn_end ihi_halo_start, jhi_halo_start, khi_halo_start = hi_halo_start ihi_halo_end, jhi_halo_end, khi_halo_end = hi_halo_end ilo_halo_start, jlo_halo_start, klo_halo_start = lo_halo_start ilo_halo_end, jlo_halo_end, klo_halo_end = lo_halo_end ilo_domn_start, jlo_domn_start, klo_domn_start = lo_domn_start ilo_domn_end, jlo_domn_end, klo_domn_end = lo_domn_end current_block = A.blocks[blockid] ilo = A.neighbor_blocks[blockid][:ilo] |> Float64 |> abs ihi = A.neighbor_blocks[blockid][:ihi] |> Float64 |> abs jlo = A.neighbor_blocks[blockid][:jlo] |> Float64 |> abs jhi = A.neighbor_blocks[blockid][:jhi] |> Float64 |> abs klo = A.neighbor_blocks[blockid][:klo] |> Float64 |> abs khi = A.neighbor_blocks[blockid][:khi] |> Float64 |> abs @test all(current_block[ilo_halo_start:ilo_halo_end, jlo_domn_start:jhi_domn_end, klo_domn_start:khi_domn_end] .== ilo) @test all(current_block[ihi_halo_start:ihi_halo_end, jlo_domn_start:jhi_domn_end, klo_domn_start:khi_domn_end] .== ihi) @test all(current_block[ilo_domn_start:ihi_domn_end, jlo_halo_start:jlo_halo_end, klo_domn_start:khi_domn_end] .== jlo) @test all(current_block[ilo_domn_start:ihi_domn_end, jhi_halo_start:jhi_halo_end, klo_domn_start:khi_domn_end] .== jhi) @test all(current_block[ilo_domn_start:ihi_domn_end, jlo_domn_start:jhi_domn_end, klo_halo_start:klo_halo_end] .== klo) @test all(current_block[ilo_domn_start:ihi_domn_end, jlo_domn_start:jhi_domn_end, khi_halo_start:khi_halo_end] .== khi) end end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
code
4188
@testitem "halo/donorview" begin include("common.jl") dims = (50, 50) nhalo = 2 n_blocks = 4 A = BlockHaloArray(dims, nhalo, n_blocks) @test size(donorview(A, 1, :ilo)) == (2, 25) @test size(haloview(A, 1, :ilo)) == (2, 25) @test size(donorview(A, 1, :jhi)) == (25, 2) @test size(haloview(A, 1, :jhi)) == (25, 2) end @testitem "domainview" begin include("common.jl") nhalo = 3 n_blocks = 4 dims = (40,40) A = BlockHaloArray(dims, nhalo, n_blocks) blockid = 1 @test size(domainview(A, blockid)) == (20, 20) @test size(domainview(A, blockid, 1)) == (22, 22) @test size(domainview(A, blockid, 2)) == (24, 24) @test size(domainview(A, blockid, 3)) == (26, 26) @test_throws ErrorException domainview(A, blockid, 4) @test_throws ErrorException domainview(A, blockid, -1) end @testitem "nblocks" begin include("common.jl") A = BlockHaloArray((50,50), 2, 4) @test nblocks(A) == 4 end @testitem "eltype" begin include("common.jl") A = BlockHaloArray((50,50), 2, 4, T=Int32) @test eltype(A) == Int32 end @testitem "size" begin include("common.jl") A = BlockHaloArray((50,50), 2, 4, T=Int32) @test size(A) == (50, 50) end @testitem "onboundary" begin include("common.jl") dims = (50, 50) nhalo = 2 n_blocks = 6 A = BlockHaloArray(dims, nhalo, n_blocks; T=Int64) # for a (3,2) block layout, here are the block id's # # *---* *---* *---* # | 4 | | 5 | | 6 | # j *---* *---* *---* # *---* *---* *---* # | 1 | | 2 | | 3 | # *---* *---* *---* # i @test onboundary(A, 1, :ilo) == true @test onboundary(A, 1, :ihi) == false @test onboundary(A, 1, :jlo) == true @test onboundary(A, 1, :jhi) == false @test onboundary(A, 2, :ilo) == false @test onboundary(A, 2, :ihi) == false @test onboundary(A, 2, :jlo) == true @test onboundary(A, 2, :jhi) == false @test onboundary(A, 3, :ilo) == false @test onboundary(A, 3, :ihi) == true @test onboundary(A, 3, :jlo) == true @test onboundary(A, 3, :jhi) == false @test onboundary(A, 4, :ilo) == true @test onboundary(A, 4, :ihi) == false @test onboundary(A, 4, :jlo) == false @test onboundary(A, 4, :jhi) == true @test onboundary(A, 5, :ilo) == false @test onboundary(A, 5, :ihi) == false @test onboundary(A, 5, :jlo) == false @test onboundary(A, 5, :jhi) == true @test onboundary(A, 6, :ilo) == false @test onboundary(A, 6, :ihi) == true @test onboundary(A, 6, :jlo) == false @test onboundary(A, 6, :jhi) == true end @testitem "1D Indexing" begin include("common.jl") x = rand(50) nhalo = 2 n_blocks = 4 A = BlockHaloArray(x, nhalo, n_blocks) @test all(A[1] .== A.blocks[1]) @test_nowarn A[4] .= 2.5 end @testitem "n-D Indexing" begin include("common.jl") x = rand(40, 40) y = rand(4, 40, 40) nhalo = 2 n_blocks = 4 A = BlockHaloArray(x, nhalo, n_blocks) halodims = (2, 3) B = BlockHaloArray(y, halodims, nhalo, n_blocks) @test A[1] == A.blocks[1] @test size(A[1]) == (24, 24) @test A[1][3,3] == x[1,1] @test_nowarn A[1][3,3] = 1.2 @test B[1][1,3,3] == y[1,1,1] @test B[1][:,3,3] == y[:,1,1] @test_nowarn B[1][1,3,3] =6.7 end @testitem "globalindices" begin x = rand(40, 40) nhalo = 2 n_blocks = 4 A = BlockHaloArray(x, nhalo, n_blocks) @test globalindices(A, 1, (3, 3)) == (1, 1) @test globalindices(A, 4, (3, 3)) == (21, 21) # @show globalindices(A, 4, (22, 22)) end @testitem "copy!" begin include("common.jl") dims = (10, 10) nhalo = 2 n_blocks = 2 AA = rand(dims...) AA2 = zeros(dims...) AA_mismatch = rand(12,10) BHA = BlockHaloArray(dims, nhalo, n_blocks) @test_throws ErrorException copy!(AA_mismatch, BHA) @test_throws ErrorException copy!(BHA, AA_mismatch) copy!(BHA, AA) # copy from the abstract array to the block halo array @test AA == flatten(BHA) copy!(AA2, BHA) # copy from the abstract array to the block halo array @test AA2 == flatten(BHA) end
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
docs
5545
# BlockHaloArrays The `BlockHaloArray` type is an array-like type (does not extend `AbstractArray`) that is designed for shared-memory multi-threaded workloads. Typical shared-memory parallelization is done via multi-threaded loops (with `@threads`, `@tturbo`, etc.), i.e.: ```julia Threads.@threads for j in jlo:jhi for i in ilo:ihi A[i,j] = ... end end ``` However, this type of parallelization tends not to scale well, especially for memory-bandwidth limited workloads. This is especially true for stencil operations, where functions access memory at addresses such as `A[i,j], A[i+1,j], A[i-1,j+1]`. The aim of the `BlockHaloArray` type do mini-domain decomposition into separate thread-specific chunks, or blocks, of memory for each thread to operate on without data race conditions or memory bandwidth contention. Because the context is shared memory however, certain operations are more efficient compared to the typical MPI domain decomposition method.Each thread will be able to operate on it's own block of memory and maintain NUMA-aware locality and communication is done via copies, rather than MPI library calls. Future releases will include an MPI-aware `BlockHaloArray` that will facilitate the MPI+Threads hybrid parallelization. An example of a blocked-style stencil operation looks like the following. Note that it can still take advantage of the single-threaded `@turbo` macro to vectorize the nested-loop. ```julia function stencil!(A::BlockHaloArray, blockid) ilo, ihi, jlo, jhi = A.loop_limits[blockid] data = @views A.blocks[blockid] @turbo for j in jlo:jhi for i in ilo:ihi data[i, j] = i * j + 0.25(data[i-2, j] + data[i-1, j] + data[i+2, j] + data[i+1, j] + data[i, j] + data[i, j-2] + data[i, j-1] + data[i, j+2] + data[i, j+1]) end end end ``` Then the `stencil!()` function is split among threads via: ```julia @sync for block_id in 1:nthreads() @tspawnat block_id stencil!(A, block_id) end ``` `BlockHaloArray` types should be used in a task-based parallel workload, which has better scaling than multi-threaded loops. The only synchronization required is during the exchange of halo data. Benchmark results are coming soon... ## Exports ### Types - `BlockHaloArray`: A blocked array-like type (does not extent `AbstractArray`) to be used in a shared-memory type system. This partitions an `Array` into N blocks that are to be operated on by threads. #### Constructors ```julia BlockHaloArray(dims::NTuple{N,Int}, halodims::NTuple{N2,Int}, nhalo::Integer, nblocks=nthreads(); T=Float64, use_numa=true) BlockHaloArray(dims::NTuple{N,Int}, nhalo::Integer, nblocks=nthreads(); T=Float64, use_numa=true) BlockHaloArray(A::AbstractArray{T,N}, nhalo::Integer, nblocks=nthreads()) BlockHaloArray(A::AbstractArray{T,N}, halodims::NTuple{N2,Integer}, nhalo::Integer, nblocks=nthreads()) ``` #### Example ```julia using .Threads using ThreadPools using BlockHaloArrays dims = (30, 20) # a 30 x 20 matrix nhalo = 2 # number of halo entries in each dimension nblocks = nthreads() # nblocks must be ≤ nthreads() or a warning will be issued A = BlockHaloArray(dims, nhalo, nblocks; T=Float64) # create with empty data B = BlockHaloArray(rand(dims...), nhalo, nblocks) # create from an existing array # Create a 3D array, but only do halo exchange on the 2nd and 3rd dimensions newdims = (4, 100, 200) haloax = (2, 3) # these must be monotonically increasing and the outer-most dims, i.e. can't be (1, 2), or (1, 3) C = BlockHaloArray(newdims, haloax, nhalo, nblocks; T=Float64) # Fill each block with it's corresponding threadid value function init(A) dom = domainview(A, threadid()) fill!(dom, threadid()) end # Let each thread initialize it's own block @sync for tid in 1:nblocks(A) @tspawnat tid init(A1) end # Let each block sync its halo region with its neighbors updatehalo!(A) Anew = flatten(A) # Anew is a 2D Array -- no longer a BlockHaloArray ``` - `MPIBlockHaloArray`: (to be implemented) An MPI-aware version of a `BlockHaloArray`. This facilitates halo communication between nodes via MPI. ### Functions - `flatten(A)`: Return a flattened `Array` of `A`. This is a copy. - `repartition(A, nblocks)`: Repartition the BlockHaloArray into a different block layout - `updatehalo!(A, include_periodic_bc=false)`: Sync all block halo regions. This uses a `@sync` loop with @tspawnat to sync each block. - `updateblockhalo!(A, block_id, include_periodic_bc=false)`: Sync the halo regions of a single block. No `@sync` or `@spawn` calls are used. - `domainview(A, blockid)`: Return a view of a the domain (no halo regions) of block `blockid` - `onboundary(A, blockid)`: Is the current block `blockid` on a boundary? This is used help apply boundary conditions in a user code. Additional overloaded methods include ```julia eltype(A::AbstractBlockHaloArray) = eltype(first(A.blocks)) size(A::AbstractBlockHaloArray) = A.globaldims size(A::AbstractBlockHaloArray, dim) = size.(A.blocks, dim) axes(A::AbstractBlockHaloArray) = axes.(A.blocks) axes(A::AbstractBlockHaloArray, dim) = axes.(A.blocks, dim) first(A::AbstractBlockHaloArray) = first(A.blocks) firstindex(A::AbstractBlockHaloArray) = firstindex(A.blocks) last(A::AbstractBlockHaloArray) = last(A.blocks) lastindex(A::AbstractBlockHaloArray) = lastindex(A.blocks) eachindex(A::AbstractBlockHaloArray) = eachindex(A.blocks) nblocks(A::AbstractBlockHaloArray) = length(A.blocks) ```
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
docs
90
# API Reference ```@autodocs Modules = [BlockHaloArrays] Order = [:type, :function] ```
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.4.10
64eca3565cebb67fb229f55867285e7fb6627431
docs
59
# BlockHaloArrays.jl Documentation for BlockHaloArrays.jl
BlockHaloArrays
https://github.com/smillerc/BlockHaloArrays.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
585
module WGPUTranspiler using CodeTracking using Infiltrator include("codegen/scalar.jl") include("codegen/abstracts.jl") include("codegen/variable.jl") include("codegen/scope.jl") include("codegen/assignment.jl") include("codegen/rangeBlock.jl") include("codegen/conditionBlock.jl") include("codegen/builtin.jl") include("codegen/expr.jl") include("codegen/funcBlock.jl") include("codegen/computeBlock.jl") include("codegen/infer.jl") include("codegen/resolve.jl") include("codegen/transpile.jl") include("codegen/tree.jl") include("codegen/compile.jl") end # module WGPUTranspiler
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
175
abstract type JLExpr end abstract type JLVariable <: JLExpr end abstract type JLBlock <: JLExpr end abstract type BinaryOp <: JLExpr end abstract type JLBuiltIn <: JLExpr end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
7470
export Scalar, assignExpr typeInfer(scope::Scope, var::WGPUVariable) = begin if symbol(var) == :WgpuArray return eval(symbol(var)) end sym = symbol(var) inferScope!(scope, var) (found, location, rootScope) = findVar(scope, sym) issamescope = rootScope.depth == scope.depth # @assert issamescope "Not on same scope! What to do ?" var.dataType = getDataTypeFrom(rootScope, location, sym) return var.dataType end typeInfer(scope::Scope, varRef::Ref{WGPUVariable}) = typeInfer(scope, varRef[]) struct LHS expr::Union{Ref{WGPUVariable}, JLExpr} newVar::Bool end isMutable(lhs::LHS) = isMutable(lhs.expr) setMutable!(lhs::LHS, b::Bool) = setMutable!(lhs.expr, b) isNew(lhs::LHS) = lhs.newVar symbol(lhs::LHS) = symbol(lhs.expr) typeInfer(scope::Scope, lhs::LHS) = begin typeInfer(scope, lhs.expr) end mutable struct RHS expr::Union{Nothing, Ref{WGPUVariable}, Scalar, JLExpr} end symbol(rhs::RHS) = symbol(rhs.expr) symbol(::Nothing) = nothing symbol(sym::Symbol) = sym symbol(::Scalar) = nothing function inferScope!(scope, lhs::LHS) sym = symbol(lhs) (found, location, rootScope) = findVar(scope, sym) if found == true && location != :typeScope setMutable!(lhs.expr, true) end end function inferScope!(scope, var::WGPUVariable) (found, _) = findVar(scope, var.sym) @assert found == true "Variable $(var.sym) is not in local, global and type scope" end function inferScope!(scope, var::Ref{WGPUVariable}) (found, _) = findVar(scope, (var[]).sym) @assert found == true "Variable $(var.sym) is not in local, global and type scope" end typeInfer(scope::Scope, rhs::RHS) = typeInfer(scope, rhs.expr) typeInfer(scope::Scope, s::Scalar) = eltype(s) struct AssignmentExpr <: JLExpr lhs::LHS rhs::RHS scope::Scope end symbol(assign::AssignmentExpr) = symbol(assign.lhs) function assignExpr(scope, lhs::Symbol, rhs::Number) rhsExpr = RHS(Scalar(rhs)) rhsType = typeInfer(scope, rhsExpr) (lhsfound, lhslocation, lhsScope) = findVar(scope, lhs) lhsExpr = Ref{LHS}() if lhsfound && lhslocation == :localScope lExpr = lhsScope.locals[lhs] lhsExpr[] = LHS(lExpr, false) rhsExpr = RHS(Scalar(rhs |> lExpr[].dataType)) setMutable!(lhsExpr[], true) elseif lhsfound && lhslocation == :globalScope lVar = lhsScope.globals[lhs] lVarRef = Ref{WGPUVariable}(lVar) lVarRef[].dataType = rhsType lhsExprp[] = LHS(lVarRef, false) setMutable!(lhsExpr[], true) elseif lhsfound == false lvar = inferExpr(scope, lhs) scope.globals[lhs] = lvar[] lvar[].dataType = rhsType scope.locals[lhs] = lvar #lvar[].undefined = true lhsExpr[] = LHS(lvar, true) setMutable!(lhsExpr[], false) else error("This should not have reached") end statement = AssignmentExpr(lhsExpr[], rhsExpr, scope) return statement end function assignExpr(scope, lhs::Expr, rhs::Number) lExpr = inferExpr(scope, lhs) rhsExpr = RHS(Scalar(rhs)) rhsType = typeInfer(scope, rhsExpr) (lhsfound, lhslocation, lhsScope) = findVar(scope, symbol(lExpr)) lhsExpr = Ref{LHS}() if typeof(lExpr) == IndexExpr if lhsfound && lhslocation == :localScope lExpr = lhsScope.locals[lhs] lhsExpr[] = LHS(lExpr, false) rhsExpr = RHS(Scalar(rhs |> lExpr[].dataType)) setMutable!(lhsExpr[], true) elseif lhsfound && lhslocation == :globalScope lVar = lhsScope.globals[symbol(lExpr)] lVarRef = Ref{WGPUVariable}(lVar) rhsExpr = RHS(Scalar(rhs |> eltype(lVar.dataType))) lhsExpr[] = LHS(lExpr, false) setMutable!(lhsExpr[], true) elseif lhsfound == false lvar = inferExpr(scope, lhs) scope.globals[lhs] = lvar[] lvar[].dataType = rhsType lhsExpr[] = LHS(lvar, true) setMutable!(lhsExpr[], false) else error("This should not have reached") end elseif typeof(lExpr) == AccessExpr else error(" This expr type is not covered : $lExpr") end statement = AssignmentExpr(lhsExpr[], rhsExpr, scope) return statement end function assignExpr(scope, lhs::Symbol, rhs::Symbol) rhsExpr = RHS(inferExpr(scope, rhs)) rhsType = typeInfer(scope, rhsExpr) (lhsfound, lhslocation, lhsScope) = findVar(scope, lhs) lhsExpr = Ref{LHS}() if lhsfound && lhslocation == :localScope lExpr = lhsScope.locals[lhs] lhsExpr[] = LHS(lExpr, false) lExpr[].dataType = rhsType setMutable!(lhsExpr[], true) elseif lhsfound && lhslocation == :globalScope lVar = lhsScope.globals[lhs] lVarRef = Ref{WGPUVariable}(lVar) #scope.locals[lhs] = lVarRef lVarRef[].dataType = rhsType lhsExpr[] = LHS(lVarRef, false) setMutable!(lhsExpr[], true) elseif found == false # setMutable!(lhsExpr[], false) end statement = AssignmentExpr(lhsExpr[], rhsExpr, scope) return statement end function assignExpr(scope, lhs::Symbol, rhs::Expr) rhsExpr = RHS(inferExpr(scope, rhs)) rhsType = typeInfer(scope, rhsExpr) (found, location, rootScope) = findVar(scope, lhs) lhsExpr = Ref{LHS}() if found && location == :localScope lExpr = rootScope.locals[lhs] lhsExpr[] = LHS(lExpr, false) @assert lExpr[].dataType == rhsType "$(lExpr[].dataType) != $rhsType" lExpr[].undefined = false setMutable!(lhsExpr[], true) elseif found && location == :globalScope lExpr = rootScope.globals[lhs] lExprRef = Ref{WGPUVariable}(lExpr) rootScope.locals[lhs] = lExprRef lhsExpr[] = LHS(lExprRef, false) @assert lExprRef[].dataType == rhsType lExprRef[].undefined = false setMutable!(lhsExpr[], true) elseif found == false && location == nothing # new var lvar = inferExpr(scope, lhs) scope.globals[lhs] = lvar[] lvar[].dataType = rhsType lvar[].undefined = true lhsExpr[] = LHS(lvar, true) setMutable!(lhsExpr[], false) else error("Not captured this case yet!!!!") end statement = AssignmentExpr(lhsExpr[], rhsExpr, scope) return statement end function assignExpr(scope, lhs::Expr, rhs::Union{Expr, Symbol}) lExpr = inferExpr(scope, lhs) rhsExpr = RHS(inferExpr(scope, rhs)) inferScope!(scope, rhsExpr.expr) rhsType = typeInfer(scope, rhsExpr) lhsExpr = Ref{LHS}() if typeof(lExpr) == IndexExpr (found, location, rootScope) = findVar(scope, symbol(lExpr)) if found && location != :typeScope lvar = location == :localScope ? rootScope.locals[symbol(lExpr)] : rootScope.globals[symbol(lExpr)] #lvar = rootScope.locals[symbol(lExpr)] lhsExpr[] = LHS(lExpr, false) lhsType = typeInfer(scope, lhsExpr[]) @assert lhsType == rhsType "$lhsType != $rhsType" #setMutable!(lhsExpr[], true) else found == false error("LHS var $(symbol(lhs)) had to be mutable for indexing") end elseif typeof(lExpr) == AccessExpr (found, location, rootScope) = findVar(scope, symbol(lExpr)) if found && location !=:typeScope lExpr = rootScope.locals[symbol(lExpr)] lhsExpr[] = LHS(lExpr[], false) setMutable!(lhsExpr[], true) else found == false error("LHS var $(symbol(lhs)) has to be mutable for `getproperty`") end elseif typeof(lExpr) == DeclExpr (found, location, rootScope) = findVar(scope, symbol(lExpr)) if found && location ==:globalScope && location != :localScope lhsExpr[] = LHS(lExpr, true) scope.locals[symbol(lExpr)] = scope.globals[symbol(lExpr)] elseif found && location ==:localScope if rootScope.depth == scope.depth error("Duplication definition is not allowed") else # set new var node end else found == false error("This state shouldn't have been reached in Decl") end else error("This $lhs type Expr is not captured yet") end statement = AssignmentExpr(lhsExpr[], rhsExpr, scope) return statement end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
522
@enum BuiltinType begin vertexIndex instanceIndex position # might collide frontFacing fragDepth localInvocationId localInvocationIndex globalInvocationId workgroupId numWorkGroups sampleIndex sampleMask end struct WorkGroupId <: JLBuiltIn x::UInt32 y::UInt32 z::UInt32 end struct GlobalInvocationId <: JLBuiltIn x::UInt32 y::UInt32 z::UInt32 end struct LocalInvocationId <: JLBuiltIn x::UInt32 y::UInt32 z::UInt32 end struct LocalInvocationIndex <: JLBuiltIn x::UInt32 y::UInt32 z::UInt32 end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
4275
using MacroTools using WGSLTypes using WGSLTypes: wgslfunctions struct WGPUKernelObject func::Function end struct WorkGroupDims x::UInt32 y::UInt32 z::UInt32 end struct WArray{T, N} # TODO define these properly end struct WArrayDims x::UInt32 y::UInt32 z::UInt32 end struct ComputeBlock <: JLBlock fname::Ref{WGPUVariable} fargs::Vector{DeclExpr} Targs::Vector{Ref{WGPUVariable}} fbody::Vector{JLExpr} scope::Union{Nothing, Scope} wgSize::NTuple{3, UInt32} wgCount::NTuple{3, UInt32} builtinArgs::Array{Expr} end makeVarPair(p::Pair{Symbol, DataType}) = WGPUVariable(p.first, p.second, Generic, nothing, false, false) function computeBlock(scope, islaunch, wgSize, wgCount, funcName, funcArgs, fexpr::Expr) @capture(fexpr, function fname_(fargs__) where Targs__ fbody__ end) workgroupSize = Base.eval(wgSize) if workgroupSize |> length < 3 workgroupSize = (workgroupSize..., repeat([1,], inner=(3 - length(workgroupSize)))...) end workgroupCount = Base.eval(wgCount) if workgroupCount |> length < 3 workgroupCount = (workgroupCount..., repeat([1,], inner=(3 - length(workgroupCount)))...) end push!(scope.code.args, quote @const workgroupDims = Vec3{UInt32}($(UInt32.(workgroupSize)...)) end ) # TODO include these only based on `symbols(funcblock)`` scope.globals[:workgroupDims] = makeVarPair(:workgroupDims => WorkGroupDims) scope.globals[:workgroupId] = makeVarPair(:workgroupId=>WorkGroupId) scope.globals[:localId] = makeVarPair(:localId=>LocalInvocationId) scope.globals[:globalId] = makeVarPair(:globalId=>GlobalInvocationId) scope.globals[:ceil] = makeVarPair(:ceil=>Function) for wgslf in wgslfunctions scope.globals[wgslf] = makeVarPair(wgslf=>Function) end builtinArgs = [ :(@builtin(global_invocation_id, globalId::Vec3{UInt32})), :(@builtin(local_invocation_id, localId::Vec3{UInt32})), :(@builtin(num_workgroups, numWorkgroups::Vec3{UInt32})), :(@builtin(workgroup_id, workgroupId::Vec3{UInt32})), ] for (inArg, symbolArg) in zip(funcArgs, fargs) if @capture(symbolArg, iovar_::ioType_{T_, N_}) #scope.globals[T] = eltype(inArg) #scope.globals[N] = Val{ndims(inArg)} scope.typeVars[T] = makeVarPair(T=>eltype(inArg)) scope.typeVars[N] = makeVarPair(N=>Val{ndims(inArg)}) end end for (idx, (inarg, symbolarg)) in enumerate(zip(funcArgs, fargs)) if @capture(symbolarg, iovar_::ioType_{T_, N_}) # TODO instead of assert we should branch for each case of argument if ioType == :WgpuArray dimsVar = Symbol(iovar, :Dims) dims = size(inarg) if dims |> length < 3 dims = (dims..., repeat([1,], inner=(3 - length(dims)))...) end push!( scope.code.args, quote @const $dimsVar = Vec3{UInt32}($(UInt32.(dims)...)) end ) scope.globals[dimsVar] = makeVarPair(dimsVar=>WArrayDims) end elseif @capture(symbolarg, iovar_::ioType_) if eltype(inarg) in [Float32, Int32, UInt32, Bool] # TODO we need to update this push!( scope.code.args, quote @const $iovar::$(eltype(inarg)) = $(Meta.parse((wgslType(inarg)))) end ) scope.globals[iovar] = makeVarPair(iovar=>Base.eval(ioType)) else scope.globals[iovar] = makeVarPair(iovar=>Val(iovar)) end end end for (idx, (inarg, symbolarg)) in enumerate(zip(funcArgs, fargs)) if @capture(symbolarg, iovar_::ioType_{T_, N_}) # TODO instead of assert we should branch for each case of argument @assert ioType == :WgpuArray #"Expecting WgpuArray Type, received $ioType instead" arrayLen = reduce(*, size(inarg)) push!( scope.code.args, quote @var StorageReadWrite 0 $(idx-1) $(iovar)::Array{$(eltype(inarg)), $(arrayLen)} end ) # scope.globals[iovar] = iovar end end fn = inferExpr(scope, fname) fa = map(_x -> inferExpr(scope, _x), fargs) # make fargs to storage read write for (i, arg) in enumerate(fa) # (arg.sym[]).dataType = typeInfer(scope, fa) (arg.sym[]).varType = StorageReadWrite (arg.sym[]).varAttr = WGPUVariableAttribute(0, i) end fb = map(x -> inferExpr(scope, x), fbody) ta = map(x -> inferExpr(scope, x), Targs) return ComputeBlock(fn, fa, ta, fb, scope, workgroupSize, workgroupCount, builtinArgs) end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
590
struct Condition <: JLExpr cond::Union{WGPUVariable, Scalar, JLExpr} end struct IfBlock <: JLBlock cond::JLExpr block::Vector{JLExpr} scope::Union{Nothing, Scope} end function ifBlock(scope::Scope, cond::Expr, block::Vector{Any}) childScope = Scope(Dict(), Dict(), Dict(), scope.depth + 1, scope, :()) condExpr = inferExpr(scope, cond) inferScope!(scope, condExpr) exprArray = JLExpr[] for jlexpr in block push!(exprArray, inferExpr(childScope, jlexpr)) end return IfBlock(condExpr, exprArray, scope) end symbol(iff::IfBlock) = (symbol(iff.cond), map(symbol, iff.block)...)
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
5921
# BinaryExpressions struct BinaryExpr <: BinaryOp op::Union{Symbol, Function} left::Union{Ref{WGPUVariable}, Scalar, JLExpr} right::Union{Ref{WGPUVariable}, Scalar, JLExpr} end function binaryOp( scope::Scope, op::Union{Symbol, Function}, a::Union{Symbol, Number, Expr}, b::Union{Number, Symbol, Expr}; ) lOperand = inferExpr(scope, a) inferScope!(scope, lOperand) rOperand = inferExpr(scope, b) inferScope!(scope, rOperand) return BinaryExpr(op, lOperand, rOperand) end typeInfer(scope::Scope, binOp::BinaryExpr) = typeintersect(typeInfer(scope, binOp.left), typeInfer(scope, binOp.right)) function symbol(binOp::BinaryExpr) syms = map(symbol, (binOp.left[], binOp.right[])) return syms end # Common inferScope! for all binary operations function inferScope!(scope::Scope, jlexpr::BinaryOp) inferScope!(scope, jlexpr.left) inferScope!(scope, jlexpr.right) end # CallExpression struct CallExpr <: JLExpr func::Union{Ref{WGPUVariable}, JLExpr} args::Vector{Union{Ref{WGPUVariable}, Scalar, JLExpr}} end function callExpr(scope::Scope, f::Union{Symbol, Expr}, args::Vector{Any}) func = inferExpr(scope, f) inferScope!(scope, func) arguments = [] for arg in args argument = inferExpr(scope, arg) inferScope!(scope, argument) push!(arguments, argument) end return CallExpr(func, arguments) end symbol(a::Vector{T}) where T <: Union{WGPUVariable, Scalar, JLExpr} = (map(symbol, a)) symbol(callexpr::CallExpr) = (symbol(callexpr.func), symbol(callexpr.args)) function inferScope!(scope::Scope, jlexpr::CallExpr) # We don't have to do anything for now end typeInfer(scope::Scope, cExpr::CallExpr) = begin # @assert allequal(cExpr.args) "All aguments are expected to be same" (found, location, rootScope) = findVar(scope, symbol(cExpr.func)) if found && location == :typeScope tVar = rootScope.typeVars[cExpr.func |> symbol] if tVar.dataType <: Number return tVar.dataType end end typejoin(map(x -> typeInfer(scope, x), cExpr.args)...) end # IndexExpressions struct IndexExpr <: JLExpr sym::Union{Ref{WGPUVariable}, JLExpr} idx::Union{Ref{WGPUVariable}, Scalar, JLExpr} end symbol(idxExpr::IndexExpr) = symbol(idxExpr.sym) function indexExpr(scope::Scope, sym::Union{Symbol, Expr}, idx::Union{Symbol, Number, Expr}) symExpr = inferExpr(scope, sym) inferScope!(scope, symExpr) idxExpr = inferExpr(scope, idx) inferScope!(scope, idxExpr) return IndexExpr(symExpr, idxExpr) end isMutable(idxExpr::IndexExpr) = isMutable(idxExpr.sym) setMutable!(idxExpr::IndexExpr, b::Bool) = setMutable!(idxExpr.sym, b) function inferScope!(scope::Scope, jlexpr::IndexExpr) end typeInfer(scope::Scope, idxExpr::IndexExpr) = begin idx = idxExpr.idx # TODO handle scalar cases for indexing ... if typeof(idx) == Scalar idx = Scalar(idx.element |> UInt32) end ty = typeInfer(scope, idx) @assert ty == UInt32 "types do not match $(symbol(idx))::$ty vs UInt32" # TODO we might have to deal with multi-indexing return eltype(typeInfer(scope, idxExpr.sym)) end # AccessorExpression struct AccessExpr<: JLExpr sym::Union{Ref{WGPUVariable}, JLExpr} field::Union{Ref{WGPUVariable}, JLExpr} end isMutable(axsExpr::AccessExpr) = isMutable(axsExpr.sym) setMutable!(axsExpr::AccessExpr, b::Bool) = setMutable!(axsExpr.sym, b) function accessExpr(scope::Scope, sym::Symbol, field::Symbol) symExpr = inferExpr(scope, sym) fieldExpr = inferExpr(scope, field) aExpr = AccessExpr(symExpr, fieldExpr) inferScope!(scope, aExpr) return aExpr end function accessExpr(scope::Scope, parent::Expr, field::Symbol) parentExpr = inferExpr(scope, parent) childExpr = inferExpr(scope, field) aExpr = AccessExpr(symExpr, fieldExpr) inferScope!(scope, aExpr) return aExpr end symbol(access::AccessExpr) = symbol(access.sym) function inferScope!(scope::Scope, jlexpr::AccessExpr) #inferScope!(scope, jlexpr.sym) #inferScope!(scope, jlexpr.field) end typeInfer(scope::Scope, axsExpr::AccessExpr) = fieldtype(typeInfer(scope, axsExpr.sym), symbol(axsExpr.field)) struct TypeExpr <: JLExpr sym::Ref{WGPUVariable} types::Vector{Ref{WGPUVariable}} end function typeExpr(scope, a::Symbol, b::Vector{Any}) aExpr = inferExpr(scope, a) bExpr = map(x -> inferExpr(scope, x), b) return TypeExpr(aExpr, bExpr) end symbol(tExpr::TypeExpr) = (symbol(tExpr.sym), map(x -> symbol(x), tExpr.types)...) typeInfer(scope::Scope, tExpr::TypeExpr) = begin if symbol(tExpr)[1] == :WgpuArray # Hardcoded return typeInfer(scope, tExpr, Val(symbol(tExpr)[1])) else return typeInfer(scope, tExpr.sym) end end struct DeclExpr <: JLExpr sym::Ref{WGPUVariable} dataType::Union{DataType, TypeExpr} end function declExpr(scope, a::Symbol, b::Symbol) (found, location, rootScope) = findVar(scope, a) if found && location == :globalScope error("Duplication declaration of variable $a") end aExpr = inferExpr(scope, a) bExpr = Base.eval(b) aExpr[].dataType = bExpr return DeclExpr(aExpr, bExpr) end function declExpr(scope, a::Symbol, b::Expr) (found, location, rootScope) = findVar(scope, a) if found && location == :localScope error("Duplicate declaration of variable $a") end bExpr = inferExpr(scope, b) bType = typeInfer(scope, bExpr) aExpr = inferExpr(scope, a) aExpr[].dataType = bType return DeclExpr(aExpr, bExpr) end isMutable(decl::DeclExpr) = isMutable(decl.sym[]) setMutable!(decl::DeclExpr, b::Bool) = setMutable!(decl.sym[], b) symbol(decl::DeclExpr) = symbol(decl.sym[]) typeInfer(scope::Scope, declexpr::DeclExpr) = begin sym = symbol(declexpr) (found, location, rootScope) = findVar(scope, sym) if found == false && location != :typeScope scope.locals[sym] = declexpr.sym var = scope.locals[sym] setproperty!(var[], :dataType, declexpr.dataType) else found == true && scope.depth == rootScope.depth error("duplicate declaration of a variable $sym is not allowed in wgsl though julia allows it") end typeInfer(scope, declexpr.sym) end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
514
struct FuncBlock <: JLBlock fname::Ref{WGPUVariable} fargs::Vector{DeclExpr} Targs::Vector{Ref{WGPUVariable}} fbody::Vector{JLExpr} scope::Union{Nothing, Scope} end function funcBlock(scope::Scope, fname::Symbol, fargs::Vector{Any}, fbody::Vector{Any}) childScope = Scope(Dict(), Dict(), Dict(), scope.depth+1, scope, quote end) fn = inferExpr(scope, fname) fa = map(x -> inferExpr(scope, x), fargs) fb = map(x -> inferExpr(scope, x), fbody) return FuncBlock(fn, fa, WGPUVariable[], fb, childScope) end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
3620
using MacroTools export inferExpr, @infer function inferExpr(scope::Scope, expr::Expr) if @capture(expr, lhs_ = rhs_) return assignExpr(scope, lhs, rhs) elseif @capture(expr, a_ + b_) return binaryOp(scope, :+, a, b) elseif @capture(expr, a_ - b_) return binaryOp(scope, :-, a, b) elseif @capture(expr, a_ * b_) return binaryOp(scope, :*, a, b) elseif @capture(expr, a_ / b_) return binaryOp(scope, :/, a, b) elseif @capture(expr, a_ < b_) return binaryOp(scope, :<, a, b) elseif @capture(expr, a_ > b_) return binaryOp(scope, :>, a, b) elseif @capture(expr, a_ <= b_) return binaryOp(scope, :<=, a, b) elseif @capture(expr, a_ >= b_) return binaryOp(scope, :>=, a, b) elseif @capture(expr, a_ == b_) return binaryOp(scope, :>=, a, b) elseif @capture(expr, a_ += b_) return binaryOp(scope, :+=, a, b) # TODO this should be assignment expr elseif @capture(expr, a_ -= b_) return binaryOp(scope, :-=, a, b) # TODO this should be assignment expr elseif @capture(expr, f_(args__)) return callExpr(scope, f, args) elseif @capture(expr, a_::b_) return declExpr(scope, a, b) elseif @capture(expr, a_[b_]) return indexExpr(scope, a, b) elseif @capture(expr, a_.b_) return accessExpr(scope, a, b) elseif @capture(expr, a_{b__}) return typeExpr(scope, a, b) elseif @capture(expr, for idx_ in range_ block__ end) return rangeBlock(scope, idx, range, block) elseif @capture(expr, if cond_ block__ end) return ifBlock(scope, cond, block) elseif @capture(expr, if cond_ ifblock__ else elseblock__ end) return ifelseBlock(scope, cond, ifblock, elseblock) elseif @capture(expr, function fname_(fargs__) fbody__ end) return funcBlock(scope, fname, fargs, fbody) elseif @capture(expr, function fname_(fargs__) where Targs__ fbody__ end) return funcBlock(scope, fname, fargs, Targs, fbody) elseif @capture(expr, @wgpukernel islaunch_ workgroupSize_ workgroupCount_ function fname_(fargs__) where Targs__ fbody__ end) return computeBlock(scope, islaunch, workgroupSize, workgroupCount, fname, fargs, Targs, fbody) elseif @capture(expr, @wgpukernel islaunch_ workgroupSize_ workgroupCount_ fname_(fargs__)) return computeBlock(scope, islaunch, workgroupSize, workgroupCount, fname, fargs) else error("Couldn't capture $expr") end end function inferExpr(scope::Scope, a::Symbol) (found, location, rootScope) = findVar(scope, a) var = Ref{WGPUVariable}() if found == false var[] = WGPUVariable(a, Any, Generic, nothing, false, true) scope.globals[a] = var[] elseif found == true && location == :globalScope var[] = rootScope.globals[a] var[].undefined = true elseif found == true && location == :typeScope var[] = rootScope.typeVars[a] var[].undefined = false else found == true && location == :localScope var = rootScope.locals[a] var[].undefined = false end return var end function inferRange(scope, expr::Expr) if @capture(expr, a_:b_) start = inferExpr(scope, a) inferScope!(scope, start) stop = inferExpr(scope, b) inferScope!(scope, stop) step = inferExpr(scope, 1) inferScope!(scope, step) return RangeExpr(start, step, stop) elseif @capture(expr, a_:b_:c_) start = inferExpr(scope, a) inferScope!(scope, start) step = inferExpr(scope, b) inferScope!(scope, step) stop = inferExpr(scope, c) inferScope!(scope, stop) return RangeExpr(start, step, stop) end end function inferExpr(scope::Scope, a::Number) return Scalar(a) end function inferExpr(scope::Scope, a::WGPUScalarType) return Scalar(a) end inferExpr(scope::Scope, a::Scalar) = a macro infer(cntxt, expr) inferExpr(cntxt, expr) end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
1405
function kernelFunc(funcExpr) if @capture(funcExpr, function fname_(fargs__) where Targs__ fbody__ end) kernelfunc = quote function $fname(args::Tuple{WgpuArray}, workgroupSizes, workgroupCount) $preparePipeline($(funcExpr), args...) $compute($(funcExpr), args...; workgroupSizes=workgroupSizes, workgroupCount=workgroupCount) return nothing end end |> unblock return esc(quote $kernelfunc end) else error("Couldnt capture function") end end function getFunctionBlock(func, args) fString = CodeTracking.definition(String, which(func, args)) return Meta.parse(fString |> first) end function wgpuCall(kernelObj::WGPUKernelObject, args...) kernelObj.kernelFunc(args...) end macro wgpukernel(launch, wgSize, wgCount, ex) code = quote end @gensym f_var kernel_f kernel_args kernel_tt kernel if @capture(ex, fname_(fargs__)) (vars, var_exprs) = assign_args!(code, fargs) push!(code.args, quote $kernel_args = ($(var_exprs...),) $kernel_tt = Tuple{map(Core.Typeof, $kernel_args)...} kernel = function wgpuKernel(args...) $preparePipeline($fname, args...; workgroupSizes=$wgSize, workgroupCount=$wgCount) $compute($fname, args...; workgroupSizes=$wgSize, workgroupCount=$wgCount) end if $launch == true wgpuCall(WGPUKernelObject(kernel), $(kernel_args)...) else WGPUKernelObject(kernel) end end ) end esc(code) end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
1491
struct RangeBlock <: JLBlock start::Union{Ref{WGPUVariable}, JLExpr, Scalar} step::Union{Ref{WGPUVariable}, JLExpr, Scalar} stop::Union{Ref{WGPUVariable}, JLExpr, Scalar} idx::Union{JLExpr} block::Vector{JLExpr} scope::Union{Nothing, Scope} end struct RangeExpr <: JLExpr start::Union{Ref{WGPUVariable}, JLExpr, Scalar} step::Union{Ref{WGPUVariable}, JLExpr, Scalar} stop::Union{Ref{WGPUVariable}, JLExpr, Scalar} end function inferExpr(scope::Scope, range::StepRangeLen) @error "Not implemented yet" end function rangeBlock(scope::Scope, idx::Symbol, range::Expr, block::Vector{Any}) # TODO deal with StepRangeLen also may be ? I don't see its use though. childScope = Scope(Dict(), Dict(), Dict(), scope.depth + 1, scope, :()) rangeExpr = inferRange(childScope, range) startExpr = rangeExpr.start if typeof(startExpr) == Ref{WGPUVariable} childScope.globals[symbol(startExpr)] = startExpr[].sym end stopExpr = rangeExpr.stop if typeof(stopExpr) == Ref{WGPUVariable} childScope.globals[symbol(stopExpr)] = stopExpr[].sym end stepExpr = rangeExpr.step if typeof(stepExpr) == Ref{WGPUVariable} childScope.globals[symbol(stepExpr)] = stepExpr[].sym end idxExpr = inferExpr(childScope, :($idx::UInt32)) setMutable!(idxExpr, true) scope.globals[idx] = idxExpr.sym[] exprArray = JLExpr[] for stmnt in block push!(exprArray, inferExpr(childScope, stmnt)) end rangeBlockExpr = RangeBlock(startExpr, stepExpr, stopExpr, idxExpr, exprArray, childScope) end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
52
#scope = Scope() #@assign cntxt=scope a::Int32 = 0
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
408
export Scalar, WGPUScalarType const WGPUScalarType = Union{Float32, UInt32, Int32, Bool} struct Scalar element::WGPUScalarType end Base.convert(::Type{WGPUScalarType}, a::Int64) = WGPUScalarType(Int32(a)) Base.convert(::Type{WGPUScalarType}, a::UInt64) = WGPUScalarType(UInt32(a)) Base.convert(::Type{WGPUScalarType}, a::Float64) = WGPUScalarType(Float32(a)) Base.eltype(s::Scalar) = typeof(s.element)
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
2317
export Scope, getDataTypeFrom, getDataType, getGlobalScope, findVar struct Scope locals::Dict{Symbol, Ref{WGPUVariable}} globals::Dict{Symbol, WGPUVariable} typeVars::Dict{Symbol, WGPUVariable} depth::Int parent::Union{Nothing, Scope} code::Expr end # TODO scope should include wgslFunctions and other builtins by default Scope() = Scope(Dict(), Dict(), Dict(), 0, nothing, quote end) function findVar(scope::Union{Nothing, Scope}, sym::Symbol) if scope == nothing return (false, nothing, scope) end localsyms=keys(scope.locals) globalsyms=keys(scope.globals) typesyms = keys(scope.typeVars) if (sym in localsyms) return (true, :localScope, scope) elseif (sym in globalsyms) return (true, :globalScope, scope) elseif (sym in typesyms) return (true, :typeScope, scope) end return findVar(scope.parent, sym) end function inferScope!(scope, scalar::Scalar) # Do nothing end function getGlobalScope(scope::Union{Nothing, Scope}) if scope == nothing @error "No global state can be retrieved from `nothing` scope" elseif scope.depth == 1 return scope else getGlobalScope(scope.parent) end end function getDataTypeFrom(scope::Union{Nothing, Scope}, location, var::Symbol) if scope == nothing @error "Nothing scope cannot be searched for $var symbol" elseif location == :localScope return getindex(scope.locals[var]).dataType elseif location == :globalScope return scope.globals[var].dataType elseif location == :typeScope return scope.typeVars[var].dataType end end function getDataType(scope::Union{Nothing, Scope}, var::Symbol) (found, location, rootScope) = findVar(scope, var) if found == true getDataTypeFrom(rootScope, location, var) else return Any end end function Base.isequal(scope::Scope, other::Scope) length(scope.locals) == length(other.locals) && keys(scope.locals) == keys(other.locals) && length(scope.globals) == length(other.globals) && keys(scope.globals) == keys(other.globals) && for (key, value) in scope.locals if !Base.isequal(other.locals[key][], value[]) return false end end for (key, value) in scope.globals if Base.isequal(other.globals[key][], value[]) return false end end for (key, value) in scope.typeVars if Base.isequal(other.typeVars[key][], value[]) return false end end return true end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
8975
using Revise using WGPUCompute using WGPUTranspiler using WGPUTranspiler: WorkGroupDims, Generic, WGPUVariable using CodeTracking using Chairmarks makeVarPair(p::Pair{Symbol, DataType}) = p.first => WGPUVariable( p.first, p.second, Generic, nothing, false, true ) # ------ scope = Scope( Dict( makeVarPair(:b=>Int32), makeVarPair(:c=>Int32), ), Dict(), Dict(), 0, nothing, quote end ) aExpr = inferExpr(scope, :(a::Int32 = b + c)) #bExpr = inferExpr(scope, :(a::Int32 = b + c)) transpile(scope, aExpr) # ------ scope = Scope( Dict( makeVarPair(:b=>Int32), makeVarPair(:c=>Int32), ), Dict(), Dict(), 0, nothing, quote end ) aExpr = inferExpr(scope, :(a::Int32 = b + c)) bExpr = inferExpr(scope, :(a = b + c)) transpile(scope, aExpr) transpile(scope, bExpr) # ------ scope = Scope( Dict( makeVarPair(:b=>Int32), makeVarPair(:c=>Int32), ), Dict(), Dict(), 0, nothing, quote end ) aExpr = inferExpr(scope, :(a = b + c)) vExpr = inferExpr(scope, :(a = b + c)) transpile(scope, aExpr) transpile(scope, vExpr) # ------ scope = Scope( Dict( makeVarPair(:b=>Int32), makeVarPair(:c=>Int32), ), Dict(), Dict(), 0, nothing, quote end ) aExpr = inferExpr(scope, :(a = b + c)) bExpr = inferExpr(scope, :(a = c)) transpile(scope, aExpr) transpile(scope, bExpr) # ------ scope = Scope( Dict( makeVarPair(:b=>Int32), makeVarPair(:c=>Int32), ), Dict(), Dict(), 0, nothing, quote end ) aExpr = inferExpr(scope, :(a = b + c)) transpile(scope, aExpr) # ------- # TODO rerunning transpile(scope, aExpr) will have declexpr for a lik a::Int32 which is a bug # This should fail because of type mismatches scope = Scope( Dict( makeVarPair(:workgroupDims=>WorkGroupDims), ), Dict(), Dict(), 0, nothing, quote end ) aExpr = inferExpr(scope, :(a::Int32 = workgroupDims.x)) transpile(scope, aExpr) # ---- scope = Scope( Dict( makeVarPair(:workgroupDims=>WorkGroupDims), ), Dict(), Dict(), 0, nothing, quote end ) aExpr = inferExpr(scope, :(a::UInt32 = workgroupDims.x)) transpile(scope, aExpr) # ---- scope = Scope( Dict( makeVarPair(:workgroupDims=>WorkGroupDims), ), Dict(), Dict(), 0, nothing, quote end ) aExpr = inferExpr(scope, :(a::UInt32 = workgroupDims.x)) transpile(scope, aExpr) # This should fail variable a in rhs is not in scope scope = Scope( Dict( makeVarPair(:b=>Int32), makeVarPair(:c=>UInt32), makeVarPair(:(+)=>Function), makeVarPair(:g=>Function) ), Dict(), Dict(), 0, nothing, quote end ) cExpr = inferredExpr = inferExpr(scope, :(a::Int32 = g(a + b + c) + g(2, 3, c))) transpile(scope, cExpr) # This should fail too datatypes are different scope = Scope( Dict( makeVarPair(:b=>Int32), makeVarPair(:c=>UInt32), makeVarPair(:(+)=>Function), makeVarPair(:g=>Function) ), Dict(), Dict(), 0, nothing, quote end ) cExpr = inferredExpr = inferExpr(scope, :(a::Int32 = g(b + c) + g(2, 3, c))) transpile(scope, cExpr) # ------ # This should fail too scope = Scope( Dict( makeVarPair(:b=>Int32), makeVarPair(:c=>UInt32), makeVarPair(:(+)=>Function), makeVarPair(:g=>Function) ), Dict(), Dict(), 0, nothing, quote end ) cExpr = inferredExpr = inferExpr(scope, :(a::Int32 = g(b + c) + g(2.0, 3, c))) transpile(scope, cExpr) # ------ scope = Scope( Dict( makeVarPair(:b=>UInt32), makeVarPair(:c=>UInt32), makeVarPair(:(+)=>Function), makeVarPair(:g=>Function) ), Dict(), Dict(), 0, nothing, quote end ) inferredExpr = inferExpr(scope, :(a::UInt32 = ( b + g(b + c)))) transpile(scope, inferredExpr) # ---- scope = Scope( Dict( makeVarPair(:a=>WgpuArray{UInt32, 16}), makeVarPair(:d=>UInt32), makeVarPair(:c=>UInt32), makeVarPair(:b=>WgpuArray{UInt32, 16}), makeVarPair(:(+)=>Function), makeVarPair(:g=>Function) ), Dict(), Dict(), 0, nothing, quote end ) inferredExpr = inferExpr(scope, :(a[d] = c + b[1])) #TODO 1 is a scalar Int32 will fail transpile(scope, inferredExpr) # ----- struct B b::WgpuArray{Int32, 16} end scope = Scope( Dict( makeVarPair(:a=>WgpuArray{Int32, 16}), makeVarPair(:c=>UInt32), makeVarPair(:g=>B), makeVarPair(:(+)=>Function) ), Dict(), Dict(), 0, nothing, quote end) inferredExpr = inferExpr(scope, :(a[c] = g.b[1])) transpile(scope, inferredExpr) # ----- struct B b::WgpuArray{Int32, 16} end struct C c::WgpuArray{Int32, 16} end scope = Scope(Dict( makeVarPair(:a=>C), makeVarPair(:g=>B) ), Dict(), Dict(), 0, nothing, quote end) inferredExpr = inferExpr(scope, :(a.c[1] = g.b[1])) # scalar indexes will fail transpile(scope, inferredExpr) # ----- scope = Scope( Dict( makeVarPair(:a=>WgpuArray{Float32, 16}), makeVarPair(:b=>WgpuArray{Float32, 16}), makeVarPair(:c=>WgpuArray{Float32, 16}), makeVarPair(:d=>WgpuArray{Float32, 16}), makeVarPair(:println=>Function), makeVarPair(:(+)=>Function) ), Dict(), Dict(), 0, nothing, quote end ) inferredExpr = inferExpr( scope, :(for i in 0:1:12 println(i) a[i] = b[i] c[i] = d[i] + c[i] + 1.0 end) ) transpile(scope, inferredExpr) # ----- scope = Scope( Dict( makeVarPair(:a=>WgpuArray{Float32, 16}), makeVarPair(:b=>WgpuArray{Float32, 16}), makeVarPair(:c=>WgpuArray{Float32, 16}), makeVarPair(:d=>WgpuArray{Float32, 16}), makeVarPair(:println=>Function), makeVarPair(:(+)=>Function) ), Dict(), Dict(), 0, nothing, quote end ) inferredExpr = inferExpr( scope, :(for i in 0:1:12 for j in 1:2:40 println(i, j) a[j] = b[i] c[i] = d[i] + c[i] + 1.0 end end) ) transpile(scope, inferredExpr) # ----- scope = Scope( Dict( makeVarPair(:x=>Int32), makeVarPair(:a=>WgpuArray{Float32, 16}), makeVarPair(:b=>WgpuArray{Float32, 16}), makeVarPair(:c=>WgpuArray{Float32, 16}), makeVarPair(:d=>WgpuArray{Float32, 16}), makeVarPair(:println=>Function), makeVarPair(:(+)=>Function) ), Dict(), Dict(), 0, nothing, quote end ) inferredExpr = inferExpr( scope, :( for i in 1:10 if x > 0 println(i) a[i] = b[i] c[i] = d[i] + c[i] + 1.0 end end ) ) transpile(scope, inferredExpr) # ---- scope = Scope( Dict( makeVarPair(:println=>Function) ), Dict(), Dict(), 0, nothing, quote end ) inferredExpr = inferExpr( scope, :(function test(a::Float32, b::Float32) for i in 1:10 println(i) end end) ) transpile(scope, inferredExpr) # ----- function cast_kernel(x::WgpuArray{T, N}, out::WgpuArray{S, N}) where {T, S, N} xdim = workgroupDims.x ydim = workgroupDims.y gIdx = workgroupId.x*xdim + localId.x gIdy = workgroupId.y*ydim + localId.y gId = xDims.x*gIdy + gIdx out[gId] = S(ceil(x[gId])) end a = WgpuArray(rand(Float32, 4, 4)); b = WgpuArray(rand(Float32, 4, 4)); scope = Scope( Dict( ), Dict(), Dict(), 0, nothing, quote end) inferredExpr = inferExpr( scope, :(@wgpukernel launch=true workgroupSize=(4, 4) workgroupCount=(1, 1) $cast_kernel($a, $b)) ) transpile(scope, inferredExpr) # ------- function cast_kernel(x::WgpuArray{T, N}, out::WgpuArray{S, N}) where {T, S, N} xdim = workgroupDims.x ydim = workgroupDims.y gIdx = workgroupId.x*xdim + localId.x gIdy = workgroupId.y*ydim + localId.y gId::UInt32 = xDims.x*gIdy + gIdx gId = 1 out[gId] = S(ceil(x[gId])) end a = WgpuArray(rand(Float32, 4, 4)); b = WgpuArray(rand(Float32, 4, 4)); scope = Scope( Dict( #makeVarPair(:out=>WgpuArray{Float32, 16}), #makeVarPair(:x=>WgpuArray{Float32, 16}) ), Dict(), Dict(), 0, nothing, quote end) inferredExpr = inferExpr( scope, :(@wgpukernel launch=true workgroupSize=(4, 4) workgroupCount=(1, 1) $cast_kernel($a, $b)) ) transpile(scope, inferredExpr) # --------- function cast_kernel(x::WgpuArray{T, N}, a::WgpuArray{S, N}) where {T, S, N} xdim = workgroupDims.x ydim = workgroupDims.y gIdx = workgroupId.x*xdim + localId.x gIdy = workgroupId.y*ydim + localId.y gId = xDims.x*gIdy + gIdx for i in 1:19 for j in 1:20 d = 1.0 a[i][j] = 1.0 d += a[i][j] end end end a = WgpuArray(rand(Float32, 4, 4)); b = WgpuArray(rand(Int32, 4, 4)); scope = Scope( Dict( #makeVarPair(:a=>WgpuArray{Float32, 16}), #makeVarPair(:x=>WgpuArray{Float32, 16}) ), Dict(), Dict(), 0, nothing, quote end) inferredExpr = inferExpr( scope, :(@wgpukernel launch=true workgroupSize=(4, 4) workgroupCount=(1, 1) $cast_kernel($a, $b)) ) transpile(scope, inferredExpr) # --------- function cast_kernel(x::WgpuArray{T, N}, a::WgpuArray{S, N}) where {T, S, N} xdim = workgroupDims.x ydim = workgroupDims.y gIdx = workgroupId.x*xdim + localId.x gIdy = workgroupId.y*ydim + localId.y gId = xDims.x*gIdy + gIdx for i in 1:19 for j in 1:20 d = 10 a[i][j] = 1 d = d + 1 end end end a = WgpuArray(rand(Float32, 4, 4)); b = WgpuArray(rand(Float32, 4, 4)); scope = Scope( Dict( #makeVarPair(:a=>WgpuArray{Float32, 16}), #makeVarPair(:x=>WgpuArray{Float32, 16}) ), Dict(), Dict(), 0, nothing, quote end) inferredExpr = inferExpr( scope, :(@wgpukernel launch=true workgroupSize=(4, 4) workgroupCount=(1, 1) $cast_kernel($a, $b)) ) transpile(scope, inferredExpr) # ----------
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
5926
export transpile transpile(scope::Scope, s::Scalar) = s.element transpile(scope::Scope, var::WGPUVariable) = begin (found, location, rootScope) = findVar(scope, var.sym) if location == :typeScope return :($(getDataTypeFrom(rootScope, location, var.sym))) else :($(var.sym)) end end transpile(scope::Scope, var::Ref{WGPUVariable}) = transpile(scope, var[]) transpile(scope::Scope, lhs::LHS) = transpile(scope, lhs.expr) transpile(scope::Scope, rhs::RHS) = transpile(scope, rhs.expr) transpile(scope::Scope, binOp::BinaryOp) = transpile(scope, binOp, Val(binOp.op)) # for each op in [:+, :-, :*, :\, :<, :>, :<=, :>=, :==, :+=, :-=] transpile(scope::Scope, binOp::BinaryOp, op::Val{:+}) = :($(transpile(scope, binOp.left)) + $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:-}) = :($(transpile(scope, binOp.left)) - $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:*}) = :($(transpile(scope, binOp.left)) * $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:/}) = :($(transpile(scope, binOp.left)) / $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:<}) = :($(transpile(scope, binOp.left)) < $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:>}) = :($(transpile(scope, binOp.left)) > $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:(<=)}) = :($(transpile(scope, binOp.left)) <= $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:(>=)}) = :($(transpile(scope, binOp.left)) >= $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:(==)}) = :($(transpile(scope, binOp.left)) == $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:(+=)}) = :($(transpile(scope, binOp.left)) += $(transpile(scope, binOp.right))) transpile(scope::Scope, binOp::BinaryOp, op::Val{:(-=)}) = :($(transpile(scope, binOp.left)) -= $(transpile(scope, binOp.right))) function transpile(scope::Scope, a::AssignmentExpr) lExpr = transpile(scope, a.lhs) rExpr = transpile(scope, a.rhs) rType = typeInfer(scope, a.rhs) if typeof(a.lhs.expr) == DeclExpr #(found, location, rootScope) = findVar(scope, symbol(a.lhs)) #if found && location != :typeScope # lExpr = rootScope.locals[symbol(a.lhs.expr)] # setMutable!(lExpr[], true) # setNew!(lExpr[], false) #end if isMutable(a.lhs) return :(@var $lExpr = $rExpr) else return :(@let $lExpr = $rExpr) end elseif typeof(a.lhs.expr) == Base.RefValue{WGPUVariable} #(found, locations, rootScope) = findVar(scope, symbol(a.lhs)) #if found == false # scope.locals[symbol(a.lhs)] = a.lhs.expr # setNew!(a.lhs.expr[], true) # setMutable!(a.lhs.expr[], false) #elseif found == true # setNew!(a.lhs.expr[], false) # setMutable!(a.lhs.expr[], true) #end ##if a.lhs.expr[].undefined == true # scope.locals[symbol(a.lhs)] = a.lhs.expr #end if isNew(a.lhs) return (isMutable(a.lhs) ? :(@var $lExpr = $rExpr) : :(@let $lExpr = $rExpr)) else return :($lExpr = $rExpr) end elseif typeof(a.lhs.expr) == IndexExpr return :($lExpr = $rExpr) elseif typeof(a.lhs.expr) == AccessExpr return :($lExpr = $rExpr) elseif typeof(a.lhs.expr) <: JLExpr error( "This is not covered yet" ) else error("This shouldn't have been reached. Assignment LHS is $(typeof(a.lhs)) and RHS is $(typeof(a.rhs))") end end function transpile(scope::Scope, cExpr::CallExpr) return Expr(:call, transpile(scope, cExpr.func), map(x -> transpile(scope, x), cExpr.args)...) end function transpile(scope::Scope, idxExpr::IndexExpr) return Expr(:ref, transpile(scope, idxExpr.sym), transpile(scope, idxExpr.idx)) end transpile(scope::Scope, idxExpr::IndexExpr, ::Val{true}) = transpile(scope, idxExpr::IndexExpr) transpile(scope::Scope, idxExpr::IndexExpr, ::Val{false}) = error("This variable cannot be indexed") function transpile(scope::Scope, acsExpr::AccessExpr) return Expr(:., transpile(scope, acsExpr.sym), QuoteNode(transpile(scope, acsExpr.field))) end transpile(scope::Scope, declExpr::DeclExpr) = Expr(:(::), map(x -> transpile(scope, x), (declExpr.sym, declExpr.dataType))... ) transpile(scope::Scope, ::Type{T}) where T = :($T) transpile(scope::Scope, typeExpr::TypeExpr) = Expr( :curly, transpile(scope, typeExpr.sym), map(x -> transpile(scope, x), typeExpr.types)... ) function transpile(scope::Scope, rblock::RangeBlock) (start, step, stop) = map(x -> transpile(rblock.scope, x), (rblock.start, rblock.step, rblock.stop)) range = :($start:$step:$stop) block = map(x -> transpile(rblock.scope, x), rblock.block) idx = transpile(rblock.scope, rblock.idx) return :(@forloop $(Expr(:for, Expr(:(=), idx, range), quote $(block...) end))) end function transpile(scope::Scope, ifblock::IfBlock) c = transpile(ifblock.scope, ifblock.cond) block = map(x -> transpile(scope, x), ifblock.block) return Expr(:if, c, quote $(block...) end) end function transpile(scope::Scope, funcblk::FuncBlock) fn = transpile(funcblk.scope, funcblk.fname) fa = map(x -> transpile(scope, x), funcblk.fargs) fb = map(x -> transpile(scope, x), funcblk.fbody) return Expr(:function, Expr(:call, fn, fa...), quote $(fb...) end) end function transpile(scope::Scope, computeBlk::ComputeBlock) fn = transpile(scope::Scope, computeBlk.fname) fa = map(x -> transpile(scope, x), computeBlk.fargs) fb = map(x -> transpile(scope, x), computeBlk.fbody) ta = map(x -> transpile(scope, x), computeBlk.Targs) workgroupSize = (computeBlk.wgSize .|> Int) code = quote end push!(code.args, map(x -> unblock(x), scope.code.args)...) bargs = computeBlk.builtinArgs fexpr = Expr(:function, Expr(:call, fn, bargs...), quote $(fb...) end) push!( code.args, :(@compute @workgroupSize($(workgroupSize...)) $(fexpr)) ) return code |> MacroTools.striplines end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
121
using AbstractTrees AbstractTrees.children(t::AssignmentExpr) = symbol(t) AbstractTrees.children(t::JLExpr) = symbol(t)
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
946
using CEnum export WGPUVariableAttribute @cenum WGPUVariableType begin Dims Global Local Constant Intrinsic Generic Private Uniform WorkGroup StorageRead StorageReadWrite end struct WGPUVariableAttribute group::Int binding::Int end mutable struct WGPUVariable <: JLVariable sym::Symbol dataType::Union{DataType, Type} varType::WGPUVariableType varAttr::Union{Nothing, WGPUVariableAttribute} mutable::Bool undefined::Bool end symbol(var::WGPUVariable) = var.sym symbol(var::Ref{WGPUVariable}) = var[].sym isMutable(var::WGPUVariable) = var.mutable isMutable(var::Ref{WGPUVariable}) = var[].mutable setMutable!(var::WGPUVariable, b::Bool) = (var.mutable = b) setMutable!(varRef::Ref{WGPUVariable}, b::Bool) = (varRef[].mutable = b) Base.isequal(var1::WGPUVariable, var2::WGPUVariable) = begin r = true for field in fieldnames(WGPUVariable) r |= getproperty(var1, field) == getproperty(var2, field) end return r end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
301
Test.@testset "DeclExpr" begin scope = Scope( Dict( makeVarPair(:b=>Int32), makeVarPair(:c=>Int32), ), Dict(), Dict(), 0, nothing, quote end ) aExpr = inferExpr(scope, :(a::Int32 = b + c)) transpile(scope, aExpr) Test.@test transpile(scope, aExpr) == :(@let a::Int32 = b + c) end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
338
using WGPUTranspiler using WGPUTranspiler: WorkGroupDims, Generic, WGPUVariable using Test makeVarPair(p::Pair{Symbol, DataType}) = p.first => WGPUVariable(p.first, p.second, Generic, nothing, false, false) @testset "WGPUTranspiler.jl" begin include("variableTests.jl") # include("declTests.jl") # include("assignmentTests.jl") end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
code
1446
using Revise using WGPUTranspiler using WGPUTranspiler: WGPUVariable, WorkGroupDims, Generic using Test makeVarPair(p::Pair{Symbol, DataType}; islocal=false) = begin if !islocal return (p.first => WGPUVariable( p.first, # sym p.second, # dataType Generic, # varType nothing, # varAttr false, # mutable false, # new true # undefined )) else return (p.first => Ref{WGPUVariable}(WGPUVariable( p.first, # sym p.second, # dataType Generic, # varType nothing, # varAttr false, # mutable false, # new true # undefined ))) end end @testset "WGPUVariable Test" begin scope = Scope( Dict{Symbol, Ref{WGPUVariable}}( makeVarPair(:b => Int32), makeVarPair(:c => Int32) ), Dict(), Dict(), 0, nothing, quote end ) scopeCopy = deepcopy(scope) aExpr = inferExpr(scope, :(b)) @test scope.globals == Dict() @test Base.isequal(scope, scopeCopy) #@test (aExpr[]).dataType == Int32 @test isequal(aExpr, scope.locals[:b]) end @testset "WGPUVariable Test" begin scope = Scope( Dict{Symbol, Ref{WGPUVariable}}( makeVarPair(:b => Int32), makeVarPair(:c => Int32) ), Dict(), Dict(), 0, nothing, quote end ) scopeCopy = deepcopy(scope) aExpr = inferExpr(scope, :(a)) @test aExpr[].undefined == true @test !(scope.globals == Dict()) @test !Base.isequal(scope, scopeCopy) @test (aExpr[]).dataType == Any @test isequal(aExpr, scope.locals[:a]) end
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.1.0
0e69c1da2e982dbe92bac774171914cf860a02ae
docs
48
# WGPUTranspiler Transpiles Julia Code to WGSL
WGPUTranspiler
https://github.com/JuliaWGPU/WGPUTranspiler.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
809
using Documenter, WeaklyHard DocMeta.setdocmeta!(WeaklyHard, :DocTestSetup, :(using WeaklyHard); recursive=true) makedocs(modules=[WeaklyHard], authors="NilsVreman <[email protected]> and contributors", repo="https://github.com/NilsVreman/WeaklyHard.jl/blob/{commit}{path}#{line}", sitename="WeaklyHard.jl", format=Documenter.HTML( canonical="https://NilsVreman.github.io/WeaklyHard.jl", assets=String[] ), pages=[ "Home" => "index.md", "Examples" => "man/examples.md", "Functions" => "man/functions.md", "Index" => "man/summary.md" ]) deploydocs(repo = "github.com/NilsVreman/WeaklyHard.jl.git")
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
517
using WeaklyHard """ Example for generating automata for (sets of) weakly-hard constraints """ # Constraints lambda1 = AnyHitConstraint(12, 15) lambda2 = RowHitConstraint(15, 47) lambda3 = RowMissConstraint(3) lambda4 = AnyMissConstraint(2, 3) lambda5 = RowHitConstraint(2, 6) # Generate automata G1 = build_automaton(lambda1) G2 = build_automaton(lambda2) G3 = build_automaton(lambda3) # set construction Lambda_star = dominant_set(Set([lambda4, lambda5])) G = build_automaton(Lambda_star) minimize_automaton!(G)
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
763
using WeaklyHard """ Example for comparing dominance and equivalence of WeaklyHard constraints """ # Constraints to test lambda1 = AnyHitConstraint(48, 54) lambda2 = AnyMissConstraint(12, 67) lambda3 = AnyHitConstraint(12, 15) lambda4 = RowMissConstraint(9) lambda5 = RowHitConstraint(20, 47) lambda6 = RowHitConstraint(5, 12) lambda7 = RowMissConstraint(3) lambdas = [lambda1, lambda2, lambda3, lambda4, lambda5, lambda6, lambda7] # Compare individual constraints for l1 in lambdas for l2 in lambdas if is_equivalent(l1, l2) println("$l1 \t===\t $l2") elseif is_dominant(l1, l2) println("$l1 \t<=\t $l2") else println("$l1 \t</=\t $l2") end # if end # for println(" ") end # for
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
960
using WeaklyHard """ Example for generating satisfaction sets for weakly-hard constraints """ # Constraints lambda1 = AnyHitConstraint(12, 15) lambda2 = RowHitConstraint(15, 47) lambda3 = RowMissConstraint(3) # Generate automata G1 = build_automaton(lambda1) G2 = build_automaton(lambda2) G3 = build_automaton(lambda3) # Generate satisfaction set of length N N = 20 S1 = all_sequences(G1, N) S2 = all_sequences(G2, N) S3 = all_sequences(G3, N) # check that all sequences satisfy the constraint for w in S1 if !is_satisfied(lambda1, w) println("Sequence ($(bitstring(w)[end-N+1:end])) does not satisfy $lambda1") end # if end # for for w in S2 if !is_satisfied(lambda2, w) println("Sequence ($(bitstring(w)[end-N+1:end])) does not satisfy $lambda2") end # if end # for for w in S3 if !is_satisfied(lambda3, w) println("Sequence ($(bitstring(w)[end-N+1:end])) does not satisfy $lambda3") end # if end # for
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
1079
module WeaklyHard #= Uses for all includes etc =# using LinearAlgebra #= Types and constructors =# include("types.jl") #= Includes =# include("alphabet.jl") # Defines the functions on the Words and Characters include("constraints.jl") # Defines constraints, dominance relations, equivalences, and satisfaction functions include("dominant_set.jl") # Defines functions to generate the dominant subset of a constraint set. include("datastructures.jl") # Defines the datastructures necessary to improve execution time of the automaton construction. include("automaton_single.jl") # Defines the automata generation functions for single constraints include("automaton_set.jl") # Defines the automata generation functions for sets of constraints include("automaton_util.jl") # Defines the utility functions applied to the automaton include("sequences.jl") # Defines functions that generate sequences of a specific automata construction. include("printing.jl") # Defines the printing statements for the existing structs end # module
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
1510
########################### ### Auxiliary Functions ### ########################### #= Create a word with n consecutive set bits as least significant. =# consword(n::T) where {T <: Integer} = (T(1) << n) - T(1) #= Counts the number of bits in the integer w =# nbits(w::T) where {T <: Integer} = 8*sizeof(T) - leading_zeros(w) nbits(w::BigInt) = (w == 0) ? Int64(0) : ndigits(w, base=2) #= Counting the number of set bits in the integer w =# nsetbits(w::T) where {T <: Integer} = count_ones(w) #= Counting the maximum number of consecutive set bits in an integer w =# function nconsbits(w::T) where {T <: Integer} n = 0 while w != Miss w &= (w << T(1)) n += 1 end # while n end # function ################# ### Functions ### ################# #= Left shifts bits once and adds new bit as LSB (according to character c). Removes the MSB if character is a Hit. =# function shift(w::T, c) where {T <: Integer} if c == Miss return w << T(1) else return ((w << T(1)) | T(1)) & consword(T(nbits(w))) end end #= Left shifts bits once and adds new bit as LSB (according to character c). Returns the word n if the bits in nw coincide with the ones in n. =# function shift_rowhit(w::T, c, n::T) where {T <: Integer} #= Shift bits according to charcter c and default to n if last few char are equal to n =# if c == Miss w <<= T(1) else w = (w << T(1)) | T(1) end return (w & n == n) ? n : w end
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
8166
# Exports export build_automaton function build_automaton(Lambda::Set{T}) where {T <: Constraint} # Find constraint with maximum K value lambda_max_k = reduce(Lambda) do x, y x.k > y.k ? x : y end # Extract necessary parameters k = lambda_max_k.k n = _get_nbr_cons_hits(Lambda) # Decide IntType IntType = _word_type(Lambda, k) # IF we are not allowed to miss a single deadline, return a one vertex automaton if !is_satisfied(Lambda, consword(IntType(k)) << IntType(1)) # Initialise Automaton initvertex = WordVertex{Int8}(Int8(Hit)) automaton = Automaton{Int8}(initvertex) initvertex.hit = initvertex automaton[Int8(Hit)] = initvertex return automaton # ELSE IF we are allowed to miss infinite number of misses, return another one vertex automaton elseif _allmissespermitted(Lambda) # Initialise Automaton initvertex = WordVertex{Int8}(Int8(Hit)) automaton = Automaton{Int8}(initvertex) initvertex.hit = initvertex initvertex.miss = initvertex automaton[Int8(Hit)] = initvertex return automaton # ELSE add next vertex to transitions and continue else # Initialise automaton initvertex = WordVertex{IntType}(consword(IntType(n))) automaton = Automaton{IntType}(initvertex) for lambda in Lambda if typeof(lambda) == RowHitConstraint # create a curried function in order to be able to call the same function for both rowhit and all other constraints return _build_automaton_set!(Lambda, automaton, initvertex, (x1, x2, x3, x4) -> _initiate_vertex_rh_set!(x1, x2, x3, x4, initvertex.w, k)) end # if end # function # Since we know something about the approximate size of the graph, # improve performance by setting the size to that automatically. sizehint!(automaton.data, binomial(k, n)) return _build_automaton_set!(Lambda, automaton, initvertex, _initiate_vertex_set!) end end # function ########################### ### Auxiliary Functions ### ########################### #= Initiate vertex by first shifting vertex to acquire children. # Then extend automaton with children (if constraint set satisfied) =# function _initiate_vertex_set!(Lambda::Set{T}, automaton::Automaton{S}, list::_UninitializedList{S}, vertex::WordVertex{S}) where {T <: Constraint, S <: Integer} (wm, wh) = _children_set(vertex) _extend_automaton_set!(Lambda, automaton, list, vertex, wm, wh) end function _initiate_vertex_rh_set!(Lambda::Set{T}, automaton::Automaton{S}, list::_UninitializedList{S}, vertex::WordVertex{S}, wi::S, k::R) where {T <: Constraint, S <: Integer, R <: Integer} (wm, wh) = _children_rh_set(vertex, wi) _extend_automaton_rh_set!(Lambda, automaton, list, vertex, wm, wh, k) end #= Return the children of vertex, disregarding satisfiability =# function _children_set(vertex::WordVertex{T}) where {T <: Integer} wm = shift(vertex.w, Miss) wh = shift(vertex.w, Hit) return (wm, wh) end function _children_rh_set(vertex::WordVertex{T}, n::T) where {T <: Integer} wm = shift_rowhit(vertex.w, Miss, n) wh = shift_rowhit(vertex.w, Hit, n) return (wm, wh) end #= Extend automaton with the children (nm, nh) if they satisfy Lambda =# function _extend_automaton_set!(Lambda::Set{T}, automaton::Automaton{S}, list::_UninitializedList{S}, vertex::WordVertex{S}, wm::S, wh::S) where {T <: Constraint, S <: Integer} vertexM = nothing vertexH = nothing # Check if miss word satisfies constraints and whether it is initialized if is_satisfied(Lambda, wm) if !haskey(automaton, wm) vertexM = WordVertex{S}(wm) automaton[wm] = vertexM _push!(list, vertexM) else vertexM = automaton[wm] end # Add miss path to vertex vertex.miss = vertexM end # check if hit word is initialised if !haskey(automaton, wh) vertexH = WordVertex{S}(wh) automaton[wh] = vertexH _push!(list, vertexH) else vertexH = automaton[wh] end # Add hit path to vertex vertex.hit = vertexH end #= Extend automaton with the children (nm, nh) if they satisfy Lambda =# function _extend_automaton_rh_set!(Lambda::Set{T}, automaton::Automaton{S}, list::_UninitializedList{S}, vertex::WordVertex{S}, wm::S, wh::S, k::R) where {T <: Constraint, S <: Integer, R <: Integer} vertexH = nothing vertexM = nothing # Check if miss word satisfies constraints and whether it is initialized if is_satisfied(Lambda, wm) wm &= consword(S(k)) # Extracting bits to reduce size of graph if !haskey(automaton, wm) vertexM = WordVertex{S}(wm) automaton[wm] = vertexM _push!(list, vertexM) else vertexM = automaton[wm] end # Add miss path to vertex vertex.miss = vertexM end # check if hit word is initialised wh &= consword(S(k)) # Extracting bits to reduce size of graph if !haskey(automaton, wh) vertexH = WordVertex{S}(wh) automaton[wh] = vertexH _push!(list, vertexH) else vertexH = automaton[wh] end # Add hit path to vertex vertex.hit = vertexH end #= Aux function to build automaton =# function _build_automaton_set!(Lambda::Set{T}, automaton::Automaton{S}, initvertex::WordVertex{S}, f_initiate_vertex!) where {T <: Constraint, S <: Integer} # First vertex initialisation list = _UninitializedList{S}() _push!(list, initvertex) automaton[initvertex.w] = initvertex # Add the remaining vertices to the while loop while !isnothing(list.head) # while we have elements to iterate # Extract first element to iterate vertex = _pop!(list) # Add new feasible vertices to structures and lists f_initiate_vertex!(Lambda, automaton, list, vertex) end #while return automaton end # function @doc """ build_automaton(Lambda::T) where {T <: Union{Constraint, Set{Constraint}}} Creates a minimal weakly-hard automaton according to the (set of) weakly-hard constraint(s) `Lambda`. NOTE: The function handles both single constraints and sets of constraints. ## Examples ```jldoctest julia> build_automaton(AnyHitConstraint(1, 3)) Automaton{Int64} with 3 vertices: { WordVertex{Int64}(100 => ---, 001) WordVertex{Int64}(010 => 100, 001) WordVertex{Int64}(001 => 010, 001) } with head: WordVertex{Int64}(1 => 10, 1) julia> build_automaton(Set([AnyHitConstraint(1, 3), RowHitConstraint(2, 6)])) Automaton{Int64} with 7 vertices: { WordVertex{Int64}(001101 => 011010, 000011) WordVertex{Int64}(000110 => 001100, 001101) WordVertex{Int64}(011001 => ------, 000011) WordVertex{Int64}(011010 => ------, 110101) WordVertex{Int64}(001100 => ------, 011001) WordVertex{Int64}(000011 => 000110, 000011) WordVertex{Int64}(110101 => ------, 000011) } with head: WordVertex{Int64}(11 => 110, 11) ``` """ build_automaton
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
10031
# Exports export build_automaton function build_automaton(lambda::T) where {T <: Constraint} # Find constraint with maximum K value # Extract necessary parameters k = lambda.k n = _get_nbr_cons_hits(lambda) # Decide IntType IntType = _word_type(lambda, k) # IF we are not allowed to miss a single deadline, return a one vertex automaton if !is_satisfied(lambda, consword(IntType(k)) << IntType(1)) # Initialise Automaton initvertex = WordVertex{Int8}(Int8(Hit)) automaton = Automaton{Int8}(initvertex) initvertex.hit = initvertex automaton[Int8(Hit)] = initvertex return automaton # ELSE IF we are allowed to miss infinite number of misses, return another one vertex automaton elseif _allmissespermitted(lambda) # Initialise Automaton initvertex = WordVertex{Int8}(Int8(Hit)) automaton = Automaton{Int8}(initvertex) initvertex.hit = initvertex initvertex.miss = initvertex automaton[Int8(Hit)] = initvertex return automaton # ELSE add next vertex to transitions and continue else # Initialise automaton initvertex = WordVertex{IntType}(consword(IntType(n))) automaton = Automaton{IntType}(initvertex) sizehint!(automaton.data, _minimal_size(lambda)) # If we have a rowhit constraint, change building method if typeof(lambda) == RowHitConstraint z = _get_nbr_cons_misses(lambda) return _build_automaton_rh!(lambda, automaton, initvertex, IntType(z), IntType(n), IntType(k)) end # if # Else return _build_automaton!(lambda, automaton, initvertex) end end # function ################################## ### Auxiliary Functions for RH ### ################################## function _initiate_vertex_rh!(lambda::T, automaton::Automaton{S}, list::_UninitializedList{S}, miss_list::Vector{WordVertex{S}}, vertex::WordVertex{S}, initword::S, k::S) where {T <: Constraint, S <: Integer} (wm, wh) = _children_rh(vertex, initword) _extend_automaton_rh!(lambda, automaton, list, miss_list, vertex, wm, wh, k) end # function #= Extend automaton with the children (nm, nh) if they satisfy lambda =# function _extend_automaton_rh!(lambda::T, automaton::Automaton{S}, list::_UninitializedList{S}, miss_list::Vector{WordVertex{S}}, vertex::WordVertex{S}, wm::S, wh::S, k::S) where {T <: Constraint, S <: Integer} vertexH = nothing # Check if miss word satisfies constraints and whether it is initialized if is_satisfied(lambda, wm) vertex.miss = miss_list[_nbr_misses_permitted(lambda, vertex.w, k)] end # Check how many consecutive misses we are permitted, # If it is more than 0: add to the automata (unless already present) if _nbr_misses_permitted(lambda, wh, k) > 0 # check if hit word is initialised if !haskey(automaton, wh) vertexH = WordVertex{S}(wh) automaton[wh] = vertexH _push!(list, vertexH) else vertexH = automaton[wh] end else vertexH = automaton[consword(S(trailing_ones(wh)))] end # Add hit path to vertex vertex.hit = vertexH end #= Return the children of vertex, disregarding satisfiability =# function _children_rh(vertex::WordVertex{T}, initword::T) where {T <: Integer} wm = shift_rowhit(vertex.w, Miss, initword) wh = shift_rowhit(vertex.w, Hit, initword) return (wm, wh) end # Returns how many consecutive misses we permit following w function _nbr_misses_permitted(lambda::T, w::S, k::S) where {T <: Constraint, S <: Integer} for z in S(1):k if !is_satisfied(lambda, (w << (z+S(1))) | S(1)) return z-S(1) end end return k end # function #= Add first nodes to the automaton by adding the maximum consecutive miss path to it. =# function _add_miss_path_rh!(lambda::T, automaton::Automaton{S}, list::_UninitializedList{S}, vertex::WordVertex{S}, z::S, n::S, k::S) where {T <: Constraint, S <: Integer} # Add "hit path" to automaton v = vertex for n_ in n-S(1):S(-1):S(1) w = consword(n_) v_prior = WordVertex{S}(w) v_prior.hit = v automaton[w] = v_prior v = v_prior end # for # A list where each index "i" corresponds to the vertex with "i" more deadlines tolerated aux_list = Vector{WordVertex{S}}(undef, z+1) # Add "miss path" to automaton v = vertex vertexM = nothing for z_ in z+S(1):S(-1):S(1) aux_list[z_] = v (wm, wh) = _children_rh(v, consword(n)) # Check if miss word satisfies constraints and whether it is initialized if is_satisfied(lambda, wm) vertexM = WordVertex{S}(wm) automaton[wm] = vertexM # Add miss path to vertex v.miss = vertexM end # check if hit word is initialised if _nbr_misses_permitted(lambda, wh, k) > 0 if !haskey(automaton, wh) vertexH = WordVertex{S}(wh) automaton[wh] = vertexH _push!(list, vertexH) else vertexH = automaton[wh] end else vertexH = automaton[consword(S(trailing_ones(wh)))] end # Add hit path to vertex v.hit = vertexH v = vertexM end # for return aux_list end # function #= Build the automaton =# function _build_automaton_rh!(lambda::T, automaton::Automaton{S}, initvertex::WordVertex{S}, z::S, n::S, k::S) where {T <: Constraint, S <: Integer} # First initialize the necessary miss path in the graph list = _UninitializedList{S}() automaton[initvertex.w] = initvertex miss_list = _add_miss_path_rh!(lambda, automaton, list, initvertex, z, n, k) # Add the remaining vertices to the while loop while !isnothing(list.head) # while we have elements to iterate # Extract first element to iterate vertex = _pop!(list) # Add new feasible vertices to structures and lists _initiate_vertex_rh!(lambda, automaton, list, miss_list, vertex, consword(n), k) end #while return automaton end # function ########################################## ### Auxiliary Functions for RM, AM, AH ### ########################################## function _initiate_vertex!(lambda::T, automaton::Automaton{S}, list::_UninitializedList{S}, vertex::WordVertex{S}) where {T <: Constraint, S <: Integer} (wm, wh) = _children(vertex) _extend_automaton!(lambda, automaton, list, vertex, wm, wh) end # function #= Extend automaton with the children (nm, nh) if they satisfy lambda =# function _extend_automaton!(lambda::T, automaton::Automaton{S}, list::_UninitializedList{S}, vertex::WordVertex{S}, wm::S, wh::S) where {T <: Constraint, S <: Integer} vertexM = nothing vertexH = nothing # Check if miss word satisfies constraints and whether it is initialized if is_satisfied(lambda, wm) if !haskey(automaton, wm) vertexM = WordVertex{S}(wm) automaton[wm] = vertexM _push!(list, vertexM) else vertexM = automaton[wm] end # Add miss path to vertex vertex.miss = vertexM end # check if hit word is initialised if !haskey(automaton, wh) vertexH = WordVertex{S}(wh) automaton[wh] = vertexH _push!(list, vertexH) else vertexH = automaton[wh] end # Add hit path to vertex vertex.hit = vertexH end #= Return the children of vertex, disregarding satisfiability =# function _children(vertex::WordVertex{T}) where {T <: Integer} wm = shift(vertex.w, Miss) wh = shift(vertex.w, Hit) return (wm, wh) end #= Building the automaton =# function _build_automaton!(lambda::T, automaton::Automaton{S}, initvertex::WordVertex{S}) where {T <: Constraint, S <: Integer} # First initialize the necessary miss path in the graph list = _UninitializedList{S}() automaton[initvertex.w] = initvertex _push!(list, initvertex) # Add the remaining vertices to the while loop while !isnothing(list.head) # while we have elements to iterate # Extract first element to iterate vertex = _pop!(list) # Add new feasible vertices to structures and lists _initiate_vertex!(lambda, automaton, list, vertex) end #while return automaton end # function
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
4987
export vertices, transitions, minimize_automaton! ################# ### Overloads ### ################# #= WordVertex - Returns whether the child s exists for n =# _childexists(n::WordVertex{T}, s::Symbol) where {T <: Integer} = !isnothing(getfield(n, s)) #= Automaton - Overloads of Base functions =# Base.getindex(g::Automaton{T}, w::T) where {T <: Integer} = g.data[w] Base.setindex!(g::Automaton{T}, v::WordVertex{T}, w::T) where {T <: Integer} = (g.data[w] = v) Base.length(g::Automaton{T}) where {T <: Integer} = length(g.data) Base.haskey(g::Automaton{T}, w::T) where {T <: Integer} = haskey(g.data, w) ###################### ### Util Functions ### ###################### """ vertices(automaton::Automaton) Returns all the vertices in `automaton`. """ function vertices(automaton::Automaton{T}) where {T <: Integer} return values(automaton.data) end # function """ transitions(automaton::Automaton) Returns all the transitions in `automaton` in the form of a set of pairs where each pair consists of `(v1, v2, c12)`, i.e., the tail of the transition `v1`, the head of the transition `v2`, and the label of the transition `c12`. """ function transitions(automaton::Automaton{T}) where {T <: Integer} trans = Set{Tuple{T, T, UInt8}}(); sizehint!(trans, 2*length(vertices(automaton))) for vertex in vertices(automaton) push!(trans, (vertex.w, vertex.hit.w, Hit)) if _childexists(vertex, :miss) push!(trans, (vertex.w, vertex.miss.w, Miss)) end # if end # for return trans end # function function _vertices_equivalent(v1::WordVertex{T}, v2::WordVertex{T}) where {T <: Integer} if v1 === v2 # If they are the same vertex return false end if _childexists(v1, :miss) && _childexists(v2, :miss) return v1.miss.w == v2.miss.w && v1.hit.w == v2.hit.w elseif !_childexists(v1, :miss) && !_childexists(v2, :miss) return v1.hit.w == v2.hit.w else return false end #if end # function """ minimize_automaton!(automaton::Automaton) Minimises the automaton representation of a set of weakly-hard constraints. """ function minimize_automaton!(automaton::Automaton{T}) where {T <: Integer} changed = true while changed changed = false for v1 in vertices(automaton) v1_identical = Vector{WordVertex{T}}() for v2 in vertices(automaton) if _vertices_equivalent(v1, v2) changed = true push!(v1_identical, v2) end end # for if !isempty(v1_identical) push!(v1_identical, v1) # find shortest word to replace v1_identical with v1_new = reduce(v1_identical) do x, y (x.w < y.w) ? x : y end for v3 in vertices(automaton) if v3 in v1_identical && !(v3 === v1_new) delete!(automaton.data, v3.w) else if _childexists(v3, :miss) && v3.miss in v1_identical v3.miss = v1_new end if v3.hit in v1_identical v3.hit = v1_new end end # if end # for end # if end # for end # while return automaton end # function ########################### ### Auxiliary Functions ### ########################### #= Find minimal sized Integer to use for automaton construction =# function _word_type(Lambda::Set{T}, k::S) where {T <: Constraint, S <: Integer} n = 0 for lambda in Lambda if typeof(lambda) == RowHitConstraint && lambda.x > n n = lambda.x end # if end # for if k + 2*n < 64 - 2 return Int64 else return BigInt end # if end # function _word_type(lambda::T, k::S) where {T <: Constraint, S <: Integer} = _word_type(Set{T}([lambda]), k) #= Find minimal size of automaton (specifically used by sizehint for the dictionary in the automaton) =# _minimal_size(lambda::AnyHitConstraint) = binomial(lambda.k, lambda.x) _minimal_size(lambda::AnyMissConstraint) = binomial(lambda.k, lambda.k - lambda.x) _minimal_size(lambda::RowMissConstraint) = lambda.x + 1 function _minimal_size(lambda::RowHitConstraint) if lambda.x > lambda.k return 0 elseif lambda.k < 2*lambda.x return 1 elseif lambda.k == 2*lambda.x return lambda.x + 1 elseif lambda.k == 2*lambda.x + 1 return lambda.x + 2 elseif lambda.k < 3*lambda.x return 2*_minimal_size(RowHitConstraint(lambda.x, lambda.k - 1)) - _minimal_size(RowHitConstraint(lambda.x, lambda.k - 2)) + 1 else return _minimal_size(RowHitConstraint(lambda.x, lambda.k - 1)) + lambda.x end # if end # function
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
13007
export is_dominant, is_equivalent, is_satisfied ################# ### Overloads ### ################# #= Override get function for structs of type Constraint =# function Base.getproperty(c::Constraint, s::Symbol) if s === :x || s === :k return getproperty(c.data, s) end # if getfield(c, s) end # function ##################### ### Aux Functions ### ##################### #= get the number of hits necessary in a window according to lambda =# _get_nbr_cons_hits(lambda::RowHitConstraint) = lambda.x _get_nbr_cons_hits(lambda::RowMissConstraint) = lambda.k - lambda.x _get_nbr_cons_hits(lambda::AnyHitConstraint) = lambda.x _get_nbr_cons_hits(lambda::AnyMissConstraint) = lambda.k - lambda.x function _get_nbr_cons_hits(Lambda::Set{T}) where {T <: Constraint} lambda_max_n = reduce(Lambda) do x, y (_get_nbr_cons_hits(x) > _get_nbr_cons_hits(y)) ? x : y end return _get_nbr_cons_hits(lambda_max_n) end # function #= get the maximum number of consecutive misses permissed a window according to Lambda =# _get_nbr_cons_misses(lambda::RowHitConstraint) = (lambda.k >= 2*lambda.x) ? lambda.k - 2*lambda.x + 1 : 0 _get_nbr_cons_misses(lambda::RowMissConstraint) = lambda.x _get_nbr_cons_misses(lambda::AnyHitConstraint) = lambda.k - lambda.x _get_nbr_cons_misses(lambda::AnyMissConstraint) = lambda.x function _get_nbr_cons_misses(Lambda::Set{T}) where {T <: Constraint} lambda_min_z = reduce(Lambda) do x, y (_get_nbr_cons_misses(x) < _get_nbr_cons_misses(y)) ? x : y end return _get_nbr_cons_misses(lambda_min_z) end # function #= Returns true if a sequence of all misses is permitted =# _allmissespermitted(lambda::RowHitConstraint) = lambda.x == 0 _allmissespermitted(lambda::RowMissConstraint) = lambda.x == lambda.k _allmissespermitted(lambda::AnyHitConstraint) = lambda.x == 0 _allmissespermitted(lambda::AnyMissConstraint) = lambda.x == lambda.k function _allmissespermitted(Lambda::Set{T}) where {T <: Constraint} for lambda in Lambda if !_allmissespermitted(lambda) return false end # if end # for return true end # function #= Extends word w with (k-n) set bits from position n to position k (counting from right to left) =# _extendword(w::T, n, k) where {T <: Integer} = (consword(T(k-n)) << T(n)) | w ############################## ### Satisfaction Functions ### ############################## #= Returns whether the word/integer w satisfies the RowHitConstraint lambda =# function is_satisfied(lambda::RowHitConstraint, w::T) where {T <: Integer} # Check if all misses is permitted if w == 0 return _allmissespermitted(lambda) end # Append hits at beginning and end of sequence w cons_w = consword(T(lambda.x)) w = (((cons_w << nbits(w)) | T(w)) << T(lambda.x)) | cons_w n = nbits(w) cmp_w = consword(T(lambda.k)) # Add hits to beginning of word if word is shorter than window if n < lambda.k w = _extendword(w, n, lambda.k) n = lambda.k end # Iterate sequence w to check if constraint is satisfied while n >= lambda.k if nconsbits(w & cmp_w) < lambda.x return false end # if w >>= T(1) n -= T(1) end # for return true end # function #= Returns whether the word/integer w satisfies the RowMissConstraint lambda =# function is_satisfied(lambda::RowMissConstraint, w::T) where {T <: Integer} # Check if all misses is permitted if w == 0 return _allmissespermitted(lambda) end # Add hits to beginning of word if word is shorter than window n = nbits(w) if n < lambda.k w = _extendword(w, n, lambda.k) n = lambda.k end # Iterate sequence w to check if constraint is satisfied cons_w = consword(T(lambda.x + 1)) while n >= lambda.k if (w & cons_w) == 0 # all misses return false end # if w >>= T(1) n -= T(1) end # for return true end # function #= Returns whether the word/integer w satisfies the AnyHitConstraint lambda =# function is_satisfied(lambda::AnyHitConstraint, w::T) where {T <: Integer} # Check if all misses is permitted if w == 0 return _allmissespermitted(lambda) end # Add hits to beginning of word if word is shorter than window n = nbits(w) if n < lambda.k w = _extendword(w, n, lambda.k) n = lambda.k end # Iterate sequence w to check if constraint is satisfied cons_w = consword(T(lambda.k)) while n >= lambda.k if nsetbits(w & cons_w) < lambda.x return false end # if w >>= T(1) n -= T(1) end # for return true end # function #= Returns whether the word/integer w satisfies the AnyMissConstraint lambda =# function is_satisfied(lambda::AnyMissConstraint, w::T) where {T <: Integer} # Check if all misses is permitted if w == 0 return _allmissespermitted(lambda) end # Add hits to beginning of word if word is shorter than window n = nbits(w) if n < lambda.k w = _extendword(w, n, lambda.k) n = lambda.k end # Iterate sequence w to check if constraint is satisfied cons_w = consword(T(lambda.k)) while n >= lambda.k if nsetbits(w & cons_w) < lambda.k - lambda.x return false end # if w >>= T(1) n -= T(1) end # for return true end # function #= Returns whether the word/integer w satisfies the Constraint Set Lambda =# function is_satisfied(Lambda::Set{T}, w::S) where {T <: Constraint, S <: Integer} for lambda in Lambda if !is_satisfied(lambda, w) return false end # if end # for return true end # function #################################### ### Domination Multiple Dispatch ### #################################### function is_dominant(lambda1::AnyMissConstraint, lambda2::AnyMissConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = AnyMiss, lambda2 = AnyMiss return is_dominant(AnyHitConstraint(lambda1.k-lambda1.x, lambda1.k), AnyHitConstraint(lambda2.k-lambda2.x, lambda2.k)) end # function function is_dominant(lambda1::AnyMissConstraint, lambda2::AnyHitConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = AnyMiss, lambda2 = AnyHit return is_dominant(AnyHitConstraint(lambda1.k-lambda1.x, lambda1.k), lambda2) end # function function is_dominant(lambda1::AnyMissConstraint, lambda2::RowMissConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = AnyMiss, lambda2 = RowMiss return is_dominant(AnyHitConstraint(lambda1.k-lambda1.x, lambda1.k), AnyHitConstraint(1, lambda2.k)) end # function function is_dominant(lambda1::AnyMissConstraint, lambda2::RowHitConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = AnyMiss, lambda2 = RowHit return is_dominant(AnyHitConstraint(lambda1.k-lambda1.x, lambda1.k), lambda2) end # function function is_dominant(lambda1::AnyHitConstraint, lambda2::AnyMissConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = AnyHit, lambda2 = AnyMiss return is_dominant(lambda1, AnyHitConstraint(lambda2.k-lambda2.x, lambda2.k)) end # function function is_dominant(lambda1::AnyHitConstraint, lambda2::AnyHitConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = AnyHit, lambda2 = AnyHit # Variable extraction x1, k1 = lambda1.x, lambda1.k x2, k2 = lambda2.x, lambda2.k # Checking the trivial case if x1 == k1 return true elseif x2 == k2 return false end # Domination condition return x2 <= max(floor(Int64, k2 / k1) * x1, k2 + ceil(Int64, k2 / k1) * (x1 - k1)) end # function function is_dominant(lambda1::AnyHitConstraint, lambda2::RowMissConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = AnyHit, lambda2 = RowMiss return is_dominant(lambda1, AnyHitConstraint(1, lambda2.k)) end # function function is_dominant(lambda1::AnyHitConstraint, lambda2::RowHitConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = AnyHit, lambda2 = RowHit # Variable extraction x1, k1 = lambda1.x, lambda1.k x2, k2 = lambda2.x, lambda2.k z1 = k1-x1 # Checking trivial case if x1 == k1 return true elseif 2*x2 > k2 return false elseif x2 == 0 return true elseif x1 == 0 return false end # Domination condition return x2 <= min(floor(Int64, k2/(z1+1)), ceil(Int64, x1/z1)) end # function function is_dominant(lambda1::RowMissConstraint, lambda2::AnyMissConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = RowMiss, lambda2 = AnyMiss return is_dominant(AnyHitConstraint(1, lambda1.k), AnyHitConstraint(lambda2.k-lambda2.x, lambda2.k)) end # function function is_dominant(lambda1::RowMissConstraint, lambda2::AnyHitConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = RowMiss, lambda2 = AnyHit return is_dominant(AnyHitConstraint(1, lambda1.k), lambda2) end # function function is_dominant(lambda1::RowMissConstraint, lambda2::RowMissConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = RowMiss, lambda2 = RowMiss return is_dominant(AnyHitConstraint(1, lambda1.k), AnyHitConstraint(1, lambda2.k)) end # function function is_dominant(lambda1::RowMissConstraint, lambda2::RowHitConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = RowMiss, lambda2 = RowHit return is_dominant(AnyHitConstraint(1, lambda1.k), lambda2) end # function function is_dominant(lambda1::RowHitConstraint, lambda2::AnyMissConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = RowHit, lambda2 = AnyMiss return is_dominant(lambda1, AnyHitConstraint(lambda2.k-lambda2.x, lambda2.k)) end # function function is_dominant(lambda1::RowHitConstraint, lambda2::AnyHitConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = RowHit, lambda2 = AnyHit # Variable Extraction x1, k1 = lambda1.x, lambda1.k x2, k2 = lambda2.x, lambda2.k z1 = k1-2*x1+1 # Checking trivial case if 2*x1 > k1 return true elseif x2 == k2 return false elseif x2 == 0 return true elseif x1 == 0 return false end # Domination condition return x2 <= max(x1*floor(Int64, k2/(z1+x1)), k2 - floor(Int64, k2/(z1+x1))*z1 - z1) end # function function is_dominant(lambda1::RowHitConstraint, lambda2::RowMissConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = RowHit, lambda2 = RowMiss return is_dominant(lambda1, AnyHitConstraint(1, lambda2.k)) end # function function is_dominant(lambda1::RowHitConstraint, lambda2::RowHitConstraint) # Returns if lambda1 dominates lambda2: lambda1 <= lambda2 # lambda1 = RowHit, lambda2 = RowHit # Variable extraction x1, k1 = lambda1.x, lambda1.k x2, k2 = lambda2.x, lambda2.k # Checking trivial case if 2*x1 > k1 return true elseif 2*x2 > k2 return false elseif x2 == 0 return true elseif x1 == 0 return false end # Domination condition return (k2 < k1 && x2 <= x1 - ceil(Int64, (k1-k2)/2 )) || (k2 >= k1 && x2 <= x1) end # function ### Equivalence function function is_equivalent(lambda1::Constraint, lambda2::Constraint) # Returns if lambda1 is equivalent to lambda2: lambda1 === lambda2 return is_dominant(lambda1, lambda2) && is_dominant(lambda2, lambda1) end # function ################## ### Docstrings ### ################## @doc """ is_satisfied(L, w) Returns whether the word `w` satisfies the constraint `L` or not; here, `L` can be either a single constraint or a constraint set. # Examples ```jldoctest julia> is_satisfied(AnyHitConstraint(1, 3), 595) # bitstring(595) = ...1001010011 true julia> is_satisfied(AnyHitConstraint(1, 3), 600) # bitstring(600) = ...1001011000 false ``` """ is_satisfied @doc """ is_dominant(l1, l2) Returns whether the weakly-hard constraint `l1` dominates `l2` or not. # Examples ```jldoctest julia> is_dominant(AnyHitConstraint(1, 3), RowMissConstraint(1)) false julia> is_dominant(AnyHitConstraint(1, 3), RowMissConstraint(2)) true ``` """ is_dominant @doc """ is_equivalent(l1, l2) Returns whether the weakly-hard constraint `l1` is equivalent to `l2` or not. # Examples ```jldoctest julia> is_equivalent(AnyHitConstraint(1, 3), RowMissConstraint(1)) false julia> is_equivalent(AnyHitConstraint(1, 3), RowMissConstraint(2)) true ``` """ is_equivalent
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
890
#= # LinkedList of not yet treated vertices =# mutable struct _ListEle{T <: Integer} vertex::WordVertex{T} next::Union{_ListEle{T}, Nothing} # _ListEle constructors _ListEle{T}(vertex, next) where {T <: Integer} = new(vertex, next) end # struct mutable struct _UninitializedList{T <: Integer} n::Int32 head::Union{_ListEle{T}, Nothing} # _UninitializedList constructors _UninitializedList{T}() where {T <: Integer} = new(0, nothing) end function _push!(l::_UninitializedList{T}, v::WordVertex{T}) where {T <: Integer} l.n += 1 l.head = _ListEle{T}(v, l.head) # Create list element end function _pop!(l::_UninitializedList{T}) where {T <: Integer} if (isnothing(l.head)) error("pop!: Can't pop from an empty list") return end l.n -= 1 v = l.head.vertex l.head = l.head.next return v end
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
2584
export dominant_set function _remove_equivalent(Lambda) #= Removes all but one of equivalent constraints =# Lambda_new = Set{Constraint}() for lambda_i in Lambda push!(Lambda_new, lambda_i) for lambda_j in Lambda if (lambda_i != lambda_j && lambda_j in Lambda_new && is_equivalent(lambda_i, lambda_j)) delete!(Lambda_new, lambda_i) break end # if end # for end # for return Lambda_new end # function """ dominant_set(Lambda::Set{Constraint}) Calculates the dominant constraint set given a set of weakly-hard constraints, `Lambda`. # Examples ```jldoctest julia> dominant_set(Set([RowMissConstraint(1), AnyMissConstraint(3, 5), AnyMissConstraint(1, 7)])) Set{Constraint} with 1 element: AnyMissConstraint(1, 7) ``` """ function dominant_set(Lambda::Set{Constraint})::Set{Constraint} Lambda = _remove_equivalent(Lambda) # Return full set if there is only one constraint if length(Lambda) == 1 return Lambda end # Add Constraints to a connectivity-graph dominance_graph = Dict(lambda => Set{Constraint}() for lambda in Lambda) for lambda_i in Lambda for lambda_j in Lambda if lambda_i != lambda_j # Add edge if lambda_i <= lambda_j if is_dominant(lambda_i, lambda_j) push!(dominance_graph[lambda_i], lambda_j) # Else, if # lambda_i </= lambda_j and lambda_j </= lambda_i, # add undirected edge elseif !is_dominant(lambda_j, lambda_i) push!(dominance_graph[lambda_i], lambda_j) push!(dominance_graph[lambda_j], lambda_i) end # if end # if end # for end # for # For all constraints for (lambda_i, doms) in dominance_graph # For all dominations of the constraint for lambda_j in doms # If lambda_j is in the dominance graph but it does not dominate # lambda_i, remove it (since lambda_i <= lambda_j). # NOTE: We do not have to remove it if it is not already in the graph. if lambda_j in keys(dominance_graph) && !(lambda_i in dominance_graph[lambda_j]) delete!(dominance_graph, lambda_j) end # if end # for end # for # Return the dominant constraints return Set(keys(dominance_graph)) end # function
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
2811
################# ### Automaton ### ################# function Base.show(io::IO, automaton::Automaton{T}) where {T <: Integer} if isempty(automaton.data) print(io, "Uninitialized $(typeof(automaton))") else k = maximum(x -> nbits(x), keys(automaton.data)) println(io, "$(typeof(automaton)) with $(length(automaton)) vertices:") println(io, "{") i = 1 for p in automaton.data if i >= 21 println(io, "\t...") break end println(io, "\t$(_compactstring(p[2], k))") i +=1 end print(io, "} with head: $(automaton.head)") end end ################## ### WordVertex ### ################## #= WordVertex - Returns a string representation of the word/integer corresponding to n =# _wordstring(n::WordVertex{BigInt}) = bitstring(n.w) _wordstring(n::WordVertex{T}) where {T <: Integer} = bitstring(n.w)[end-nbits(n.w)+1:end] #= WordVertex - Returns a string representation of the word/integer corresponding to the child s of n =# _childstring(n::WordVertex{T}, s::Symbol) where {T <: Integer} = !_childexists(n, s) ? '-' : _wordstring(getfield(n, s)) #= WordVertex - Returns a compact bitstring representation of the WordVertex n (of length k) =# function _compactstring(n::WordVertex{T}, k::Integer) where {T <: Integer} "$(typeof(n))($(bitstring(n.w)[end-k+1:end]) => "* "$(!_childexists(n, :miss) ? '-'^k : bitstring(n.miss.w)[end-k+1:end]), " * "$(bitstring(n.hit.w)[end-k+1:end]))" end # function function _compactstring(n::WordVertex{BigInt}, k::Integer) "$(typeof(n))($(bitstring(n.w)) => "* "$(!_childexists(n, :miss) ? '-' : bitstring(n.miss.w)), " * "$(bitstring(n.hit.w)))" end # function #= WordVertex - Printing =# function Base.String(n::WordVertex{T}) where {T <: Integer} "$(typeof(n))($(_wordstring(n)) => $(_childstring(n, :miss)), $(_childstring(n, :hit)))" end function Base.show(io::IO, n::WordVertex{T}) where {T <: Integer} print(io, String(n)) end ################ ### Alphabet ### ################ """ bitstring(w::BigInt [, n::Integer]) A String giving the literal bit representation of a big integer `w`. If `n` is specified, it pads the bit representation to contain _at least_ `n` characters. ## Examples ```jldoctest julia> bitstring(BigInt(4)) "100" julia> bitstring(BigInt(4), 5) "00100" ``` """ Base.bitstring(w::BigInt) = string(w, base = 2) Base.bitstring(w::BigInt, N::Integer) = string(w, pad = unsigned(N), base = 2) ################## ### Constraint ### ################## function Base.show(io::IO, lambda::Constraint) print(io, typeof(lambda)) print(io, (lambda.x, lambda.k)) end
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
3171
export random_sequence, all_sequences ################# ### Functions ### ################# """ random_sequence(automaton::Automaton, N::Integer) The function takes an arbitrary walk of length `N` in `automaton`. Returns a sequence that satisfy all weakly-hard constraints used to build the automaton. """ function random_sequence(automaton::Automaton{T}, N::S) where {T <: Integer, S <: Integer} if N < 8 return _rand_seq(automaton.head, N, Int8(1)) elseif N < 16 return _rand_seq(automaton.head, N, Int16(1)) elseif N < 32 return _rand_seq(automaton.head, N, Int32(1)) elseif N < 64 return _rand_seq(automaton.head, N, Int64(1)) else return _rand_seq(automaton.head, N, BigInt(1)) end end # function """ all_sequences(automaton::Automaton, N::Integer) The function returns a set containing all sequences of length `N` satisfying the constraints used to build the automaton. In other words, the function generates the satisfaction set of length `N` sequences. ## Example ```jldoctest julia> all_sequences(build_automaton(AnyHitConstraint(2, 3)), 5) Set{Int8} with 9 elements: 22 13 15 29 27 31 30 14 23 ``` """ function all_sequences(automaton::Automaton{T}, N::S) where {T <: Integer, S <: Integer} if N < 8 return _recursive!(automaton.head, Set{Int8}(), N, Int8(0)) elseif N < 16 return _recursive!(automaton.head, Set{Int16}(), N, Int16(0)) elseif N < 32 return _recursive!(automaton.head, Set{Int32}(), N, Int32(0)) elseif N < 64 return _recursive!(automaton.head, Set{Int64}(), N, Int64(0)) else return _recursive!(automaton.head, Set{BigInt}(), N, BigInt(0)) end end # function ##################### ### Aux functions ### ##################### function _rand_seq(vertex::WordVertex{T}, N::S, seq::R) where {T <: Integer, S <: Integer, R} # Random walk for _ in 1:N-1 seq <<= R(1) c::Symbol = _rand_neighbour!(vertex) vertex = getfield(vertex, c) seq |= (c === :miss) ? R(0) : R(1) end # for return seq end # function function _rand_neighbour!(vertex::WordVertex{T})::Symbol where {T <: Integer} #= Picks a random neighbour =# if _childexists(vertex, :miss) return rand([:miss, :hit]) else return :hit end end # function function _recursive!(vertex::WordVertex{T}, seq_set::Set{R}, N::S, seq::R) where {T <: Integer, R <: Integer, S <: Integer} _recursive_sequence!(vertex, seq_set, N, seq) return seq_set end # function function _recursive_sequence!(vertex::WordVertex{T}, seq_set::Set{R}, N::S, seq::R) where {T <: Integer, R <: Integer, S <: Integer} if N == 0 # base case push!(seq_set, seq) else if _childexists(vertex, :miss) _recursive_sequence!(vertex.miss, seq_set, N-S(1), seq << R(1)) end _recursive_sequence!(vertex.hit, seq_set, N-S(1), (seq << R(1)) | R(1)) end end # function
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
3091
export AbstractAutomaton, Automaton, WordVertex, Constraint, RowHitConstraint, RowMissConstraint, AnyHitConstraint, AnyMissConstraint, Hit, H, Miss, M ################ ### Alphabet ### ################ """ A deadline miss -- representated as UInt8(0) """ const Miss = UInt8(0) """ A deadline miss -- representated as UInt8(0) (equivalent to Miss) """ const M = Miss """ A deadline hit -- representated as UInt8(1) """ const Hit = UInt8(1) """ A deadline hit -- representated as UInt8(1) (equivalent to Hit) """ const H = Hit ################## ### WordVertex ### ################## """ A struct keep track of the current node and its direct children (if some exist). """ mutable struct WordVertex{T <: Integer} w::T miss::Union{Nothing, WordVertex{T}} hit::Union{Nothing, WordVertex{T}} #= WordVertex constructors =# WordVertex{T}(w) where {T <: Integer} = new(w, nothing, nothing) WordVertex{T}(w, miss, hit) where {T <: Integer} = new(w, miss, hit) end # struct ################# ### Automaton ### ################# """ Abstract representation of an automaton type """ abstract type AbstractAutomaton end """ Automaton() Automaton struct containing a dict to represent the vertices (including head) and transitions of the automaton. * Key = Word (represented by integer). * Value = WordVertex (containing current vertex and its direct children vertices) """ struct Automaton{T <: Integer} <: AbstractAutomaton head::Union{Nothing, WordVertex{T}} data::Dict{T, WordVertex{T}} #= Automaton Constructor =# Automaton{T}(head) where {T <: Integer} = new(head, Dict{T, WordVertex{T}}()) Automaton{T}() where {T <: Integer} = new(nothing, Dict{T, WordVertex{T}}()) end # struct ################### ### Constraints ### ################### """ Abstract representation of a constraint type """ abstract type Constraint end #= Data representation for individual constraints =# struct ConstraintData x::Int64 k::Int64 ConstraintData(x, k) = (x < 0 || x > k || k < 1) ? error("Invalid input") : new(x, k) end struct RowHitConstraint <: Constraint data::ConstraintData end struct RowMissConstraint <: Constraint data::ConstraintData end struct AnyHitConstraint <: Constraint data::ConstraintData end struct AnyMissConstraint <: Constraint data::ConstraintData end #= Constraint Constructors =# """ RowMissConstraint(x) Constructor for RowMissConstraint. """ RowMissConstraint(x::Int64) = RowMissConstraint(ConstraintData(x, x+1)) RowMissConstraint(x, k) = RowMissConstraint(ConstraintData(x, x+1)) """ RowHitConstraint(x, k) Constructor for RowHitConstraint. """ RowHitConstraint(x, k) = RowHitConstraint(ConstraintData(x, k)) """ AnyMissConstraint(x, k) Constructor for AnyMissConstraint. """ AnyMissConstraint(x, k) = AnyMissConstraint(ConstraintData(x, k)) """ AnyHitConstraint(x, k) Constructor for AnyHitConstraint. """ AnyHitConstraint(x, k) = AnyHitConstraint(ConstraintData(x, k))
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
8102
module AutomatonTests using Test using WeaklyHard using WeaklyHard: nbits, shift, shift_rowhit, _childexists, consword ########################## #### Common Variables #### ########################## k_max = 20 n_constraints = 6 n_tests = 1_000 types = [Int8, Int16, Int32, Int64, BigInt] ##################### #### Shift tests #### ##################### function test_shift_correctness(w::T, c) where {T <: Integer} newWord = (w << 1) | T(c) if c == M return newWord == shift(w, c) else return newWord - T(2^(nbits(newWord)-1)) == shift(w, c) end # if end # function function test_shift_rowhit_correctness(w::T, c, n::T) where {T <: Integer} newWord = (w << 1) | T(c) if c == M return newWord == shift_rowhit(w, c, n) else return ((newWord & n == n) ? n : newWord) == shift_rowhit(w, c, n) end # if end # function @testset "Shift Tests" begin chars = [H, M] for T in types for _ in 1:n_tests @test test_shift_correctness(rand(T(1):T(8*sizeof(T)-1)), rand(chars)) end # for end # for end # testset @testset "Shift_RowHit Tests" begin chars = [H, M] for T in types n = consword( rand( T(1) : max( T(sizeof(T) - 1), T(1) ) ) ) for _ in 1:n_tests @test test_shift_rowhit_correctness(rand(T(1):T(8*sizeof(T)-1)), rand(chars), n) end # for end # for end # testset #################### ### Vertex tests ### #################### function test_vertex_correctness(Lambda::Set{T}) where {T <: Constraint} if length(Lambda) == 1 L = pop!(Lambda) else L = dominant_set(Lambda) end automaton = build_automaton(L) seq = random_sequence(automaton, 5000) c = is_satisfied(L, seq) if !c return false end for n in vertices(automaton) if (!is_satisfied(L, Int64(n.w)) || (_childexists(n, :miss) && !is_satisfied(L, Int64(n.miss.w))) || !is_satisfied(L, Int64(n.hit.w))) return false end end true end # function @testset "Vertices Tests" begin constraint_names = ["RowMissConstraint", "RowHitConstraint", "AnyMissConstraint", "AnyHitConstraint"] tested = Set{Set{Constraint}}() for _ in 1:n_tests Lambda = Set{Constraint}() nbr_c = rand(1:n_constraints) for _ in 1:nbr_c k = rand(1:k_max) x = rand(1:max(k-1, 1)) lambda_type = rand(constraint_names) if lambda_type == "RowHitConstraint" x = x #floor(Int, x/2) end push!(Lambda, getfield(WeaklyHard, Symbol(lambda_type))(x, k)) end # for L = dominant_set(Lambda) if !(L in tested) push!(tested, L) c = test_vertex_correctness(Lambda) @test c if !c @show "###############" @show "Lambda:" for l in Lambda @show l end @show "---------------" @show "Lambda_star:" Lambda_star = dominant_set(Lambda) for l in Lambda_star @show l end @show "###############" return end end end # for println(" ") println("Executed tests on $(length(tested)) different automata") end # testset ############################ ##### Transitions tests #### ############################ function test_transition_correctness(Lambda::Set{T}) where {T <: Constraint} if length(Lambda) == 1 L = pop!(Lambda) else L = Lambda end automaton = build_automaton(L) trans = transitions(automaton) for v in vertices(automaton) v1 = v.hit if !((v.w, v1.w, H) in trans) return false end if _childexists(v, :miss) v2 = v.miss if !((v.w, v2.w, M) in trans) return false end end end # for return true end # function @testset "Transitions Tests" begin constraint_names = ["RowMissConstraint", "RowHitConstraint", "AnyMissConstraint", "AnyHitConstraint"] tested = Set{Set{Constraint}}() for _ in 1:n_tests Lambda = Set{Constraint}() nbr_c = rand(1:n_constraints) for _ in 1:nbr_c k = rand(1:k_max) x = rand(1:max(k-1, 1)) lambda_type = rand(constraint_names) if lambda_type == "RowHitConstraint" x = x #floor(Int, x/2) end push!(Lambda, getfield(WeaklyHard, Symbol(lambda_type))(x, k)) end # for L = dominant_set(Lambda) if !(L in tested) push!(tested, L) c = test_transition_correctness(Lambda) @test c if !c @show "###############" @show "Lambda:" @show Lambda @show "---------------" @show "Lambda_star:" Lambda_star = dominant_set(Lambda) @show Lambda_star @show "###############" return end end end # for println(" ") println("Executed tests on $(length(tested)) different automata") end # testset ############################ ##### Automata tests ####### ############################ @testset "Set-construction Tests" begin constraint_names = ["RowMissConstraint", "RowHitConstraint", "AnyMissConstraint", "AnyHitConstraint"] n_constraints = 3 k_max = 15 n_tests = 1_000 for _ in 1:n_tests Lambda = Set{Constraint}() n = rand(1:n_constraints) for _ in 1:n k = rand(1:k_max) x = rand(0:k) lambda_type = rand(constraint_names) if lambda_type == "RowHitConstraint" x = floor(Int, x/2) end push!(Lambda, getfield(WeaklyHard, Symbol(lambda_type))(x, k)) end # for Lambda_star = dominant_set(Lambda) G = build_automaton(Lambda_star) minimize_automaton!(G) all_seq = all_sequences(G, k_max+1) # +1 to account for RowMissConstraints for seq in all_seq if !is_satisfied(Lambda_star, seq) @show Lambda @show Lambda_star @show seq @show bitstring(seq) end @test is_satisfied(Lambda_star, seq) end # for end # for end # testset function equivalence_test_min(g_min::Automaton, g::Automaton) ks_min = keys(g_min.data) ks = keys(g.data) for k_min in ks_min if !(k_min in ks) return false # if the vertex doesn't exist in both automata elseif WeaklyHard._childexists(g.data[k_min], :miss) if g_min.data[k_min].miss.w != g.data[k_min].miss.w || g_min.data[k_min].hit.w != g.data[k_min].hit.w return false # if the vertices children differ in the different automata end # if else if g_min.data[k_min].hit.w != g.data[k_min].hit.w return false # if the vertices children differ in the different automata end # if end # if end # for return true end # function @testset "Minimizing single-constraint automata" begin constraint_names = ["RowMissConstraint", "RowHitConstraint", "AnyMissConstraint", "AnyHitConstraint"] k_max = 15 n_tests = 1_000 for _ in 1:n_tests k = rand(1:k_max) x = rand(0:k) lambda_type = rand(constraint_names) if lambda_type == "RowHitConstraint" x = floor(Int, x/2) end l = getfield(WeaklyHard, Symbol(lambda_type))(x, k) g_min = build_automaton(l) g = build_automaton(l) minimize_automaton!(g_min) @test equivalence_test_min(g_min, g) end # for end # testset end # module
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
13558
module ConstraintTests using Test using WeaklyHard using WeaklyHard: consword ############################## ### Generate all sequences ### ############################## const k_max = 5 const types = [Int8, Int16, Int32, Int64, BigInt] generate_all_seq(k::T) where {T <: Integer} = (k <= 8*sizeof(T) - 1) ? [(T(1) << k) | i for i in T(0):T(2^k-1)] : error("Can't create that long sequences of $T") const seqs = generate_all_seq(Int32(k_max)) @show length(seqs) generate_all_valid(lambda::T) where {T <: Constraint} = Set{Int32}(filter(x -> is_satisfied(lambda, x), seqs)) ################################################ ### Aux functions for individual constraints ### ################################################ function trivial_rowhit(x, k) lambda = RowHitConstraint(x, k) # Parameter tests @test lambda.x == x @test lambda.k == k z = k - 2*x + 1 # Function tests for T in types s = 8*sizeof(T) if k + 2*x < s # Trivial tests @test (x==0) ? is_satisfied(lambda, T(0)) : !is_satisfied(lambda, T(0)) @test (2*x > k) ? !is_satisfied(lambda, consword(T(k)) << 1) : is_satisfied(lambda, consword(T(k)) << 1) end # if end # for end # function function trivial_rowmiss(x, k) lambda = RowMissConstraint(x, k) # Parameter tests @test lambda.x == x @test lambda.k == x+1 # Function tests for T in types s = 8*sizeof(T) if k < s # Trivial tests if x == 0 @test !is_satisfied(lambda, T(1) << 1) else @test is_satisfied(lambda, T(1) << lambda.x) @test !is_satisfied(lambda, T(1) << (lambda.x+1)) end # if end # if end # for end # function function trivial_anymiss(x, k) lambda = AnyMissConstraint(x, k) # Parameter tests @test lambda.x == x @test lambda.k == k # Function tests for T in types s = 8*sizeof(T) if k < s # Trivial tests if x == 0 @test !is_satisfied(lambda, T(1) << 1) elseif x == k @test is_satisfied(lambda, T(0)) else @test is_satisfied(lambda, consword(T(lambda.k)) << lambda.x) @test !is_satisfied(lambda, consword(T(lambda.k)) << (lambda.x+1)) end # if end #if end # for end # function function trivial_anyhit(x, k) lambda = AnyHitConstraint(x, k) # Parameter tests @test lambda.x == x @test lambda.k == k # Function tests for T in types s = 8*sizeof(T) if k < s # Trivial tests if x == 0 @test is_satisfied(lambda, T(0)) elseif x == k @test !is_satisfied(lambda, T(1) << 1) else @test is_satisfied(lambda, consword(T(lambda.k)) << (lambda.k - lambda.x)) @test !is_satisfied(lambda, consword(T(lambda.k)) << (lambda.k - lambda.x + 1)) end # if end # if end # for end # function ######################################## ### Tests for individual constraints ### ######################################## @testset "Trivial Tests - RowHitConstraint" begin for k in 1:200 for x in 0:k trivial_rowhit(x, k) end # for end # for end # testset @testset "Trivial Tests - RowMissConstraint" begin for k in 1:200 for x in 0:k trivial_rowmiss(x, k) end # for end # for end # testset @testset "Trivial Tests - AnyMissConstraint" begin for k in 1:200 for x in 0:k trivial_anymiss(x, k) end # for end # for end # testset @testset "Trivial Tests - AnyHitConstraint" begin for k in 1:200 for x in 0:k trivial_anyhit(x, k) end # for end # for end # testset ############################### ### Aux dominance functions ### ############################### function rowmissrowmiss_tests(x1, x2) c1 = RowMissConstraint(x1) c2 = RowMissConstraint(x2) if x1 == x2 @test is_dominant(c1, c2) && is_dominant(c2, c1) elseif x1 < x2 @test is_dominant(c1, c2) else @test is_dominant(c2, c1) end end # function function rowhitrowhit_tests(x1, k1, x2, k2) c1 = RowHitConstraint(x1, k1) c2 = RowHitConstraint(x2, k2) if x2 == 0 @test is_dominant(c1, c2) elseif x1 == 0 @test !is_dominant(c1, c2) elseif k2 >= k1 @test (x2 <= x1) ? is_dominant(c1, c2) : !is_dominant(c1, c2) else @test (x2 <= x1 - ceil( (k1-k2)/2 )) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end end # function function anymissanymiss_tests(x1, k1, x2, k2) c1 = AnyMissConstraint(x1, k1) c2 = AnyMissConstraint(x2, k2) n1 = k1 - x1 n2 = k2 - x2 @test (n2 <= max(n1*floor(Int, k2/k1), k2+ceil(Int, k2/k1)*(n1-k1))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function function anyhitanyhit_tests(x1, k1, x2, k2) c1 = AnyHitConstraint(x1, k1) c2 = AnyHitConstraint(x2, k2) @test (x2 <= max(x1*floor(Int, k2/k1), k2+ceil(Int, k2/k1)*(x1-k1))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function ####################### ### Dominance tests ### ####################### @testset "RowMiss-RowMiss - Tests" begin for i in 1:10000 x1 = rand(0:i) x2 = rand(0:i) rowmissrowmiss_tests(x1, x2) end # for end # testset @testset "RowHit-RowHit - Tests" begin for i in 2:10001 k1 = rand(1:i) k2 = rand(1:i) x1 = rand(0:floor(Int, k1/2)) x2 = rand(0:floor(Int, k2/2)) rowhitrowhit_tests(x1, k1, x2, k2) end # for end # testset @testset "AnyMiss-AnyMiss - Tests" begin for i in 1:10000 k1 = rand(1:i) k2 = rand(1:i) x1 = rand(0:k1) x2 = rand(0:k2) anymissanymiss_tests(x1, k1, x2, k2) end # for end # testset @testset "AnyHit-AnyHit - Tests" begin for i in 1:10000 k1 = rand(1:i) k2 = rand(1:i) x1 = rand(0:k1) x2 = rand(0:k2) anyhitanyhit_tests(x1, k1, x2, k2) end # for end # testset ################################# ### Aux cross-dominance tests ### ################################# ### RowMiss-X ### function rowmissrowhit_tests(x1, k1, x2, k2) c1 = RowMissConstraint(x1) c2 = RowHitConstraint(x2, k2) x1 = 1 k1 = c1.x+1 z1 = k1-x1 @test (x2 <= min(floor(k2/(z1+1)), max(floor(k1/(z1+1)), ceil(x1/z1)))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function function rowmissanymiss_tests(x1, k1, x2, k2) c1 = RowMissConstraint(x1) c2 = AnyMissConstraint(x2, k2) x1 = 1 k1 = c1.x+1 x2 = k2 - x2 @test (x2 <= max(x1*floor(Int, k2/k1), k2+ceil(Int, k2/k1)*(x1-k1))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function function rowmissanyhit_tests(x1, k1, x2, k2) c1 = RowMissConstraint(x1) c2 = AnyHitConstraint(x2, k2) x1 = 1 k1 = c1.x+1 x2 = x2 @test (x2 <= max(x1*floor(Int, k2/k1), k2+ceil(Int, k2/k1)*(x1-k1))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function ### RowHit-X ### function rowhitrowmiss_tests(x1, k1, x2, k2) c1 = RowHitConstraint(x1, k1) c2 = RowMissConstraint(x2) z1 = k1-2x1+1 x2 = 1 k2 = c2.x+1 @test (x2 <= max(x1*floor(k2/(z1+x1)), k2 - floor(k2/(z1+x1))*z1 - z1)) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function function rowhitanymiss_tests(x1, k1, x2, k2) c1 = RowHitConstraint(x1, k1) c2 = AnyMissConstraint(x2, k2) z1 = k1-2x1+1 x2 = k2-x2 @test (x2 <= max(x1*floor(k2/(z1+x1)), k2 - floor(k2/(z1+x1))*z1 - z1)) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function function rowhitanyhit_tests(x1, k1, x2, k2) c1 = RowHitConstraint(x1, k1) c2 = AnyHitConstraint(x2, k2) z1 = k1-2x1+1 return x2 <= max(x1*floor(k2/(z1+x1)), k2 - floor(k2/(z1+x1))*z1 - z1) end # function ### AnyMiss-X ### function anymissrowmiss_tests(x1, k1, x2, k2) c1 = AnyMissConstraint(x1, k1) c2 = RowMissConstraint(x2) x1 = k1 - x1 x2 = 1 k2 = c2.x+1 @test (x2 <= max(x1*floor(Int, k2/k1), k2+ceil(Int, k2/k1)*(x1-k1))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function function anymissrowhit_tests(x1, k1, x2, k2) c1 = AnyMissConstraint(x1, k1) c2 = RowHitConstraint(x2, k2) z1 = x1 x1 = k1-x1 @test (x2 <= min(floor(k2/(z1+1)), max(floor(k1/(z1+1)), ceil(x1/z1)))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function function anymissanyhit_tests(x1, k1, x2, k2) c1 = AnyMissConstraint(x1, k1) c2 = AnyHitConstraint(x2, k2) x1 = k1 - x1 @test (x2 <= max(x1*floor(Int, k2/k1), k2+ceil(Int, k2/k1)*(x1-k1))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function ### AnyHit-X ### function anyhitrowmiss_tests(x1, k1, x2, k2) c1 = AnyHitConstraint(x1, k1) c2 = RowMissConstraint(x2) x2 = 1 k2 = c2.x+1 @test (x2 <= max(x1*floor(Int, k2/k1), k2+ceil(Int, k2/k1)*(x1-k1))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function function anyhitrowhit_tests(x1, k1, x2, k2) c1 = AnyHitConstraint(x1, k1) c2 = RowHitConstraint(x2, k2) z1 = k1-x1 @test (x2 <= min(floor(k2/(z1+1)), max(floor(k1/(z1+1)), ceil(x1/z1)))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function function anyhitanymiss_tests(x1, k1, x2, k2) c1 = AnyHitConstraint(x1, k1) c2 = AnyMissConstraint(x2, k2) x2 = k2-x2 @test (x2 <= max(x1*floor(Int, k2/k1), k2+ceil(Int, k2/k1)*(x1-k1))) ? is_dominant(c1, c2) : !is_dominant(c1, c2) end # function ############################# ### Cross-dominance tests ### ############################# @testset "RowMiss-X - Analytic Tests" begin for i in 1:10000 k = rand(1:i, 4) x = [rand(0:j) for j in k] rowmissrowhit_tests(x[1], x[1]+1, floor(Int, x[2]/2), k[2]) rowmissanymiss_tests(x[1], x[1]+1, x[3], k[3]) rowmissanyhit_tests(x[1], x[1]+1, x[4], k[4]) end # for end # testset @testset "RowHit-X - Analytic Tests" begin for i in 1:10000 k = rand(1:i, 4) x = [rand(0:j) for j in k] rowhitrowmiss_tests(floor(Int, x[2]/2), k[2], x[1], x[1]+1) rowhitanymiss_tests(floor(Int, x[2]/2), k[2], x[3], k[3]) rowhitanyhit_tests(floor(Int, x[2]/2), k[2], x[4], k[4]) end # for end # testset @testset "AnyMiss-X - Analytic Tests" begin for i in 1:10000 k = rand(1:i, 4) x = [rand(0:j) for j in k] anymissrowmiss_tests(x[3], k[3], x[1], x[1]+1) anymissrowhit_tests(x[3], k[3], floor(Int, x[2]/2), k[2]) anymissanyhit_tests(x[3], k[3], x[4], k[4]) end # for end # testset @testset "AnyHit-X - Analytic Tests" begin for i in 1:10000 k = rand(1:i, 4) x = [rand(0:j) for j in k] anyhitrowmiss_tests(x[4], k[4], x[1], x[1]+1) anyhitrowhit_tests(x[4], k[4], floor(Int, x[2]/2), k[2]) anyhitanymiss_tests(x[4], k[4], x[3], k[3]) end # for end # testset ####################### ### satisfied tests ### ####################### Threads.@threads for k1 = 1:k_max-1 for x1 in 0:k1 l1 = RowMissConstraint(x1) S1 = generate_all_valid(l1) @testset "BruteForce Tests" begin for k2 = 1:k_max for x2 = 0:k2 l2 = RowHitConstraint(x2, k2) S2 = generate_all_valid(l2) @test is_dominant(l1, l2) ? isempty(setdiff(S1, S2)) : !isempty(setdiff(S1, S2)) @test is_dominant(l2, l1) ? isempty(setdiff(S2, S1)) : !isempty(setdiff(S2, S1)) for k3 = 1:k_max for x3 = 0:k3 l3 = AnyMissConstraint(x3, k3) S3 = generate_all_valid(l3) @test is_dominant(l1, l3) ? isempty(setdiff(S1, S3)) : !isempty(setdiff(S1, S3)) @test is_dominant(l2, l3) ? isempty(setdiff(S2, S3)) : !isempty(setdiff(S2, S3)) @test is_dominant(l3, l1) ? isempty(setdiff(S3, S1)) : !isempty(setdiff(S3, S1)) @test is_dominant(l3, l2) ? isempty(setdiff(S3, S2)) : !isempty(setdiff(S3, S2)) for k4 = 1:k_max for x4 = 0:k4 l4 = AnyHitConstraint(x4, k4) S4 = generate_all_valid(l4) @test is_dominant(l1, l4) ? isempty(setdiff(S1, S4)) : !isempty(setdiff(S1, S4)) @test is_dominant(l2, l4) ? isempty(setdiff(S2, S4)) : !isempty(setdiff(S2, S4)) @test is_dominant(l3, l4) ? isempty(setdiff(S3, S4)) : !isempty(setdiff(S3, S4)) @test is_dominant(l4, l1) ? isempty(setdiff(S4, S1)) : !isempty(setdiff(S4, S1)) @test is_dominant(l4, l2) ? isempty(setdiff(S4, S2)) : !isempty(setdiff(S4, S2)) @test is_dominant(l4, l3) ? isempty(setdiff(S4, S3)) : !isempty(setdiff(S4, S3)) end # for end # for end # for end # for end # for end # for end # testset end # for end # for end # module
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
2540
module DominantSetTests using Test using WeaklyHard const n_tests = 10_000 const k_max = 200 @testset "2 Random Constraints" begin constraint_names = ["RowMissConstraint", "RowHitConstraint", "AnyMissConstraint", "AnyHitConstraint"] for _ in 1:n_tests k1 = rand(1:k_max) k2 = rand(1:k_max) x1 = rand(0:k1) x2 = rand(0:k2) l1_type = rand(constraint_names) l2_type = rand(constraint_names) if l1_type == "RowHitConstraint" x1 = floor(Int, x1/2) end if l2_type == "RowHitConstraint" x2 = floor(Int, x2/2) end lambda_1 = getfield(WeaklyHard, Symbol(l1_type))(x1, k1) lambda_2 = getfield(WeaklyHard, Symbol(l2_type))(x2, k2) Lambda = Set{Constraint}([lambda_1, lambda_2]) Lambda_star = dominant_set(Lambda) if is_equivalent(lambda_1, lambda_2) @test length(Lambda_star) == 1 elseif is_dominant(lambda_1, lambda_2) @test length(Lambda_star) == 1 && (lambda_1 in Lambda_star) elseif !is_dominant(lambda_2, lambda_1) @test length(Lambda_star) == 2 && (lambda_1 in Lambda_star) && (lambda_2 in Lambda_star) else @test length(Lambda_star) == 1 && (lambda_2 in Lambda_star) end #if end # for end # testset @testset "Arbitrary Random Constraints" begin constraint_names = ["RowMissConstraint", "RowHitConstraint", "AnyMissConstraint", "AnyHitConstraint"] n_constraints = 30 for _ in 1:n_tests Lambda = Set{Constraint}() n = rand(1:n_constraints) for _ in 1:n k = rand(1:k_max) x = rand(0:k) lambda_type = rand(constraint_names) if lambda_type == "RowHitConstraint" x = floor(Int, x/2) end push!(Lambda, getfield(WeaklyHard, Symbol(lambda_type))(x, k)) end # for Lambda_star = dominant_set(Lambda) Lambda_comp = setdiff(Lambda, Lambda_star) test_res = true for lambda_c in Lambda_comp exist_dominant = false for lambda_s in Lambda_star if is_dominant(lambda_s, lambda_c) exist_dominant = true break end end if !exist_dominant @show Lambda test_res = false break end # if end # for @test test_res end # for end # testset end # module
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
1145
module PrintingTests using Test using WeaklyHard @testset "Print automaton" begin g1 = build_automaton(AnyHitConstraint(1, 3)) @test_nowarn println(Base.DevNull(), 1) @test_nowarn println(Base.DevNull(), g1.head) g2 = build_automaton(AnyHitConstraint(10, 16)) @test_nowarn println(Base.DevNull(), g2) @test_nowarn println(Base.DevNull(), g2.head) g3 = build_automaton(RowHitConstraint(10, 60)) @test_nowarn println(Base.DevNull(), g3) @test_nowarn println(Base.DevNull(), g3.head) end #testset @testset "Print BigInt" begin g1 = build_automaton(AnyHitConstraint(1, 3)) seq1 = random_sequence(g1, 200) @test_nowarn bitstring(seq1) seq2 = random_sequence(g1, 100_000) @test_nowarn bitstring(seq2, 10) end #testset @testset "Print Constraint" begin l1 = AnyHitConstraint(1, 3) @test_nowarn println(Base.DevNull(), l1) l2 = AnyMissConstraint(1, 3) @test_nowarn println(Base.DevNull(), l2) l3 = RowHitConstraint(1, 3) @test_nowarn println(Base.DevNull(), l3) l4 = RowMissConstraint(1, 3) @test_nowarn println(Base.DevNull(), l4) end #testset end # module
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
183
module RunTests include("constraint_tests.jl") include("dominant_set_tests.jl") include("automaton_tests.jl") include("sequence_tests.jl") include("printing_tests.jl") end # module
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
code
9447
module SequenceTests using Test using WeaklyHard ############################## ### Generate all sequences ### ############################## function generate_all_seq(k) return [(1 << k) | i for i in 0:2^k-1] end # function function generate_all_valid(lambda::T, seqs::Vector{R}, k) where {T <: Constraint, R <: Integer} IntType = BigInt if k + 1 < 8 IntType = Int8 elseif k + 1 < 16 IntType = Int16 elseif k + 1 < 32 IntType = Int32 elseif k + 1 < 64 IntType = Int64 end cmp_w = IntType(2^k - 1) return Set{IntType}(map(x -> IntType(x) & IntType(cmp_w), filter(x -> is_satisfied(lambda, x), seqs))) end # function function generate_all_valid(Lambda::Set{T}, seqs::Vector{R}, k) where {T <: Constraint, R <: Integer} IntType = BigInt if k + 1 < 8 IntType = Int8 elseif k + 1 < 16 IntType = Int16 elseif k + 1 < 32 IntType = Int32 elseif k + 1 < 64 IntType = Int64 end cmp_w = IntType(2^k - 1) return Set{IntType}(map(x -> IntType(x) & IntType(cmp_w), filter(x -> is_satisfied(Lambda, x), seqs))) end # function ########################## ### All Sequence tests ### ########################## k_max = 15 @testset "Test all sequences generated by automaton - Not RowHitConstraint" begin for k in 1:k_max IntType = BigInt if k < 8 IntType = Int8 elseif k < 16 IntType = Int16 elseif k < 32 IntType = Int32 elseif k < 64 IntType = Int64 end all_seqs = generate_all_seq(k) for x in 0:k lambda = AnyMissConstraint(x, k) all_valid = generate_all_valid(lambda, all_seqs, k) g = build_automaton(lambda) all_g_seq = all_sequences(g, k) @test isempty(setdiff(all_valid, all_g_seq)) @test isempty(setdiff(all_g_seq, all_valid)) lambda = AnyHitConstraint(x, k) all_valid = generate_all_valid(lambda, all_seqs, k) g = build_automaton(lambda) all_g_seq = all_sequences(g, k) @test isempty(setdiff(all_valid, all_g_seq)) @test isempty(setdiff(all_g_seq, all_valid)) if x < k lambda = RowMissConstraint(x) all_valid = generate_all_valid(lambda, all_seqs, k) g = build_automaton(lambda) all_g_seq = all_sequences(g, k) @test isempty(setdiff(all_valid, all_g_seq)) @test isempty(setdiff(all_g_seq, all_valid)) end end # for end # for end # testset @testset "Test all sequences generated by automaton - Only RowHitConstraint" begin for k in 1:k_max IntType = BigInt if 2*k + 2 < 8 IntType = Int8 elseif 2*k + 2 < 16 IntType = Int16 elseif 2*k + 2 < 32 IntType = Int32 elseif 2*k + 2 < 64 IntType = Int64 end all_seqs = generate_all_seq(k) for x in 0:ceil(k/2) lambda = RowHitConstraint(x, k) all_valid = generate_all_valid(lambda, all_seqs, k) g = build_automaton(lambda) all_g_seq = all_sequences(g, k) @test isempty(setdiff(all_valid, all_g_seq)) @test isempty(setdiff(all_g_seq, all_valid)) end # for end #for end # testset @testset "Test all sequences generated by automaton - Sets of All but RowHitConstraint" begin k = k_max n_tests = 100 n_cstr = 4 constraint_names = ["AnyMissConstraint", "AnyHitConstraint", "RowMissConstraint"] all_seqs = generate_all_seq(k) for n_c in 2:n_cstr for _ in 1:n_tests Lambda = Set{Constraint}() while length(Lambda) < n_c Lambda = Set{Constraint}() for _ in 1:n_c lk = rand(1:k) lx = rand(0:lk) lambda_type = rand(constraint_names) l = getfield(WeaklyHard, Symbol(lambda_type))(lx, lk) push!(Lambda, l) end # for end # while all_valid = generate_all_valid(Lambda, all_seqs, k) g = build_automaton(Lambda) minimize_automaton!(g) all_g_seq = all_sequences(g, k) @test isempty(setdiff(all_valid, all_g_seq)) @test isempty(setdiff(all_g_seq, all_valid)) if !isempty(setdiff(all_valid, all_g_seq)) || !isempty(setdiff(all_g_seq, all_valid)) println(Lambda) end end # for end # for end # testset @testset "Test all sequences generated by automaton - Only Sets of RowHitConstraint" begin k = k_max n_tests = 100 n_cstr = 4 all_seqs = generate_all_seq(k) for n_c in 2:n_cstr for _ in 1:n_tests Lambda = Set{RowHitConstraint}() while length(Lambda) < n_c Lambda = Set{RowHitConstraint}() for _ in 1:n_c lk = rand(1:k) lx = rand(0:lk) l = RowHitConstraint(lx, lk) push!(Lambda, l) end # for end # while all_valid = generate_all_valid(Lambda, all_seqs, k) g = build_automaton(Lambda) minimize_automaton!(g) all_g_seq = all_sequences(g, k) @test isempty(setdiff(all_valid, all_g_seq)) @test isempty(setdiff(all_g_seq, all_valid)) if !isempty(setdiff(all_valid, all_g_seq)) || !isempty(setdiff(all_g_seq, all_valid)) println(Lambda) end end # for end # for end # testset @testset "Test all sequences generated by automaton - Arbitrary sets" begin k = k_max n_tests = 100 n_cstr = 4 constraint_names = ["AnyMissConstraint", "AnyHitConstraint", "RowMissConstraint", "RowHitConstraint"] all_seqs = generate_all_seq(k) for n_c in 2:n_cstr for _ in 1:n_tests Lambda = Set{Constraint}() while length(Lambda) < n_c Lambda = Set{Constraint}() for _ in 1:n_c lk = rand(1:k) lx = rand(0:lk) lambda_type = rand(constraint_names) l = getfield(WeaklyHard, Symbol(lambda_type))(lx, lk) push!(Lambda, l) end # for end # while all_valid = generate_all_valid(Lambda, all_seqs, k) g = build_automaton(Lambda) minimize_automaton!(g) all_g_seq = all_sequences(g, k) @test isempty(setdiff(all_valid, all_g_seq)) @test isempty(setdiff(all_g_seq, all_valid)) if !isempty(setdiff(all_valid, all_g_seq)) || !isempty(setdiff(all_g_seq, all_valid)) println(Lambda) end end # for end # for end # testset ###################### ### Sequence tests ### ###################### N = 200 @testset "Random sequence tests - AnyMissConstraint" begin n_max = 0 for k in 1:k_max for x in 0:k lambda = AnyMissConstraint(x, k) automaton = build_automaton(lambda) for n in k_max:N seq = random_sequence(automaton, n) @test is_satisfied(lambda, seq) end # for n_max = max(n_max, length(automaton)) end # for end # for println("Biggest automaton for AnyMissConstraint: $n_max") end # testset @testset "Random sequence tests - AnyHitConstraint" begin n_max = 0 for k in 1:k_max for x in 0:k lambda = AnyHitConstraint(x, k) automaton = build_automaton(lambda) for n in k_max:N seq = random_sequence(automaton, n) @test is_satisfied(lambda, seq) end # for n_max = max(n_max, length(automaton)) end # for end # for println("Biggest automaton for AnyHitConstraint: $n_max") end # testset @testset "Random sequence tests - RowMissConstraint" begin n_max = 0 for k in 1:k_max for x in 0:k lambda = RowMissConstraint(x, k) automaton = build_automaton(lambda) for n in k_max:N seq = random_sequence(automaton, n) @test is_satisfied(lambda, seq) end # for n_max = max(n_max, length(automaton)) end # for end # for println("Biggest automaton for RowMissConstraint: $n_max") end # testset @testset "Random sequence tests - RowHitConstraint" begin n_max = 0 for k in 1:k_max for x in 0:k lambda = RowHitConstraint(x, k) automaton = build_automaton(lambda) for n in k_max:N seq = random_sequence(automaton, n) @test is_satisfied(lambda, seq) end # for n_max = max(n_max, length(automaton)) end # for end # for println("Biggest automaton for RowHitConstraint: $n_max") end # testset end # module
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
docs
3394
# WeaklyHard.jl [![Build Status](https://github.com/NilsVreman/WeaklyHard.jl/workflows/CI/badge.svg)](https://github.com/NilsVreman/WeaklyHard.jl/actions) [![Coverage](https://codecov.io/gh/NilsVreman/WeaklyHard.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/NilsVreman/WeaklyHard.jl) [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://NilsVreman.github.io/WeaklyHard.jl/stable) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://NilsVreman.github.io/WeaklyHard.jl/dev) A toolbox for analysing weakly-hard constraints in Julia. ## Installation To install, in the Julia REPL: ```julia using Pkg; Pkg.add("WeaklyHard") ``` ## Documentation All functions have docstrings which can be viewed from the REPL, using for example `?build_automaton`. ## Usage We provide a number of weakly-hard constraint structs, used as input to different analysis functions. * `AnyHitConstraint(x, k)`: For _any_ window of `k` consecutive job activations, _at least_ `x` jobs hit their corresponding deadline; * `AnyMissConstraint(x, k)`: For _any_ window of `k` consecutive job activations, _at most_ `x` jobs miss their corresponding deadline; * `RowHitConstraint(x, k)`: For _any_ window of `k` consecutive job activations, _at least_ `x` consecutive jobs hit their corresponding deadline; * `RowMissConstraint(x)`: For _any_ window of `k` consecutive job activations, _at most_ `x` consecutive jobs miss their corresponding deadline. An automaton representation of a weakly-hard constraint is a struct consisting of a record containing `X` amount of integers as: ```julia Automaton{Int} with X vertices: { WordVertex{Int}(x => y, z) ... } with head: WordVertex{Int}(x => y, z) ``` Here, `WordVertex{Int}(x => y, z)` indicates a vertex represented by an `Integer` type, where `x` is the word the vertex is representating and `y`, `z` are the direct successors corresponding to respectively a deadline miss and a deadline hit. ## Example ```julia using WeaklyHard # Constraints lambda1 = AnyHitConstraint(1, 3) lambda2 = RowHitConstraint(2, 6) # Check dominance is_dominant(lambda1, lambda2) # false is_dominant(lambda2, lambda1) # false # Generate automaton for lambda1 G1 = build_automaton(lambda1) # This generates the automaton: # Automaton{Int64} with 3 vertices: # { # WordVertex{Int64}(100 => ---, 001) # --- is an infeasible vertex # WordVertex{Int64}(010 => 100, 001) # WordVertex{Int64}(001 => 010, 001) # } with head: WordVertex{Int64}(1 => 10, 1) G2 = build_automaton(lambda2) # This generates the automaton: # Automaton{Int64} with 6 vertices: # { # WordVertex{Int64}(01100 => 11000, 00001) # WordVertex{Int64}(11000 => -----, 00001) # WordVertex{Int64}(01101 => 11000, 00011) # WordVertex{Int64}(00011 => 00110, 00011) # WordVertex{Int64}(00110 => 01100, 01101) # WordVertex{Int64}(00001 => -----, 00011) # } with head: WordVertex{Int64}(11 => 110, 11) # Generate a random sequence of length N satisfying the constraint represented by G2 N = 100_000 seq = random_sequence(G2, N) bitstring(seq) # The bit representation of the integer ``` if the bitstring has `M < N` characters, it implies that the first `N-M` characters are misses (since julia interpret zeros before the MSB in a bit string as non-existent) ## Additional examples See the examples folder
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
docs
1574
# WeaklyHard.jl Documentation [WeaklyHard](https://github.com/NilsVreman/WeaklyHard.jl) is a toolbox for analysing the real-time concept of weakly-hard constraints, in Julia. ## Installation To install the package, simply run ```julia using Pkg; Pkg.add("WeaklyHard") ``` ## Introduction We provide a number of weakly-hard constraint structs, used as input to different analysis functions. * `AnyHitConstraint(x, k)`: For _any_ window of `k` consecutive job activations, _at least_ `x` jobs hit their corresponding deadline; * `AnyMissConstraint(x, k)`: For _any_ window of `k` consecutive job activations, _at most_ `x` jobs miss their corresponding deadline; * `RowHitConstraint(x, k)`: For _any_ window of `k` consecutive job activations, _at least_ `x` consecutive jobs hit their corresponding deadline; * `RowMissConstraint(x)`: For _any_ window of `k` consecutive job activations, _at most_ `x` consecutive jobs miss their corresponding deadline. An automaton representation of a weakly-hard constraint is a struct consisting of a record containing `X` amount of integers as: ```julia Automaton{Int} with X vertices: { WordVertex{Int}(x => y, z) ... } with head: WordVertex{Int}(x => y, z) ``` Here, `WordVertex{Int}(x => y, z)` indicates a vertex represented by an `Integer` type, where `x` is the word the vertex is representating and `y`, `z` are the direct successors corresponding to respectively a deadline miss and a deadline hit. ## Guide ```@contents Pages = ["man/examples.md", "man/functions.md", "man/summary.md"] Depth = 1 ```
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
docs
2012
# Examples ## Building Automata Generates the automaton representations of the constraints `AnyHitConstraint(1, 3)` and `RowHitConstraint(2, 6)`. ```julia # Constraints lambda1 = AnyHitConstraint(1, 3) lambda2 = RowHitConstraint(2, 6) # Check dominance is_dominant(lambda1, lambda2) # false is_dominant(lambda2, lambda1) # false # Generate automaton for lambda1 G1 = build_automaton(lambda1) # This generates the automaton: # Automaton{Int64} with 3 vertices: # { # WordVertex{Int64}(100 => ---, 001) # --- is an infeasible vertex # WordVertex{Int64}(010 => 100, 001) # WordVertex{Int64}(001 => 010, 001) # } with head: WordVertex{Int64}(1 => 10, 1) G2 = build_automaton(lambda2) # This generates the automaton: # Automaton{Int64} with 6 vertices: # { # WordVertex{Int64}(01100 => 11000, 00001) # WordVertex{Int64}(11000 => -----, 00001) # WordVertex{Int64}(01101 => 11000, 00011) # WordVertex{Int64}(00011 => 00110, 00011) # WordVertex{Int64}(00110 => 01100, 01101) # WordVertex{Int64}(00001 => -----, 00011) # } with head: WordVertex{Int64}(11 => 110, 11) ``` ## Generating sequences satisfying constraints Generates a random sequence satisfying the constraint `AnyHitConstraint(3, 5)`. ```julia l = AnyHitConstraint(3, 5) G = build_automaton(l) N = 100_000 seq = random_sequence(G, N) bitstring(seq) ``` if the bitstring has `M < N` characters, it implies that the first `N-M` characters are misses (since julia interpret zeros before the MSB in a bit string as non-existent) ## Generating satisfaction set Generates all the sequences of length `N` that satisfy the constraint `AnyHitConstraint(2, 3)`. ```julia l = AnyHitConstraint(2, 3) G = build_automaton(l) N = 10 S = all_sequences(G, N) for s in S println(bitstring(s)[end-N+1:end]) end ``` `S` is here a `Set{<: Integer}`, meaning we have to get the bitstring representation of the sequences in order to represent it as a sequence of deadline hits and misses.
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.2.1
abe2e5bb5f679eb33d7240cb760371c7c3ca82c9
docs
425
# Functions ```@index Pages = ["functions.md"] ``` ## Types and Structs ```@docs Miss Hit M H WordVertex AbstractAutomaton Automaton Constraint RowHitConstraint RowMissConstraint AnyHitConstraint AnyMissConstraint ``` ## Constructors and Functions ```@docs build_automaton transitions vertices is_dominant is_equivalent is_satisfied random_sequence all_sequences dominant_set minimize_automaton! bitstring(::BigInt) ```
WeaklyHard
https://github.com/NilsVreman/WeaklyHard.jl.git
[ "MIT" ]
0.1.1
5a840b20445ba4b6c84826e734d899724852c51a
code
604
# This file is part of ReduceLinAlg.jl. It is licensed under the MIT license # Copyright (C) 2018 Michael Reed using Documenter, ReduceLinAlg makedocs( # options modules = [ReduceLinAlg], doctest = false, format = :html, sitename = "ReduceLinAlg.jl", authors = "Michael Reed", pages = Any[ "User's Manual" => "index.md", ] ) deploydocs( target = "build", repo = "github.com/JuliaReducePkg/ReduceLinAlg.jl.git", branch = "gh-pages", latest = "master", osname = "linux", julia = "0.6", deps = nothing, make = nothing, )
ReduceLinAlg
https://github.com/JuliaReducePkg/ReduceLinAlg.jl.git
[ "MIT" ]
0.1.1
5a840b20445ba4b6c84826e734d899724852c51a
code
4271
__precompile__() module ReduceLinAlg using Reduce, LinearAlgebra # This file is part of ReduceLinAlg.jl. It is licensed under the MIT license # Copyright (C) 2018 Michael Reed const VectorAny = Union{Vector,Adjoint} const lin = [ :hessian, :mat_jacobian, :band_matrix, :block_matrix, :char_matrix, :char_poly, :diagonal, :extend, :gram_schmidt, :hilbert, :jordan_block, :kronecker_product, ] const unr = [ :cholesky, :coeff_matrix, :hermitian_tp, :symmetricp, :toeplitz, :triang_adjoint, :vandermonde, ] :(export $([lin;unr]...)) |> eval for fun in lin @eval begin $(Reduce.parsegen(fun,:args)) $(Reduce.unfoldgen(fun,:args)) function $fun(expr::String,s...;be=0) convert(String, $fun(RExpr(expr),s...;be=be)) end end end for fun in unr @eval begin $(Reduce.parsegen(fun,:unary)) $(Reduce.unfoldgen(fun,:unary)) function $fun(expr::String;be=0) convert(String, $fun(RExpr(expr);be=be)) end end end const MatExpr = Union{Array{Any,2},Array{Expr,2},Array{Symbol,2},Expr,Symbol} band_matrix(r::Union{Vector,Adjoint,Expr,Symbol},v::Integer) = band_matrix(list(r),v) |> parse band_matrix(r::T,v::Integer) where T <: Tuple = band_matrix(RExpr(r),v) |> parse block_matrix(r::Integer,c::Integer,s::VectorAny) = block_matrix(RExpr(r),RExpr(c),list(s)) |> parse block_matrix(r::Integer,c::Integer,s::T) where T <: Tuple = block_matrix(RExpr(r),RExpr(c),RExpr(s)) |> parse char_matrix(r::MatExpr,v::Any) = mat(char_matrix(list(r),RExpr(v)) |> parse,r) char_poly(r::MatExpr,v::Any) = mat(char_matrix(list(r),RExpr(v)) |> parse,r) extend(a::MatExpr,r::Integer,c::Integer,s) = mat(extend(RExpr(a),r,c,RExpr(s)) |> parse,a) hessian(r::Reduce.ExprSymbol,l::T) where T <: VectorAny = hessian(r,list(l)) hessian(r::Reduce.ExprSymbol,l::T) where T <: Tuple = hessian(r,RExpr(l)) @doc """ hessian(expr,var_list::Vector) Computes the Hessian matrix of `expr` with respect to the variables in `var_list`. This is an n×n matrix where n is the number of variables and the (i,j)th entry is `df(expr,var_list[i],var_list[j])`. """ hessian hilbert(a::Integer,r) = hilbert(RExpr(a),RExpr(r)) |> parse function mat_jacobian(r::T,v::S) where T <: VectorAny where S <: VectorAny mat_jacobian(list(r),list(v)) |> parse end function mat_jacobian(r::T,v::S) where T <: Tuple where S <: Tuple mat_jacobian(RExpr(r),RExpr(v)) |> parse end @doc """ mat_jacobian(expr_list::Vector,var_list::Vector) Computes the Jacobian matrix of `expr_list` with respect to `var_list`. This is a matrix whose (i,j)th entry is `df(expr_list[i],var_list[j])`. The matrix is n×m where n is the number of variables and m is the number of expressions. """ mat_jacobian export jacobian jacobian = mat_jacobian @doc """ jordan_block(expr,square_size::Integer) Computes the square Jordan block matrix `J` of dimension `square_size`. The entries of `J` are `J[i,i] = expr` for i = 1,...,n, `J[i,i+1] = 1` for i = 1,...,n-1, and all other entries are 0. """ jordan_block kronecker_product(a::MatExpr,b::MatExpr) = mat(kronecker(RExpr(a),RExpr(b)) |> parse,a,b) cholesky(r::Array{T,2}) where T <: Number = cholesky(RExpr(r)) |> parse |> mat coeff_matrix(r::VectorAny) = coeff_matrix(list(r)) |> parse coeff_matrix(r::T) where T <: Tuple = coeff_matrix(RExpr(r)) |> parse diagonal(r::VectorAny) = diagonal(list(r)) |> parse diagonal(r::T) where T <: Tuple = diagonal(RExpr(r)) |> parse gram_schmidt(r::Vector{<:Vector}) = gram_schmidt(list(r)) |> parse gram_schmidt(r::T) where T <: Tuple = gram_schmidt(RExpr(r)) |> parse gram_schmidt(r::Matrix) = gram_schmidt(list(r)) |> parse hermitian_tp(r::MatExpr) = mat(hermitian_tp(RExpr(r)) |> parse, r) symmetricp(r::MatExpr) = mat(symmetricp(RExpr(r)) |> parse, r) toeplitz(r::VectorAny) = toeplitz(list(r)) |> parse toeplitz(r::T) where T <: Tuple = toeplitz(RExpr(r)) |> parse triang_adjoint(r::MatExpr) = mat(triang_adjoint(RExpr(r)) |> parse, r) vandermonde(r::VectorAny) = vandermonde(list(r)) |> parse vandermonde(r::T) where T <: Tuple = vandermonde(RExpr(r)) |> parse function __init__() load_package(:linalg) end Reduce.stop() end # module
ReduceLinAlg
https://github.com/JuliaReducePkg/ReduceLinAlg.jl.git
[ "MIT" ]
0.1.1
5a840b20445ba4b6c84826e734d899724852c51a
code
262
using Reduce using ReduceLinAlg using Test # write your own tests here @test mat_jacobian((:x,),(:x,)) == mat_jacobian([:x],[:x]) @test hessian(:x,(:x,)) == hessian(:x,[:x]) @test jordan_block(:x,1) == jordan_block(Reduce.RExpr("x"),Reduce.RExpr("1")) |> parse
ReduceLinAlg
https://github.com/JuliaReducePkg/ReduceLinAlg.jl.git
[ "MIT" ]
0.1.1
5a840b20445ba4b6c84826e734d899724852c51a
docs
1989
<p align="center"> <img src="https://github.com/chakravala/Reduce.jl/blob/master/docs/src/assets/logo.png" alt="Reduce.jl"/> </p> # ReduceLinAlg.jl **LINALG: Linear algebra package** *A selection of functions that are useful in the world of linear algebra* [![Build Status](https://travis-ci.org/JuliaReducePkg/ReduceLinAlg.jl.svg?branch=master)](https://travis-ci.org/JuliaReducePkg/ReduceLinAlg.jl) [![Build status](https://ci.appveyor.com/api/projects/status/e239kk217a0lb92w?svg=true)](https://ci.appveyor.com/project/chakravala/reducelinalg-jl) [![Coverage Status](https://coveralls.io/repos/JuliaReducePkg/ReduceLinAlg.jl/badge.svg?branch=master&service=github)](https://coveralls.io/github/JuliaReducePkg/ReduceLinAlg.jl?branch=master) [![codecov.io](http://codecov.io/github/JuliaReducePkg/ReduceLinAlg.jl/coverage.svg?branch=master)](http://codecov.io/github/JuliaReducePkg/ReduceLinAlg.jl?branch=master) [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaReducePkg.github.io/ReduceLinAlg.jl/stable) [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://JuliaReducePkg.github.io/ReduceLinAlg.jl/latest) [![Join the chat at gitter](https://badges.gitter.im/Reduce-jl/Lobby.svg)](https://gitter.im/Reduce-jl/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) Upstream REDUCE package by Matt Rebbeck. This Julia package relies on the [Reduce.jl](https://github.com/chakravala/Reduce.jl) parser generator, Julia docs ([stable](https://chakravala.github.io/Reduce.jl/stable) / [latest](https://chakravala.github.io/Reduce.jl/latest)). Meta-package [ReduceAlgebra.jl](https://github.com/JuliaReducePkg/ReduceAlgebra.jl), upstream docs ([LINALG](http://www.reduce-algebra.com/manual/manualse127.html) / [pdf](http://www.reduce-algebra.com/manual/contributed/linalg.pdf)), Julia docs ([stable](https://JuliaReducePkg.github.io/ReduceLinAlg.jl/stable) / [latest](https://JuliaReducePkg.github.io/ReduceLinAlg.jl/latest))
ReduceLinAlg
https://github.com/JuliaReducePkg/ReduceLinAlg.jl.git
[ "MIT" ]
0.1.1
5a840b20445ba4b6c84826e734d899724852c51a
docs
1460
# ReduceLinAlg.jl **LINALG: Linear algebra package** *A selection of functions that are useful in the world of linear algebra* This Julia package relies on the [Reduce.jl](https://github.com/chakravala/Reduce.jl) parser generator, Julia docs ([stable](https://chakravala.github.io/Reduce.jl/stable) / [latest](https://chakravala.github.io/Reduce.jl/latest)). Meta-package [ReduceAlgebra.jl](https://github.com/JuliaReducePkg/ReduceAlgebra.jl), upstream docs ([LINALG](http://www.reduce-algebra.com/manual/manualse127.html) / [pdf](http://www.reduce-algebra.com/manual/contributed/linalg.pdf)), Julia docs ([stable](https://JuliaReducePkg.github.io/ReduceLinAlg.jl/stable) / [latest](https://JuliaReducePkg.github.io/ReduceLinAlg.jl/latest)) ```@contents ``` ```@index ``` ## 16.37 LINALG: Linear algebra package This package provides a selection of functions that are useful in the world of linear algebra. Author: Matt Rebbeck. ### 16.37.1 Introduction This package provides a selection of functions that are useful in the world of linear algebra. These functions are described alphabetically in subsection 16.37.3 and are labelled 16.37.3.1 to 16.37.3.53. They can be classified into four sections(n.b: the numbers after the dots signify the function label in section 16.37.3). Contributions to this package have been made by Walter Tietze (ZIB). ## Library ```@docs ReduceLinAlg.hessian ReduceLinAlg.mat_jacobian ReduceLinAlg.jordan_block ```
ReduceLinAlg
https://github.com/JuliaReducePkg/ReduceLinAlg.jl.git
[ "MPL-2.0" ]
0.1.0
f719b0bdb256f5ad4c331549b14f581dd961f95d
code
413
using Documenter using JobQueueMPI const JQM = JobQueueMPI makedocs(; modules = [JobQueueMPI], doctest = true, clean = true, format = Documenter.HTML(; mathengine = Documenter.MathJax2()), sitename = "JobQueueMPI.jl", authors = "psrenergy", pages = [ "Home" => "index.md", ] ) deploydocs(; repo = "github.com/psrenergy/JobQueueMPI.jl.git", push_preview = true, )
JobQueueMPI
https://github.com/psrenergy/JobQueueMPI.jl.git
[ "MPL-2.0" ]
0.1.0
f719b0bdb256f5ad4c331549b14f581dd961f95d
code
164
module JobQueueMPI using MPI include("mpi_utils.jl") include("job.jl") include("worker.jl") include("controller.jl") include("pmap.jl") end # module JobQueueMPI
JobQueueMPI
https://github.com/psrenergy/JobQueueMPI.jl.git