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" ]
0.1.2
60341f3f9a9f7634574034d06740914489f12317
docs
35
# References ```@bibliography ```
ParameterizedQuantumControl
https://github.com/JuliaQuantumControl/ParameterizedQuantumControl.jl.git
[ "MIT" ]
1.0.0
f78110dacfc8bfac774adf73570473da058bc593
code
5158
module DebuggingUtilities export @showln, @showlnt, test_showline, time_showline """ DebuggingUtilities contains a few tools that may help debug julia code. The exported tools are: - `@showln`: like `@show`, but displays file and line number information as well - `@showlnt`: like `@showlnt`, but also uses indentation to display recursion depth - `test_showline`: a function that displays progress as it executes a file - `time_showline`: a function that displays execution time for each expression in a file """ DebuggingUtilities ## @showln and @showlnt mutable struct FlushedIO <: IO io end function Base.println(io::FlushedIO, args...) println(io.io, args...) flush(io.io) end Base.getindex(io::FlushedIO) = io.io Base.setindex!(io::FlushedIO, newio) = io.io = newio const showlnio = FlushedIO(stdout) """ `@showln x` prints "x = val", where `val` is the value of `x`, along with information about the function, file, and line number at which this statement was executed. For example: ```julia function foo() x = 5 @showln x x = 7 @showln x nothing end ``` might produce output like x = 5 (in foo at ./error.jl:26 at /tmp/showln_test.jl:52) x = 7 (in foo at ./error.jl:26 at /tmp/showln_test.jl:54) If you need call depth information, see [`@showlnt`](@ref). """ macro showln(exs...) blk = showexprs(exs) blk = quote local indent = 0 $blk println(showlnio[], "(in ", $(string(__source__.file)), ':', $(__source__.line), ')') end if !isempty(exs) push!(blk.args, :value) end blk end """ `@showlnt x` prints "x = val", where `val` is the value of `x`, along with information about the function, file, and line number at which this statement was executed, using indentation to indicate recursion depth. For example: ```julia function recurses(n) @showlnt n n += 1 @showlnt n if n < 10 n = recurses(n) end return n end ``` might produce output like x = 5 (in foo at ./error.jl:26 at /tmp/showln_test.jl:52) x = 7 (in foo at ./error.jl:26 at /tmp/showln_test.jl:54) This macro causes a backtrace to be taken, and looking up the corresponding code information is relatively expensive, so using `@showlnt` can have a substantial performance cost. The indentation of the line is proportional to the length of the backtrace, and consequently is an indication of recursion depth. """ macro showlnt(exs...) blk = showexprs(exs) blk = quote local bt = backtrace() local indent = length(bt) # to mark recursion $blk print(showlnio[], " "^indent*"(") show_backtrace1(showlnio[], bt) println(showlnio[], ")") end if !isempty(exs) push!(blk.args, :value) end blk end function showexprs(exs) blk = Expr(:block) for ex in exs push!(blk.args, :(println(showlnio[], " "^indent, sprint(Base.show_unquoted,$(Expr(:quote, ex)),indent)*" = ", repr(begin value=$(esc(ex)) end)))) end blk end # backtrace utilities function print_btinfo(io, frm) print(io, "in ", frm.func, " at ", frm.file, ":", frm.line) end function show_backtrace1(io, bt) st = stacktrace(bt) for frm in st funcname = frm.func if funcname != :backtrace && funcname != Symbol("macro expansion") print_btinfo(io, frm) break end end end """ `test_showline(filename)` is equivalent to `include(filename)`, except that it also displays the expression and file-offset (in characters) for each expression it executes. This can be useful for debugging errors, especially those that cause a segfault. """ function test_showline(filename) str = read(filename, String) Core.eval(Main, Meta.parse("using Test")) idx = 1 while idx < length(str) ex, idx = Meta.parse(str, idx) try println(showlnio, idx, ": ", ex) catch println(showlnio, "failed to print line starting at file-offset ", idx) end Core.eval(Main,ex) end println(showlnio, "done") end """ `time_showline(filename)` is equivalent to `include(filename)`, except that it also analyzes the time expended on each expression within the file. Once finished, it displays the file-offset (in characters), elapsed time, and expression in order of increasing duration. This can help you identify bottlenecks in execution. This is less useful now that julia has package precompilation, but can still be handy on occasion. """ function time_showline(filename) str = read(filename, String) idx = 1 exprs = Any[] t = Float64[] pos = Int[] while idx < length(str) ex, idx = Meta.parse(str, idx) push!(exprs, ex) push!(t, @elapsed Core.eval(Main,ex)) push!(pos, idx) end perm = sortperm(t) for p in perm print(showlnio[], pos[p], " ", t[p], ": ") str = string(exprs[p]) println(showlnio[], split(str, '\n')[1]) end println(showlnio[], "done") end function __init__() showlnio[] = stdout end end # module
DebuggingUtilities
https://github.com/timholy/DebuggingUtilities.jl.git
[ "MIT" ]
1.0.0
f78110dacfc8bfac774adf73570473da058bc593
code
47
# The next line is a deliberate error sqrt(-3)
DebuggingUtilities
https://github.com/timholy/DebuggingUtilities.jl.git
[ "MIT" ]
1.0.0
f78110dacfc8bfac774adf73570473da058bc593
code
263
# Note: tests are sensitive to the line numbers of statements below function foo() x = 5 @showln x x = 7 @showln x end function recurses(n) @showlnt n n += 1 @showlnt n if n < 10 n = recurses(n+1) end return n end
DebuggingUtilities
https://github.com/timholy/DebuggingUtilities.jl.git
[ "MIT" ]
1.0.0
f78110dacfc8bfac774adf73570473da058bc593
code
1491
using DebuggingUtilities using Test include("funcdefs.jl") funcdefs_path = joinpath(@__DIR__, "funcdefs.jl") @testset "DebuggingUtilities" begin io = IOBuffer() DebuggingUtilities.showlnio[] = io @test foo() == 7 str = chomp(String(take!(io))) target = ("x = 5", "(in $funcdefs_path:4)", "x = 7", "(in $funcdefs_path:6)") for (i,ln) in enumerate(split(str, '\n')) ln = lstrip(ln) @test ln == target[i] end @test recurses(1) == 10 str = chomp(String(take!(io))) lines = split(str, '\n') offset = lstrip(lines[1]).offset for i = 1:5 j = 2*i-1 k = 4*i-3 ln = String(lines[k]) lns = lstrip(ln) @test lns.offset == offset + i - 1 @test lns == "n = $j" ln = String(lines[k+1]) lns = lstrip(ln) @test lns.offset == offset + i - 1 @test lns == "(in recurses at $funcdefs_path:10)" j += 1 ln = String(lines[k+2]) lns = lstrip(ln) @test lns.offset == offset + i - 1 @test lns == "n = $j" ln = String(lines[k+3]) lns = lstrip(ln) @test lns.offset == offset + i - 1 @test lns == "(in recurses at $funcdefs_path:12)" end # Just make sure these run io = IOBuffer() DebuggingUtilities.showlnio[] = io test_showline("noerror.jl") @test_throws DomainError test_showline("error.jl") time_showline("noerror.jl") DebuggingUtilities.showlnio[] = stdout end
DebuggingUtilities
https://github.com/timholy/DebuggingUtilities.jl.git
[ "MIT" ]
1.0.0
f78110dacfc8bfac774adf73570473da058bc593
docs
3295
# DebuggingUtilities [![Build Status](https://travis-ci.org/timholy/DebuggingUtilities.jl.svg?branch=master)](https://travis-ci.org/timholy/DebuggingUtilities.jl) This package contains simple utilities that may help debug julia code. # Installation Install with ```julia pkg> dev https://github.com/timholy/DebuggingUtilities.jl.git ``` When you use it in packages, you should `activate` the project and add DebuggingUtilities as a dependency use `project> dev DebuggingUtilities`. # Usage ## @showln `@showln` shows variable values and the line number at which the statement was executed. This can be useful when variables change value in the course of a single function. For example: ```julia using DebuggingUtilities function foo() x = 5 @showln x x = 7 @showln x nothing end ``` might, when called (`foo()`), produce output like ``` x = 5 (in /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:5) x = 7 (in /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:7) 7 ``` ## @showlnt `@showlnt` is for recursion, and uses indentation to show nesting depth. For example, ```julia function recurses(n) @showlnt n n += 1 @showlnt n if n < 10 n = recurses(n+1) end return n end ``` might, when called as `recurses(1)`, generate ``` n = 1 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:10) n = 2 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:12) n = 3 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:10) n = 4 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:12) n = 5 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:10) n = 6 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:12) n = 7 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:10) n = 8 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:12) n = 9 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:10) n = 10 (in recurses at /home/tim/.julia/dev/DebuggingUtilities/test/funcdefs.jl:12) ``` Each additional space indicates one additional layer in the call chain. Most of the initial space (even for `n=1`) is due to Julia's own REPL. ## test_showline This is similar to `include`, except it displays progress. This can be useful in debugging long scripts that cause, e.g., segfaults. ## time_showline Also similar to `include`, but it also measures the execution time of each expression, and prints them in order of increasing duration.
DebuggingUtilities
https://github.com/timholy/DebuggingUtilities.jl.git
[ "MIT" ]
0.2.1
53c9f486b447ad390a87559a440ca5fe4c830643
code
253
""" Block and braille rendering of julia arrays, for terminal graphics. """ module UnicodeGraphics const DEFAULT_METHOD = :braille include("api.jl") include("ndarray.jl") include("core.jl") include("deprecate.jl") export uprint, ustring end # module
UnicodeGraphics
https://github.com/JuliaGraphics/UnicodeGraphics.jl.git
[ "MIT" ]
0.2.1
53c9f486b447ad390a87559a440ca5fe4c830643
code
3458
""" uprint([io::IO], A, [method]) Write to `io` (or to the default output stream `stdout` if `io` is not given) a binary unicode representation of `A` , filling values that are `true` or greater than zero. The printing method can be specified by passing either `:braille` or `:block`. The default is `:$DEFAULT_METHOD`. # Example ```julia-repl julia> A = rand(Bool, 8, 8) 8ร—8 Matrix{Bool}: 0 1 0 1 0 1 0 1 0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 0 1 1 0 0 0 0 1 0 0 1 0 1 1 1 0 1 1 1 0 0 julia> uprint(A) โ œโ šโฃ˜โฃš โฃ›โข†โฃบโ ฉ julia> uprint(A, :block) โ–ˆโ–„โ–ˆ โ–ˆโ–„โ–ˆ โ–€ โ–„โ–„โ–„โ–„ โ–ˆโ–ˆโ–„ โ–„โ–ˆโ–€โ–€ โ–„โ–„โ–€โ–„โ–„โ–ˆ โ–€ ``` """ uprint(A::AbstractArray, method::Symbol=DEFAULT_METHOD) = uprint(stdout, A, method) function uprint(io::IO, A::AbstractArray, method::Symbol=DEFAULT_METHOD) return uprint(io, >(zero(eltype(A))), A, method) end """ uprint([io::IO], f, A, [method]) Write to `io` (or to the default output stream `stdout` if `io` is not given) a binary unicode representation of `A` , filling values for which `f` returns `true`. The printing method can be specified by passing either `:braille` or `:block`. The default is `:$DEFAULT_METHOD`. # Example ```julia-repl julia> A = rand(1:9, 8, 8) 8ร—8 Matrix{Int64}: 9 1 6 3 4 2 9 6 4 1 2 8 2 5 9 1 7 5 6 1 1 4 8 8 4 8 3 4 8 7 8 8 4 2 2 6 2 6 1 7 9 1 4 1 8 1 6 1 3 8 4 3 9 5 5 6 1 4 4 2 8 6 3 9 julia> uprint(iseven, A) โฃ‚โข—โกซโฃฌ โขฉโฃโฃ‹โ ข julia> uprint(>(3), A, :block) โ–ˆ โ–€โ–„โ–€โ–„โ–ˆโ–€ โ–ˆโ–ˆโ–€โ–„โ–„โ–ˆโ–ˆโ–ˆ โ–ˆ โ–„โ–€โ–„โ–€โ–„โ–€ โ–ˆโ–ˆ โ–ˆโ–ˆโ–€โ–ˆ ``` """ function uprint(f::Function, A::AbstractArray, method::Symbol=DEFAULT_METHOD) return uprint(stdout, f, A, method) end function uprint(io::IO, f::Function, A::AbstractArray, method::Symbol=DEFAULT_METHOD) return _uprint_nd(io::IO, f::Function, A::AbstractArray, method::Symbol) end """ ustring(A, [method]) Return a string containing a binary unicode representation of `A` , filling values that are `true` or greater than zero. The printing method can be specified by passing either `:braille` or `:block`. The default is `:$DEFAULT_METHOD`. # Example ```julia-repl julia> A = rand(Bool, 8, 8) 8ร—8 Matrix{Bool}: 1 1 1 1 0 1 0 0 1 0 0 1 1 1 0 0 1 0 0 0 1 0 1 0 1 0 1 0 1 1 1 1 0 0 0 0 0 0 1 0 0 1 1 0 1 0 0 1 0 0 1 0 0 1 1 1 1 1 1 1 0 0 1 1 julia> ustring(A) "โกโก™โฃžโฃ„\nโฃโฃ†โ ขโฃต\n" julia> ustring(A, :block) "โ–ˆโ–€โ–€โ–ˆโ–„โ–ˆ \nโ–ˆ โ–„ โ–ˆโ–„โ–ˆโ–„\n โ–„โ–„ โ–„ โ–€โ–„\nโ–„โ–„โ–ˆโ–„ โ–€โ–ˆโ–ˆ\n" ``` """ function ustring(A::AbstractArray, method::Symbol=DEFAULT_METHOD) return ustring(>(zero(eltype(A))), A, method) end """ ustring(f, A, [method]) Return a string containing a binary unicode representation of `A`, filling values for which `f` returns `true`. The printing method can be specified by passing either `:braille` or `:block`. The default is `:$DEFAULT_METHOD`. # Example ```julia-repl julia> A = rand(1:9, 8, 8) 8ร—8 Matrix{Int64}: 8 7 9 6 9 8 3 7 9 9 3 3 5 5 3 2 1 6 8 3 7 9 3 7 9 4 4 7 8 7 3 4 3 8 7 2 2 1 6 6 4 8 9 4 1 3 4 6 4 9 6 2 3 4 8 4 7 2 7 9 8 2 6 7 julia> ustring(iseven, A) "โขกโกŒโกˆโข\nโขžโ ผโฃกโกฟ\n" julia> ustring(>(3), A, :block) "โ–ˆโ–ˆโ–€โ–€โ–ˆโ–ˆ โ–€\nโ–„โ–ˆโ–ˆโ–„โ–ˆโ–ˆ โ–ˆ\nโ–„โ–ˆโ–ˆโ–„ โ–ˆโ–ˆ\nโ–ˆโ–€โ–ˆโ–„โ–„โ–€โ–ˆโ–ˆ\n" ``` """ function ustring(f::Function, A::AbstractArray, method::Symbol=DEFAULT_METHOD) io = IOBuffer() uprint(io, f, A, method) return String(take!(io)) end
UnicodeGraphics
https://github.com/JuliaGraphics/UnicodeGraphics.jl.git
[ "MIT" ]
0.2.1
53c9f486b447ad390a87559a440ca5fe4c830643
code
1192
const BRAILLE_HEX = (0x01, 0x02, 0x04, 0x40, 0x08, 0x10, 0x20, 0x80) function to_braille(io::IO, f::Function, A::AbstractMatrix) h, w = axes(A) yrange = first(h):4:last(h) xrange = first(w):2:last(w) for y in yrange for x in xrange ch = 0x2800 for j in 0:3, i in 0:1 if checkval(f, A, y + j, x + i, h, w) @inbounds ch += BRAILLE_HEX[1 + j % 4 + 4 * (i % 2)] end end print(io, Char(ch)) end println(io) end return nothing end function to_block(io::IO, f::Function, A::AbstractMatrix) h, w = axes(A) yrange = first(h):2:last(h) for y in yrange for x in w top = checkval(f, A, y, x, h, w) bottom = checkval(f, A, y + 1, x, h, w) if top print(io, bottom ? 'โ–ˆ' : 'โ–€') else print(io, bottom ? 'โ–„' : ' ') end end println(io) end return nothing end @inline function checkval(f, a, y, x, yrange, xrange) x > last(xrange) && return false y > last(yrange) && return false return @inbounds f(a[y, x]) end
UnicodeGraphics
https://github.com/JuliaGraphics/UnicodeGraphics.jl.git
[ "MIT" ]
0.2.1
53c9f486b447ad390a87559a440ca5fe4c830643
code
118
@deprecate brailize(A, cutoff=0) ustring(>(cutoff), A) @deprecate blockize(A, cutoff=0) ustring(>(cutoff), A, :block)
UnicodeGraphics
https://github.com/JuliaGraphics/UnicodeGraphics.jl.git
[ "MIT" ]
0.2.1
53c9f486b447ad390a87559a440ca5fe4c830643
code
1274
# For matrices, directly call core.jl method matching method Symbol. function _uprint_nd(io::IO, f::Function, A::AbstractMatrix, method::Symbol) if method == :braille to_braille(io, f, A) elseif method == :block to_block(io, f, A) else throw(ArgumentError("Valid methods are :braille and :block, got :$method.")) end return nothing end # View vectors as 1xn adjoints function _uprint_nd(io::IO, f::Function, v::AbstractVector, method::Symbol) _uprint_nd(io, f, adjoint(v), method) return nothing end # For multi-dimensional arrays, iterate over tail-indices function _uprint_nd(io::IO, f::Function, A::AbstractArray, method::Symbol) axs= axes(A) tailinds = Base.tail(Base.tail(axs)) Is = CartesianIndices(tailinds) for I in Is idxs = I.I _show_nd_label(io, idxs) slice = view(A, axs[1], axs[2], idxs...) # matrix-shaped slice _uprint_nd(io, f, slice, method) print(io, idxs == map(last,tailinds) ? "" : "\n") end return nothing end # adapted from Base._show_nd_label function _show_nd_label(io::IO, idxs) print(io, "[:, :, ") for i = 1:length(idxs)-1 print(io, idxs[i], ", ") end println(io, idxs[end], "] =") return nothing end
UnicodeGraphics
https://github.com/JuliaGraphics/UnicodeGraphics.jl.git
[ "MIT" ]
0.2.1
53c9f486b447ad390a87559a440ca5fe4c830643
code
3585
using Test using ReferenceTests using Suppressor: @capture_out using UnicodeGraphics, OffsetArrays pac = [ 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 ] @test_reference "references/braille_pac.txt" ustring(pac) @test_reference "references/block_pac.txt" ustring(pac, :block) @test_reference "references/braille_pac.txt" @capture_out uprint(pac) @test_reference "references/block_pac.txt" @capture_out uprint(pac, :block) @test_throws ArgumentError ustring(pac, :foo) ghost = [ 0.0 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.0 0.0 0.0 1.0 0.0 0.0 1.0 1.0 1.0 1.0 0.0 0.0 1.0 1.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 1.0 1.0 0.0 0.0 1.0 1.0 1.0 1.0 0.0 0.0 1.0 1.0 0.0 1.0 1.0 1.0 0.0 0.0 1.0 1.0 1.0 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 0.0 0.0 1.0 1.0 1.0 1.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 0.0 1.0 1.0 1.0 0.0 0.0 1.0 1.0 1.0 0.0 1.0 1.0 1.0 0.0 0.0 0.0 1.0 1.0 0.0 0.0 1.0 1.0 0.0 0.0 0.0 1.0 ] @test_reference "references/braille_ghost.txt" ustring(ghost) @test_reference "references/block_ghost.txt" ustring(ghost, :block) offset_ghost = OffsetArray(ghost, 3:15, 4:17) @test_reference "references/braille_ghost.txt" ustring(offset_ghost) @test_reference "references/block_ghost.txt" ustring(offset_ghost, :block) ghost2 = [ 1 7 7 7 7 8 6 4 6 3 9 9 9 7 1 5 3 6 6 8 2 8 2 2 2 9 3 7 9 5 4 8 8 6 4 8 4 8 2 6 5 9 5 2 5 1 8 8 6 8 3 3 6 8 6 9 9 9 9 3 1 8 4 5 3 7 9 6 8 3 3 8 8 7 5 6 4 4 2 5 5 6 4 1 2 8 8 3 7 4 6 2 8 9 7 6 8 2 2 4 9 7 2 6 2 4 1 5 6 4 8 8 8 2 4 4 4 4 8 6 4 4 6 4 2 2 6 8 2 6 4 4 8 6 4 2 4 4 2 8 4 2 6 4 2 6 8 6 6 2 8 8 8 8 8 2 3 6 6 8 9 1 2 4 8 5 4 8 8 3 7 3 8 6 9 3 6 6 1 9 1 6 ] @test_reference "references/braille_ghost.txt" ustring(iseven, ghost2) @test_reference "references/block_ghost.txt" ustring(iseven, ghost2, :block) @test_reference "references/braille_ghost.txt" @capture_out uprint(iseven, ghost2) @test_reference "references/block_ghost.txt" @capture_out uprint(iseven, ghost2, :block) # Test vector and n-dimensional arrays v = [0, 1, 0, 1, 1, 0, 0, 1] @test ustring(v) == "โ ˆโ ˆโ โ ˆ\n" A = reshape(v, 2, 2, 1, 1, 2) @test ustring(A) == "[:, :, 1, 1, 1] =\nโ ’\n\n[:, :, 1, 1, 2] =\nโ ‘\n" # Remove deprecations before next breaking release: @test_reference "references/braille_ghost.txt" (@test_deprecated brailize(ghost)) @test_reference "references/block_ghost.txt" (@test_deprecated blockize(ghost))
UnicodeGraphics
https://github.com/JuliaGraphics/UnicodeGraphics.jl.git
[ "MIT" ]
0.2.1
53c9f486b447ad390a87559a440ca5fe4c830643
docs
1679
# UnicodeGraphics.jl ## Version `v0.2.1` * ![Feature][badge-feature] Added support for multidimensional arrays ([#7][pr-7]) ## Version `v0.2.0` * ![Feature][badge-feature] Directly write to `stdout` using `uprint(A)` or to any IO using `uprint(io, A)` ([#5][pr-5]) * ![Feature][badge-feature] Added support for filtering functions to `uprint` and `ustring`. `uprint(f, A)` shows values of `A` for which `f` returns `true` ([#5][pr-5]) * ![Deprecation][badge-deprecation] Deprecated `brailize(A)`, use `ustring(A)` or `ustring(A, :braille)` instead ([#5][pr-5]) * ![Deprecation][badge-deprecation] Deprecated `blockize(A)`, use `ustring(A, :block)` instead ([#5][pr-5]) <!-- # Badges ![BREAKING][badge-breaking] ![Deprecation][badge-deprecation] ![Feature][badge-feature] ![Enhancement][badge-enhancement] ![Bugfix][badge-bugfix] ![Experimental][badge-experimental] ![Maintenance][badge-maintenance] ![Documentation][badge-docs] --> [pr-5]: https://github.com/JuliaGraphics/UnicodeGraphics.jl/pull/5 [pr-7]: https://github.com/JuliaGraphics/UnicodeGraphics.jl/pull/7 [badge-breaking]: https://img.shields.io/badge/BREAKING-red.svg [badge-deprecation]: https://img.shields.io/badge/deprecation-orange.svg [badge-feature]: https://img.shields.io/badge/feature-green.svg [badge-enhancement]: https://img.shields.io/badge/enhancement-blue.svg [badge-bugfix]: https://img.shields.io/badge/bugfix-purple.svg [badge-security]: https://img.shields.io/badge/security-black.svg [badge-experimental]: https://img.shields.io/badge/experimental-lightgrey.svg [badge-maintenance]: https://img.shields.io/badge/maintenance-gray.svg [badge-docs]: https://img.shields.io/badge/docs-orange.svg
UnicodeGraphics
https://github.com/JuliaGraphics/UnicodeGraphics.jl.git
[ "MIT" ]
0.2.1
53c9f486b447ad390a87559a440ca5fe4c830643
docs
3569
# UnicodeGraphics [![Build Status](https://travis-ci.org/rafaqz/UnicodeGraphics.jl.svg?branch=master)](https://travis-ci.org/rafaqz/UnicodeGraphics.jl) [![codecov.io](http://codecov.io/github/rafaqz/UnicodeGraphics.jl/coverage.svg?branch=master)](http://codecov.io/github/rafaqz/UnicodeGraphics.jl?branch=master) Convert any matrix into a braille or block Unicode string, real fast and dependency free. ## Installation This package supports Julia โ‰ฅ1.6. To install it, open the Julia REPL and run ```julia-repl julia> ]add UnicodeGraphics ``` ## Examples By default, `uprint` prints all values in an array that are true or greater than zero: ```julia julia> pac = [ 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 0 0 0 0 0 0 0 ]; julia> uprint(pac) # same as uprint(pac, :braille) โ €โฃ โฃดโฃพโฃฟโฃฟโฃทโฃฆโฃ„โ € โฃฐโฃฟโฃฟโฃฟโฃงโฃผโฃฟโกฟโ Ÿโ ƒ โฃฟโฃฟโฃฟโฃฟโฃฟโฃโกโ €โ €โ   โ นโฃฟโฃฟโฃฟโฃฟโฃฟโฃฟโฃทโฃฆโก„ โ €โ ™โ ปโขฟโฃฟโฃฟโกฟโ Ÿโ ‹โ € julia> uprint(pac, :block) โ–„โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–„ โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–„ โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ โ–„โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–€ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–€ โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–„ โ–€ โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–„โ–„ โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–€ โ–€โ–€โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–€โ–€ ``` It is also possible to pass a filtering function, filling values for which the function returns `true`, e.g. all even numbers in the following array: ```julia julia> ghost = [ 1 7 7 7 7 8 6 4 6 3 9 9 9 7 1 5 3 6 6 8 2 8 2 2 2 9 3 7 9 5 4 8 8 6 4 8 4 8 2 6 5 9 5 2 5 1 8 8 6 8 3 3 6 8 6 9 9 9 9 3 1 8 4 5 3 7 9 6 8 3 3 8 8 7 5 6 4 4 2 5 5 6 4 1 2 8 8 3 7 4 6 2 8 9 7 6 8 2 2 4 9 7 2 6 2 4 1 5 6 4 8 8 8 2 4 4 4 4 8 6 4 4 6 4 2 2 6 8 2 6 4 4 8 6 4 2 4 4 2 8 4 2 6 4 2 6 8 6 6 2 8 8 8 8 8 2 3 6 6 8 9 1 2 4 8 5 4 8 8 3 7 3 8 6 9 3 6 6 1 9 1 6 ]; julia> uprint(iseven, ghost) โข€โ ดโฃพโฃฟโ ทโฃฆโก€ โฃดโ †โฃธโฃทโ †โฃธโฃง โฃฟโขฟโฃฟโ ฟโฃฟโกฟโฃฟ โ โ €โ ‰โ €โ ‰โ €โ ˆ ``` Non-number type inputs are also supported, as long as the filtering function returns boolean values: ```julia-repl julia> A = rand("abc123", 4, 4) 4ร—4 Matrix{Char}: '3' 'c' '3' '1' 'a' 'c' '1' 'c' '1' '1' '2' 'a' 'b' 'a' '2' 'a' julia> uprint(isletter, A, :block) โ–„โ–ˆ โ–„ โ–„โ–„ โ–ˆ ``` Multidimensional arrays are also supported: ```julia-repl julia> A = rand(Bool, 4, 4, 1, 2) 4ร—4ร—1ร—2 Array{Bool, 4}: [:, :, 1, 1] = 0 1 0 0 1 0 1 0 0 1 1 1 0 0 1 1 [:, :, 1, 2] = 1 1 0 0 1 1 0 0 0 0 1 0 0 0 1 0 julia> uprint(A, :block) [:, :, 1, 1] = โ–„โ–€โ–„ โ–€โ–ˆโ–ˆ [:, :, 1, 2] = โ–ˆโ–ˆ โ–ˆ ``` `uprint` can be used to write into any `IO` stream, defaulting to `stdout`. ```julia-repl julia> io = IOBuffer(); julia> uprint(io, pac) julia> String(take!(io)) |> print โ €โฃ โฃดโฃพโฃฟโฃฟโฃทโฃฆโฃ„โ € โฃฐโฃฟโฃฟโฃฟโฃงโฃผโฃฟโกฟโ Ÿโ ƒ โฃฟโฃฟโฃฟโฃฟโฃฟโฃโกโ €โ €โ   โ นโฃฟโฃฟโฃฟโฃฟโฃฟโฃฟโฃทโฃฆโก„ โ €โ ™โ ปโขฟโฃฟโฃฟโกฟโ Ÿโ ‹โ € ``` To directly return a string instead of printing to IO, `ustring` can be used: ```julia-repl julia> ustring(pac) "โ €โฃ โฃดโฃพโฃฟโฃฟโฃทโฃฆโฃ„โ €\nโฃฐโฃฟโฃฟโฃฟโฃงโฃผโฃฟโกฟโ Ÿโ ƒ\nโฃฟโฃฟโฃฟโฃฟโฃฟโฃโกโ €โ €โ  \nโ นโฃฟโฃฟโฃฟโฃฟโฃฟโฃฟโฃทโฃฆโก„\nโ €โ ™โ ปโขฟโฃฟโฃฟโกฟโ Ÿโ ‹โ €\n" ```
UnicodeGraphics
https://github.com/JuliaGraphics/UnicodeGraphics.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
515
using Polymer using Documenter makedocs(; modules=[Polymer], authors="Yi-Xin Liu <[email protected]> and contributors", repo="https://github.com/liuyxpp/Polymer.jl/blob/{commit}{path}#L{line}", sitename="Polymer.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://liuyxpp.github.io/Polymer.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/liuyxpp/Polymer.jl", )
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
3821
module Polymer using LinearAlgebra using ArgCheck using REPL: symbol_latex using LaTeXStrings using Configurations using YAML using Setfield include("utils.jl") export unicodesymbol2string, reverse_dict include("parameters.jl") export AbstractParameter, PolymerParameter export ฯ‡Type, NType, ฯ‡NType, fType, ฯ•Type, RgType, CType, bType, ฮฑType, ฯ„Type, ฯ‡Param, NParam, ฯ‡NParam, fParam, ฯ•Param, RgParam, CParam, bParam, ฮฑParam, ฯ„Param, DEFAULT_PARAMETERS export description, value_type, variable_symbol, as_variable_name, as_ascii_label, as_plot_label include("chiN.jl") export Abstractฯ‡NMatrix, ฯ‡NMatrix # Not exported but useful: # ฯ‡N, ฯ‡Nmap include("types.jl") export PolymerSystemType, NeatPolymer, PolymerBlend, PolymerSolution export ComponentNumberType, MonoSystem, BinarySystem, TernarySystem, MultiComponentSystem export SpecieNumberType, SingleSpecieSystem, TwoSpeciesSystem, MultiSpeciesSystem export SpaceDimension, D1, D2, D3 export ConfinementType, BulkConfinement, BoxConfinement, SlabConfinement, DiskConfinement, SphereConfinement, CylinderConfinement export ChargedType, Neutral, SmearedCharge, DiscreteCharge export BlockEnd, FreeEnd, BranchPoint, PolymerBlock export AbstractSpecie, KuhnSegment export AbstractMolecule, SmallMolecule, AbstractPolymer, BlockCopolymer, RandomCopolymer, AlternatingCopolymer, Particle, GiantMolecule export AbstractComponent, Component, AbstractSystem, PolymerSystem include("control_parameters.jl") export AbstractControlParameter, ฯ•ControlParameter, ฮฑControlParameter, fControlParameter, ฯ‡NControlParameter, bControlParameter include("properties.jl") export isconfined, ischarged, isfreeblockend, multicomponent, ncomponents, specie, species, nspecies, nblocks, systemtype, component_number_type, specie_number_type, component_label, component_labels, component_id, component_ids, molecule_id, molecule_ids, molecule_label, molecule_labels, block_id, block_ids, block_label, block_labels, block_length, block_lengths, block_specie, block_species, block_b, block_bs # not exported but useful functions: # ฯ•, ฯ•s, ฮฑ, ฮฑs, molecules, molecule, # blocks, block # getparam include("systems.jl") export branchpoints, freeends, homopolymer_chain, diblock_chain, linearABC, solvent, AB_system, ABC_system, A_B_system, AB_A_system, AB_A_B_system, AB_S_system, A_B_S_system, A_B_S1_S2_system include("config.jl") export SpecieConfig, BlockConfig, BlockCopolymerConfig, ComponentConfig, PolymerSystemConfig include("make.jl") export ObjType export load_config, save_config, make include("serialize.jl") export specie_object, specie_objects, to_config, from_config include("update.jl") # update! is not exported because of possible name confilication # setparam! is an alias of update! import PrecompileTools: @setup_workload, @compile_workload @setup_workload begin system = AB_A_system() @compile_workload begin ฯ•Ac = ฯ•ControlParameter(:hA, system) fc = fControlParameter(:B, :AB, system) ฮฑc = ฮฑControlParameter(:AB, system) ฯ‡Nc = ฯ‡NControlParameter(:A, :B, system) bc = bControlParameter(:A, bParam) update!(system, 0.6, ฯ•Ac) update!(system, 0.2, fc) update!(system, 0.3, ฮฑc) update!(system, 2.0, ฯ‡Nc) update!(system, 0.5, bc) end end end # module
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
4283
abstract type Abstractฯ‡NMatrix{T} <: AbstractMatrix{T} end struct ฯ‡NMatrix{T} <: Abstractฯ‡NMatrix{T} map::Dict{Set{Symbol}, T} mat::Matrix{T} imat::Matrix{T} # the inverse of mat end function _species(map::Dict{Set{Symbol}, T}) where T<:Real sps = Symbol[] for key in keys(map) append!(sps, key) end return unique(sps) |> sort end function _check_consistency(map::Dict{Set{Symbol}, T}) where T<:Real # Now sps is a list of sorted and unique symbols. # which make sure following loops sp1 and sp2 are distinct. sps = _species(map) for i in 1:length(sps) sp1 = sps[i] for j in (i+1):length(sps) sp2 = sps[j] !haskey(map, Set((sp1,sp2))) && return false end end return true end function _ฯ‡Nmap_to_matrix(map::Dict{Set{Symbol}, T}) where T<:Real _check_consistency(map) || error("Full map of interactions should be specified!") sps = _species(map) nc = length(sps) mat = zeros(T, nc, nc) for i in 1:nc sp1 = sps[i] for j in (i+1):nc sp2 = sps[j] ฯ‡N = map[Set((sp1,sp2))] mat[i, j] = ฯ‡N mat[j, i] = ฯ‡N end end r = rank(mat) (r == size(mat)[1]) || error("ฯ‡N map is singular! Possible indistinguishable speices are presented in the map. Consider to combine them.") return mat end function ฯ‡NMatrix(map::Dict{Set{Symbol}, T}) where T<:Real mat = _ฯ‡Nmap_to_matrix(map) imat = inv(mat) e1 = first(imat) mapnew = Dict(keys(map) .=> [promote(v, e1)[1] for v in values(map)]) return ฯ‡NMatrix(mapnew, promote(mat, imat)...) end """ ฯ‡NMatrix(m) Convert a dictionary of interaction pairs to an interaction matrix. The input argument `m` can be a dictionary of `Dict{Tuple{Symobl}, <:Real}`, `Dict{Tuple{String}, <:Real}`, `Dict{<:AbstractArray{Symbol}, <:Real}`, `Dict{<:AbstractArray{String}, <:Real}`. Example: ```julia map = Dict((:A, :B)=>10.0, (:A, :C)=>20.0, (:B, :C)=>30.0) map = Dict(("A", "B")=>10.0, ("A", "C")=>20.0, ("B", "C")=>30.0) map = Dict([:A, :B]=>10, [:A, :C]=>10.0, [:B, :C]=>20.0) map = Dict(["A", "B"]=>10.0, ["A", "C"]=>20.0, ["B", "C"]=>30.0) ``` """ function ฯ‡NMatrix(m) mapnew = Dict(Set.([Symbol.(k) for k in keys(m)]) .=> promote(values(m)...)) return ฯ‡NMatrix(mapnew) end species(m::ฯ‡NMatrix) = _species(m.map) Base.size(A::ฯ‡NMatrix) = size(A.mat) Base.getindex(A::ฯ‡NMatrix, i::Int) = getindex(A.mat, i) Base.getindex(A::ฯ‡NMatrix, I::Vararg{Int, N}) where N = getindex(A.mat, I...) Base.getindex(::ฯ‡NMatrix{T}, ::Symbol) where T = zero(T) function Base.getindex(A::ฯ‡NMatrix{T}, sp1::Symbol, sp2::Symbol) where T (sp1 == sp2) && return zero(T) return A.map[Set((sp1, sp2))] end function _setindex!(A::ฯ‡NMatrix, v, sp1::Symbol, sp2::Symbol) A.map[Set((sp1, sp2))] = v # call _ฯ‡Nmap_to_matrix to validate the matrix mat = _ฯ‡Nmap_to_matrix(A.map) # If no error, set the value # update the inverse matrix A.mat .= mat A.imat .= inv(mat) end function _setindex!(A::ฯ‡NMatrix, v, i, j) # Do not set value for j = k (i == j) && return nothing sps = _species(A.map) _setindex!(A, v, sps[i], sps[j]) end function Base.setindex!(A::ฯ‡NMatrix, v, i::Int) j, k = Tuple(CartesianIndices(A)[i]) _setindex!(A, v, j, k) return nothing end function Base.setindex!(A::ฯ‡NMatrix, v, i::Int, j::Int) _setindex!(A, v, i, j) return nothing end Base.setindex!(::ฯ‡NMatrix, v, ::Symbol) = nothing function Base.setindex!(A::ฯ‡NMatrix, v, sp1::Symbol, sp2::Symbol) _setindex!(A, v, sp1, sp2) end Base.eltype(::ฯ‡NMatrix{T}) where T = T Base.showarg(io::IO, A::ฯ‡NMatrix, toplevel) = print(io, typeof(A), " of species: ", _species(A.map)) function Base.show(io::IO, m::ฯ‡NMatrix) println(io, "Flory-Huggins interaction parameters betwen species:") for (k, v) in m.map sp1, sp2 = k println(io, " ($sp1, $sp2) => $v") end end function Base.show(io::IO, ::MIME"text/plain", m::ฯ‡NMatrix) println(io, "Flory-Huggins interaction parameters between species:") for (k, v) in m.map sp1, sp2 = k println(io, " ($sp1, $sp2) => $v") end println(io, "as a matrix:") show(io, "text/plain", m.mat) end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
1727
@option struct SpecieConfig label::Symbol=:A "Can be: :Segment, :Small" type::Symbol=:Segment b::Float64=1.0 M::Union{Float64, Nothing}=nothing end @option struct BlockConfig label::Symbol=:A segment::Symbol=:A length::Float64=0.5 ends::Vector{Symbol}=[:AB] end @option struct BlockCopolymerConfig label::Symbol=:BCP species::Vector{SpecieConfig}=SpecieConfig[] blocks::Vector{BlockConfig}=BlockConfig[] end @option struct ComponentConfig "Can be: :BCP, :SMOL" type::Symbol=:BCP label::Symbol=:AB length::Float64=1.0 volume_fraction::Float64=1.0 blocks::Vector{BlockConfig}=BlockConfig[] end @option struct PolymerSystemConfig label::Union{String, Nothing}=nothing species::Vector{SpecieConfig}=[SpecieConfig(), SpecieConfig(; label=:B)] ฯ‡N_map::Vector{Vector{Any}}=[[:A, :B, 20.0]] components::Vector{ComponentConfig}=[ComponentConfig(; blocks=[BlockConfig(), BlockConfig(; label=:B, segment=:B)])] chain_density::Float64=1.0 end Configurations.from_dict(::Type{SpecieConfig}, ::Type{Symbol}, s) = Symbol(s) Configurations.from_dict(::Type{ComponentConfig}, ::Type{Symbol}, s) = Symbol(s) Configurations.from_dict(::Type{BlockConfig}, ::Type{Symbol}, s) = Symbol(s) Configurations.from_dict(::Type{BlockCopolymerConfig}, ::Type{Symbol}, s) = Symbol(s) "`top` is the key of the top level of the config in the yaml." function load_config(yamlfile, T=PolymerSystemConfig; top=nothing) d = YAML.load_file(yamlfile; dicttype=Dict{String, Any}) d = isnothing(top) ? d : d[top] return from_dict(T, d) end function save_config(yamlfile, config) d = to_dict(config, YAMLStyle) return YAML.write_file(yamlfile, d) end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
4898
""" AbstractControlParameter provides a unified interface to represent a control parameter for a polymer system. The control parameter can be varied to change the properties of a polymer system. Concrete types include: * ฯ•ControlParameter * ฮฑControlParameter * fControlParameter * ฯ‡NControlParameter * bControlParameter The functor of each concrete type will return either a list or a scalar values of the parameters which fully detemines its setting. """ abstract type AbstractControlParameter end struct ฯ•ControlParameter{F<:Function} <: AbstractControlParameter id::Integer # the unique id for a molecule in a polymer system param::ฯ•Type func::F end """ Default function is for binary system. """ function ฯ•ControlParameter(id::Integer, param::ฯ•Type=ฯ•Param, func=(ฯ•)->[one(ฯ•)-ฯ•]) ฯ•s = func(0.1) @argcheck sum(ฯ•s) + 0.1 == 1.0 "func should return a vector with a sum equal to 1!" return ฯ•ControlParameter(id, param, func) end function ฯ•ControlParameter(label::Symbol, s::PolymerSystem; param::ฯ•Type=ฯ•Param, func=(ฯ•)->[one(ฯ•)-ฯ•]) id = molecule_id(label, s) @argcheck !isnothing(id) "$label is not a component label!" return ฯ•ControlParameter(id, param, func) end """ This functor produce a vector of ฯ• whose order is assumed to be consistent with the polymer system it acts on. """ (c::ฯ•ControlParameter)(ฯ•) = insert!(c.func(ฯ•), c.id, ฯ•) struct ฮฑControlParameter <: AbstractControlParameter id::Integer # the unique id for a molecule in a polymer system param::ฮฑType end ฮฑControlParameter(id, param::ฮฑType=ฮฑParam) = ฮฑControlParameter(id, param) function ฮฑControlParameter(label::Symbol, s::PolymerSystem; param::ฮฑType=ฮฑParam) id = molecule_id(label, s) @argcheck !isnothing(id) "$label is not a component label!" return ฮฑControlParameter(id, param) end (::ฮฑControlParameter)(ฮฑ) = ฮฑ """ Set([sp1, sp2]) will determine which ฯ‡N is the control parameter. For example, sp1=:A, sp2=:B, ฯ‡_AB N will be the control parameter. """ struct ฯ‡NControlParameter <: AbstractControlParameter sp1::Symbol # the unique name for the specie of a polymer system sp2::Symbol # the unique name for the specie of a polymer system param::ฯ‡NType end ฯ‡NControlParameter(sp1, sp2, param::ฯ‡NType=ฯ‡NParam) = ฯ‡NControlParameter(sp1, sp2, param) function ฯ‡NControlParameter(sp1::Symbol, sp2::Symbol, s::PolymerSystem; param::ฯ‡NType=ฯ‡NParam) @argcheck sp1 โˆˆ species(s) "$sp1 is not a specie in the polymer system!" @argcheck sp2 โˆˆ species(s) "$sp2 is not a specie in the polymer system!" return ฯ‡NControlParameter(sp1, sp2, param) end (::ฯ‡NControlParameter)(ฯ‡N) = ฯ‡N struct fControlParameter{F<:Function} <: AbstractControlParameter id_block::Integer # the unique id for a block in a molecule id_mol::Integer # the unique id for a molecule in a polymer system param::fType func::F end """ Default function is for diblock copolymer. """ function fControlParameter(id_block, id_mol, param::fType=fParam, func=(f)->[one(f)-f]) fs = func(0.1) @argcheck sum(fs) + 0.1 == 1.0 "func should return a vector with a sum equal to 1!" return fControlParameter(id_block, id_mol, param, func) end function fControlParameter(id_block::Integer, label::Symbol, s::PolymerSystem; param::fType=fParam, func=(f)->[one(f)-f]) id_mol = molecule_id(label, s) @argcheck !isnothing(id_mol) "$label is not a component label!" @argcheck 0 < id_block <= nblocks(molecule(id_mol, s)) "Polymer block #$id_block is not in the polymer component!" return fControlParameter(id_block, id_mol, param, func) end function fControlParameter(label_block::Symbol, label_mol::Symbol, s::PolymerSystem; param::fType=fParam, func=(f)->[one(f)-f]) id_mol = molecule_id(label_mol, s) @argcheck !isnothing(id_mol) "$label_mol is not a component label!" id_block = block_id(label_block, molecule(id_mol, s)) @argcheck !isnothing(id_block) "Polymer block $label_block is not in the polymer component!" return fControlParameter(id_block, id_mol, param, func) end """ This functor produce a vector of f whose order is assumed to be consistent with the molecule it acts on. """ (c::fControlParameter)(f) = insert!(c.func(f), c.id_block, f) struct bControlParameter <: AbstractControlParameter sp::Symbol # the unique name for the specie of a polymer system param::bType end bControlParameter(sp, param::bType=bParam) = bControlParameter(sp, param) function bControlParameter(sp::Symbol, s::PolymerSystem; param::bType=bParam) @argcheck sp โˆˆ species(s) "$sp is not a specie in the polymer system!" return bControlParameter(sp, param) end (::bControlParameter)(b) = b
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
6886
using Random: randstring """ load_config(yamlfile) Load configurations which directs creation of a polymer system and its components from a YAML file given at `yamlfile`. The configurations are stored in a nested Dicts. """ # load_config(yamlfile) = YAML.load_file(yamlfile) """ ObjType{name} A type representing the type of an object defined in Polymer.jl. A `ObjType` object can be passed to the first argument of [`make`](@ref) to dispatch to the correction version of this method to create an object designated by `name`: * :System: PolymerSystem * :Component: Component * :ฯ‡N_map: Dict{Set{Symbol},AbstractFloat} * :Specie: AbstractSpecie (KuhnSegment) and SmallMolecule * :SMOL: SmallMolecule * :BCP: BlockCopolymer * :Block: PolymerBlock * :BlockEnd: BlockEnd (FreeEnd and BranchPoint) """ struct ObjType{name} end function make(::ObjType{:BlockEnd}, config) if isempty(config) return FreeEnd(Symbol(randstring(3))), FreeEnd(Symbol(randstring(3))) end if length(config) == 1 return FreeEnd(Symbol(randstring(3))), BranchPoint(Symbol(config[1])) end e1, e2 = Symbol.(config) return BranchPoint(e1), BranchPoint(e2) end function make(::ObjType{:Block}, config, sps) label = Symbol(config["label"]) if haskey(config, "segment") && !isnothing(config["segment"]) slabel = Symbol(config["segment"]) else slabel= label end segment = nothing for sp in sps if sp.label == slabel segment = sp continue end end f = config["length"] E1, E2 = make(ObjType{:BlockEnd}(), config["ends"]) return PolymerBlock(label, segment, f, E1, E2) end function make(::ObjType{:BCP}, config, sps) label = Symbol(config["label"]) blocks = [make(ObjType{:Block}(), c, sps) for c in config["blocks"]] return BlockCopolymer(label, blocks) end function make(::ObjType{:SMOL}, config, sps) label = Symbol(config["label"]) for sp in sps if sp.label == label return sp end end end function make(::ObjType{:Component}, config, sps) molecule = make(ObjType{Symbol(config["type"])}(), config, sps) kwargs = Dict() if haskey(config, "length") kwargs[:ฮฑ] = config["length"] end if haskey(config, "volume_fraction") kwargs[:ฯ•] = config["volume_fraction"] end return Component(molecule; kwargs...) end function make(::ObjType{:Specie}, config) label = Symbol(config["label"]) kwargs = Dict() if haskey(config, "b") && !isnothing(config["b"]) kwargs[:b] = config["b"] end if haskey(config, "M") && !isnothing(config["M"]) kwargs[:M] = config["M"] end if haskey(config, "type") t = config["type"] else t = "Segment" end if t == "Segment" return KuhnSegment(label; kwargs...) else return SmallMolecule(label; kwargs...) end end function make(::ObjType{:ฯ‡N_map}, config) sp1, sp2, ฯ‡N = first(config) ฯ‡N_map = Dict{Set{Symbol}, eltype(ฯ‡N)}() for a in config s1, s2, ฯ‡N = a ฯ‡N_map[Set([Symbol(s1), Symbol(s2)])] = ฯ‡N end return ฯ‡N_map end """ make(::ObjType{:System}, config) Make an `PolymerSystem` object. Note: `confinement` is not implmented. """ function make(::ObjType{:System}, config) sps = [make(ObjType{:Specie}(), c) for c in config["species"]] components = [make(ObjType{:Component}(), c, sps) for c in config["components"]] kwargs = Dict() if haskey(config, "ฯ‡N_map") ฯ‡N_map = make(ObjType{:ฯ‡N_map}(), config["ฯ‡N_map"]) else error("Must provide an interaction map.") end if haskey(config, "chain_density") kwargs[:C] = config["chain_density"] end return PolymerSystem(components, ฯ‡N_map; kwargs...) end make(config) = make(ObjType{:System}(), config) function make(config::SpecieConfig) label = config.label kwargs = isnothing(config.M) ? (; b=config.b) : (; b=config.b, M=config.M) (config.type == :Segment) && return KuhnSegment(label; kwargs...) (config.type == :Small) && return SmallMolecule(label; kwargs...) error("Unknown specie type!") end function make(config::BlockConfig, sps) i = findfirst(sp -> sp.label == config.segment, sps) isnothing(i) && error("No specie found for block!") label = config.label if isempty(config.ends) E1, E2 = FreeEnd(Symbol(randstring(3))), FreeEnd(Symbol(randstring(3))) elseif length(config.ends) == 1 E1, E2 = FreeEnd(Symbol(randstring(3))), BranchPoint(config.ends[1]) else E1, E2 = BranchPoint(config.ends[1]), BranchPoint(config.ends[2]) end return PolymerBlock(label, sps[i], config.length, E1, E2) end function make(config::ComponentConfig, sps) (config.type โˆˆ [:BCP, :SMOL]) || error("Only BCP and SMOL is allowed for molecule type!") (config.type == :BCP && isempty(config.blocks)) && error("At least one block is expected for a block copolymer!") if config.type == :SMOL i = findfirst(sp -> sp.label == config.label, sps) isnothing(i) && error("No specie found for small molecule found!") molecule = sps[i] else blocks = make.(config.blocks, Ref(sps)) molecule = BlockCopolymer(config.label, blocks) end return Component(molecule; ฮฑ=config.length, ฯ•=config.volume_fraction) end function _make_ฯ‡Nmap(config) ฯ‡N_map = Dict{Set{Symbol}, Float64}() for a in config s1, s2, ฯ‡N = a ฯ‡N_map[Set([Symbol(s1), Symbol(s2)])] = ฯ‡N end return ฯ‡N_map end function make(config::PolymerSystemConfig) sps = make.(config.species) components = make.(config.components, Ref(sps)) ฯ‡N_map = _make_ฯ‡Nmap(config.ฯ‡N_map) return PolymerSystem(components, ฯ‡N_map; C=config.chain_density) end function KuhnSegment(config::SpecieConfig) sp = make(config) (sp isa SmallMolecule) && error("Configuration is for SmallMolecule!") return sp end function SmallMolecule(config::SpecieConfig) sp = make(config) (sp isa KuhnSegment) && error("Configuration is for KuhnSegment!") return sp end function BlockCopolymer(config::ComponentConfig, sps) mol = make(config, sps).molecule (mol isa SmallMolecule) && error("Configuration is for SmallMolecule!") return mol end function BlockCopolymer(config::BlockCopolymerConfig) sps = make.(config.species) blocks = make.(config.blocks, Ref(sps)) return BlockCopolymer(config.label, blocks) end function SmallMolecule(config::ComponentConfig, sps) mol = make(config, sps).molecule (mol isa BlockCopolymer) && error("Configuration is for BlockCopolymer") return mol end PolymerBlock(config::BlockConfig, sps) = make(config, sps) Component(config::ComponentConfig, sps) = make(config, sps) PolymerSystem(config::PolymerSystemConfig) = make(config)
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
5004
""" ## Parameteric types * `T`: should be a symbol to identify the parameter. * `R`: the value type of the parameter. """ abstract type AbstractParameter{T,R} end """ PolymerParameter{T, R} <: AbstractParameter Type represents phyiscal parameters of a polymer system. Each type with a specific T (normally a symbol) defines a parameter. E.g. ```julia PolymerParameter{:ฯ•} # define the ฯ• parameter ``` Pre-defined parameter symbols: * ฯ‡: Flory-Huggins interaction parameters. * N: chain length in number of monomers or Kuhn segments. * f: volume fraction of a block in a block copolymer. * ฯ•: volume fraction of a type of chain in a polymer system. * Rg: radius of gyration of a polymer chain. * C: chain density C = ฯโ‚€Rg^3/N. * b: length of a monomer or a Kuhn segment. * ฮฑ: chain length of a chain with respect to a reference chain. * ฯ„: ratio of length of two or more blocks. Fields * `description`: a description of the parameter. * `variable_name`: a string representation of the parameter which can be used as Julia variable name. * `ascii_label`: a label with pure ascii characters which shall be used for file names, directory names, etc. * `plot_label`: a LaTeXStrings used as label for plotting. * `value_type`: the number type of the parameter, e.g. integer, float, complex, etc. * `allowed_min`: minimum value allowed. If negative infinity, using `typemin(Type)`. * `allowed_max`: maximum value allowed. If positive infinity, using `typemax(Type)`. * `allowed_values`: only used for discrete finite set. If the allowed values are infinite, use `allowed_min` and `allowed_max` instead. * `disallowed_values`: an array of values which are invalid. User can define their own parameter symbols as long as they also define following two field values. Other fields are deduced automatically from parametric type `T`. * `description` * `plot_label` """ struct PolymerParameter{T, R<:Real} <: AbstractParameter{T,R} description::String variable_name::String ascii_label::String plot_label::LaTeXString value_type::Type{R} allowed_min::Union{R, typeof(Inf)} allowed_max::Union{R, typeof(Inf)} allowed_values::AbstractVector{R} disallowed_values::AbstractVector{R} function PolymerParameter{T}(desc, plot_label, value_type::Type{R}; allowed_min=-Inf, allowed_max=Inf, allowed_values=R[], disallowed_values=R[]) where {T, R<:Real} varname = String(T) ascii_label = "" for c in varname ascii_label *= unicodesymbol2string(c) end new{T, R}(desc, varname, ascii_label, plot_label, value_type, allowed_min, allowed_max, allowed_values, disallowed_values) end end """ A list of pre-defined polymer parameters. """ const ฯ‡Type = PolymerParameter{:ฯ‡, <:Real} const NType = PolymerParameter{:N, <:Real} const ฯ‡NType = PolymerParameter{:ฯ‡N, <:Real} const fType = PolymerParameter{:f, <:Real} const ฯ•Type = PolymerParameter{:ฯ•, <:Real} const RgType = PolymerParameter{:Rg, <:Real} const CType = PolymerParameter{:C, <:Real} const bType = PolymerParameter{:b, <:Real} const ฮฑType = PolymerParameter{:ฮฑ, <:Real} const ฯ„Type = PolymerParameter{:ฯ„, <:Real} const ฯ‡Param = PolymerParameter{:ฯ‡}( "Flory-Huggins Interaction Parameter.", L"\chi", Float64) const NParam = PolymerParameter{:N}( "Chain length in number of monomers or Kuhn segments.", L"N", Int; allowed_min=zero(Int)) const ฯ‡NParam = PolymerParameter{:ฯ‡N}( "Flory-Huggins Interaction Parameter times N.", L"\chi N", Float64) const fParam = PolymerParameter{:f}( "Volume fraction of a block in a block copolymer.", L"f", Float64; allowed_min=0, allowed_max=1) const ฯ•Param = PolymerParameter{:ฯ•}( "volume fraction of a type of chain in a polymer system.", L"\phi", Float64; allowed_min=0, allowed_max=1) const RgParam = PolymerParameter{:Rg}( "Radius of gyration of a polymer chain.", L"R_g", Float64; allowed_min=0) const CParam = PolymerParameter{:C}( "Chain density C = ฯโ‚€Rg^3/N.", L"C", Float64; allowed_min=0) const bParam = PolymerParameter{:b}( "Length of a monomer or a Kuhn segment.", L"b", Float64; allowed_min=0) const ฮฑParam = PolymerParameter{:ฮฑ}( "Chain length of a chain with respect to a reference chain.", L"\alpha", Float64; allowed_min=0) const ฯ„Param = PolymerParameter{:ฯ„}( "Ratio of length of two or more blocks.", L"\tau", Float64; allowed_min=0) const DEFAULT_PARAMETERS = Dict( :ฯ‡ => ฯ‡Param, :N => NParam, :ฯ‡N => ฯ‡NParam, :f => fParam, :ฯ• => ฯ•Param, :Rg => RgParam, :C => CParam, :b => bParam, :ฮฑ => ฮฑParam, :ฯ„ => ฯ„Param, ) """ Accessors for the `PolymerParameter` type. """ description(p::AbstractParameter) = p.description value_type(p::AbstractParameter) = p.value_type variable_symbol(::AbstractParameter{T,R}) where {T,R} = T as_variable_name(p::AbstractParameter) = p.variable_name as_ascii_label(p::AbstractParameter) = p.ascii_label as_plot_label(p::AbstractParameter) = p.plot_label
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
8668
specie_object(m::SmallMolecule) = m specie_object(b::PolymerBlock) = b.segment specie_objects(bcp::BlockCopolymer) = specie_object.(bcp.blocks) |> unique specie_objects(m::SmallMolecule) = [m] specie_objects(c::Component) = specie_objects(c.molecule) function specie_objects(s::PolymerSystem) species = Any[] for c in s.components append!(species, specie_objects(c)) end return unique(species) end isconfined(::BulkConfinement) = false isconfined(::ConfinementType) = true isconfined(s::PolymerSystem) = isconfined(s.confinement) ischarged(::Neutral) = false ischarged(::ChargedType) = true ฯ‡N(s::PolymerSystem, sp1::Symbol, sp2::Symbol) = s.ฯ‡Nmatrix[sp1, sp2] ฯ‡Nmap(s::PolymerSystem) = s.ฯ‡Nmatrix.map ฯ‡Nmatrix(s::PolymerSystem) = s.ฯ‡Nmatrix multicomponent(s::PolymerSystem) = length(s.components) == 1 ? false : true ncomponents(s::PolymerSystem) = length(s.components) specie(s::AbstractSpecie) = s.label specie(m::SmallMolecule) = m.label specie(b::PolymerBlock) = specie(b.segment) species(c::BlockCopolymer) = [specie(b) for b in c.blocks] |> unique |> sort nspecies(c::BlockCopolymer) = species(c) |> length species(m::SmallMolecule) = [specie(m)] nspecies(m::SmallMolecule) = 1 function _species(components) sps = Symbol[] for c in components append!(sps, species(c)) end return unique(sps) |> sort end species(c::Component) = species(c.molecule) nspecies(c::Component) = species(c) |> length species(s::PolymerSystem) = _species(s.components) nspecies(s::PolymerSystem) = species(s) |> length function systemtype(s::PolymerSystem) if !multicomponent(s) return NeatPolymer() end for c in s.components if c.molecule isa SmallMolecule return PolymerSolution() end end return PolymerBlend() end function component_number_type(s::PolymerSystem) nc = ncomponents(s) if nc == 1 t = MonoSystem() elseif nc == 2 t = BinarySystem() elseif nc == 3 t = TernarySystem() else t = MultiComponentSystem() end return t end function _specie_number_type(ns) if ns == 1 t = SingleSpecieSystem() elseif ns == 2 t = TwoSpeciesSystem() else t = MultiSpeciesSystem() end return t end function specie_number_type(bcp::BlockCopolymer) return _specie_number_type(nspecies(bcp)) end function specie_number_type(s::PolymerSystem) return _specie_number_type(nspecies(s)) end label(e::BlockEnd) = e.label label(s::AbstractSpecie) = s.label label(b::AbstractBlock) = b.label label(m::AbstractMolecule) = m.label label(c::Component) = label(c.molecule) const name = label components(s::PolymerSystem) = s.components function component(id::Integer, s::PolymerSystem) (id < 1 || id > ncomponents(s)) && return nothing return components(s)[id] end component_label(c::Component) = label(c) component_labels(s::PolymerSystem) = label.(components(s)) component_ids(s::PolymerSystem) = collect(1:ncomponents(s)) component_id(label::Symbol, s::PolymerSystem) = findfirst(component_labels(s) .== label) component_id(c::Component, s::PolymerSystem) = component_id(component_label(c), s) function component_label(id::Integer, s::PolymerSystem) (id < 1 || id > ncomponents(s)) && return nothing return component_labels(s)[id] end label(id::Integer, s::PolymerSystem) = component_label(id, s) function component(label::Symbol, s::PolymerSystem) id = component_id(label, s) return isnothing(id) ? nothing : component(id, s) end ฯ•s(s::PolymerSystem) = [c.ฯ• for c in s.components] ฯ•(id::Integer, s::PolymerSystem) = ฯ•s(s)[id] ฯ•(label::Symbol, s::PolymerSystem) = ฯ•(component_id(label, s), s) ฮฑ(c::Component) = c.ฮฑ ฮฑs(s::PolymerSystem) = ฮฑ.(components(s)) ฮฑ(id::Integer, s::PolymerSystem) = ฮฑs(s)[id] ฮฑ(label::Symbol, s::PolymerSystem) = ฮฑ(component_id(label, s), s) molecules(s::PolymerSystem) = [c.molecule for c in s.components] molecule(c::Component) = c.molecule molecule(id::Integer, s::PolymerSystem) = molecules(s)[id] molecule(label::Symbol, s::PolymerSystem) = molecule(component_id(label, s), s) molecule_labels(s::PolymerSystem) = component_labels(s) molecule_label(id::Integer, s::PolymerSystem) = component_label(id, s) molecule_label(mol::AbstractMolecule) = mol.label molecule_ids(s::PolymerSystem) = component_ids(s) molecule_id(label::Symbol, s::PolymerSystem) = component_id(label, s) molecule_id(mol::AbstractMolecule, s::PolymerSystem) = molecule_id(molecule_label(mol), s) isfreeblockend(::BlockEnd) = false isfreeblockend(::FreeEnd) = true block_ends(b::PolymerBlock) = [b.E1, b.E2] segment(b::PolymerBlock) = b.segment nblocks(sm::SmallMolecule) = 0 nblocks(bc::BlockCopolymer) = length(bc.blocks) nblocks(c::Component) = nblocks(c.molecule) nblocks(s::PolymerSystem) = sum(nblocks.(s.components)) blocks(bcp::BlockCopolymer) = bcp.blocks blocks(::SmallMolecule) = [] blocks(c::Component) = blocks(c.molecule) block_labels(sm::SmallMolecule) = [label(sm)] block_labels(bcp::BlockCopolymer) = [b.label for b in bcp.blocks] block_labels(c::Component) = block_labels(molecule(c)) block_labels(label::Symbol, s::PolymerSystem) = block_labels(molecule(label, s)) block_label(b::AbstractBlock) = b.label block_ids(bcp::BlockCopolymer) = collect(1:nblocks(bcp)) block_id(label::Symbol, bcp::BlockCopolymer) = findfirst(block_labels(bcp) .== label) function block_label(id::Integer, bcp::BlockCopolymer) (id < 1 || id > nblocks(bcp)) && return nothing return block_labels(bcp)[id] end block_label(::Integer, ::SmallMolecule) = nothing label(id::Integer, m::AbstractMolecule) = block_label(id, m) label(id::Integer, c::Component) = label(id, molecule(c)) block_id(b::AbstractBlock, bcp::BlockCopolymer) = block_id(block_label(b), bcp) block(id::Integer, bcp::BlockCopolymer) = bcp.blocks[id] block(label::Symbol, bcp::BlockCopolymer) = block(block_id(label, bcp), bcp) block_lengths(bcp::BlockCopolymer) = [b.f for b in bcp.blocks] block_lengths(::SmallMolecule) = [] block_lengths(c::Component) = block_lengths(c.molecule) block_length(id::Integer, bcp::BlockCopolymer) = block_lengths(bcp)[id] block_length(label::Symbol, bcp::BlockCopolymer) = block_length(block_id(label, bcp), bcp) block_length(b::PolymerBlock) = b.f block_species(bcp::BlockCopolymer) = [specie(b) for b in bcp.blocks] block_species(::SmallMolecule) = [] block_species(c::Component) = block_species(c.molecule) species(m::AbstractMolecule) = block_species(m) block_specie(id::Integer, bcp::BlockCopolymer) = block_species(bcp)[id] block_specie(label::Symbol, bcp::BlockCopolymer) = block_specie(block_id(label, bcp), bcp) block_bs(bcp::BlockCopolymer) = [b.segment.b for b in bcp.blocks] block_bs(::SmallMolecule) = [] block_bs(c::Component) = block_bs(c.molecule) block_b(id::Integer, bcp::BlockCopolymer) = block_bs(bcp)[id] block_b(label::Symbol, bcp::BlockCopolymer) = block_b(block_id(label, bcp), bcp) block_b(b::PolymerBlock) = b.segment.b function b(sp::Symbol, system::PolymerSystem) (sp โˆˆ species(system)) || error("$sp is not existing!") for mol in molecules(system) if mol isa SmallMolecule (sp == specie(mol)) && return mol.b else id_block = findfirst(sp .== block_species(mol)) return block_b(id_block, mol) end end end bs(system) = [b(sp, system) for sp in species(system)] getparam(system::PolymerSystem, cp::ฯ•ControlParameter) = ฯ•(cp.id, system) getparam(system::PolymerSystem, cp::ฮฑControlParameter) = ฮฑ(cp.id, system) getparam(bcp::BlockCopolymer, cp::fControlParameter) = block_length(cp.id_block, bcp) getparam(system::PolymerSystem, cp::fControlParameter) = getparam(molecule(cp.id_mol, system), cp) getparam(system::PolymerSystem, cp::ฯ‡NControlParameter) = ฯ‡N(system, cp.sp1, cp.sp2) getparam(system::PolymerSystem, cp::bControlParameter) = b(cp.sp, system) """ ฯ•ฬ„(c::Component{SmallMolecule}, sp::Symbol) ฯ•ฬ„(c::Component{<:BlockCopolymer}, sp::Symbol) ฯ•ฬ„(s::PolymerSystem, sp::Symbol) The averaging density (volume fraction) of specie `sp` in a `PolymerSystem` or a `Component`. This functionality can be used to compute the enthalpy energy in the Flory-Huggins theory. """ function ฯ•ฬ„(c::Component{<:SmallMolecule}, sp::Symbol) (sp โˆˆ species(c)) || return 0.0 return c.ฯ• end function ฯ•ฬ„(c::Component{<:BlockCopolymer}, sp::Symbol) (sp โˆˆ species(c)) || return 0.0 ฯ• = 0.0 for b in c.molecule.blocks (specie(b) == sp) && (ฯ• += c.ฯ• * b.f) end return ฯ• end function ฯ•ฬ„(s::PolymerSystem, sp::Symbol) (sp โˆˆ species(s)) || return 0.0 return sum([ฯ•ฬ„(c, sp) for c in s.components]) end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
1455
function to_config(sp::KuhnSegment) return SpecieConfig(label=sp.label, type=:Segment, b=sp.b, M=sp.M) end function to_config(sp::SmallMolecule) return SpecieConfig(label=sp.label, type=:Small, b=sp.b, M=sp.M) end function to_config(b::PolymerBlock) ends = Symbol[] (b.E1 isa BranchPoint) && push!(ends, b.E1.label) (b.E2 isa BranchPoint) && push!(ends, b.E2.label) return BlockConfig(label=b.label, segment=specie(b), length=b.f, ends=ends) end function to_config(bcp::BlockCopolymer) sps = to_config.(specie_objects(bcp)) bs = to_config.(blocks(bcp)) return BlockCopolymerConfig(label=label(bcp), species=sps, blocks=bs) end function to_config(c::Component) type = c.molecule isa BlockCopolymer ? :BCP : :SMOL blocks = type == :BCP ? to_config.(c.molecule.blocks) : BlockConfig[] return ComponentConfig(type=type, label=c.molecule.label, length=c.ฮฑ, volume_fraction=c.ฯ•, blocks=blocks) end function to_config(ฯ‡Nmatrix::ฯ‡NMatrix) map = [] for ((sp1, sp2), v) in ฯ‡Nmatrix.map push!(map, [sp1, sp2, v]) end return map end function to_config(system::PolymerSystem) species = to_config.(specie_objects(system)) ฯ‡N_map = to_config(system.ฯ‡Nmatrix) components = to_config.(system.components) return PolymerSystemConfig(species=species, ฯ‡N_map=ฯ‡N_map, components=components, chain_density=system.C) end "`from_config` is an alias for `make`" const from_config = make
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
5813
## Convenient functions for creating polymer chains. branchpoints(n, prefix="EB") = [BranchPoint(Symbol(prefix*string(i))) for i in 1:n] freeends(n, prefix="A") = [FreeEnd(Symbol(prefix*string(i))) for i in 1:n] function homopolymer_chain(; label=:A, segment=KuhnSegment(label)) labelE1 = Symbol(label, :1) labelE2 = Symbol(label, :2) A = PolymerBlock(label, segment, 1.0, FreeEnd(labelE1), FreeEnd(labelE2)) return BlockCopolymer(label, [A]) end function diblock_chain(; labelA=:A, labelB=:B, segmentA=KuhnSegment(labelA), segmentB=KuhnSegment(labelB), fA=0.5) labelAB = Symbol(labelA, labelB) fB = 1.0 - fA eAB = BranchPoint(labelAB) A = PolymerBlock(labelA, segmentA, fA, FreeEnd(labelA), eAB) B = PolymerBlock(labelB, segmentB, fB, FreeEnd(labelB), eAB) return BlockCopolymer(labelAB, [A,B]) end function linearABC(fA=0.3, fB=0.3) sA = KuhnSegment(:A) sB = KuhnSegment(:B) sC = KuhnSegment(:C) eb = branchpoints(2) fe = freeends(2) A = PolymerBlock(:A, sA, fA, eb[1], fe[1]) C = PolymerBlock(:C, sC, 1-fA-fB, eb[2], fe[2]) B = PolymerBlock(:B, sB, fB, eb[1], eb[2]) return BlockCopolymer(:ABC, [A, B, C]) end ## Convenient functions for creating non-polymer components. solvent(; label=:S) = SmallMolecule(label) ## Convenient functions for creating polymer systems. "Default AB diblock copolymer system: two species are A and B, lengths of both segmeents are 1.0. However, ฯ‡N and fA can be changed by Keyword argument. Default values are: ฯ‡N=20.0 and fA=0.5." function AB_system(; ฯ‡N=20.0, fA=0.5) polymer = Component(diblock_chain(; fA=fA)) return PolymerSystem([polymer], Dict(Set([:A, :B])=>ฯ‡N)) end function ABC_system(; ฯ‡ABN=40.0, ฯ‡ACN=40.0, ฯ‡BCN=40.0, fA=0.3, fB=0.4) polymer = Component(linearABC(fA, fB)) return PolymerSystem([polymer], Dict( Set([:A,:B])=>ฯ‡ABN, Set([:A,:C])=>ฯ‡ACN, Set([:B,:C])=>ฯ‡BCN ) ) end "A/B homopolymers binary blend." function A_B_system(; ฯ‡N=20.0, ฯ•A=0.5, ฮฑA=1.0, ฮฑB=1.0) polymerA = Component(homopolymer_chain(label=:A), ฮฑA, ฯ•A) polymerB = Component(homopolymer_chain(label=:B), ฮฑB, 1-ฯ•A) return PolymerSystem([polymerA, polymerB], Dict([:A, :B]=>ฯ‡N)) end "AB diblock copolymers / A homopolymers blend." function AB_A_system(; ฯ‡N=20.0, ฯ•AB=0.5, fA=0.5, ฮฑ=0.5) polymerAB = Component(diblock_chain(; fA=fA), 1.0, ฯ•AB) polymerA = Component(homopolymer_chain(; label=:hA, segment=KuhnSegment(:A)), ฮฑ, 1-ฯ•AB) return PolymerSystem([polymerAB, polymerA], Dict(Set([:A, :B])=>ฯ‡N)) end "AB diblock copolymers / A homopolymers / B homopolymers blend." function AB_A_B_system(; ฯ‡N=20.0, ฯ•AB=0.5, fA=0.5, ฯ•A=0.1, ฮฑA=0.5, ฮฑB=0.5) polymerAB = Component(diblock_chain(; fA=fA), 1.0, ฯ•AB) polymerA = Component(homopolymer_chain(; label=:hA, segment=KuhnSegment(:A)), ฮฑA, ฯ•A) polymerB = Component(homopolymer_chain(; label=:hB, segment=KuhnSegment(:B)), ฮฑB, 1-ฯ•AB-ฯ•A) return PolymerSystem([polymerAB, polymerA, polymerB], Dict(Set([:A, :B])=>ฯ‡N)) end function A_B_AB_system(; ฯ‡N=20.0, fA=0.5, ฯ•A=0.2, ฮฑA=0.5, ฯ•B=0.2, ฮฑB=0.5) polymerAB = Component(diblock_chain(; fA=fA), 1.0, 1-ฯ•A-ฯ•B) polymerA = Component(homopolymer_chain(; label=:hA, segment=KuhnSegment(:A)), ฮฑA, ฯ•A) polymerB = Component(homopolymer_chain(; label=:hB, segment=KuhnSegment(:B)), ฮฑB, ฯ•B) return PolymerSystem([polymerA, polymerB, polymerAB], Dict(Set([:A, :B])=>ฯ‡N)) end "AB diblock copolymers + solvent solution." function AB_S_system(; ฯ‡NAB=20.0, ฯ‡NAS=100.0, ฯ‡NBS=100.0, ฯ•AB=0.1, fA=0.5, ฮฑ=0.01) polymer = Component(diblock_chain(; fA=fA), 1.0, ฯ•AB) sol = Component(solvent(), ฮฑ, 1-ฯ•AB) return PolymerSystem([polymer, sol], Dict( Set([:A,:B])=>ฯ‡NAB, Set([:A,:S])=>ฯ‡NAS, Set([:B,:S])=>ฯ‡NBS ) ) end "A homopolymer + B homopolymer + solvent solution." function A_B_S_system(; ฯ‡NAB=20.0, ฯ‡NAS=100.0, ฯ‡NBS=100.0, ฯ•A=0.1, ฯ•B=0.1, ฮฑA=1.0, ฮฑB=1.0, ฮฑS=0.01) polymerA = Component(homopolymer_chain(; label=:A, segment=KuhnSegment(:A)), ฮฑA, ฯ•A) polymerB = Component(homopolymer_chain(; label=:B, segment=KuhnSegment(:B)), ฮฑB, ฯ•B) sol = Component(solvent(), ฮฑS, one(ฯ•A)-ฯ•A-ฯ•B) return PolymerSystem([polymerA, polymerB, sol], Dict( Set([:A,:B])=>ฯ‡NAB, Set([:A,:S])=>ฯ‡NAS, Set([:B,:S])=>ฯ‡NBS ) ) end "A homopolymer + B homopolymer + solvent1 + solvent2 solution." function A_B_S1_S2_system(; ฯ‡NAB=20.0, ฯ‡NAS1=100.0, ฯ‡NBS1=100.0, ฯ‡NAS2=100.0, ฯ‡NBS2=100.0, ฯ‡NS1S2=100.0, ฯ•A=0.1, ฯ•B=0.1, ฯ•S1=0.4, ฮฑA=1.0, ฮฑB=1.0, ฮฑS1=0.01, ฮฑS2=0.01) polymerA = Component(homopolymer_chain(; label=:A, segment=KuhnSegment(:A)), ฮฑA, ฯ•A) polymerB = Component(homopolymer_chain(; label=:B, segment=KuhnSegment(:B)), ฮฑB, ฯ•B) S1 = Component(solvent(label=:S1), ฮฑS1, ฯ•S1) S2 = Component(solvent(label=:S2), ฮฑS2, one(ฯ•A)-ฯ•A-ฯ•B-ฯ•S1) return PolymerSystem([polymerA, polymerB, S1, S2], Dict( Set([:A,:B])=>ฯ‡NAB, Set([:A,:S1])=>ฯ‡NAS1, Set([:B,:S1])=>ฯ‡NBS1, Set([:A,:S2])=>ฯ‡NAS2, Set([:B,:S2])=>ฯ‡NBS2, Set([:S1,:S2])=>ฯ‡NS1S2 ) ) end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
8586
# traits for space dimension abstract type SpaceDimension end struct D1 <: SpaceDimension end struct D2 <: SpaceDimension end struct D3 <: SpaceDimension end # traits for the type of confinement abstract type ConfinementType end struct BulkConfinement <: ConfinementType end struct BoxConfinement <: ConfinementType end struct SlabConfinement <: ConfinementType end struct DiskConfinement <: ConfinementType end struct SphereConfinement <: ConfinementType end struct CylinderConfinement <: ConfinementType end # traits for the type of polymer system abstract type PolymerSystemType end struct NeatPolymer <: PolymerSystemType end struct PolymerBlend <: PolymerSystemType end struct PolymerSolution <: PolymerSystemType end # traits for multicomponent system abstract type ComponentNumberType end struct MonoSystem <: ComponentNumberType end struct BinarySystem <: ComponentNumberType end struct TernarySystem <: ComponentNumberType end struct MultiComponentSystem <: ComponentNumberType end # traits for multi-species system abstract type SpecieNumberType end struct SingleSpecieSystem <: SpecieNumberType end struct TwoSpeciesSystem <: SpecieNumberType end struct MultiSpeciesSystem <: SpecieNumberType end # traits for the type of charge distribution abstract type ChargedType end struct Neutral <: ChargedType end struct SmearedCharge <: ChargedType end struct DiscreteCharge <: ChargedType end abstract type AbstractSpecie end struct KuhnSegment{T} <: AbstractSpecie label::Symbol b::T # length M::T # molecular weight in g/mol KuhnSegment(label::Symbol, b::T, M::T) where T = new{T}(label, b, M) end KuhnSegment(label; b=1.0, M=1.0) = KuhnSegment(Symbol(label), promote(b, M)...) Base.show(io::IO, s::KuhnSegment) = print(io, "KuhnSegment $(s.label) with b=$(s.b)") abstract type BlockEnd end struct FreeEnd <: BlockEnd label::Symbol end FreeEnd(; label=:EF) = FreeEnd(label) struct BranchPoint <: BlockEnd label::Symbol end Base.show(io::IO, fe::FreeEnd) = print(io, "FreeEnd $(fe.label)") Base.show(io::IO, bp::BranchPoint) = print(io, "BranchPoint $(bp.label)") abstract type AbstractBlock end struct PolymerBlock{T} <: AbstractBlock label::Symbol segment::KuhnSegment f::T # = N_b / N, N is the total number of segments in a whole polymer chain E1::BlockEnd E2::BlockEnd end function PolymerBlock(; label=:A, specie=:A, f=1.0, E1=FreeEnd(), E2=FreeEnd()) return PolymerBlock(Symbol(label), KuhnSegment(specie), f, E1, E2) end function PolymerBlock(segment::KuhnSegment; label=segment.label, f=1.0, E1=FreeEnd(), E2=FreeEnd()) return PolymerBlock(Symbol(label), segment, f, E1, E2) end Base.show(io::IO, b::PolymerBlock) = print(io, "PolymerBlock $(b.label) with f=$(b.f) of specie $(b.segment.label)") function Base.show(io::IO, ::MIME"text/plain", b::PolymerBlock) f = round(b.f, digits=4) println(io, "PolymerBlock $(b.label) with f=$f of $(b.segment)") println(io, " Chain ends:") println(io, " * ", b.E1) print(io, " * ", b.E2) end """ - Check whether each block has a unqiue label. - Check whether the length of all blocks in a chain sum to 1.0. """ function _isachain(blocks) labels = map(x->x.label, blocks) length(unique(labels)) == length(labels) || return false mapreduce(x->x.f, +, blocks) โ‰ˆ 1.0 || return false return true end abstract type AbstractMolecule end struct SmallMolecule{T} <: AbstractMolecule label::Symbol b::T # length M::T # molecular weight in g/mol SmallMolecule(label::Symbol, b::T, M::T) where T = new{T}(label, b, M) end SmallMolecule(label; b=1.0, M=1.0) = SmallMolecule(Symbol(label), promote(b, M)...) Base.show(io::IO, smol::SmallMolecule) = print(io, "SmallMolecule $(smol.label) with b=$(smol.b)") abstract type AbstractPolymer <: AbstractMolecule end struct BlockCopolymer{T<:AbstractBlock} <: AbstractPolymer label::Symbol blocks::Vector{T} function BlockCopolymer(label::Symbol, blocks::Vector{T}; check=true) where {T<:PolymerBlock} check && @argcheck _isachain(blocks) new{T}(label, blocks) end end function Base.show(io::IO, bcp::BlockCopolymer) n = length(bcp.blocks) println(io, "BlockCopolymer $(bcp.label) with $n blocks:") for b in bcp.blocks println(io, " * $b") end end function Base.show(io::IO, ::MIME"text/plain", bcp::BlockCopolymer) n = length(bcp.blocks) println(io, "BlockCopolymer $(bcp.label) with $n blocks:") for b in bcp.blocks print(io, " * ") show(io, "text/plain", b) println(io) end end struct RandomCopolymer <: AbstractPolymer end struct AlternatingCopolymer <: AbstractPolymer end struct Particle <: AbstractMolecule end struct GiantMolecule <: AbstractMolecule end abstract type AbstractComponent end struct Component{T<:AbstractMolecule, S<:Real} <: AbstractComponent molecule::T ฮฑ::S # N / N_ref, N_ref is the total number of segments in a reference polymer chain ฯ•::S # = n*N/V, number density of this component in the system. function Component(molecule::T, ฮฑ::S, ฯ•::S) where {T<:AbstractMolecule, S} new{T, S}(molecule, ฮฑ, ฯ•) end end ## Do not define `Base.show` for `Component` object to avoid disable tree view functionality of Pluto.jl. # Base.show(io::IO, c::Component) = print(io, "Component $(c.molecule.label) with ฯ•=$(c.ฯ•) and ฮฑ=$(c.ฮฑ) contains $(c.molecule)") # function Base.show(io::IO, ::MIME"text/plain", c::Component) # println(io, "Polymer system component $(c.molecule.label):") # print(io, "* ", c.molecule) # println(io, "* ฯ• = $(c.ฯ•)") # println(io, "* ฮฑ = $(c.ฮฑ)") # end Component(molecule::T; ฮฑ=1.0, ฯ•=1.0) where {T<:AbstractMolecule} = Component(molecule, promote(ฮฑ, ฯ•)...) abstract type AbstractSystem end """ PolymerSystem{T} <: AbstractSystem The key of `ฯ‡N_map` should be a two-element `Set`. Each element is the unique symbol for a specie. For example, the `ฯ‡N_map` of an AB diblock copolymer is a `Dict` with one entry `Set([:A, :B]) => ฯ‡N`. Note: For Edwards Model A (homopolymer + implicit solvent), one has to add a dummy solvent component in the `components` array to make the function `multicomponent` return correct result. """ struct PolymerSystem{T} <: AbstractSystem components::Vector{Component} confinement::ConfinementType ฯ‡Nmatrix::ฯ‡NMatrix{T} C::T # = \rho_0 R_g^3 / N, dimensionless chain density function PolymerSystem(components::Vector{S}, conf, ฯ‡Nmatrix::ฯ‡NMatrix{T}, C) where {S<:AbstractComponent, T} @argcheck _isasystem(components) @argcheck _isasystem(components, ฯ‡Nmatrix) new{T}(components, conf, ฯ‡Nmatrix, T(C)) end end function PolymerSystem(components::Vector{T}, ฯ‡Nmatrix::ฯ‡NMatrix; conf=BulkConfinement(), C=1.0) where {T<:AbstractComponent} return PolymerSystem(components, conf, ฯ‡Nmatrix, C) end """ PolymerSystem(components, ฯ‡Nmap; conf=BulkConfinement(), C=1.0) Constructor for `PolymerSystem`. `components` is a collection of `Component` objects. `ฯ‡Nmap` is a dictionary of interaction pairs. See [`ฯ‡NMatrix`](@ref) for how to write a valid `ฯ‡Nmap`. """ function PolymerSystem(components, ฯ‡Nmap; conf=BulkConfinement(), C=1.0) return PolymerSystem(collect(components), ฯ‡NMatrix(ฯ‡Nmap); conf=conf, C=C) end ## Here, we define a `Base.print` instead of a `Base.show` to show `PolymerSystem`. If we define `Base.show` for `PolymerSystem`, then the tree view of this object will be disabled and fall back to this `Base.show`. # This a compromise to show `PoymerSystem` object in their best representation in both REPL and Pluto.jl. # To get a clean plain text display of `PolymerSystem`, use `print(system)` where `system` is a `PolymerSystem` object. function Base.print(io::IO, s::PolymerSystem) n = length(s.components) name = "" for i in 1:n label = string(s.components[i].molecule.label) name = i < n ? name * label * " + " : name * label end println(io, "PolymerSystem ($name) contains $n components:") println(io) for c in s.components print(io, "Component $(c.molecule.label) with ฯ•=$(c.ฯ•) and ฮฑ=$(c.ฮฑ) contains ") println(io, c.molecule) end println(io) print(io, "with ", s.ฯ‡Nmatrix) end """ Check if the volume fraction of all compnents sums to 1.0. """ function _isasystem(components) return mapreduce(x->x.ฯ•, +, components) โ‰ˆ 1.0 ? true : false end function _isasystem(components, ฯ‡Nmatrix::ฯ‡NMatrix) return _species(components) == species(ฯ‡Nmatrix) end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
9509
################ # update ฯ‡NParam ################ function update!(system::PolymerSystem, sp1::Symbol, sp2::Symbol, ฯ‡N, ::ฯ‡NType) system.ฯ‡Nmatrix[sp1, sp2] = ฯ‡N return system end function update!(system::PolymerSystem, ฯ‡N::Real, ::ฯ‡NType) (ncomponents(system) == 2) || return system sp1, sp2 = species(system) return update!(system, sp1, sp2, ฯ‡N, ฯ‡NParam) end function update!(system::PolymerSystem, ฯ‡Nmap, ::ฯ‡NType) system.ฯ‡Nmatrix .= ฯ‡NMatrix(ฯ‡Nmap) return system end ################# # update molecule ################# function update!(system::PolymerSystem, id_mol::Integer, mol::AbstractMolecule) c = system.components[id_mol] system.components[id_mol] = @set c.molecule = mol return system end """ `mol_old` can be a label or an instance of AbstractMolecule """ function update!(system::PolymerSystem, mol_old, mol_new::AbstractMolecule) return update!(system, molecule_id(mol_old, system), mol_new) end ################# # update ฯ•Param ################# function update!(system::PolymerSystem, ids::AbstractVector{<:Integer}, ฯ•s::AbstractVector, ::ฯ•Type) isapprox(sum(ฯ•s), 1.0) || error("ฯ•s should have sum 1.0!") nc = ncomponents(system) (nc == 1) && return system (nc == length(ฯ•s)) || error("Length of ฯ•s should be equal to the number of components of the polymer system!") (nc == length(ids)) || error("Length of ids (or labels) should be equal to the number of components of the polymer system!") for i in 1:nc id = ids[i] c = system.components[id] system.components[id] = @set c.ฯ• = ฯ•s[i] end return system end function update!(system::PolymerSystem, labels::AbstractVector{<:Symbol}, ฯ•s::AbstractVector, ::ฯ•Type) ids = [component_id(label, system) for label in labels] return update!(system, ids, ฯ•s, ฯ•Param) end """ The sequence of the input ฯ•s should be consistent with `component_ids`, i.e. ฯ•s[1] corresponds to the ฯ• for components[1], etc. """ function update!(system::PolymerSystem, ฯ•s::AbstractVector, ::ฯ•Type) return update!(system, 1:ncomponents(system), ฯ•s, ฯ•Param) end """ Binary system is assumed implicitly. """ function update!(system::PolymerSystem, ฯ•::Real, ::ฯ•Type) nc = ncomponents(system) (nc == 2) || error("Binary system expected!") return update!(system, [ฯ•, one(ฯ•)-ฯ•], ฯ•Param) end ################# # update ฮฑParam ################# function update!(system::PolymerSystem, id::Integer, ฮฑ::Real, ::ฮฑType) c = system.components[id] system.components[id] = @set c.ฮฑ = ฮฑ return system end function update!(system::PolymerSystem, label::Symbol, ฮฑ::Real, ::ฮฑType) return update!(system, component_id(label, system), ฮฑ, ฮฑParam) end function update!(system::PolymerSystem, ids::AbstractVector{<:Integer}, ฮฑs::AbstractVector, ::ฮฑType) nc = ncomponents(system) (nc == 1) && return system (length(ids) == length(ฮฑs)) || error("Length of ids and ฮฑs should be equal!") for (id, ฮฑ) in zip(ids, ฮฑs) update!(system, id, ฮฑ, ฮฑParam) end return system end function update!(system::PolymerSystem, labels::AbstractVector{<:Symbol}, ฮฑs::AbstractVector, ::ฮฑType) ids = [component_id(label, system) for label in labels] return update!(system, ids, ฮฑs, ฮฑParam) end """ The sequence of the input ฯ•s should be consistent with `component_ids`, i.e. ฯ•s[1] corresponds to the ฯ• for components[1], etc. """ function update!(system::PolymerSystem, ฮฑs::AbstractVector, ::ฮฑType) nc = ncomponents(system) (nc == length(ฮฑs)) || error("Length of ฮฑs should be equal to the number of components!") return update!(system, 1:nc, ฮฑs, ฮฑParam) end ################# # update fParam ################# function update!(bcp::BlockCopolymer, ids::AbstractVector{<:Integer}, fs::AbstractVector, ::fType) nb = nblocks(bcp) isapprox(sum(fs), 1.0) || error("All f in one blockcopolymer must = 1.") (nb == length(fs)) || error("Length of fs should be equal to the number of blocks of the block polymer!") (nb == length(ids)) || error("Length of ids (or labels) should be equal to the number of blocks of the block polymer!") # Homopolymer chain f = 1.0 always (nb == 1) && (return bcp) for i in 1:length(fs) id = ids[i] b = block(id, bcp) bcp.blocks[id] = @set b.f = fs[i] end return bcp end function update!(bcp::BlockCopolymer, labels::AbstractVector{<:Symbol}, fs::AbstractVector, ::fType) ids = [block_id(label, bcp) for label in labels] return update!(bcp, ids, fs, fParam) end """ The sequence of `fs` should be consistent with `block_ids`. """ function update!(bcp::BlockCopolymer, fs::AbstractVector, ::fType) return update!(bcp, 1:nblocks(bcp), fs, fParam) end """ Two-block blockcopolymer and the first block is assumed. """ function update!(bcp::BlockCopolymer, f::Real, ::fType) (nblocks(bcp) == 2) || return bcp return update!(bcp, [f, one(f)-f], fParam) end function update!(system::PolymerSystem, id_mol::Integer, ids_or_labels::AbstractVector, fs::AbstractVector, ::fType) mol = molecule(id_mol, system) update!(mol, ids_or_labels, fs, fParam) return update!(system, id_mol, mol) end """ `bcp` can be the label or instance of a BlockCopolymer. """ function update!(system::PolymerSystem, bcp, ids_or_labels::AbstractVector, fs::AbstractVector, ::fType) return update!(system, molecule_id(bcp, system), ids_or_labels, fs, fParam) end function update!(system::PolymerSystem, id_mol::Integer, fs::AbstractVector, ::fType) return update!(system, id_mol, 1:length(fs), fs, fParam) end """ `bcp` can be the label or instance of a BlockCopolymer. """ function update!(system::PolymerSystem, bcp, fs::AbstractVector, ::fType) return update!(system, molecule_id(bcp, system), fs, fParam) end """ Two-block block copolymer is assumed. """ function update!(system::PolymerSystem, id_mol::Integer, f::Real, ::fType) return update!(system, id_mol, [f, one(f)-f], fParam) end """ Two-block block copolymer is assumed. `bcp` can be the label or instance of a BlockCopolymer. """ function update!(system::PolymerSystem, bcp, f::Real, ::fType) return update!(system, molecule_id(bcp, system), f, fParam) end ################# # update bParam ################# function _update!(bcp::BlockCopolymer, id_block::Integer, b::Real, ::bType) bk = bcp.blocks[id_block] bcp.blocks[id_block] = @set bk.segment.b = b return bcp end function _update!(bcp::BlockCopolymer, label_block::Symbol, b::Real, ::bType) id_block = block_id(label_block, bcp) return _update!(bcp, id_block, b, bParam) end function _update!(bcp::BlockCopolymer, ids::AbstractVector{<:Integer}, bs::AbstractVector, ::bType) (length(ids) == length(bs)) || error("Length of ids and bs should be equal!") for (id, b) in zip(ids, bs) _update!(bcp, id, b, bParam) end return bcp end function _update!(bcp::BlockCopolymer, labels::AbstractVector{<:Symbol}, bs::AbstractVector, ::bType) ids = [block_id(label, bcp) for label in labels] return _update!(bcp, ids, bs, bParam) end """ The sequence of `bs` should be consistent with `block_ids`. """ function _update!(bcp::BlockCopolymer, bs::AbstractVector, ::bType) nb = nblocks(bcp) (nb == length(bs)) || error("Length of bs must be equal to the number of blocks!") return _update!(bcp, 1:nb, bs, bParam) end function _update(smol::SmallMolecule, b, ::bType) return @set smol.b = b end """ All blocks and/or small molecules consisting of the same specie should be updated together. `sp` is the label of a specie (KuhnSegment and SmallMolecule). """ function update!(system::PolymerSystem, sp::Symbol, b::Real, ::bType) for mol in molecules(system) if mol isa SmallMolecule (specie(mol) == sp) && update!(system, mol, _update(mol, b, bParam)) else id_mol = molecule_id(mol, system) labels = Symbol[] for bk in blocks(mol) (specie(bk) == sp) && push!(labels, block_label(bk)) end if !isempty(labels) _update!(mol, labels, fill(b, length(labels)), bParam) update!(system, id_mol, mol) end end end return system end function update!(system::PolymerSystem, sps::AbstractVector, bs::AbstractVector, ::bType) (length(sps) == length(bs)) || error("Lengths of sps and bs must be equal!") for (sp, b) in zip(sps, bs) update!(system, sp, b, bParam) end return system end """ Update for a full list of b. The order of list `bs` should be consistent with the order of `spcices(system)`, i.e. the internal order of the spcies in the BlockCopolymer instance. """ function update!(system::PolymerSystem, bs::AbstractVector, ::bType) (nspecies(system) == length(bs)) || error("Length of bs must be equal to the number of species in the system!") return update!(system, species(system), bs, bParam) end update!(system::PolymerSystem, ฯ•, cp::ฯ•ControlParameter) = update!(system, cp(ฯ•), ฯ•Param) update!(system::PolymerSystem, ฮฑ, cp::ฮฑControlParameter) = update!(system, cp.id, ฮฑ, ฮฑParam) update!(system::PolymerSystem, f, cp::fControlParameter) = update!(system, cp.id_mol, cp(f), fParam) update!(system::PolymerSystem, ฯ‡N, cp::ฯ‡NControlParameter) = update!(system, cp.sp1, cp.sp2, ฯ‡N, ฯ‡NParam) update!(system::PolymerSystem, b, cp::bControlParameter) = update!(system, cp.sp, b, bParam) const setparam! = update!
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
1413
""" unicodesymbol2string(us::Char) Return an ascii representation (LaTeX name for a unicode symbol) for the input character. If the input character is already an ASCII or it is not listed in `REPL.REPLCompletions.latex_symbols`, the input string is returned. ```julia-repl julia> unicodesymbol2string("ฮฒ") "beta" julia> unicodesymbol2string("b") "b" ``` """ function unicodesymbol2string(us::Char) us = string(us) return isascii(us) ? us : isempty(symbol_latex(us)) ? us : symbol_latex(us)[2:end] end """ reverse_dict(d::Dict) Return a Dict instance with each `key => val` pair in `d` reversed as `val => key` pair. Same values in `d` will be overwirten by the last occurd pair. """ reverse_dict(d::Dict) = Dict(v => k for (k, v) in d) """ _sort_tuple2(t) Sort two-element Tuple to increase order. Example ```julia-REPL julia> _sort_tuple2((2, 1)) (1, 2) julia> _sort_tuple2((1, 2)) (1, 2) ``` """ function _sort_tuple2(t) a, b = t return a > b ? (b, a) : (a, b) end """ retrieve(dict, key_of_interest, output=[]) Return all values matched the `key_of_interest` in a nested Dict. """ function retrieve(dict, key_of_interest, output=[]) for (key, value) in dict if key == key_of_interest push!(output, value) end if value isa AbstractDict retrieve(value, key_of_interest, output) end end return output end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
318
using Polymer using Test # include("test_utils.jl") # include("test_parameters.jl") # include("test_chiN.jl") # include("test_types.jl") include("test_properties.jl") # include("test_update.jl") # include("test_systems.jl") # include("test_config.jl") # include("test_make.jl") # include("test_serialize.jl") nothing
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
291
using Polymer using Test include("test_utils.jl") include("test_parameters.jl") include("test_chiN.jl") include("test_types.jl") include("test_properties.jl") include("test_update.jl") include("test_systems.jl") include("test_config.jl") include("test_make.jl") include("test_serialize.jl")
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
2033
ฯ‡NmapAB = Dict(Set((:A,:B))=>20.0) ฯ‡NmapABS = Dict(Set((:A,:B))=>20.0, Set((:A, :S))=>80.0, Set((:B, :S))=>120.0) ฯ‡NmapABS_bad = Dict(Set((:A,:B))=>20.0, Set((:A, :S))=>80.0) ฯ‡NmapABS_singular = Dict(Set((:A,:B))=>20.0, Set((:A, :S))=>0.0, Set((:B, :S))=>20.0) @testset "chiN.jl: _species" begin @test Polymer._species(ฯ‡NmapAB) == [:A, :B] @test Polymer._species(ฯ‡NmapABS) == [:A, :B, :S] end @testset "chiN.jl: _check_consistency" begin @test Polymer._check_consistency(ฯ‡NmapAB) @test Polymer._check_consistency(ฯ‡NmapABS) @test !Polymer._check_consistency(ฯ‡NmapABS_bad) end @testset "chiN.jl: _ฯ‡Nmap_to_matrix" begin mat = Polymer._ฯ‡Nmap_to_matrix(ฯ‡NmapAB) @test mat == [0 20.0; 20.0 0] mat = Polymer._ฯ‡Nmap_to_matrix(ฯ‡NmapABS) @test mat == [0 20.0 80.0; 20.0 0 120.0; 80.0 120.0 0] @test_throws ErrorException Polymer._ฯ‡Nmap_to_matrix(ฯ‡NmapABS_singular) end @testset "chiN.jl: ฯ‡NMatrix" begin m = ฯ‡NMatrix(ฯ‡NmapAB) @test m == [0 20.0; 20.0 0] m = ฯ‡NMatrix(ฯ‡NmapABS) @test m == [0 20.0 80.0; 20.0 0 120.0; 80.0 120.0 0] @test size(m) == (3,3) @test_throws ErrorException ฯ‡NMatrix(ฯ‡NmapABS_bad) @test_throws ErrorException ฯ‡NMatrix(ฯ‡NmapABS_singular) end @testset "chiN.jl: getindex" begin m = ฯ‡NMatrix(ฯ‡NmapABS) @test m[1] == 0 @test m[7] == 80.0 @test m[1, 2] == 20.0 @test m[2, 1] == 20.0 @test m[1, 3] == 80.0 @test m[2, 3] == 120.0 @test m[:A] == 0 @test m[:B, :B] == 0 @test m[:B, :A] == 20.0 @test m[:A, :S] == 80.0 @test m[:S, :B] == 120.0 end @testset "chiN.jl: setindex" begin m = ฯ‡NMatrix(ฯ‡NmapABS) m[1] = 10.0 @test m[1] == 0 @test m[:A] == 0 @test m[:A, :A] == 0 m[7] = 88.0 @test m[7] == 88.0 @test m[1, 3] == 88.0 @test m[3, 1] == 88.0 m[:A, :A] = 99.0 @test m[1] == 0 @test m[1, 1] == 0 @test m[:A] == 0 @test m[:A, :A] == 0 m[:S, :B] = 102.0 @test m[:B, :S] == 102.0 @test m[2, 3] == 102.0 @test m[3, 2] == 102.0 end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
592
@testset "config.jl: load_config" begin configfile = joinpath(@__DIR__, "ABS.yml") config_abs = load_config(configfile, top="system") @test config_abs isa PolymerSystemConfig end @testset "config.jl: save_config" begin configfile = joinpath(@__DIR__, "ABS.yml") config_abs = load_config(configfile, top="system") configfile = joinpath(@__DIR__, "ABS_save.yml") save_config(configfile, config_abs) # The config file is saved without top level key. config_abs_reload = load_config(configfile) @test config_abs_reload isa PolymerSystemConfig end nothing
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
1024
@testset "control_parameters.jl: ControlParameter" begin fฯ•(ฯ•) = [0.8-ฯ•, 0.2] # TernarySystem, with third component ฯ• fixed at 0.2. ฯ•c = ฯ•ControlParameter(1, ฯ•Param, fฯ•) @test ฯ•c(0.3) == [0.3, 0.5, 0.2] abs = A_B_S_system() ฯ•c2 = ฯ•ControlParameter(:B, abs; func=fฯ•) @test ฯ•c2(0.3) == [0.5, 0.3, 0.2] ฮฑc = ฮฑControlParameter(1, ฮฑParam) @test ฮฑc(1.1) == 1.1 ฮฑc2 = ฮฑControlParameter(:A, abs) # control ฮฑ value for A component ฯ‡Nc = ฯ‡NControlParameter(:A, :B, ฯ‡NParam) @test ฯ‡Nc(10.0) == 10.0 ฯ‡Nc2 = ฯ‡NControlParameter(:A, :B, abs) ff(f) = [0.8-f, 0.2] # triblock copolymer, with third block f fixed at 0.2 fc = fControlParameter(1, 1, fParam, ff) @test fc(0.3) == [0.3, 0.5, 0.2] abc = ABC_system() fc2 = fControlParameter(1, :ABC, abc; func=ff) @test fc2(0.3) == [0.3, 0.5, 0.2] fc3 = fControlParameter(:B, :ABC, abc; func=ff) @test fc3(0.3) == [0.5, 0.3, 0.2] bc = bControlParameter(:A, bParam) @test bc(1.1) == 1.1 end nothing
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
1123
@testset "make.jl: make" begin configfile = joinpath(@__DIR__, "ABS.yml") config = load_config(configfile, top="system") abs = make(config) @test systemtype(abs) == PolymerSolution() end @testset "make.jl: constructors" begin abs = AB_S_system() config = to_config(abs) sp1 = KuhnSegment(config.species[1]) @test sp1.label == :A sp2 = KuhnSegment(config.species[2]) @test sp2.label == :B sp3 = SmallMolecule(config.species[3]) @test sp3.label == :S sps = [sp1, sp2, sp3] blockA = PolymerBlock(config.components[1].blocks[1], sps) @test blockA.label == :A blockB = PolymerBlock(config.components[1].blocks[2], sps) @test blockB.label == :B bcp = BlockCopolymer(config.components[1], sps) @test bcp.label == :AB smol = SmallMolecule(config.components[2], sps) @test smol.label == :S c1 = Component(config.components[1], sps) @test c1.molecule isa BlockCopolymer c2 = Component(config.components[2], sps) @test c2.molecule isa SmallMolecule abs1 = PolymerSystem(config) @test systemtype(abs) == PolymerSolution() end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
364
using Polymer @testset "parameters.jl: AbstractParameter" begin @test ฯ•Param.allowed_min == 0.0 @test ฯ•Param.allowed_max == 1.0 @test ฯ‡Param.allowed_min == -Inf @test ฯ‡Param.allowed_max == Inf @test NParam.allowed_min == 0 @test NParam.allowed_max == Inf @test fParam.allowed_min == 0.0 @test fParam.allowed_max == 1.0 end nothing
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
4462
using Polymer using Polymer: label, components, component, blocks, segment, block_ends, molecule @testset "properties.jl" begin model = AB_system() @test component_number_type(model) == MonoSystem() @test specie_number_type(model) == TwoSpeciesSystem() @test Polymer.ฯ•ฬ„(model, :A) == 0.5 @test Polymer.ฯ•ฬ„(model, :B) == 0.5 model = AB_A_system() bcp = Polymer.molecule(:AB, model) @test component_number_type(model) == BinarySystem() @test specie_number_type(model) == TwoSpeciesSystem() @test Polymer.ฯ•ฬ„(model, :A) == 0.75 @test Polymer.ฯ•ฬ„(model, :B) == 0.25 @test component_label(1, model) == :AB @test component_labels(model) == [:AB, :hA] @test component_id(:AB, model) == 1 @test component_ids(model) == [1, 2] @test Polymer.ฯ‡N(model, :A, :B) == 20.0 @test Polymer.ฯ•(1, model) == 0.5 @test Polymer.ฯ•(:AB, model) == 0.5 @test Polymer.ฯ•s(model) == [0.5, 0.5] @test Polymer.ฮฑ(2, model) == 0.5 @test Polymer.ฮฑ(:hA, model) == 0.5 @test Polymer.ฮฑs(model) == [1.0, 0.5] @test Polymer.molecule(1, model) == model.components[1].molecule @test Polymer.molecule(:AB, model) == model.components[1].molecule @test molecule_labels(model) == [:AB, :hA] @test molecule_label(1, model) == :AB @test molecule_label(Polymer.molecule(:AB, model)) == :AB @test molecule_ids(model) == [1, 2] @test molecule_id(:AB, model) == 1 @test molecule_id(Polymer.molecule(:AB, model), model) == 1 blockA = Polymer.block(:A, bcp) blockB = Polymer.block(:B, bcp) @test Polymer.blocks(bcp) == bcp.blocks @test block_labels(bcp) == [:A, :B] @test block_label(blockA) == :A @test block_label(1, bcp) == :A @test block_ids(bcp) == [1, 2] @test block_id(:A, bcp) == 1 @test block_id(blockA, bcp) == 1 @test Polymer.block(1, bcp) == blockA @test Polymer.block(:A, bcp) == Polymer.block(1, bcp) @test block_lengths(bcp) == [0.5, 0.5] @test block_length(1, bcp) == 0.5 @test block_length(:A, bcp) == 0.5 @test block_species(bcp) == [:A, :B] @test block_specie(1, bcp) == :A @test block_specie(:A, bcp) == :A @test block_bs(bcp) == [1.0, 1.0] @test block_b(1, bcp) == 1.0 @test block_b(:A, bcp) == 1.0 @test Polymer.b(:A, model) == 1.0 @test Polymer.b(:B, model) == 1.0 @test Polymer.bs(model) == [1.0, 1.0] ฯ•c = ฯ•ControlParameter(1, ฯ•Param) @test Polymer.getparam(model, ฯ•c) == 0.5 ฮฑc = ฮฑControlParameter(2, ฮฑParam) @test Polymer.getparam(model, ฮฑc) == 0.5 ฯ‡Nc = ฯ‡NControlParameter(:A, :B, ฯ‡NParam) @test Polymer.getparam(model, ฯ‡Nc) == 20.0 fc = fControlParameter(1, 1, fParam) @test Polymer.getparam(model, fc) == 0.5 bc = bControlParameter(:A, bParam) @test Polymer.getparam(model, bc) == 1.0 model = AB_S_system() @test component_number_type(model) == BinarySystem() @test Polymer.ฯ•ฬ„(model, :A) == 0.05 @test Polymer.ฯ•ฬ„(model, :B) == 0.05 @test Polymer.ฯ•ฬ„(model, :S) == 0.9 s3 = A_B_S_system() @test component_number_type(s3) == TernarySystem() @test specie_number_type(s3) == MultiSpeciesSystem() s4 = A_B_S1_S2_system() @test component_number_type(s4) == MultiComponentSystem() @test specie_number_type(s4) == MultiSpeciesSystem() end @testset "properties.jl: label" begin model = AB_A_system() cs = components(model) @test label.(cs) == component_labels(model) c1 = first(cs) @test label(c1) == :AB @test label(c1) == component_label(c1) AB = molecule(c1) @test label(AB) == :AB b1 = first(blocks(AB)) @test label(b1) == :A s1 = segment(b1) @test label(s1) == :A e1 = first(block_ends(b1)) @test label(e1) == :A @test label.(blocks(AB)) == block_labels(AB) @test label(1, model) == :AB @test isnothing(label(3, model)) @test label(1, AB) == :A @test isnothing(label(0, AB)) end @testset "properties.jl: specie, species" begin model = AB_S_system() @test species(model) == [:A, :B, :S] cs = components(model) c1 = first(cs) c2 = last(cs) @test species(c1) == [:A, :B] @test species(c2) == [:S] AB = molecule(c1) S = molecule(c2) @test species(AB) == [:A, :B] @test species(S) == [:S] bA = first(blocks(AB)) bB = last(blocks(AB)) @test specie(bA) == :A @test specie(bB) == :B @test specie(S) == :S @test isempty(blocks(S)) end nothing
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
211
@testset "serialize.jl: to_config" begin config_aba = to_config(AB_A_system()) @test config_aba isa PolymerSystemConfig aba = make(config_aba) @test systemtype(aba) == PolymerBlend() end nothing
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
988
@testset "systems.jl: Components" begin chainA = homopolymer_chain() @test length(chainA.blocks) == 1 chainAB = diblock_chain() @test length(chainAB.blocks) == 2 @test chainAB.blocks[1].E2 == chainAB.blocks[2].E2 @test chainAB.blocks[1].E1 != chainAB.blocks[2].E1 sol = solvent() @test sol.label == :S end @testset "systems.jl: Systems" begin ab = AB_system() @test systemtype(ab) == NeatPolymer() @test multicomponent(ab) == false @test ncomponents(ab) == 1 @test species(ab) == [:A, :B] @test nspecies(ab) == 2 aba = AB_A_system() @test systemtype(aba) == PolymerBlend() @test multicomponent(aba) == true @test ncomponents(aba) == 2 @test species(aba) == [:A, :B] @test nspecies(aba) == 2 abs = AB_S_system() @test systemtype(abs) == PolymerSolution() @test multicomponent(abs) == true @test ncomponents(abs) == 2 @test species(abs) == [:A, :B, :S] @test nspecies(abs) == 3 end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
3624
@testset "types.jl: Confinement" begin @test isconfined(BulkConfinement()) == false @test isconfined(BoxConfinement()) == true @test isconfined(SlabConfinement()) == true @test isconfined(DiskConfinement()) == true @test isconfined(SphereConfinement()) == true @test isconfined(CylinderConfinement()) == true end @testset "types.jl: Charge" begin @test ischarged(Neutral()) == false @test ischarged(SmearedCharge()) == true @test ischarged(DiscreteCharge()) == true end @testset "types.jl: Specie" begin segment = KuhnSegment(:A) @test segment.b == 1.0 @test segment.M == 1.0 end @testset "types.jl: Block" begin sA = KuhnSegment(:A) e1A = FreeEnd(:A1) e2A = FreeEnd(:A2) A = PolymerBlock(:A, sA, 1.0, e1A, e2A) @test A.f == 1.0 end @testset "types.jl: Component" begin sA = KuhnSegment(:A) sB = KuhnSegment(:B) e1A = FreeEnd(:A1) e2A = BranchPoint(:A2) e1B = FreeEnd(:B1) e2B = BranchPoint(:B2) A = PolymerBlock(:A, sA, 0.4, e1A, e2A) B = PolymerBlock(:B, sB, 0.6, e1B, e2B) c = BlockCopolymer(:AB, [A,B]) pc = Component(c) @test pc.ฮฑ == 1.0 @test pc.ฯ• == 1.0 smol = SmallMolecule(:S) @test smol.b == 1.0 @test smol.M == 1.0 sc = Component(smol) @test sc.ฮฑ == 1.0 @test sc.ฯ• == 1.0 end @testset "types.jl: Polymer System AB+S" begin sA = KuhnSegment(:A) sB = KuhnSegment(:B) e1A = FreeEnd(:A1) e2A = BranchPoint(:A2) e1B = FreeEnd(:B1) e2B = BranchPoint(:B2) A = PolymerBlock(:A, sA, 0.4, e1A, e2A) B = PolymerBlock(:B, sB, 0.6, e1B, e2B) chain = BlockCopolymer(:AB, [A,B]) smol = SmallMolecule(:S) polymer = Component(chain, 1.0, 0.1) solvent = Component(smol, 0.01, 0.9) ฯ‡N_map = Dict( Set([:A,:B])=>20.0, Set([:A,:S])=>80.0, Set([:B,:S])=>120.0) m = ฯ‡NMatrix(ฯ‡N_map) ABS = PolymerSystem([polymer, solvent], m) @test isconfined(ABS.confinement) == false @test ABS.C == 1.0 @test multicomponent(ABS) == true @test ncomponents(ABS) == 2 @test species(chain) == [:A, :B] @test nspecies(chain) == 2 @test species(smol) == [:S] @test nspecies(smol) == 1 @test species(polymer) == species(chain) @test nspecies(polymer) == nspecies(chain) @test species(solvent) == species(smol) @test nspecies(solvent) == nspecies(smol) @test species(ABS) == [:A, :B, :S] @test nspecies(ABS) == 3 @test systemtype(ABS) == PolymerSolution() end @testset "types.jl: Polymer System AB+A" begin sA = KuhnSegment(:A) sB = KuhnSegment(:B) eA = FreeEnd(:A1) eAB = BranchPoint(:AB) eB = FreeEnd(:B1) A = PolymerBlock(:A, sA, 0.4, eA, eAB) B = PolymerBlock(:B, sB, 0.6, eB, eAB) chainAB = BlockCopolymer(:AB, [A,B]) hA = PolymerBlock(:hA, sA, 1.0, FreeEnd(:hA1), FreeEnd(:hA2)) chainA = BlockCopolymer(:hA, [hA]) polymerAB = Component(chainAB, 1.0, 0.5) polymerA = Component(chainA, 0.5, 0.5) ฯ‡N_map = Dict(Set([:A,:B])=>20.0) AB_A = PolymerSystem([polymerAB, polymerA], ฯ‡N_map) @test multicomponent(AB_A) == true @test ncomponents(AB_A) == 2 @test species(chainAB) == [:A, :B] @test nspecies(chainAB) == 2 @test species(chainA) == [:A] @test nspecies(chainA) == 1 @test species(polymerAB) == species(chainAB) @test nspecies(polymerAB) == nspecies(chainAB) @test species(polymerA) == species(chainA) @test nspecies(polymerA) == nspecies(chainA) @test species(AB_A) == [:A, :B] @test nspecies(AB_A) == 2 @test systemtype(AB_A) == PolymerBlend() end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
8642
using Polymer import Polymer: update!, molecule, block_lengths, block_bs, setparam!, getparam function starAB3(; fA=0.4, fB1=0.2, fB2=0.2, fB3=0.2) sA = KuhnSegment(:A) sB = KuhnSegment(:B) eb0 = BranchPoint(:EB0) A = PolymerBlock(:A, sA, fA, FreeEnd(:A), eb0) B1 = PolymerBlock(:B1, sB, fB1, FreeEnd(:B1), eb0) B2 = PolymerBlock(:B2, sB, fB2, FreeEnd(:B2), eb0) B3 = PolymerBlock(:B3, sB, fB3, FreeEnd(:B3), eb0) return BlockCopolymer(:AB3, [A, B1, B2, B3]) end function AB3_A_system(; ฯ‡N=12.0, ฯ•AB3=0.8, ฮฑAB3=1.0, ฮฑA=0.35) polymerAB3 = Component(starAB3(), ฮฑAB3, ฯ•AB3) polymerA = Component(homopolymer_chain(; label=:A, segment=KuhnSegment(:A)), ฮฑA, 1-ฯ•AB3) return PolymerSystem([polymerAB3, polymerA], Dict(Set([:A, :B])=>ฯ‡N)) end @testset "update.jl: ฯ‡NParam" begin system = AB3_A_system() update!(system, :A, :B, 10.0, ฯ‡NParam) @test Polymer.ฯ‡N(system, :A, :B) == 10.0 system = AB3_A_system() update!(system, 11.0, ฯ‡NParam) @test Polymer.ฯ‡N(system, :A, :B) == 11.0 system = AB3_A_system() update!(system, Dict(Set([:A, :B])=>13.0), ฯ‡NParam) @test Polymer.ฯ‡N(system, :A, :B) == 13.0 end @testset "update.jl: molecule" begin system = AB3_A_system() bcp = starAB3(; fA=0.1, fB1=0.3, fB2=0.3, fB3=0.3) update!(system, 1, bcp) @test block_lengths(molecule(1, system)) == [0.1, 0.3, 0.3, 0.3] system = AB3_A_system() bcp = starAB3(; fA=0.1, fB1=0.3, fB2=0.3, fB3=0.3) update!(system, :AB3, bcp) @test block_lengths(molecule(:AB3, system)) == [0.1, 0.3, 0.3, 0.3] system = AB3_A_system() bcp = starAB3(; fA=0.1, fB1=0.3, fB2=0.3, fB3=0.3) update!(system, molecule(:AB3, system), bcp) @test block_lengths(molecule(:AB3, system)) == [0.1, 0.3, 0.3, 0.3] end @testset "update.jl: ฯ•Param" begin system = AB3_A_system() update!(system, [2, 1], [0.6, 0.4], ฯ•Param) @test Polymer.ฯ•(1, system) == 0.4 @test Polymer.ฯ•(2, system) == 0.6 system = AB3_A_system() update!(system, [:A, :AB3], [0.6, 0.4], ฯ•Param) @test Polymer.ฯ•(:AB3, system) == 0.4 @test Polymer.ฯ•(:A, system) == 0.6 system = AB3_A_system() update!(system, [0.4, 0.6], ฯ•Param) @test Polymer.ฯ•(:AB3, system) == 0.4 @test Polymer.ฯ•(:A, system) == 0.6 system = AB3_A_system() update!(system, 0.4, ฯ•Param) @test Polymer.ฯ•(:AB3, system) == 0.4 @test Polymer.ฯ•(:A, system) == 0.6 end @testset "update.jl: ฮฑParam" begin system = AB3_A_system() update!(system, 2, 0.5, ฮฑParam) @test Polymer.ฮฑ(1, system) == 1.0 @test Polymer.ฮฑ(2, system) == 0.5 system = AB3_A_system() update!(system, :A, 0.5, ฮฑParam) @test Polymer.ฮฑ(:AB3, system) == 1.0 @test Polymer.ฮฑ(:A, system) == 0.5 system = AB3_A_system() update!(system, [2, 1], [0.5, 1.0], ฮฑParam) @test Polymer.ฮฑ(:AB3, system) == 1.0 @test Polymer.ฮฑ(:A, system) == 0.5 system = AB3_A_system() update!(system, [:A, :AB3], [0.5, 1.0], ฮฑParam) @test Polymer.ฮฑ(:AB3, system) == 1.0 @test Polymer.ฮฑ(:A, system) == 0.5 system = AB3_A_system() update!(system, [2], [0.5], ฮฑParam) @test Polymer.ฮฑ(:AB3, system) == 1.0 @test Polymer.ฮฑ(:A, system) == 0.5 system = AB3_A_system() update!(system, [:A], [0.5], ฮฑParam) @test Polymer.ฮฑ(:AB3, system) == 1.0 @test Polymer.ฮฑ(:A, system) == 0.5 system = AB3_A_system() update!(system, [1.0, 0.5], ฮฑParam) @test Polymer.ฮฑ(:AB3, system) == 1.0 @test Polymer.ฮฑ(:A, system) == 0.5 end @testset "update.jl: fParam" begin bcp = starAB3() update!(bcp, [2, 3, 4, 1], [0.2, 0.3, 0.4, 0.1], fParam) @test block_lengths(bcp) == [0.1, 0.2, 0.3, 0.4] bcp = starAB3() update!(bcp, [:B1, :B2, :B3, :A], [0.2, 0.3, 0.4, 0.1], fParam) @test block_lengths(bcp) == [0.1, 0.2, 0.3, 0.4] bcp = starAB3() update!(bcp, [0.1, 0.2, 0.3, 0.4], fParam) @test block_lengths(bcp) == [0.1, 0.2, 0.3, 0.4] bcp = diblock_chain() update!(bcp, 0.4, fParam) @test block_lengths(bcp) == [0.4, 0.6] system = AB3_A_system() update!(system, 1, [2, 3, 4, 1], [0.2, 0.3, 0.4, 0.1], fParam) @test block_lengths(molecule(1, system)) == [0.1, 0.2, 0.3, 0.4] system = AB3_A_system() update!(system, :AB3, [2, 3, 4, 1], [0.2, 0.3, 0.4, 0.1], fParam) @test block_lengths(molecule(:AB3, system)) == [0.1, 0.2, 0.3, 0.4] system = AB3_A_system() update!(system, molecule(:AB3, system), [2, 3, 4, 1], [0.2, 0.3, 0.4, 0.1], fParam) @test block_lengths(molecule(:AB3, system)) == [0.1, 0.2, 0.3, 0.4] system = AB3_A_system() update!(system, 1, [0.1, 0.2, 0.3, 0.4], fParam) @test block_lengths(molecule(1, system)) == [0.1, 0.2, 0.3, 0.4] system = AB3_A_system() update!(system, :AB3, [0.1, 0.2, 0.3, 0.4], fParam) @test block_lengths(molecule(:AB3, system)) == [0.1, 0.2, 0.3, 0.4] system = AB3_A_system() update!(system, molecule(:AB3, system), [0.1, 0.2, 0.3, 0.4], fParam) @test block_lengths(molecule(:AB3, system)) == [0.1, 0.2, 0.3, 0.4] system = AB_A_system() update!(system, 1, 0.4, fParam) @test block_lengths(molecule(1, system)) == [0.4, 0.6] system = AB_A_system() update!(system, :AB, 0.4, fParam) @test block_lengths(molecule(:AB, system)) == [0.4, 0.6] system = AB_A_system() update!(system, molecule(:AB, system), 0.4, fParam) @test block_lengths(molecule(:AB, system)) == [0.4, 0.6] end @testset "update.jl: bParam" begin bcp = starAB3() Polymer._update!(bcp, 3, 1.2, bParam) @test block_bs(bcp) == [1.0, 1.0, 1.2, 1.0] bcp = starAB3() Polymer._update!(bcp, :B2, 1.2, bParam) @test block_bs(bcp) == [1.0, 1.0, 1.2, 1.0] bcp = starAB3() Polymer._update!(bcp, [:B3, :B1, :B2], [1.3, 1.1, 1.2], bParam) @test block_bs(bcp) == [1.0, 1.1, 1.2, 1.3] bcp = starAB3() Polymer._update!(bcp, [1.0, 1.2, 1.2, 1.2], bParam) @test block_bs(bcp) == [1.0, 1.2, 1.2, 1.2] system = AB3_A_system() update!(system, :A, 1.2, bParam) @test block_bs(molecule(1,system)) == [1.2, 1.0, 1.0, 1.0] @test block_bs(molecule(2,system)) == [1.2] system = AB3_A_system() update!(system, :B, 1.2, bParam) @test block_bs(molecule(1,system)) == [1.0, 1.2, 1.2, 1.2] @test block_bs(molecule(2,system)) == [1.0] system = AB3_A_system() update!(system, [:A, :B], [1.1, 1.2], bParam) @test block_bs(molecule(1,system)) == [1.1, 1.2, 1.2, 1.2] @test block_bs(molecule(2,system)) == [1.1] @test Polymer.b(:A, system) == 1.1 @test Polymer.b(:B, system) == 1.2 system = AB3_A_system() update!(system, [1.1, 1.2], bParam) @test block_bs(molecule(1,system)) == [1.1, 1.2, 1.2, 1.2] @test block_bs(molecule(2,system)) == [1.1] @test Polymer.b(:A, system) == 1.1 @test Polymer.b(:B, system) == 1.2 end @testset "update.jl: AbstractControlParameter" begin system = AB3_A_system() ฯ•c = ฯ•ControlParameter(2, ฯ•Param) update!(system, 0.6, ฯ•c) @test Polymer.ฯ•(1, system) == 0.4 @test getparam(system, ฯ•c) == 0.6 setparam!(system, 0.3, ฯ•c) @test Polymer.ฯ•(1, system) == 0.7 @test getparam(system, ฯ•c) == 0.3 system = AB3_A_system() ฮฑc = ฮฑControlParameter(2, ฮฑParam) update!(system, 0.8, ฮฑc) @test getparam(system, ฮฑc) == 0.8 system = AB3_A_system() ฯ‡Nc = ฯ‡NControlParameter(:A, :B, ฯ‡NParam) update!(system, 12.0, ฯ‡Nc) @test getparam(system, ฯ‡Nc) == 12.0 system = AB3_A_system() ff(f) = (one(f) - f)/3 * [1, 1, 1] id_mol = molecule_id(:AB3, system) id_block = block_id(:A, molecule(id_mol, system)) fc = fControlParameter(id_block, id_mol, fParam, ff) update!(system, 0.4, fc) @test block_lengths(molecule(id_mol, system)) โ‰ˆ [0.4, 0.2, 0.2, 0.2] system = AB3_A_system() bc = bControlParameter(:A, bParam) update!(system, 1.1, bc) @test getparam(system, bc) == 1.1 @test block_b(:A, molecule(:AB3, system)) == 1.1 @test block_b(:B1, molecule(:AB3, system)) == 1.0 @test block_b(:B2, molecule(:AB3, system)) == 1.0 @test block_b(:B3, molecule(:AB3, system)) == 1.0 @test block_b(:A, molecule(:A, system)) == 1.1 system = AB3_A_system() bc = bControlParameter(:B, bParam) update!(system, 1.2, bc) @test getparam(system, bc) == 1.2 @test block_b(:A, molecule(:AB3, system)) == 1.0 @test block_b(:B1, molecule(:AB3, system)) == 1.2 @test block_b(:B2, molecule(:AB3, system)) == 1.2 @test block_b(:B3, molecule(:AB3, system)) == 1.2 @test block_b(:A, molecule(:A, system)) == 1.0 end nothing
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
code
544
import Polymer @testset "utils.jl" begin @test unicodesymbol2string('ฯ•') == "phi" @test unicodesymbol2string('ฮฒ') == "beta" @test unicodesymbol2string('b') == "b" d = Dict("a"=>1, "b"=>2, "c"=>3) @test reverse_dict(d) == Dict(1=>"a", 2=>"b", 3=>"c") d = Dict("c"=>1, "a"=>1, "b"=>2) @test reverse_dict(d) == Dict(1=>"a", 2=>"b") d = Dict("a"=>1, "b"=>2, "c"=>1) @test reverse_dict(d) == Dict(1=>"a", 2=>"b") @test Polymer._sort_tuple2((2,1)) == (1,2) @test Polymer._sort_tuple2((1,2)) == (1,2) end
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
docs
4414
# Polymer.jl **Polymer.jl** defines a common interface to describe a polymer system. *Warning: Be aware that this package is currently under active development. The interface is highly unstable and subjects to change frequently.* ## Usage ### Construct a `PolymerSystem` object form scratch ```julia julia> using Polymer # Create A and B monomers. julia> sA = KuhnSegment(:A) julia> sB = KuhnSegment(:B) # Create free end and branch point (joint) julia> eA = FreeEnd(:A1) julia> eAB = BranchPoint(:AB) julia> eB = FreeEnd(:B1) # Create A and B blocks julia> A = PolymerBlock(:A, sA, 0.5, eA, eAB) julia> B = PolymerBlock(:B, sB, 0.5, eB, eAB) # Create a AB diblock copolymer chain julia> chainAB = BlockCopolymer(:AB, [A,B]) # Create a homopolymer chain julia> hA = PolymerBlock(:hA, sA, 1.0, FreeEnd(), FreeEnd()) julia> chainA = BlockCopolymer(:hA, [hA]) # Create components julia> polymerAB = Component(chainAB; ฯ•=0.5) julia> polymerA = Component(chainA; ฯ•=0.5) # Create AB/A polymer blend system. julia> AB_A = PolymerSystem([polymerAB, polymerA]; ฯ‡N_map=Dict([:A, :B]=>20.0)) ``` Convenient functions are also provided to create common polymer chains and systems. For example, above AB chain, A chain, AB/A polymer blend system can be simply created by a single line of code, respectively. ```julia julia> diblock_chain() # AB chain julia> homopolymer_chain() # A chain julia> AB_A_system() # AB/A polymer blend ``` ### Properties ```julia julia> abc = linear_ABC() julia> Polymer.block_labels(abc) # get block labels julia> ab_a = AB_A_system() julia> Polymer.block_labels(:AB, ab_a) # get block labels of a specific component ``` Available properties are listed below: ```julia specie_object, specie_objects, isconfined, ischarged, ฯ‡N, ฯ‡Nmap, ฯ‡Nmatrix, multicomponent, ncomponents, specie, species, nspecies, systemtype, component_number_type, specie_number_type, label, name, components, component, component_label, component_id, ฯ•s, ฯ•, ฮฑ, ฮฑs, molecules, molecule, molecule_label, molecule_id, molecule_labels, molecule_ids, isfreeblockend, block_ends, segment, nblocks, blocks, block_label, block_labels, block_id, block_ids, block_lengths, block_length, block_specie, block_bs, block_b, b, bs, getparam, ฯ•ฬ„ ``` ### Update/Modify a `PolymerSystem` object Parameters in a parameters can be achieved or updated easily via `update!` or `setparam!` function. There are two kinds of parameter defined by `AbstractParameter` and `AbstractControlParameter`, respectively. The first kind makes lower level setting of parameters possible. However, it is more complicated and the signature of `update!` is less unified. The second kind provides a convenient and unified way to read and write a PolymerSystem instance. However, it only supports update a single value of any parameter. One can use `AbstractControlParameter` to define a parameter which is considered to be an independent variable in a set of simulations or for construction of a phase diagram. Currently, there are 5 concrete types of `AbstractControlParameter`: * `ฯ•ControlParameter` * `ฮฑControlParameter` * `ฯ‡NControlParameter` * `fControlParameter` * `bControlParameter` ```julia julia> system = AB_A_system() # ฯ•AB = 0.5, ฯ•A = 0.5 julia> ฯ•A = ฯ•ControlParameter(:hA, system) # ฯ•A is the control parameter julia> update!(system, 0.6, ฯ•A) # ฯ•AB will be updated accordingly due to the conservation of mass. # ฯ•AB = 0.4, ฯ•A = 0.6 ``` For more details, consult the testing codes reside in `test` folder. ### Serialization and configurations Based on Configurations.jl, we can serialize a `PolymerSystem` object to a `PolymerSystemConfig` object. Then the `PolymerSystemConfig` object can be saved to a YAML file. ```julia julia> config = to_config(AB_A_system()) julia> save_config("./AB_A.yml", config) ``` We can load the `PolymerSystemConfig` object back from the YAML file. Then we can re-construct the `PolymerSystem` object from the `PolymerSystemConfig` object. ```julia julia> config = load_config("./AB_A.yml", PolymerSystemConfig) julia> AB_A = Polymer.make(config) # or julia> AB_A = PolymerSystem(config) ``` ## Contribute * Star the package on [github.com](https://github.com/liuyxpp/Polymer.jl). * File an issue or make a pull request on [github.com](https://github.com/liuyxpp/Polymer.jl). * Contact the author via email <[email protected]>. ## Links * [Source code](https://github.com/liuyxpp/Polymer.jl)
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "BSD-3-Clause" ]
0.8.11
acb934136ab1344643fbfbc188d981aaa017dec5
docs
101
```@meta CurrentModule = Polymer ``` # Polymer ```@index ``` ```@autodocs Modules = [Polymer] ```
Polymer
https://github.com/liuyxpp/Polymer.jl.git
[ "MIT" ]
0.1.5
8a5d4332019e086e06b68563bd1b26073ac1dbfc
code
591
using Jl2Py using Documenter DocMeta.setdocmeta!(Jl2Py, :DocTestSetup, :(using Jl2Py); recursive=true) makedocs(; modules=[Jl2Py], authors="Gabriel Wu <[email protected]> and contributors", repo="https://github.com/lucifer1004/Jl2Py.jl/blob/{commit}{path}#{line}", sitename="Jl2Py.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://lucifer1004.github.io/Jl2Py.jl", assets=String[]), pages=["Home" => "index.md"]) deploydocs(; repo="github.com/lucifer1004/Jl2Py.jl", devbranch="main")
Jl2Py
https://github.com/lucifer1004/Jl2Py.jl.git
[ "MIT" ]
0.1.5
8a5d4332019e086e06b68563bd1b26073ac1dbfc
code
20095
module Jl2Py export jl2py, unparse using MLStyle using PythonCall const AST = PythonCall.pynew() const OP_DICT = Dict{Symbol,Py}() const OP_UDICT = Dict{Symbol,Py}() const TYPE_DICT = Dict{Symbol,String}() const BUILTIN_DICT = Dict{Symbol,String}() function __unaryop(jl_expr, op) operand = __jl2py(jl_expr.args[2]) unaryop = AST.UnaryOp(op(), operand) return unaryop end function __binop(jl_expr, op) left = __jl2py(jl_expr.args[2]) right = __jl2py(jl_expr.args[3]) binop = AST.BinOp(left, op(), right) return binop end function __boolop(jl_expr, op) left = __jl2py(jl_expr.args[1]) right = __jl2py(jl_expr.args[2]) boolop = AST.BoolOp(op(), [left, right]) return boolop end function __compareop_from_comparison(jl_expr) elts = __jl2py(jl_expr.args[1:2:end]) ops = map(x -> OP_DICT[x](), jl_expr.args[2:2:end]) compareop = AST.Compare(elts[1], ops, elts[2:end]) return compareop end function __compareop_from_call(jl_expr, op) elts = __jl2py(jl_expr.args[2:end]) compareop = AST.Compare(elts[1], [op()], elts[2:end]) return compareop end function __multiop(jl_expr, op) left = __jl2py(jl_expr.args[2]) right = __jl2py(jl_expr.args[3]) binop = AST.BinOp(left, op(), right) argcnt = length(jl_expr.args) for i in 4:argcnt right = __jl2py(jl_expr.args[i]) binop = AST.BinOp(binop, op(), right) end return binop end function __parse_arg(arg::Union{Symbol,Expr}) if isa(arg, Symbol) return AST.arg(pystr(arg)) elseif arg.head == :(::) return AST.arg(pystr(arg.args[1]), __parse_type(arg.args[2])) end end function __parse_args(params) posonlyargs = [] defaults = [] kwonlyargs = [] kw_defaults = [] kwarg = nothing vararg = nothing for arg in params if isa(arg, Symbol) || arg.head == :(::) push!(posonlyargs, __parse_arg(arg)) elseif arg.head == :kw push!(posonlyargs, __parse_arg(arg.args[1])) push!(defaults, __jl2py(arg.args[2])) elseif arg.head == :... vararg = __parse_arg(arg.args[1]) elseif arg.head == :parameters for param in arg.args if isa(param, Symbol) push!(kwonlyargs, __parse_arg(param)) push!(kw_defaults, nothing) elseif param.head == :kw push!(kwonlyargs, __parse_arg(param.args[1])) push!(kw_defaults, __jl2py(param.args[2])) elseif param.head == :... kwarg = __parse_arg(param.args[1]) end end end end return AST.arguments(; args=PyList(), posonlyargs=PyList(posonlyargs), kwonlyargs=PyList(kwonlyargs), defaults=PyList(defaults), kw_defaults=PyList(kw_defaults), kwarg=kwarg, vararg=vararg) end function __parse_pair(expr::Expr) (expr.head == :call && expr.args[1] == :(=>)) || error("Invalid pair expr") return __jl2py(expr.args[2]), __jl2py(expr.args[3]) end """ Parse a Julia range (leading by :(:)). We modify the end when all args are `Integer`s. For example: - `1:3` becomes `range(1, 4)` - `1:5:11` becomes `range(1, 12, 5)` - `1:-5:-9` becomes `range(1, -10, -5)` We also modify the end when the step is implicit (=1). For example: - `a:b` becomes `range(a, b + 1)` This might cause problems in such cases as `1.5:1.8`, but since Python only supports integer-indexed implicit ranges, we do not consider such edge cases here. """ function __parse_range(args::AbstractVector) @match args begin [start::Integer, stop::Integer] => [AST.Constant(start), AST.Constant(stop + 1)] [start, stop] => [__jl2py(start), AST.BinOp(__jl2py(stop), AST.Add(), AST.Constant(1))] [start::Integer, step::Integer, stop::Integer] => [AST.Constant(start), AST.Constant(stop + sign(step)), __jl2py(step)] [start, step, stop] => [__jl2py(start), __jl2py(stop), __jl2py(step)] end end function __parse_type(typ::Union{Symbol,Expr}) @match typ begin ::Symbol => AST.Name(get(TYPE_DICT, typ, pystr(typ))) Expr(:curly, arg1, arg2) => AST.Subscript(__parse_type(arg1), __parse_type(arg2)) Expr(:curly, arg1, args...) => AST.Subscript(__parse_type(arg1), AST.Tuple(map(__parse_type, args))) end end function __parse_generator(args::AbstractVector) return PyList(vcat(map(args) do arg if arg.head == :(=) target = __jl2py(arg.args[1]) iter = __jl2py(arg.args[2]) [AST.comprehension(target, iter, PyList(); is_async=false)] else __jl2py(arg) end end...)) end function __parse_if(expr::Expr) # Julia's `if` is always an expression, while Python's `if` is mostly a statement. test = __jl2py(expr.args[1]) @match expr.args[2] begin Expr(:block, _...) => begin # AST.If body = __jl2py(expr.args[2]) orelse = length(expr.args) == 3 ? __jl2py(expr.args[3]) : nothing if !isnothing(orelse) && !isa(orelse, Vector) orelse = PyList([orelse]) end AST.If(test, body, orelse) end _ => begin # AST.IfExp body = __jl2py(expr.args[2]) orelse = __jl2py(expr.args[3]) AST.IfExp(test, body, orelse) end end end function __parse_function(expr::Expr) returns = nothing if expr.args[1].head == :call name = expr.args[1].args[1] params = expr.args[1].args[2:end] elseif expr.args[1].head == :(::) returns = __parse_type(expr.args[1].args[2]) name = expr.args[1].args[1].args[1] params = expr.args[1].args[1].args[2:end] else expr.head = :-> # Assume it to be a lambda return __jl2py(expr) end arguments = __parse_args(params) # # The following code tries to handle return issue in Julia # # but still has some issues. # # i = lastindex(jl_expr.args[2].args) # while i > 0 && isa(jl_expr.args[2].args[i], LineNumberNode) # i -= 1 # end # if i > 0 # last_arg = jl_expr.args[2].args[i] # if !(isa(last_arg, Expr) && last_arg.head == :return) # jl_expr.args[2].args[i] = Expr(:return, last_arg) # end # end body = __jl2py(expr.args[2]) if isempty(body) push!(body, AST.Pass()) elseif !pyisinstance(body[end], AST.Return) if pyisinstance(body[end], AST.Assign) push!(body, AST.Return(body[end].targets[0])) elseif pyisinstance(body[end], AST.AugAssign) push!(body, AST.Return(body[end].target)) elseif pyisinstance(body[end], AST.Expr) body[end] = AST.Return(body[end].value) elseif !pyisinstance(body[end], AST.For) && !pyisinstance(body[end], AST.While) body[end] = AST.Return(body[end]) end end return AST.fix_missing_locations(AST.FunctionDef(pystr(name), arguments, PyList(body), PyList(); returns=returns)) end function __parse_lambda(expr::Expr) begin body = __jl2py(expr.args[2]) if isa(expr.args[1], Expr) && expr.args[1].head == :(::) && !isa(expr.args[1].args[1], Symbol) expr = expr.args[1] end if isa(expr.args[1], Symbol) || expr.args[1].head == :(::) arguments = __parse_args([expr.args[1]]) else map!(expr.args[1].args, expr.args[1].args) do arg return isa(arg, Expr) && arg.head == :(=) ? Expr(:kw, arg.args[1], arg.args[2]) : arg end if expr.args[1].head == :tuple arguments = __parse_args(expr.args[1].args) else expr.args[1].head == :block || error("Invalid lambda") split_pos = findfirst(x -> isa(x, LineNumberNode), expr.args[1].args) wrapped_args = expr.args[1].args[1:(split_pos - 1)] keyword_args = Expr(:parameters, map(expr.args[1].args[(split_pos + 1):end]) do arg return arg.head == :(=) ? Expr(:kw, arg.args[1], arg.args[2]) : arg end...) push!(wrapped_args, keyword_args) arguments = __parse_args(wrapped_args) end end length(body) >= 2 && error("Python lambdas can only have one statement.") # # Use a hacky way to compress all lines of body into one line # if length(body) > 1 # prev = map(x -> AST.BoolOp(AST.And(), [x, AST.Constant(false)]), body[1:(end - 1)]) # body = AST.BoolOp(AST.Or(), PyList([prev..., body[end]])) # else # body = body[1] # end return AST.Lambda(arguments, body[1]) end end function __parse_ref(value, slices) value = __jl2py(value) map!(slices, slices) do arg if isa(arg, Expr) && arg.args[1] == :(:) slice = AST.Slice(__parse_range(arg.args[2:end])...) else slice = __jl2py(arg) end end slice = length(slices) == 1 ? slices[1] : AST.Tuple(PyList(slices)) return AST.Subscript(value, slice) end function __parse_generator(arg1, args; isflatten, iscomprehension) if isflatten elt, extra_gens = __jl2py(arg1; iscomprehension=iscomprehension) gens = __parse_generator(args) append!(gens, extra_gens) else elt = __jl2py(arg1) gens = __parse_generator(args) end return iscomprehension ? (elt, gens) : AST.GeneratorExp(elt, gens) end function __parse_filter(filter, args) filter = __jl2py(filter) return map(1:length(args)) do i arg = args[i] target = __jl2py(arg.args[1]) iter = __jl2py(arg.args[2]) return i == length(args) ? AST.comprehension(target, iter, PyList([filter]); is_async=false) : AST.comprehension(target, iter, PyList(); is_async=false) end end function __parse_call(jl_expr, arg1, args; topofblock) if arg1 == :+ if length(args) == 1 __unaryop(jl_expr, OP_UDICT[arg1]) else __multiop(jl_expr, OP_DICT[arg1]) end elseif arg1 โˆˆ [:-, :~, :(!)] if length(args) == 1 __unaryop(jl_expr, OP_UDICT[arg1]) else __binop(jl_expr, OP_DICT[arg1]) end elseif arg1 == :* __multiop(jl_expr, OP_DICT[arg1]) elseif arg1 == :(:) AST.Call(AST.Name("range"), __parse_range(args), []) elseif arg1 โˆˆ [:/, :รท, :div, :%, :mod, :^, :&, :|, :โŠป, :xor, :(<<), :(>>)] __binop(jl_expr, OP_DICT[arg1]) elseif arg1 โˆˆ [:(==), :(===), :โ‰ , :(!=), :(!==), :<, :<=, :>, :>=, :โˆˆ, :โˆ‰, :in] __compareop_from_call(jl_expr, OP_DICT[arg1]) elseif arg1 == :(=>) AST.Tuple(__jl2py(args)) elseif arg1 == :Dict || (isa(arg1, Expr) && arg1.head == :curly && arg1.args[1] == :Dict) # Handle generator separately if length(args) == 1 && args[1].head == :generator generator = __jl2py(args[1]) dict_call = AST.Call(AST.Name("dict"), PyList([generator]), PyList()) return topofblock ? AST.Expr(dict_call) : dict_call end _keys = [] values = [] for arg in args if isa(arg, Expr) && arg.head == :... push!(_keys, nothing) push!(values, __jl2py(arg.args[1])) else key, value = __parse_pair(arg) push!(_keys, key) push!(values, value) end end AST.fix_missing_locations(AST.Dict(PyList(_keys), PyList(values))) else if isa(arg1, Symbol) || arg1.head == :curly # We discard the curly braces trailing a function call arg = isa(arg1, Symbol) ? arg1 : arg1.args[1] if arg โˆˆ keys(BUILTIN_DICT) func = AST.Name(BUILTIN_DICT[arg]) elseif string(arg1)[end] != '!' func = AST.Name(string(arg)) else func = AST.Name(string(arg)[1:(end - 1)] * "_inplace") end else func = __jl2py(arg1) end parameters = [] keywords = [] for arg in args if isa(arg, Expr) && arg.head == :parameters for param in arg.args if param.head == :kw key = pystr(param.args[1]) value = __jl2py(param.args[2]) push!(keywords, AST.keyword(key, value)) elseif param.head == :... value = __jl2py(param.args[1]) push!(keywords, AST.keyword(nothing, value)) end end else push!(parameters, __jl2py(arg)) end end call = AST.Call(func, parameters, keywords) topofblock ? AST.Expr(call) : call end end function __parse_assign(args) @match args[1] begin Expr(:(::), target, annotation) => AST.fix_missing_locations(AST.AnnAssign(__jl2py(target), __parse_type(annotation), __jl2py(args[2]), nothing)) # AnnAssign _ => begin # Assign targets = PyList() curr = args while isa(curr[2], Expr) && curr[2].head == :(=) push!(targets, __jl2py(curr[1])) curr = curr[2].args end last_target, value = __jl2py(curr) push!(targets, last_target) return AST.fix_missing_locations(AST.Assign(targets, value)) end end end __jl2py(args::AbstractVector) = map(__jl2py, args) function __jl2py(jl_constant::Union{Number,String}; topofblock::Bool=false) return topofblock ? AST.Expr(AST.Constant(jl_constant)) : AST.Constant(jl_constant) end function __jl2py(jl_symbol::Symbol; topofblock::Bool=false) name = jl_symbol == :nothing ? AST.Constant(nothing) : AST.Name(pystr(jl_symbol)) return topofblock ? AST.Expr(name) : name end function __jl2py(jl_qnode::QuoteNode; topofblock::Bool=false) return string(jl_qnode.value) end __jl2py(::Nothing) = AST.Constant(nothing) function __jl2py(jl_expr::Expr; topofblock::Bool=false, isflatten::Bool=false, iscomprehension::Bool=false) @match jl_expr begin Expr(:block, args...) || Expr(:toplevel, args...) => PyList([__jl2py(expr; topofblock=true) for expr in args if !isa(expr, LineNumberNode)]) Expr(:function, _...) => __parse_function(jl_expr) Expr(:(&&), _...) || Expr(:(||), _...) => __boolop(jl_expr, OP_DICT[jl_expr.head]) Expr(:tuple, args...) => AST.Tuple(__jl2py(jl_expr.args)) Expr(:..., arg) => AST.Starred(__jl2py(arg)) Expr(:., arg1, arg2) => AST.Attribute(__jl2py(arg1), __jl2py(arg2)) Expr(:->, _...) => __parse_lambda(jl_expr) Expr(:if, _...) || Expr(:elseif, _...) => __parse_if(jl_expr) Expr(:while, test, body) => AST.While(__jl2py(test), __jl2py(body), nothing) Expr(:for, Expr(_, target, iter), body) => AST.fix_missing_locations(AST.For(__jl2py(target), __jl2py(iter), __jl2py(body), nothing, nothing)) Expr(:continue) => AST.Continue() Expr(:break) => AST.Break() Expr(:return, arg) => AST.Return(__jl2py(arg)) Expr(:ref, value, slices...) => __parse_ref(value, slices) Expr(:comprehension, arg) => AST.ListComp(__jl2py(arg; iscomprehension=true)...) Expr(:generator, arg1, args...) => __parse_generator(arg1, args; isflatten, iscomprehension) Expr(:filter, filter, args...) => __parse_filter(filter, args) Expr(:flatten, arg) => __jl2py(arg; isflatten=true, iscomprehension=iscomprehension) Expr(:comparison, _...) => __compareop_from_comparison(jl_expr) Expr(:call, arg1, args...) => __parse_call(jl_expr, arg1, args; topofblock) Expr(:(=), args...) => __parse_assign(args) Expr(:vect, args...) => AST.List(__jl2py(args)) Expr(op, target, value) => AST.fix_missing_locations(AST.AugAssign(__jl2py(target), OP_DICT[op](), __jl2py(value))) _ => begin @warn("Pattern unmatched") return AST.Constant(nothing) end end end jl2py(ast) = __jl2py(ast) unparse(ast) = AST.unparse(ast) function jl2py(jl_str::String; ast_only::Bool=false, apply_polyfill::Bool=false) jl_ast = Meta.parse(jl_str) if isnothing(jl_ast) return "" end py_ast = __jl2py(jl_ast) if ast_only return py_ast end _module = AST.Module(PyList([py_ast]), []) py_str = AST.unparse(_module) if apply_polyfill polyfill = read(joinpath(@__DIR__, "..", "polyfill", "polyfill.py"), String) return polyfill * "\n" * string(py_str) end return string(py_str) end function __init__() PythonCall.pycopy!(AST, pyimport("ast")) OP_UDICT[:+] = AST.UAdd OP_UDICT[:-] = AST.USub OP_UDICT[:~] = AST.Invert OP_UDICT[:(!)] = AST.Not OP_DICT[:+] = AST.Add OP_DICT[:-] = AST.Sub OP_DICT[:*] = AST.Mult OP_DICT[:/] = AST.Div OP_DICT[:รท] = AST.FloorDiv OP_DICT[:div] = AST.FloorDiv OP_DICT[:%] = AST.Mod OP_DICT[:mod] = AST.Mod OP_DICT[:^] = AST.Pow OP_DICT[:(==)] = AST.Eq OP_DICT[:(===)] = AST.Eq OP_DICT[:โ‰ ] = AST.NotEq OP_DICT[:(!=)] = AST.NotEq OP_DICT[:(!==)] = AST.NotEq OP_DICT[:<] = AST.Lt OP_DICT[:<=] = AST.LtE OP_DICT[:>=] = AST.GtE OP_DICT[:>] = AST.Gt OP_DICT[:in] = AST.In OP_DICT[:โˆˆ] = AST.In OP_DICT[:โˆ‰] = AST.NotIn OP_DICT[:(<<)] = AST.LShift OP_DICT[:(>>)] = AST.RShift OP_DICT[:&] = AST.BitAnd OP_DICT[:|] = AST.BitOr OP_DICT[:โŠป] = AST.BitXor OP_DICT[:xor] = AST.BitXor OP_DICT[:(&&)] = AST.And OP_DICT[:(||)] = AST.Or OP_DICT[:+=] = AST.Add OP_DICT[:-=] = AST.Sub OP_DICT[:*=] = AST.Mult OP_DICT[:/=] = AST.Div OP_DICT[:รท=] = AST.FloorDiv OP_DICT[:%=] = AST.Mod OP_DICT[:^=] = AST.Pow OP_DICT[:(<<=)] = AST.LShift OP_DICT[:(>>=)] = AST.RShift OP_DICT[:&=] = AST.BitAnd OP_DICT[:|=] = AST.BitOr OP_DICT[:โŠป=] = AST.BitXor TYPE_DICT[:Float32] = "float" TYPE_DICT[:Float64] = "float" TYPE_DICT[:Int] = "int" TYPE_DICT[:Int8] = "int" TYPE_DICT[:Int16] = "int" TYPE_DICT[:Int32] = "int" TYPE_DICT[:Int64] = "int" TYPE_DICT[:Int128] = "int" TYPE_DICT[:UInt] = "int" TYPE_DICT[:UInt8] = "int" TYPE_DICT[:UInt16] = "int" TYPE_DICT[:UInt32] = "int" TYPE_DICT[:UInt64] = "int" TYPE_DICT[:UInt128] = "int" TYPE_DICT[:Bool] = "bool" TYPE_DICT[:Char] = "str" TYPE_DICT[:String] = "str" TYPE_DICT[:Vector] = "List" TYPE_DICT[:Set] = "Set" TYPE_DICT[:Dict] = "Dict" TYPE_DICT[:Tuple] = "Tuple" TYPE_DICT[:Pair] = "Tuple" TYPE_DICT[:Union] = "Union" TYPE_DICT[:Nothing] = "None" BUILTIN_DICT[:length] = "len" BUILTIN_DICT[:sort] = "sorted" BUILTIN_DICT[:print] = "print" BUILTIN_DICT[:println] = "print" BUILTIN_DICT[:Set] = "set" return end end
Jl2Py
https://github.com/lucifer1004/Jl2Py.jl.git
[ "MIT" ]
0.1.5
8a5d4332019e086e06b68563bd1b26073ac1dbfc
code
15192
using Jl2Py using PythonCall using Test @testset "Jl2Py.jl" begin @testset "Basic functions" begin @testset "Empty" begin @test jl2py("") == "" @test jl2py("#comment") == "" end @testset "Literal constants" begin @test jl2py("2") == "2" @test jl2py("2.0") == "2.0" @test jl2py("\"hello\"") == "'hello'" @test jl2py("false") == "False" @test jl2py("true") == "True" @test jl2py("nothing") == "None" @test jl2py("foo") == "foo" end @testset "Attributes" begin @test jl2py("a.b") == "a.b" @test jl2py("a.b.c") == "a.b.c" @test jl2py("a.b.c.d") == "a.b.c.d" end @testset "UAdd & USub" begin @test jl2py("+3") == "3" @test jl2py("-3") == "-3" @test jl2py("+a") == "+a" @test jl2py("-a") == "-a" end @testset "Add" begin @test jl2py("1 + 1") == "1 + 1" @test jl2py("1 + 1 + 1") == "1 + 1 + 1" @test jl2py("1 + 1 + 1 + 1") == "1 + 1 + 1 + 1" @test jl2py("a + 2") == "a + 2" @test jl2py("a + b") == "a + b" end @testset "Sub" begin @test jl2py("1 - 1") == "1 - 1" @test jl2py("a - 2") == "a - 2" @test jl2py("a - b") == "a - b" end @testset "Mult" begin @test jl2py("1 * 2") == "1 * 2" @test jl2py("1 * 2 * 3") == "1 * 2 * 3" end @testset "Div & FloorDiv" begin @test jl2py("1 / 2") == "1 / 2" @test jl2py("1 รท 3") == "1 // 3" @test jl2py("div(3, 1)") == "3 // 1" end @testset "Mod" begin @test jl2py("1 % 2") == "1 % 2" @test jl2py("mod(3, 1)") == "3 % 1" end @testset "Pow" begin @test jl2py("10 ^ 5") == "10 ** 5" end @testset "Bitwise operators" begin @test jl2py("~2") == "~2" @test jl2py("1 & 2") == "1 & 2" @test jl2py("1 | 2") == "1 | 2" @test jl2py("1 โŠป 2") == "1 ^ 2" @test jl2py("xor(1, 2)") == "1 ^ 2" @test jl2py("1 << 2") == "1 << 2" @test jl2py("1 >> 2") == "1 >> 2" @test jl2py("1 + (-2 * 6) >> 2") == "1 + (-2 * 6 >> 2)" # Note the different association order end @testset "Logical operators" begin @test jl2py("!true") == "not True" @test jl2py("!false") == "not False" @test jl2py("!a") == "not a" @test jl2py("true && false") == "True and False" @test jl2py("true || false") == "True or False" end @testset "Complex arithmetic" begin @test jl2py("(1 + 5) * (2 - 5) / (3 * 6)") == "(1 + 5) * (2 - 5) / (3 * 6)" end @testset "Binary comparisons" begin @test jl2py("1 == 2") == "1 == 2" @test jl2py("1 === 2") == "1 == 2" @test jl2py("1 != 2") == "1 != 2" @test jl2py("1 < 2") == "1 < 2" @test jl2py("1 <= 2") == "1 <= 2" @test jl2py("1 > 2") == "1 > 2" @test jl2py("1 >= 2") == "1 >= 2" @test jl2py("a โˆˆ b") == "a in b" @test jl2py("a in b") == "a in b" @test jl2py("a โˆ‰ b") == "a not in b" end @testset "Multiple comparisons" begin @test jl2py("1 < 2 < 3") == "1 < 2 < 3" @test jl2py("1 < 2 < 3 < 4") == "1 < 2 < 3 < 4" @test jl2py("3 > 2 != 3 == 3") == "3 > 2 != 3 == 3" end @testset "Ternary operator" begin @test jl2py("x > 2 ? 1 : 0") == "1 if x > 2 else 0" end @testset "Ranges" begin @test jl2py("1:10") == "range(1, 11)" @test jl2py("1:2:10") == "range(1, 11, 2)" @test jl2py("a:b") == "range(a, b + 1)" @test jl2py("1:0.1:5") == "range(1, 5, 0.1)" end @testset "List" begin @test jl2py("[1, 2, 3]") == "[1, 2, 3]" @test jl2py("[1, 2 + 3, 3]") == "[1, 2 + 3, 3]" @test jl2py("[1, 2, [3, 4], []]") == "[1, 2, [3, 4], []]" end @testset "Pair" begin @test jl2py("1 => 2") == "(1, 2)" @test jl2py("a => b") == "(a, b)" @test jl2py("a => b => c") == "(a, (b, c))" end @testset "Tuple" begin @test jl2py("(1,)") == "(1,)" @test jl2py("(1, 2, 3)") == "(1, 2, 3)" @test jl2py("(1, 2, 3,)") == "(1, 2, 3)" @test jl2py("(a, a + b, c)") == "(a, a + b, c)" end @testset "Dict" begin @test jl2py("Dict(1=>2, 3=>14)") == "{1: 2, 3: 14}" @test jl2py("Dict{Number,Number}(1=>2, 3=>14)") == "{1: 2, 3: 14}" # Type info is discarded end @testset "Expansion" begin @test jl2py("(a...,)") == "(*a,)" @test jl2py("[a..., b...]") == "[*a, *b]" @test jl2py("Dict(a..., b => c)") == "{**a, b: c}" end @testset "Assign" begin @test jl2py("a = 2") == "a = 2" @test jl2py("a = 2 + 3") == "a = 2 + 3" @test jl2py("a = b = 2") == "a = b = 2" @test jl2py("a = b = c = 23 + 3") == "a = b = c = 23 + 3" end @testset "AnnAssign" begin @test jl2py("a::Int = 2") == "(a): int = 2" end @testset "AugAssign" begin @test jl2py("a += 2") == "a += 2" @test jl2py("a -= 2 + 3") == "a -= 2 + 3" @test jl2py("a *= 2") == "a *= 2" @test jl2py("a /= 2") == "a /= 2" @test jl2py("a รท= 2") == "a //= 2" @test jl2py("a %= 2") == "a %= 2" @test jl2py("a ^= 2") == "a **= 2" @test jl2py("a <<= 2") == "a <<= 2" @test jl2py("a >>= 2") == "a >>= 2" @test jl2py("a &= 2") == "a &= 2" @test jl2py("a |= 2") == "a |= 2" @test jl2py("a โŠป= 2") == "a ^= 2" end @testset "If statement" begin @test jl2py("if x > 3 x += 2 end") == "if x > 3:\n x += 2" @test jl2py("if x > 3 x += 2 else x -= 1 end") == "if x > 3:\n x += 2\nelse:\n x -= 1" @test jl2py("if x > 3 x += 2 elseif x < 0 x -= 1 end") == "if x > 3:\n x += 2\nelif x < 0:\n x -= 1" end @testset "Loops" begin @testset "While statement" begin @test jl2py("while x > 3 x -= 1 end") == "while x > 3:\n x -= 1" end @testset "For statement" begin @test jl2py("for (x, y) in zip(a, b) print(x) end") == "for (x, y) in zip(a, b):\n print(x)" end @testset "Loop with continue & break" begin @test jl2py(""" for i in 1:10 if i % 2 == 0 continue elseif i % 7 == 0 break else print(i) end end""") == "for i in range(1, 11):\n" * " if i % 2 == 0:\n" * " continue\n" * " elif i % 7 == 0:\n" * " break\n" * " else:\n" * " print(i)" end end @testset "Subscript" begin @test jl2py("a[1]") == "a[1]" @test jl2py("a[1:5]") == "a[1:6]" @test jl2py("a[1:2:5]") == "a[1:6:2]" @test jl2py("a[1,2,3]") == "a[1, 2, 3]" @test jl2py("a[1,2:5,3]") == "a[1, 2:6, 3]" @test jl2py("a[:,1,2:4]") == "a[:, 1, 2:5]" @test jl2py("d[\"a\"]") == "d['a']" end @testset "GeneratorExp" begin @test jl2py("sum(x for x in 1:100)") == "sum((x for x in range(1, 101)))" @test jl2py("Set(x for x in 1:100)") == "set((x for x in range(1, 101)))" @test jl2py("Dict(x=>y for (x, y) in zip(1:5, 1:6))") == "dict(((x, y) for (x, y) in zip(range(1, 6), range(1, 7))))" end @testset "List Comprehension" begin @test jl2py("[x for x in 1:5]") == "[x for x in range(1, 6)]" @test jl2py("[x for x in 1:5 if x % 2 == 0]") == "[x for x in range(1, 6) if x % 2 == 0]" @test jl2py("[(x, y) for (x, y) in zip(1:5, 5:-1:1)]") == "[(x, y) for (x, y) in zip(range(1, 6), range(5, 0, -1))]" @test jl2py("[x + 2 for x in 1:5 if x > 0]") == "[x + 2 for x in range(1, 6) if x > 0]" @test jl2py("[x for x in 1:5 if x > 4 for y in 1:5 if y >4]") == "[x for x in range(1, 6) if x > 4 for y in range(1, 6) if y > 4]" @test jl2py("[1 for y in 1:5, z in 1:6 if y > z]") == "[1 for y in range(1, 6) for z in range(1, 7) if y > z]" @testset "GeneratorExp within Generator" begin @test jl2py("[x for x in 1:5 if x > 4 for y in 1:5 if y >4 for z in 1:sum(x for x in 1:5)]") == "[x for x in range(1, 6) if x > 4 for y in range(1, 6) if y > 4 for z in range(1, sum((x for x in range(1, 6))) + 1)]" end end @testset "Function call (and builtins)" begin @test jl2py("print(2)") == "print(2)" @test jl2py("println(2)") == "print(2)" @test jl2py("length(a)") == "len(a)" @test jl2py("sort([2, 3, 4])") == "sorted([2, 3, 4])" @test jl2py("sort!([1, 5, 3])") == "sort_inplace([1, 5, 3])" # The trailing "!" is replaced by "_inplace" @test jl2py("f(a)") == "f(a)" @test jl2py("f(a, b)") == "f(a, b)" @test jl2py("f(a, b; c = 2)") == "f(a, b, c=2)" @test jl2py("f(a, b; kw...)") == "f(a, b, **kw)" @test jl2py("f(a, b, d...; c = 2, e...)") == "f(a, b, *d, c=2, **e)" @test jl2py("f(g(x))") == "f(g(x))" @test jl2py("f(x)(y)") == "f(x)(y)" @test jl2py("Set{Int}([1,2,3])") == "set([1, 2, 3])" end @testset "Multi-line" begin @test jl2py("a = 2; b = 3") == "a = 2\nb = 3" @test jl2py(""" begin function f(x::Int64, y::Int64) x + y end a = f(3) f(4) end """) == "def f(x: int, y: int, /):\n return x + y\na = f(3)\nf(4)" end @testset "Function defintion" begin @test jl2py("function f(x) end") == "def f(x, /):\n pass" @test jl2py("function f(x) return end") == "def f(x, /):\n return None" @test jl2py("function f(x) return x end") == "def f(x, /):\n return x" @test jl2py("function f(x) y; x + 1 end") == "def f(x, /):\n y\n return x + 1" @test jl2py("function f(x) x + 2 end") == "def f(x, /):\n return x + 2" @test jl2py("function f(x) x = 2 end") == "def f(x, /):\n x = 2\n return x" @test jl2py("function f(x) x += 2 end") == "def f(x, /):\n x += 2\n return x" @test jl2py("function f(x) g(x) end") == "def f(x, /):\n return g(x)" @test jl2py("function f(x::Float64) x + 2 end") == "def f(x: float, /):\n return x + 2" @test jl2py("function f(x::Int64, y) x + y end") == "def f(x: int, y, /):\n return x + y" @test jl2py("function f(x::Int)::Int x end") == "def f(x: int, /) -> int:\n return x" @test jl2py("function f(x::Int, y::Int)::Int x + y end") == "def f(x: int, y: int, /) -> int:\n return x + y" @test jl2py("function f(x=2, y=3) x + y end") == "def f(x=2, y=3, /):\n return x + y" @test jl2py("function f(x::Int=2, y=3) x + y end") == "def f(x: int=2, y=3, /):\n return x + y" @test jl2py("function f(;x::Int=2, y=3) x + y end") == "def f(*, x: int=2, y=3):\n return x + y" @test jl2py("function f(b...;x::Float32=2, y) x + y end") == "def f(*b, x: float=2, y):\n return x + y" @test jl2py("function f(a,b,c...;x::Float32=2, y) x + y end") == "def f(a, b, /, *c, x: float=2, y):\n return x + y" @test jl2py("function f(a,b,c...;x::Float32=2, y, z...) x + y end") == "def f(a, b, /, *c, x: float=2, y, **z):\n return x + y" @test jl2py("function f() for i in 1:10 print(i) end end") == "def f():\n for i in range(1, 11):\n print(i)" end @testset "Lambda" begin @test jl2py("x -> x + 1") == "lambda x, /: x + 1" @test jl2py("x::Float64 -> x + 1") == "lambda x: float, /: x + 1" @test jl2py("(x::Float64, y) -> x + y") == "lambda x: float, y, /: x + y" @test jl2py("(x::Float64, y)::Float64 -> x + y") == "lambda x: float, y, /: x + y" @test jl2py("function (x) x + 1 end") == "lambda x, /: x + 1" @test jl2py("(x; y = 2) -> x + y") == "lambda x, /, *, y=2: x + y" @test jl2py("(x, y = 2) -> x + y") == "lambda x, y=2, /: x + y" @test jl2py("(x; y::Float64 = 2, z = 3) -> x + y") == "lambda x, /, *, y: float=2, z=3: x + y" @test jl2py("(x, pos::Int; y::Float64 = 2, z = 3) -> x + y") == "lambda x, pos: int, /, *, y: float=2, z=3: x + y" @test_throws ErrorException jl2py("function (x) x + 1; y + 1 end") end @testset "Type annotations" begin @test jl2py("a::Nothing = nothing") == "(a): None = None" @test jl2py("a::Vector{Int} = 2") == "(a): List[int] = 2" @test jl2py("a::Set{Int} = Set([2, 3])") == "(a): Set[int] = set([2, 3])" @test jl2py("a::Dict{Int, Pair{Int, Tuple{String, Int, Char}}} = Dict()") == "(a): Dict[int, Tuple[int, Tuple[str, int, str]]] = {}" @test jl2py("a::Union{Int, Nothing} = nothing") == "(a): Union[int, None] = None" @test jl2py("a::ListNode = ListNode()") == "(a): ListNode = ListNode()" # Unknown types are not changed end @testset "Unmatched expressions" begin @test (@test_logs (:warn, "Pattern unmatched") jl2py("a = ")) == "None" end end @testset "Misc" begin @testset "AST to AST" begin a = jl2py(1) @test pyconvert(Bool, pyisinstance(a, Jl2Py.AST.Constant) && a.value == 1) end @testset "Reexported unparse" begin @test pyconvert(String, unparse(jl2py("a + b"; ast_only=true))) == "a + b" end @testset "Apply Polyfill" begin polyfill = read(joinpath(@__DIR__, "..", "polyfill", "polyfill.py"), String) @test jl2py("print(1)"; apply_polyfill=true) == polyfill * "\n" * "print(1)" end end end
Jl2Py
https://github.com/lucifer1004/Jl2Py.jl.git
[ "MIT" ]
0.1.5
8a5d4332019e086e06b68563bd1b26073ac1dbfc
docs
1749
# Jl2Py [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://lucifer1004.github.io/Jl2Py.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://lucifer1004.github.io/Jl2Py.jl/dev) [![Build Status](https://github.com/lucifer1004/Jl2Py.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/lucifer1004/Jl2Py.jl/actions/workflows/CI.yml?query=branch%3Amain) [![Coverage](https://codecov.io/gh/lucifer1004/Jl2Py.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/lucifer1004/Jl2Py.jl) ## Examples Conversion results of [LeetCode.jl - 1. Two Sum](https://github.com/JuliaCN/LeetCode.jl/blob/master/src/problems/1.two-sum.jl) ```python def two_sum(nums: List[int], target: int, /) -> Union[None, Tuple[int, int]]: seen = {} for (i, n) in enumerate(nums): m = target - n if haskey(seen, m): return (seen[m], i) else: seen[n] = i ``` Conversion results of [LeetCode.jl - 2. Add Two Numbers](https://github.com/JuliaCN/LeetCode.jl/blob/master/src/problems/2.add-two-numbers.jl) ```python def add_two_numbers(l1: ListNode, l2: ListNode, /) -> ListNode: carry = 0 fake_head = cur = ListNode() while not isnothing(l1) or (not isnothing(l2) or not iszero(carry)): (v1, v2) = (0, 0) if not isnothing(l1): v1 = val(l1) l1 = next(l1) if not isnothing(l2): v2 = val(l2) l2 = next(l2) (carry, v) = divrem(v1 + v2 + carry, 10) next_inplace(cur, ListNode(v)) cur = next(cur) val_inplace(cur, v) return next(fake_head) ``` We can see that we only need to define a few polyfill functions to make the generated Python code work.
Jl2Py
https://github.com/lucifer1004/Jl2Py.jl.git
[ "MIT" ]
0.1.5
8a5d4332019e086e06b68563bd1b26073ac1dbfc
docs
164
```@meta CurrentModule = Jl2Py ``` # Jl2Py Documentation for [Jl2Py](https://github.com/lucifer1004/Jl2Py.jl). ```@index ``` ```@autodocs Modules = [Jl2Py] ```
Jl2Py
https://github.com/lucifer1004/Jl2Py.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
616
using Documenter using VLConstraintBasedModelGenerationUtilities makedocs( sitename = "Model", format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true" ), modules = [VLConstraintBasedModelGenerationUtilities], pages = [ "Home" => "index.md", ], ) # Documenter can also automatically deploy documentation to gh-pages. # See "Hosting Documentation" and deploydocs() in the Documenter manual # for more information. deploydocs( repo = "github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git", devurl = "stable", devbranch = "main", )
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
664
# setup project paths - const _PATH_TO_SRC = dirname(pathof(@__MODULE__)) const _PATH_TO_BASE = joinpath(_PATH_TO_SRC, "base") const _PATH_TO_CONFIG = joinpath(_PATH_TO_SRC, "config") # packages that I'm going to use ... using Test using TOML using DataFrames using CSV using JSON using BioSequences using BioSymbols using FASTX using DelimitedFiles using Logging using BSON # load my codes ... include(joinpath(_PATH_TO_BASE, "VLTypes.jl")) include(joinpath(_PATH_TO_BASE, "VLBase.jl")) include(joinpath(_PATH_TO_BASE, "VLSequenceUtilities.jl")) include(joinpath(_PATH_TO_BASE, "VLMetabolicUtilities.jl")) include(joinpath(_PATH_TO_BASE, "VLFileUtilities.jl"))
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
705
module VLConstraintBasedModelGenerationUtilities # Include my files - include("Include.jl") # export methods and types - export VLResult export check export build_gene_table export build_protein_table export build_metabolic_reaction_table export build_transcription_reaction_table export build_translation_reaction_table export build_transport_reaction_table export transcribe export translate export count # metabolic methods - export build_reaction_id_array export build_flux_bounds_array export build_species_symbol_array export build_stoichiometric_matrix # private: but has a unit test # export extract_stochiometric_coefficient_from_phrase # export complement function - export ! end # module
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
2294
using Base: has_nondefault_cmd_flags import Base.+ import Base.! import Base.count function !(nucleotide::BioSymbols.DNA)::BioSymbols.RNA # ok: use watson-crick base pairing rules to return the opposite nucleotide if nucleotide == DNA_T return RNA_A elseif nucleotide == DNA_A return RNA_U elseif nucleotide == DNA_C return RNA_G elseif nucleotide == DNA_G return RNA_C else return RNA_N end end function +(buffer::Array{String,1}, content::String; prefix::Union{String,Nothing}=nothing,suffix::Union{String,Nothing}=nothing) # create a new content line - new_line = content # prefix - if (prefix !== nothing) new_line = prefix*new_line end # suffix - if (suffix !== nothing) new_line = new_line*suffix end # cache - push!(buffer,new_line) end function read_file_from_path(path_to_file::String)::Array{String,1} # initialize - buffer = String[] # Read in the file - open("$(path_to_file)", "r") do file for line in eachline(file) +(buffer,line) end end # return - return buffer end function +(buffer::Array{String,1}, content_array::Array{String,1}) for line in content_array push!(buffer, line) end end function check(result::VLResult)::(Union{Nothing,T} where T <: Any) # ok, so check, do we have an error object? # Yes: log the error if we have a logger, then throw the error. # No: return the result.value # Error case - if (isa(result.value, Exception) == true) # get the error object - error_object = result.value # get the error message as a String - error_message = sprint(showerror, error_object, backtrace()) @error(error_message) # throw - throw(result.value) end # default - return result.value end function count(sequence::BioSequences.LongSequence, bioSymbol::BioSymbol)::Int64 # initialize - number_of_biosymbols = 0 # iterate - for test_symbol in sequence if (test_symbol == bioSymbol) number_of_biosymbols = number_of_biosymbols + 1 end end # return - return number_of_biosymbols end
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
7912
# === PRIVATE METHODS BELOW HERE =================================================================== # function _build_vff_reaction_table(path_to_reaction_file::String)::DataFrame # vff: CSV format with record structure # name,[ec;...],reactant,product,reversible # initialize - id_array = String[] forward_reaction_string = String[] reverse_reaction_string = String[] reversibility_array = Bool[] ec_number_array = Union{Missing,String}[] # get file buffer (array of strings) - vff_file_buffer = read_file_from_path(path_to_reaction_file) # process - for (_, reaction_line) in enumerate(vff_file_buffer) # skip comments and empty lines - if (occursin("//", reaction_line) == false && isempty(reaction_line) == false) # split around , reaction_record_components_array = split(reaction_line, ",") # process each of the components - # 1: id - push!(id_array, string(reaction_record_components_array[1])) # 2: ec numbers - ec_number_component = reaction_record_components_array[2] if (ec_number_component == "[]") push!(ec_number_array, missing) else push!(ec_number_array, string(ec_number_component[2:end - 1])) end # 3: L phrase - push!(forward_reaction_string, string(reaction_record_components_array[3])) # 4: R phrase - push!(reverse_reaction_string, string(reaction_record_components_array[4])) # 5: reverse - push!(reversibility_array, parse(Bool, string(reaction_record_components_array[5]))) end end # build the df - df_metabolic_reactions = DataFrame(id=id_array, forward=forward_reaction_string, reverse=reverse_reaction_string, reversibility=reversibility_array, ec=ec_number_array) # return - return df_metabolic_reactions end function _build_json_reaction_table(path_to_reaction_file::String)::DataFrame end function _build_sbml_reaction_table(path_to_reaction_file::String)::DataFrame end # === PRIVATE METHODS ABOVE HERE =================================================================== # # === PUBLIC METHODS BELOW HERE ==================================================================== # function build_gene_table(path_to_gene_file::String; logger::Union{Nothing,SimpleLogger}=nothing)::VLResult try # initialize - local_data_row = Union{String,Symbol,Missing,FASTA.Record}[] # ok - lets load the gene file open(FASTA.Reader, path_to_gene_file) do reader for record in reader push!(local_data_row, record) end end # create a data frame - sequence_data_frame = DataFrame(id=String[], description=String[], gene_sequence=Union{Missing,BioSequences.LongSequence}[]) sequence_data_record = Union{String,Missing,BioSequences.LongSequence}[] for record in local_data_row # get attributes from record - id_value = FASTX.FASTA.identifier(record) description_value = FASTX.FASTA.description(record) sequence_value = FASTX.FASTA.sequence(record) # pack - push!(sequence_data_record, id_value) push!(sequence_data_record, description_value) push!(sequence_data_record, sequence_value) push!(sequence_data_frame, tuple(sequence_data_record...)) end # return - return VLResult(sequence_data_frame) catch error return VLResult(error) end end function build_gene_table(gene_path_array::Array{String,1}; logger::Union{Nothing,SimpleLogger}=nothing) try # initialize - gene_table_dictionary::Dict{String,DataFrame}() # ok, so let process the array of files - for file_path in gene_path_array sequence_data_frame = build_gene_table(file_path; logger=logger) |> check gene_table_dictionary[file_path] = sequence_data_frame end # return a dictionary of gene tables - return VLResult(gene_table_dictionary) catch error return VLResult(error) end end function build_protein_table(path_to_protein_file::String; logger::Union{Nothing,SimpleLogger}=nothing)::VLResult try # initialize - local_data_row = Union{String,Symbol,Missing,FASTA.Record}[] # ok - lets load the gene file open(FASTA.Reader, path_to_protein_file) do reader for record in reader push!(local_data_row, record) end end # create a data frame - sequence_data_frame = DataFrame(id=String[], description=String[], protein_sequence=Union{Missing,BioSequences.LongSequence}[]) for record in local_data_row # init a row - sequence_data_record = Union{String,Missing,BioSequences.LongSequence}[] # get attributes from record - id_value = FASTX.FASTA.identifier(record) description_value = FASTX.FASTA.description(record) sequence_value = FASTX.FASTA.sequence(record) # pack - push!(sequence_data_record, id_value) push!(sequence_data_record, description_value) push!(sequence_data_record, sequence_value) push!(sequence_data_frame, tuple(sequence_data_record...)) end # return - return VLResult(sequence_data_frame) catch error return VLResult(error) end end function build_protein_table(protein_path_array::Array{String,1}; logger::Union{Nothing,SimpleLogger}=nothing)::VLResult try # initialize - protein_table_dictionary::Dict{String,DataFrame}() # ok, so let process the array of files - for file_path in protein_path_array sequence_data_frame = build_protein_table(file_path; logger=logger) |> check protein_table_dictionary[file_path] = sequence_data_frame end # return a dictionary of protein tables - return VLResult(protein_table_dictionary) catch error return VLResult(error) end end function build_metabolic_reaction_table(path_to_reaction_file::String; logger::Union{Nothing,SimpleLogger}=nothing)::VLResult try # what is the set of extensions that we can parse? extension_set = Set{String}() push!(extension_set, ".vff") push!(extension_set, ".json") push!(extension_set, ".sbml") push!(extension_set, ".xml") # get the file name from the path - reaction_filename = basename(path_to_reaction_file) # do we support this extension? reaction_file_extension = string(last(splitext(reaction_filename))) if (in(reaction_file_extension, extension_set) == false) throw(ArgumentError("Reaction file extension not supported: $(reaction_file_extension)")) end # ok: if we get here then we support this extension - reaction_table = nothing if (reaction_file_extension == ".vff") reaction_table = _build_vff_reaction_table(path_to_reaction_file) elseif (reaction_file_extension == ".json") reaction_table = _build_json_reaction_table(path_to_reaction_file) elseif (reaction_file_extension == ".sbml" || reaction_file_extension == ".xml") reaction_table = _build_sbml_reaction_table(path_to_reaction_file) end # return - return VLResult(reaction_table) catch error return VLResult(error) end end # === PUBLIC METHODS ABOVE HERE ==================================================================== #
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
6869
# == PRIVATE METHODS BELOW HERE ======================================================================================= # function _extract_species_from_phrase(phrase::String)::Array{String,1} # cut around the +'s species_array = Array{String,1}() species_substring_array = split(phrase, "+") # process each substring - for species_substring in species_substring_array # get the last value after we split for * - species_value = string(last(split(species_substring, "*"))) # grab - push!(species_array, species_value) end # return - return species_array end function _extract_stochiometric_coefficient_from_phrase(phrase::String, species::String)::Float64 # check: does this species occur in this phrase? if (occursin(species, phrase) == false) return 0.0 end # ok: if we get here, then we have this species - # split around the + plus_split_product_array = split(phrase, "+") # process each component of the phrase - for species_substring in plus_split_product_array # get the values after we split for * - tmp_value_array = string.(split(species_substring, "*")) # ok: the last element will always be the species. If we have two elements the first is the st coeff - if (last(tmp_value_array) == species) if (length(tmp_value_array) == 2) return parse(Float64, first(tmp_value_array)) else return 1.0 end end end # default returns 0.0 - return 0.0 end function _process_left_phrase(phrase::String, species::String)::Float64 # get coeff - stm_coeff = _extract_stochiometric_coefficient_from_phrase(phrase, species) # ok: if non-zero, then multiply by -1 if (stm_coeff > 0) return -1.0 * stm_coeff end # default - return stm_coeff end function _process_right_phrase(phrase::String, species::String)::Float64 return _extract_stochiometric_coefficient_from_phrase(phrase, species) end # == PRIVATE METHODS ABOVE HERE ======================================================================================= # # == PUBLIC METHODS BELOW HERE ======================================================================================== # function build_stoichiometric_matrix(reactionTable::DataFrame)::VLResult try # initialize - reaction_id_array = build_reaction_id_array(reactionTable) |> check species_symbol_array = build_species_symbol_array(reactionTable) |> check number_of_reactions = length(reaction_id_array) number_of_species = length(species_symbol_array) stoichiometric_matrx = zeros(number_of_species, number_of_reactions) # main - for species_index = 1:number_of_species # rows # grab species symbol - species_symbol = species_symbol_array[species_index] # does this symbol appear in a reaction? for reaction_index = 1:number_of_reactions # get the L and R phrases - L = reactionTable[reaction_index,:forward] R = reactionTable[reaction_index,:reverse] # get the stcoeff from the L phrase - L_st_coeff = _process_left_phrase(L, species_symbol) # get the stcoeff from the R phrase - R_st_coeff = _process_right_phrase(R, species_symbol) # update the stoichiometric_matrx - stoichiometric_matrx[species_index,reaction_index] = (L_st_coeff + R_st_coeff) end end # return - return VLResult(stoichiometric_matrx) catch error return VLResult(error) end end function build_flux_bounds_array(reactionTable::DataFrame; defaultFluxBoundValue::Float64=100.0)::VLResult try # initialize - reaction_id_array = build_reaction_id_array(reactionTable) |> check number_of_reactions = length(reaction_id_array) flux_bounds_array = Array{Float64,2}(undef, number_of_reactions, 2) # iterate through the reaction id's and determine if the reaction is reversible. If so, then build the bounds array # using the default values - for (index, id_value) in enumerate(reaction_id_array) # is this reaction reversible? is_reversible = reactionTable[index,:reversibility] if (is_reversible == true) flux_bounds_array[index,1] = -1.0 * defaultFluxBoundValue flux_bounds_array[index,2] = defaultFluxBoundValue elseif (is_reversible == false) flux_bounds_array[index,1] = 0.0 flux_bounds_array[index,2] = defaultFluxBoundValue end end # return - return VLResult(flux_bounds_array) catch error return VLResult(error) end end function build_species_bounds_array()::VLResult try catch error return VLResult(error) end end function build_species_symbol_array(reactionTable::DataFrame)::VLResult try # initialize - species_symbol_array = Array{String,1}() reaction_phrase_array = Array{String,1}() (number_of_reactions, _) = size(reactionTable) # populate the array of reaction phrases - for reaction_index = 1:number_of_reactions # get the L and R phrases - L = reactionTable[reaction_index,:forward] R = reactionTable[reaction_index,:reverse] # capture - push!(reaction_phrase_array, L) push!(reaction_phrase_array, R) end # ok, so now lets populate the tmp species set - for reaction_phrase in reaction_phrase_array # get species sub array - species_in_reaction_phrase = _extract_species_from_phrase(reaction_phrase) # push into set - for tmp_species_symbol in species_in_reaction_phrase if (in(tmp_species_symbol, species_symbol_array) == false) push!(species_symbol_array, tmp_species_symbol) end end end # return - return VLResult(species_symbol_array) catch error return VLResult(error) end end function build_reaction_id_array(reactionTable::DataFrame)::VLResult try # get the id col - id_col = reactionTable[!,:id] # return - return VLResult(id_col) catch error return VLResult(error) end end # == PUBLIC METHODS ABOVE HERE ======================================================================================== #
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
13192
function build_transcription_reaction_table(gene_name::String, sequence::BioSequences.LongSequence; polymeraseSymbol::Symbol=:RNAP, ecnumber::String="2.7.7.6", logger::Union{Nothing,SimpleLogger}=nothing)::VLResult try # initialize - id_array = String[] forward_reaction_string = String[] reverse_reaction_string = String[] reversibility_array = Bool[] ec_number_array = Union{Missing,String}[] polymeraseSymbol = string(polymeraseSymbol) # get a count on G,C,A,U - number_of_A = count(sequence, DNA_A) number_of_U = count(sequence, DNA_T) number_of_C = count(sequence, DNA_C) number_of_G = count(sequence, DNA_G) total_nucleotides = number_of_A + number_of_U + number_of_C + number_of_G # setup reactions - # gene + RNAP <=> gene_RNAP_closed push!(id_array, "$(gene_name)_binding") push!(forward_reaction_string, "$(gene_name)+$(polymeraseSymbol)") push!(reverse_reaction_string, "$(gene_name)_$(polymeraseSymbol)_closed") push!(reversibility_array, true) push!(ec_number_array, missing) # gene_RNAP_closed => gene_RNAP_open push!(id_array, "$(gene_name)_open") push!(forward_reaction_string, "$(gene_name)_$(polymeraseSymbol)_closed") push!(reverse_reaction_string, "$(gene_name)_$(polymeraseSymbol)_open") push!(reversibility_array, false) push!(ec_number_array, missing) # transcription - push!(id_array, "$(gene_name)_transcription") push!(forward_reaction_string, "$(gene_name)_$(polymeraseSymbol)_open+$(number_of_A)*M_atp_c+$(number_of_U)*M_utp_c+$(number_of_C)*M_ctp_c+$(number_of_G)*M_gtp_c+$(total_nucleotides)*M_h2o_c") push!(reverse_reaction_string, "mRNA_$(gene_name)+$(gene_name)+$(polymeraseSymbol)+$(total_nucleotides)*M_ppi_c") push!(reversibility_array, false) push!(ec_number_array, ecnumber) # mRNA degradation - push!(id_array, "mRNA_$(gene_name)_degradation") push!(forward_reaction_string, "mRNA_$(gene_name)") push!(reverse_reaction_string, "$(number_of_A)*M_amp_c+$(number_of_U)*M_ump_c+$(number_of_C)*M_cmp_c+$(number_of_G)*M_gmp_c") push!(reversibility_array, false) push!(ec_number_array, missing) # package into DataFrame - reaction_dataframe = DataFrame(id=id_array, forward=forward_reaction_string, reverse=reverse_reaction_string, reversibility=reversibility_array, ec=ec_number_array) # return - return VLResult(reaction_dataframe) catch error return VLResult(error) end end function build_translation_reaction_table(protein_name::String, sequence::BioSequences.LongAminoAcidSeq; ribosomeSymbol::Symbol=:RIBOSOME, ecnumber::String="3.1.27.10", logger::Union{Nothing,SimpleLogger}=nothing)::VLResult try # initailize - id_array = String[] forward_reaction_string = String[] reverse_reaction_string = String[] reversibility_array = Bool[] ec_number_array = Union{Missing,String}[] ribosomeSymbol = string(ribosomeSymbol) total_residue_count = 0 protein_aa_map = Dict{BioSymbol,Int64}() aa_biosymbol_array = [ AA_A, AA_R, AA_N, AA_D, AA_C, AA_Q, AA_E, AA_G, AA_H, AA_I, AA_L, AA_K, AA_M, AA_F, AA_P, AA_S, AA_T, AA_W, AA_Y, AA_V ]; # load AA map - aa_metabolite_map = TOML.parsefile(joinpath(_PATH_TO_CONFIG, "AAMap.toml")) # build the protein_aa_map - for residue in aa_biosymbol_array protein_aa_map[residue] = count(sequence, residue) end # total residue count - for residue in aa_biosymbol_array number_per_AA = protein_aa_map[residue] total_residue_count = total_residue_count + number_per_AA end # setup reactions - # mRNA + RIBOSOME <=> mRNA_RIBOSOME_closed push!(id_array, "$(protein_name)_binding") push!(forward_reaction_string, "mRNA_$(protein_name)+$(ribosomeSymbol)") push!(reverse_reaction_string, "mRNA_$(protein_name)_$(ribosomeSymbol)_closed") push!(reversibility_array, true) push!(ec_number_array, missing) # mRNA_RIBOSOME_closed => mRNA_RIBOSOME_start push!(id_array, "mRNA_$(protein_name)_open") push!(forward_reaction_string, "mRNA_$(protein_name)_$(ribosomeSymbol)_closed") push!(reverse_reaction_string, "mRNA_$(protein_name)_$(ribosomeSymbol)_start") push!(reversibility_array, false) push!(ec_number_array, missing) # mRNA_RIBOSOME_translation - push!(id_array, "mRNA_$(protein_name)_translation") push!(forward_reaction_string, "mRNA_$(protein_name)_$(ribosomeSymbol)_start+$(2 * total_residue_count)*M_gtp_c+$(2 * total_residue_count)*M_h2o_c") push!(reverse_reaction_string, "mRNA_$(protein_name)+$(ribosomeSymbol)+P_$(protein_name)+$(2 * total_residue_count)*M_gdp_c+$(2 * total_residue_count)*M_pi_c+$(total_residue_count)*tRNA_c") push!(reversibility_array, false) push!(ec_number_array, missing) # charge the tRNA - for residue in aa_biosymbol_array # get the key symbol - key_value = "AA_" * (string(residue)) # get the number and M_* of this residue - number_of_AA_residue = protein_aa_map[residue] metabolite_symbol = aa_metabolite_map[key_value] # build the reaction record - push!(id_array, "tRNA_charging_$(metabolite_symbol)_$(protein_name)") push!(forward_reaction_string, "$(number_of_AA_residue)*$(metabolite_symbol)+$(number_of_AA_residue)*M_atp_c+$(number_of_AA_residue)*tRNA_c+$(number_of_AA_residue)*M_h2o_c") push!(reverse_reaction_string, "$(number_of_AA_residue)*$(metabolite_symbol)_tRNA_c+$(number_of_AA_residue)*M_amp_c+$(number_of_AA_residue)*M_ppi_c") push!(reversibility_array, false) push!(ec_number_array, missing) end # package into DataFrame - reaction_dataframe = DataFrame(id=id_array, forward=forward_reaction_string, reverse=reverse_reaction_string, reversibility=reversibility_array, ec=ec_number_array) # return - return VLResult(reaction_dataframe) catch error return VLResult(error) end end function build_transport_reaction_table()::VLResult try # initailize - id_array = String[] forward_reaction_string = String[] reverse_reaction_string = String[] reversibility_array = Bool[] ec_number_array = Union{Missing,String}[] aa_biosymbol_array = [ AA_A, AA_R, AA_N, AA_D, AA_C, AA_Q, AA_E, AA_G, AA_H, AA_I, AA_L, AA_K, AA_M, AA_F, AA_P, AA_S, AA_T, AA_W, AA_Y, AA_V ]; # load AA map - aa_metabolite_map = TOML.parsefile(joinpath(_PATH_TO_CONFIG, "AAMap.toml")) # add exchange water reactions - push!(id_array, "M_h2o_c_exchange") push!(forward_reaction_string, "M_h2o_e") push!(reverse_reaction_string, "M_h2o_c") push!(reversibility_array, true) push!(ec_number_array, missing) # add M_ppi_e exchange - push!(id_array, "M_ppi_c_exchange") push!(forward_reaction_string, "M_ppi_e") push!(reverse_reaction_string, "M_ppi_c") push!(reversibility_array, true) push!(ec_number_array, missing) # add M_amp_c exchange - push!(id_array, "M_amp_c_exchange") push!(forward_reaction_string, "M_amp_e") push!(reverse_reaction_string, "M_amp_c") push!(reversibility_array, true) push!(ec_number_array, missing) # add M_gmp_c exchange - push!(id_array, "M_gmp_c_exchange") push!(forward_reaction_string, "M_gmp_e") push!(reverse_reaction_string, "M_gmp_c") push!(reversibility_array, true) push!(ec_number_array, missing) # add M_cmp_c exchange - push!(id_array, "M_cmp_c_exchange") push!(forward_reaction_string, "M_cmp_e") push!(reverse_reaction_string, "M_cmp_c") push!(reversibility_array, true) push!(ec_number_array, missing) # add M_ump_c exchange - push!(id_array, "M_ump_c_exchange") push!(forward_reaction_string, "M_ump_e") push!(reverse_reaction_string, "M_ump_c") push!(reversibility_array, true) push!(ec_number_array, missing) # add M_atp_c exchange - push!(id_array, "M_atp_c_exchange") push!(forward_reaction_string, "M_atp_e") push!(reverse_reaction_string, "M_atp_c") push!(reversibility_array, true) push!(ec_number_array, missing) # add M_gtp_c exchange - push!(id_array, "M_gtp_c_exchange") push!(forward_reaction_string, "M_gtp_e") push!(reverse_reaction_string, "M_gtp_c") push!(reversibility_array, true) push!(ec_number_array, missing) # add M_ctp_c exchange - push!(id_array, "M_ctp_c_exchange") push!(forward_reaction_string, "M_ctp_e") push!(reverse_reaction_string, "M_ctp_c") push!(reversibility_array, true) push!(ec_number_array, missing) # add M_utp_c exchange - push!(id_array, "M_utp_c_exchange") push!(forward_reaction_string, "M_utp_e") push!(reverse_reaction_string, "M_utp_c") push!(reversibility_array, true) push!(ec_number_array, missing) push!(id_array, "tRNA_c_exchange") push!(forward_reaction_string, "tRNA_e") push!(reverse_reaction_string, "tRNA_c") push!(reversibility_array, true) push!(ec_number_array, missing) # transfer AAs - for residue in aa_biosymbol_array # get the key symbol - key_value = "AA_" * (string(residue)) # metabilite - metabolite_symbol_c = aa_metabolite_map[key_value] metabolite_symbol_e = replace(metabolite_symbol_c, "_c" => "_e") # write the record - push!(id_array, "$(metabolite_symbol_c)_exchange") push!(forward_reaction_string, metabolite_symbol_e) push!(reverse_reaction_string, metabolite_symbol_c) push!(reversibility_array, true) push!(ec_number_array, missing) end # package into DataFrame - reaction_dataframe = DataFrame(id=id_array, forward=forward_reaction_string, reverse=reverse_reaction_string, reversibility=reversibility_array, ec=ec_number_array) # return - return VLResult(reaction_dataframe) catch error return VLResult(error) end end function transcribe(sequence::BioSequences.LongSequence; complementOperation::Function=!, logger::Union{Nothing,SimpleLogger}=nothing)::VLResult try # initialize - new_sequence_array = Array{BioSymbol,1}() # ok: let's iterate the sequence, call the complementOperation function for each nt - for nt in sequence # call the complementOperation function to get the complementary nucleotide - complementary_nt = complementOperation(nt) # push - push!(new_sequence_array, complementary_nt) end # create new sequence - new_seq_from_array = LongSequence{RNAAlphabet{4}}(new_sequence_array) # return - return VLResult(new_seq_from_array) catch error return VLResult(error) end end function transcribe(table::DataFrame, complementOperation::Function=!; logger::Union{Nothing,SimpleLogger}=nothing) try # initailize - transcription_dictionary = Dict{String,Any}() # get the length of the table - (number_of_rows, _) = size(table) for row_index = 1:number_of_rows # get id - sequence_id = table[row_index, :id] sequence = table[row_index, :sequence] # transcribe - result = transcribe_sequence(sequence, complementOperation; logger=logger) |> check # package - transcription_dictionary[sequence_id] = result end # return - return VLResult(transcription_dictionary) catch error return VLResult(error) end end function translate(sequence::BioSequences.LongAminoAcidSeq, complementOperation::Function; logger::Union{Nothing,SimpleLogger}=nothing)::VLResult try catch error return VLResult(error) end end function translate(table::DataFrame, complementOperation::Function; logger::Union{Nothing,SimpleLogger}=nothing)::VLResult try # get the size of the table - (number_of_proteins, _) = size(table) for protein_index in number_of_proteins # get the sequence - protein_seq = table[protein_index, :protein_sequence] end catch error return VLResult(error) end end
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
56
# concrete types - struct VLResult{T} value::T end
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
874
using VLConstraintBasedModelGenerationUtilities using DataFrames # setup path to sequence file - path_to_protein_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/P-MZ373340.fasta" # load - protein_table = build_protein_table(path_to_protein_sequence_file) |> check seq = protein_table[1,:protein_sequence] seq_name = protein_table[1,:id] # build the translation table - translation_dictionary = Dict{String,DataFrame}() (number_of_proteins, _) = size(protein_table) for protein_index = 1:number_of_proteins local_seq = protein_table[protein_index,:protein_sequence] local_seq_name = protein_table[protein_index,:id] translation_table = build_translation_reaction_table(local_seq_name, local_seq) |> check # grab - translation_dictionary[local_seq_name] = translation_table end
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
352
using VLConstraintBasedModelGenerationUtilities using Test # -- Model creation tests ------------------------------------------------------ # function run_default_test() return true end # ------------------------------------------------------------------------------- # @testset "default_test_set" begin @test run_default_test() == true end
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
1848
using VLConstraintBasedModelGenerationUtilities using DataFrames # setup path to sequence file - path_to_gene_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/G-MZ373340.fasta" # load - gene_table = build_gene_table(path_to_gene_sequence_file) |> check # get the sequence - gene_seq = gene_table[!,:gene_sequence][1] gene_seq_name = gene_table[!,:id][1] # transcription table - transcription_table = build_transcription_reaction_table(gene_seq_name, gene_seq) |> check # setup path to protein sequence file - path_to_protein_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/P-MZ373340.fasta" # load - protein_table = build_protein_table(path_to_protein_sequence_file) |> check # build the translation table - translation_dictionary = Dict{String,DataFrame}() translation_array = Array{DataFrame,1}() (number_of_proteins, _) = size(protein_table) for protein_index = 1:number_of_proteins local_seq = protein_table[protein_index,:protein_sequence] local_seq_name = protein_table[protein_index,:id] translation_table = build_translation_reaction_table(local_seq_name, local_seq) |> check # grab - # translation_dictionary[local_seq_name] = translation_table push!(translation_array, translation_table) end # add together - master_translation_table = reduce(vcat, translation_array) # lastly - let's build the transport reactions - transport_reaction_table = build_transport_reaction_table() |> check # append reactions into master reaction table - master_reaction_table = reduce(vcat, [transcription_table, master_translation_table, transport_reaction_table]) # build the flux bounds array - fba = build_flux_bounds_array(master_reaction_table; defaultFluxBoundValue=1.0) |> check
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
1728
using VLConstraintBasedModelGenerationUtilities using DataFrames # setup path to sequence file - path_to_gene_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/G-MZ373340.fasta" # load - gene_table = build_gene_table(path_to_gene_sequence_file) |> check # get the sequence - gene_seq = gene_table[!,:gene_sequence][1] gene_seq_name = gene_table[!,:id][1] # transcription table - transcription_table = build_transcription_reaction_table(gene_seq_name, gene_seq) |> check # setup path to protein sequence file - path_to_protein_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/P-MZ373340.fasta" # load - protein_table = build_protein_table(path_to_protein_sequence_file) |> check # build the translation table - translation_dictionary = Dict{String,DataFrame}() translation_array = Array{DataFrame,1}() (number_of_proteins, _) = size(protein_table) for protein_index = 1:number_of_proteins local_seq = protein_table[protein_index,:protein_sequence] local_seq_name = protein_table[protein_index,:id] translation_table = build_translation_reaction_table(local_seq_name, local_seq) |> check # grab - # translation_dictionary[local_seq_name] = translation_table push!(translation_array, translation_table) end # add together - master_translation_table = reduce(vcat, translation_array) # lastly - let's build the transport reactions - transport_reaction_table = build_transport_reaction_table() |> check # append reactions into master reaction table - master_reaction_table = reduce(vcat, [transcription_table, master_translation_table, transport_reaction_table])
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
527
using VLConstraintBasedModelGenerationUtilities # setup path to protein sequence file - path_to_vff_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/Test.vff" # let's build the reaction table - metabolic_reaction_table = build_metabolic_reaction_table(path_to_vff_file) |> check # get list of species - list_of_species = build_species_symbol_array(metabolic_reaction_table) |> check # build the stm - stm = build_stoichiometric_matrix(metabolic_reaction_table) |> check
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
219
using VLConstraintBasedModelGenerationUtilities # test phrase - reaction_phrase = "3*M_a_c+8*M_b_c+M_d_c" # test: species = "M_gtp_c" stm_coeff = extract_stochiometric_coefficient_from_phrase(reaction_phrase, species)
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
207
using VLConstraintBasedModelGenerationUtilities # setup path to JSON file - path_to_json_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/iJO1366.json"
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
296
using VLConstraintBasedModelGenerationUtilities # setup path to sequence file - path_to_gene_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/G-MZ373340.fasta" # load - result = build_gene_table(path_to_gene_sequence_file) |> check
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
305
using VLConstraintBasedModelGenerationUtilities # setup path to sequence file - path_to_protein_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/P-MZ373340.fasta" # load - result = build_protein_table(path_to_protein_sequence_file) |> check
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
335
using VLConstraintBasedModelGenerationUtilities # setup path to protein sequence file - path_to_vff_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/Test.vff" # let's build the reaction table - metabolic_reaction_table = build_metabolic_reaction_table(path_to_vff_file) |> check
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
1824
using VLConstraintBasedModelGenerationUtilities using DataFrames # setup path to sequence file - path_to_gene_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/G-MZ373340.fasta" # load - gene_table = build_gene_table(path_to_gene_sequence_file) |> check # get the sequence - gene_seq = gene_table[!,:gene_sequence][1] gene_seq_name = gene_table[!,:id][1] # transcription table - transcription_table = build_transcription_reaction_table(gene_seq_name, gene_seq) |> check # setup path to protein sequence file - path_to_protein_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/P-MZ373340.fasta" # load - protein_table = build_protein_table(path_to_protein_sequence_file) |> check # build the translation table - translation_dictionary = Dict{String,DataFrame}() translation_array = Array{DataFrame,1}() (number_of_proteins, _) = size(protein_table) for protein_index = 1:number_of_proteins local_seq = protein_table[protein_index,:protein_sequence] local_seq_name = protein_table[protein_index,:id] translation_table = build_translation_reaction_table(local_seq_name, local_seq) |> check # grab - # translation_dictionary[local_seq_name] = translation_table push!(translation_array, translation_table) end # add together - master_translation_table = reduce(vcat, translation_array) # lastly - let's build the transport reactions - transport_reaction_table = build_transport_reaction_table() |> check # append reactions into master reaction table - master_reaction_table = reduce(vcat, [transcription_table, master_translation_table, transport_reaction_table]) # build the flux bounds array - ssa = build_species_symbol_array(master_reaction_table) |> check
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
831
using VLConstraintBasedModelGenerationUtilities using BioSymbols # setup path to sequence file - path_to_gene_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/G-MZ373340.fasta" # load - gene_table = build_gene_table(path_to_gene_sequence_file) |> check # get the sequence - gene_seq = gene_table[!,:gene_sequence][1] # setup local complementOp function - function complementOp(nucleotide::BioSymbols.DNA)::BioSymbols.RNA if nucleotide == DNA_T return RNA_U elseif nucleotide == DNA_A return RNA_A elseif nucleotide == DNA_C return RNA_C elseif nucleotide == DNA_G return RNA_G else return RNA_N end end # table - transcription_table = transcribe(gene_seq; complementOperation=complementOp) |> check
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
code
465
using VLConstraintBasedModelGenerationUtilities # setup path to sequence file - path_to_gene_sequence_file = "/Users/jeffreyvarner/Desktop/julia_work/VLConstraintBasedModelGenerationUtilities.jl/test/data/G-MZ373340.fasta" # load - gene_table = build_gene_table(path_to_gene_sequence_file) |> check # get the sequence - gene_seq = gene_table[!,:gene_sequence][1] # table - transcription_table = build_transcription_reaction_table("test_gene", gene_seq) |> check
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.1.0
6932df6a6deb4c6c63f88b04a9fef8bf1ac830c0
docs
2167
[![CI](https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl/actions/workflows/varnerlab.yml/badge.svg?event=push)](https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl/actions/workflows/varnerlab.yml) [![Documentation](https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl/actions/workflows/docdeploy.yml/badge.svg?event=push)](https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl/actions/workflows/docdeploy.yml) [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://varnerlab.github.io/VLConstraintBasedModelGenerationUtilities.jl/) ## Introduction ``VLConstraintBasedModelGenerationUtlities.jl`` is a [Julia](https://julialang.org/downloads/) package holding constraint based model generation utility functions and types. ## Installation and requirements ``VLConstraintBasedModelGenerationUtlities.jl`` is organized as a [Julia](http://julialang.org) package which can be installed in the ``package mode`` of Julia. Start of the [Julia REPL](https://docs.julialang.org/en/v1/stdlib/REPL/index.html) and enter the ``package mode`` using the ``]`` key (to get back press the ``backspace`` or ``^C`` keys). Then, at the prompt enter: (v1.1) pkg> add VLConstraintBasedModelGenerationUtlities This will install the ``VLConstraintBasedModelGenerationUtlities.jl`` package and the other required packages. ``VLConstraintBasedModelGenerationUtlities.jl`` requires Julia 1.6.x and above. ``VLConstraintBasedModelGenerationUtlities.jl`` is open source. You can download this repository as a zip file, or clone or pull it by using the command (from the command-line): $ git pull https://github.com/varnerlab/VLConstraintBasedModelGenerationUtlities.jl.git or $ git clone https://github.com/varnerlab/VLConstraintBasedModelGenerationUtlities.jl.git ## How do I contribute to this package? [Fork the project](https://guides.github.com/activities/forking/) and go crazy with it! Check out [Rob Allen's DevNotes](https://akrabat.com/the-beginners-guide-to-contributing-to-a-github-project/) for a beginner's guide to contributing to a GitHub project to get started.
VLConstraintBasedModelGenerationUtilities
https://github.com/varnerlab/VLConstraintBasedModelGenerationUtilities.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
554
using Documenter using IntervalConstraintProgramming, IntervalArithmetic makedocs( modules = [IntervalConstraintProgramming], doctest = true, format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true"), authors = "David P. Sanders", sitename = "IntervalConstraintProgramming.jl", pages = Any[ "Home" => "index.md", "API" => "api.md" ] ) deploydocs( repo = "github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git", target = "build", deps = nothing, make = nothing, )
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
1132
using Makie using Colors using IntervalConstraintProgramming, IntervalArithmetic ## Constraint programming solid_torus = @constraint (3 - sqrt(x^2 + y^2))^2 + z^2 <= 1 half_space = @constraint (x + y) + z <= 1 x = interval(-5, 5) Y = IntervalBox(x, 3) @time paving = pave(solid_torus โˆฉ half_space, Y, 0.1); inner = paving.inner boundary = paving.boundary; ## Makie plotting set-up positions = Point{3, Float32}[Point3(mid(x)...) for x in vcat(inner, boundary)] scales = Vec3f0[Vec3f0([diam(x) for x in xx]) for xx in vcat(inner, boundary)] zs = Float32[x[3] for x in positions] minz = minimum(zs) maxz = maximum(zs) xs = Float32[x[1] for x in positions] minx = minimum(xs) maxx = maximum(xs) colors1 = RGBA{Float32}[RGBA( (zs[i]-minz)/(maxz-minz), (xs[i]-minx)/(maxx-minx), 0f0, 0.1f0) for i in 1:length(inner)]; colors2 = RGBA{Float32}[RGBA( 0.5f0, 0.5f0, 0.5f0, 0.02f0) for x in boundary]; colors = vcat(colors1, colors2); ## Makie plotting: cube = Rect{3, Float32}(Vec3f0(-0.5, -0.5, -0.5), Vec3f0(1, 1, 1)) # centre, widths meshscatter(positions, marker=cube, scale=scales, color=colors, transparency=true)
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
663
__precompile__() module IntervalConstraintProgramming using IntervalArithmetic, IntervalContractors using Requires using MacroTools import Base: show, โˆฉ, โˆช, !, โІ, setdiff import IntervalArithmetic: sqr, setindex export BasicContractor, @contractor, Contractor, Separator, @constraint, @function, SubPaving, Paving, pave, Vol const reverse_operations = IntervalContractors.reverse_operations include("ast.jl") include("code_generation.jl") include("contractor.jl") include("separator.jl") include("paving.jl") include("setinversion.jl") include("volume.jl") include("functions.jl") include("init.jl") end # module
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
11144
const symbol_numbers = Dict{Symbol, Int}() """Return a new, unique symbol like _z3_""" function make_symbol(s::Symbol) # default is :z i = get(symbol_numbers, s, 0) symbol_numbers[s] = i + 1 if i == 0 return Symbol("_", s) else return Symbol("_", s, i) end end make_symbol(c::Char) = make_symbol(Symbol(c)) let current_symbol = 'a' global function make_symbol() current_sym = current_symbol if current_sym < 'z' current_symbol += 1 else current_symbol = 'a' end return make_symbol(current_sym) end end make_symbols(n::Integer) = [make_symbol() for i in 1:n] make_symbols(v::Vector{Symbol}) = make_symbols(length(v)) # The following function is not used """Check if a symbol like `:a` has been uniqued to `:_a_1_`""" function isuniqued(s::Symbol) ss = string(s) contains(ss, "_") && isdigit(ss[end-1]) end # Types for representing a flattened AST: # Combine Assignment and FunctionAssignment ? struct Assignment lhs op args end struct FunctionAssignment f # function name args # input arguments return_arguments intermediate # tuple of intermediate variables end # Close to single assignment form mutable struct FlatAST top # topmost variable(s) input_variables::Vector{Symbol} intermediate::Vector{Symbol} # generated vars code # ::Vector{Assignment} variables::Vector{Symbol} # cleaned version of input_variables end function Base.show(io::IO, flatAST::FlatAST) println(io, "top: ", flatAST.top) println(io, "input vars: ", flatAST.input_variables) println(io, "intermediate vars: ", flatAST.intermediate) println(io, "code: ", flatAST.code) end FlatAST() = FlatAST([], [], [], [], []) export FlatAST ## set_top!(flatAST::FlatAST, vars) = flatAST.top = vars # also returns vars add_variable!(flatAST::FlatAST, var) = push!(flatAST.input_variables, var) add_intermediate!(flatAST::FlatAST, var::Symbol) = push!(flatAST.intermediate, var) add_intermediate!(flatAST::FlatAST, vars::Vector{Symbol}) = append!(flatAST.intermediate, vars) add_code!(flatAST::FlatAST, code) = push!(flatAST.code, code) export flatten function flatten(ex, var = []) ex = MacroTools.striplines(ex) flatAST = FlatAST() if !isempty(var) for i in var push!(flatAST.input_variables, i) end end top = flatten!(flatAST, ex, var) return top, flatAST end """`flatten!` recursively converts a Julia expression into a "flat" (one-dimensional) structure, stored in a FlatAST object. This is close to SSA (single-assignment form, https://en.wikipedia.org/wiki/Static_single_assignment_form). Variables that are found are considered `input_variables`. Generated variables introduced at intermediate nodes are stored in `intermediate`. Returns the variable at the top of the current piece of the tree.""" # TODO: Parameters function _load_MT_flatten() return quote # numbers: function flatten!(flatAST::FlatAST, ex::Constant, var) return ex.value # nothing to do the AST; return the number end function flatten!(flatAST::FlatAST, ex::Variable, var) # symbols are leaves if isempty(var) add_variable!(flatAST, Symbol(ex)) # add the discovered symbol as an input variable end return Symbol(ex) end function flatten!(flatAST::FlatAST, ex::Operation, var) # top = process_operation!(flatAST, ex, var) # set_top!(flatAST, top) if ex.op isa Variable return flatten!(flatAST, ex.op, var) else top = process_operation!(flatAST, ex, var) set_top!(flatAST, top) end end end end function flatten!(flatAST::FlatAST, ex, var) return ex # nothing to do to the AST; return the number end # symbols: function flatten!(flatAST::FlatAST, ex::Symbol, var) if isempty(var) add_variable!(flatAST, ex) # add the discovered symbol as an input variable end return ex end function flatten!(flatAST::FlatAST, ex::Expr, var = []) local top if ex.head == :$ # constants written as $a top = process_constant!(flatAST, ex) elseif ex.head == :call # function calls top = process_call!(flatAST, ex, var) elseif ex.head == :(=) # assignments top = process_assignment!(flatAST, ex) elseif ex.head == :block top = process_block!(flatAST, ex) elseif ex.head == :tuple top = process_tuple!(flatAST, ex) elseif ex.head == :return top = process_return!(flatAST, ex) else error("Currently unable to process expressions with ex.head=$(ex.head)") end set_top!(flatAST, top) end function process_constant!(flatAST::FlatAST, ex) return esc(ex.args[1]) # interpolate the value of the external constant end """A block represents a linear sequence of Julia statements. They are processed in order. """ function process_block!(flatAST::FlatAST, ex) local top for arg in ex.args isa(arg, LineNumberNode) && continue top = flatten!(flatAST, arg) end return top # last variable assigned end # function process_iterated_function!(flatAST::FlatAST, ex) function process_tuple!(flatAST::FlatAST, ex) # println("Entering process_tuple") # @show flatAST # @show ex top_args = [flatten!(flatAST, arg) for arg in ex.args] # top_args = [] # the arguments returned for each element of the tuple # for arg in ex.args # top = flatten!(flatAST, arg) # push!(top_args, top) # end return top_args end """An assigment is of the form a = f(...). The name a is currently retained. TODO: It should later be made unique. """ function process_assignment!(flatAST::FlatAST, ex) # println("process_assignment!:") # @show ex # @show ex.args[1], ex.args[2] top = flatten!(flatAST, ex.args[2]) # @show top var = ex.args[1] # @show var # TODO: Replace the following by multiple dispatch if isa(var, Expr) && var.head == :tuple vars = [var.args...] elseif isa(var, Tuple) vars = [var...] elseif isa(var, Vector) vars = var else vars = [var] end add_intermediate!(flatAST, vars) top_level_code = Assignment(vars, :(), top) # empty operation add_code!(flatAST, top_level_code) # j@show flatAST return var end """Processes something of the form `(fโ†‘4)(x)` (write as `\\uparrow<TAB>`) by rewriting it to the equivalent set of iterated functions""" function process_iterated_function!(flatAST::FlatAST, ex) total_function_call = ex.args[1] args = ex.args[2:end] # @show args function_name = total_function_call.args[2] power = total_function_call.args[3] # assumed integer new_expr = :($function_name($(args...))) # @show new_expr for i in 2:power new_expr = :($function_name($new_expr)) end # @show new_expr flatten!(flatAST, new_expr) # replace the current expression with the new one end """A call is something like +(x, y). A new variable is introduced for the result; its name can be specified using the new_var optional argument. If none is given, then a new, generated name is used. """ function process_call!(flatAST::FlatAST, ex, var = [], new_var=nothing) #println("Entering process_call!") #@show ex #@show flatAST #@show new_var op = ex.args[1] #@show op if isa(op, Expr) if op.head == :line return elseif op.head == :call && op.args[1]==:โ†‘ # iterated function like f โ†‘ 4 return process_iterated_function!(flatAST, ex) end end # rewrite +(a,b,c) as +(a,+(b,c)) by recursive splitting # TODO: Use @match here! if op in (:+, :*) && length(ex.args) > 3 return flatten!(flatAST, :( ($op)($(ex.args[2]), ($op)($(ex.args[3:end]...) )) ), var) end top_args = [] for arg in ex.args[2:end] isa(arg, LineNumberNode) && continue top = flatten!(flatAST, arg, var) if isa(top, Vector) # TODO: make top always a Vector? append!(top_args, top) else push!(top_args, top) end end top_level_code = quote end #@show op if op โˆˆ keys(reverse_operations) # standard operator if isnothing(new_var) new_var = make_symbol() end add_intermediate!(flatAST, new_var) top_level_code = Assignment(new_var, op, top_args) else if haskey(registered_functions, op) f = registered_functions[op] # make enough new variables for all the returned arguments: return_args = make_symbols(f.return_arguments) intermediate = make_symbols(f.intermediate) #registered_functions[op].intermediate # make_symbol(:z_tuple) add_intermediate!(flatAST, return_args) add_intermediate!(flatAST, intermediate) top_level_code = FunctionAssignment(op, top_args, return_args, intermediate) new_var = return_args else throw(ArgumentError("Function $op not available. Use @function to define it.")) end end add_code!(flatAST, top_level_code) return new_var end function process_operation!(flatAST::FlatAST, ex, var, new_var=nothing) # println("\n\n--") # @show flatAST # @show ex # @show var # @show new_var op = ex.op if op in (+, *) && length(ex.args) > 2 return flatten!(flatAST, Expression( (op)((ex.args[1]), (op)((ex.args[2:end]...) )) ), var) end top_args = [] for arg in ex.args[1:end] isa(arg, LineNumberNode) && continue top = flatten!(flatAST, arg, var) if isa(top, Vector) append!(top_args, top) else push!(top_args, top) end end top_level_code = quote end #@show op if Symbol(op) โˆˆ keys(reverse_operations) # standard operator if isnothing(new_var) new_var = make_symbol() end add_intermediate!(flatAST, new_var) top_level_code = Assignment(new_var, Symbol(op), top_args) else if haskey(registered_functions, Symbol(op)) f = registered_functions[Symbol(op)] # make enough new variables for all the returned arguments: return_args = make_symbols(f.return_arguments) intermediate = make_symbols(f.intermediate) #registered_functions[op].intermediate # make_symbol(:z_tuple) add_intermediate!(flatAST, return_args) add_intermediate!(flatAST, intermediate) top_level_code = FunctionAssignment(Symbol(op), top_args, return_args, intermediate) new_var = return_args else throw(ArgumentError("Function $op not available. Use @function to define it.")) end end add_code!(flatAST, top_level_code) return new_var end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
5156
""" A generated function, with the code that generated it """ struct GeneratedFunction{F} f::F code::Expr end #GeneratedFunction(code::Expr) = GeneratedFunction(eval(code), code) (f::GeneratedFunction{F})(x...) where {F} = f.f(x...) function make_tuple(args) if isa(args, Symbol) # args = [args] return args end length(args) == 1 && return args[1] return Expr(:tuple, args...) end function really_make_tuple(args) return Expr(:tuple, args...) end function emit_forward_code(a::Assignment) args = isa(a.args, Vector) ? a.args : [a.args] lhs = make_tuple(a.lhs) if a.op == :() # empty args = make_tuple(args) :($lhs = $args) else :($lhs = $(a.op)($(args...) ) ) end end function emit_backward_code(a::Assignment) args = isa(a.args, Vector) ? a.args : [a.args] return_args = [a.lhs, args...] rev_op = reverse_operations[a.op] # find reverse operation if rev_op == :() # empty args = make_tuple(args) lhs = make_tuple(a.lhs) return :($args = $lhs) #return :($(args...) = $(a.lhs)) else rev_code = :($(rev_op)($(return_args...))) end # delete non-symbols in return args: for (i, arg) in enumerate(return_args) if !(isa(arg, Symbol)) return_args[i] = :_ end end return_tuple = Expr(:tuple, return_args...) # make tuple out of array # or: :($(return_args...),) return :($(return_tuple) = $(rev_code)) end # TODO: Just pass intermediate as tuple between forward and backward for functions function emit_forward_code(a::FunctionAssignment) f = a.f args = isa(a.args, Vector) ? a.args : [a.args] args_tuple = really_make_tuple(args) return_tuple = really_make_tuple(a.return_arguments) intermediate = really_make_tuple(a.intermediate) # Remove the following once https://github.com/JuliaLang/julia/issues/20524 fixed and replace with # :( ( $return_tuple, $intermediate ) = $(esc(f)).forward($args_tuple)) temp1 = make_symbol(:z_tuple) temp2 = make_symbol(:z_tuple) return quote ($temp1, $temp2) = $(esc(f)).forward($args_tuple) $return_tuple = $temp1 $intermediate = $temp2 end end function emit_backward_code(a::FunctionAssignment) f = a.f args = isa(a.args, Vector) ? a.args : [a.args] args_tuple = really_make_tuple(args) intermediate = really_make_tuple(a.intermediate) return_tuple = really_make_tuple(a.return_arguments) :($args_tuple = $(esc(f)).backward($args_tuple, $return_tuple, $intermediate)) end function emit_forward_code(code) # code::Vector{Assignment}) new_code = quote end new_code.args = vcat([emit_forward_code(line) for line in code]) return new_code end function emit_backward_code(code) #::Vector{Assignment}) new_code = quote end new_code.args = vcat([emit_backward_code(line) for line in reverse(code)]) return new_code end function forward_backward(flatAST::FlatAST) # @show flatAST.input_variables # @show flatAST.intermediate input = collect(flatAST.input_variables) # @show flatAST.top if isa(flatAST.top, Symbol) output = [flatAST.top] elseif isa(flatAST.top, Expr) && flatAST.top.head == :tuple output = flatAST.top.args else output = flatAST.top # @show output end # @show input # @show flatAST.intermediate # @show output input = setdiff(input, flatAST.intermediate) # remove local variables intermediate = setdiff(flatAST.intermediate, output) flatAST.variables = input forward_code = emit_forward_code(flatAST.code) forward = make_forward_function(input, output, intermediate, forward_code) # @show input # @show intermediate # @show output backward_code = emit_backward_code(flatAST.code) backward = make_backward_function(input, output, intermediate, input, backward_code) # @show input # @show output # @show intermediate return (forward, backward) end """ Generate code for an anonymous function with given input arguments, output arguments, and code block. """ function make_forward_function(input_args, output_args, intermediate, code) input = really_make_tuple(input_args) # make a tuple of the variables intermediate = really_make_tuple(intermediate) output = make_tuple(output_args) # make a tuple of the variables quote t -> begin $input = t $code return ($output, $intermediate) end end end function make_backward_function(input1, input2, input3, output_args, code) input1 = really_make_tuple(input1) # make a tuple of the variables input2 = really_make_tuple(input2) input3 = really_make_tuple(input3) output = really_make_tuple(output_args) # make a tuple of the variables quote (t1, t2, t3) -> begin $input1 = t1 $input2 = t2 $input3 = t3 $code return $output end end end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
6319
""" `Contractor` represents a `Contractor` from ``\\mathbb{R}^N`` to ``\\mathbb{R}^N``. Nout is the output dimension of the forward part. """ abstract type AbstractContractor end struct Contractor{N, Nout, F1<:Function, F2<:Function, ex} <:AbstractContractor variables::Vector{Symbol} # input variables forward::GeneratedFunction{F1} backward::GeneratedFunction{F2} expression::ex end struct BasicContractor{F1<:Function, F2<:Function} <:AbstractContractor forward::F1 backward::F2 end function Contractor(variables::Vector{Symbol}, top, forward, backward, expression) # @show variables # @show top N = length(variables) # input dimension local Nout # number of outputs if isa(top, Symbol) Nout = 1 elseif isa(top, Expr) && top.head == :tuple Nout = length(top.args) else Nout = length(top) end Contractor{N, Nout, typeof(forward.f), typeof(backward.f), typeof(expression)}(variables, forward, backward, expression) end function Base.show(io::IO, C::Contractor{N,Nout,F1,F2,ex}) where {N,Nout,F1,F2,ex} println(io, "Contractor in $(N) dimensions:") println(io, " - forward pass contracts to $(Nout) dimensions") println(io, " - variables: $(C.variables)") print(io, " - expression: $(C.expression)") end (C::Contractor)(X) = C.forward(X)[1] (C::BasicContractor)(X) = C.forward(X)[1] function contract(C::AbstractContractor, A::IntervalBox{Nout,T}, X::IntervalBox{N,T})where {N,Nout,T} output, intermediate = C.forward(X) # @show output # @show intermediate output_box = IntervalBox(output) constrained = output_box โˆฉ A # if constrained is already empty, eliminate call to backward propagation: if isempty(constrained) return emptyinterval(X) end # @show X # @show constrained # @show intermediate # @show C.backward(X, constrained, intermediate) return IntervalBox{N,T}(C.backward(X, constrained, intermediate) ) end function (C::Contractor)(A::IntervalBox{Nout,T}, X::IntervalBox{N,T})where {N,Nout,T} return contract(C, A, X) end # allow 1D contractors to take Interval instead of IntervalBox for simplicty: (C::Contractor)(A::Interval{T}, X::IntervalBox{N,T}) where {N,T} = C(IntervalBox(A), X) function (C::BasicContractor)(A::IntervalBox{Nout,T}, X::IntervalBox{N,T})where {N,Nout,T} return contract(C, A, X) end # allow 1D contractors to take Interval instead of IntervalBox for simplicty: (C::BasicContractor)(A::Interval{T}, X::IntervalBox{N,T}) where {N,T} = C(IntervalBox(A), X) function Base.show(io::IO, C::BasicContractor{F1,F2}) where {F1,F2} println(io, " Basic version of Contractor") end function _load_MT_contractor() return quote """ Contractor can also be construct without the use of macros vars = @variables x y z C = Contractor(x + y , vars) C(-Inf..1, IntervalBox(0.5..1.5,3)) """ function Contractor(variables, expr::Operation) var = [i.op.name for i in variables] top, linear_AST = flatten(expr, var) forward_code, backward_code = forward_backward(linear_AST) # @show top if isa(top, Symbol) top = [top] end forward = eval(forward_code) backward = eval(backward_code) Contractor(linear_AST.variables, top, GeneratedFunction(forward, forward_code), GeneratedFunction(backward, backward_code), expr) end function BasicContractor(variables, expr::Operation) var = [i.op.name for i in variables] top, linear_AST = flatten(expr, var) forward_code, backward_code = forward_backward(linear_AST) forward = eval(forward_code) backward = eval(backward_code) BasicContractor{typeof(forward), typeof(backward)}(forward, backward) end BasicContractor(expr::Operation) = BasicContractor([], expr::Operation) BasicContractor(vars::Union{Vector{Operation}, Tuple{Vararg{Operation,N}}}, g::Function) where N = BasicContractor(vars, g(vars...)) #Contractor can be constructed by function name only BasicContractor(vars, f::Function) = BasicContractor([Variable(Symbol(i))() for i in vars], f([Variable(Symbol(i))() for i in vars]...))#if vars is not vector of Operation Contractor(expr::Operation) = Contractor([], expr::Operation) Contractor(vars::Union{Vector{Operation}, Tuple{Vararg{Operation,N}}}, g::Function) where N = Contractor(vars, g(vars...)) #Contractor can be constructed by function name only Contractor(vars, f::Function) = Contractor([Variable(Symbol(i))() for i in vars], f([Variable(Symbol(i))() for i in vars]...))#if vars is not vector of Operation end end function make_contractor(expr::Expr, var = []) # println("Entering Contractor(ex) with ex=$ex") # expr, constraint_interval = parse_comparison(ex) # if constraint_interval != entireinterval() # warn("Ignoring constraint; include as first argument") # end top, linear_AST = flatten(expr, var) # @show expr # @show top # @show linear_AST forward_code, backward_code = forward_backward(linear_AST) # @show top if isa(top, Symbol) top = [top] elseif isa(top, Expr) && top.head == :tuple top = top.args end # @show forward_code # @show backward_code :(Contractor($(linear_AST.variables), $top, GeneratedFunction($forward_code, $(Meta.quot(forward_code))), GeneratedFunction($backward_code, $(Meta.quot(backward_code))), $(Meta.quot(expr)))) end """Usage: ``` C = @contractor(x^2 + y^2) A = -โˆž..1 # the constraint interval x = y = @interval(0.5, 1.5) C(A, x, y) `@contractor` makes a function that takes as arguments the variables contained in the expression, in lexicographic order ``` TODO: Hygiene for global variables, or pass in parameters """ macro contractor(ex, variables=[]) isa(variables, Array) ? var = [] : var = variables.args make_contractor(ex, var) end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
2532
""" A `ConstraintFunction` contains the created forward and backward code """ mutable struct ConstraintFunction{F <: Function, G <: Function} input::Vector{Symbol} # input arguments for forward function output::Vector{Symbol} # output arguments for forward function forward::F backward::G forward_code::Expr backward_code::Expr expression::Expr end function (C::ConstraintFunction)(args...) return C.forward(args)[1] end function Base.show(io::IO, f::ConstraintFunction{F,G}) where {F,G} println(io, "ConstraintFunction:") println(io, " - input arguments: $(f.input)") println(io, " - output arguments: $(f.output)") print(io, " - expression: $(MacroTools.striplines(f.expression))") end struct FunctionArguments input return_arguments intermediate end const registered_functions = Dict{Symbol, FunctionArguments}() # """ # `@function` registers a function to be used in forwards and backwards mode. # # Example: `@function f(x, y) = x^2 + y^2` # """ # this docstring does not work! @eval macro ($(:function))(ex) # workaround to define macro @function (f, args, code) = match_function(ex) return_arguments, flatAST = flatten(code) # make into an array: if !(isa(return_arguments, Array)) return_arguments = [return_arguments] end # rearrange so actual return arguments come first: flatAST.intermediate = setdiff(flatAST.intermediate, return_arguments) # println("HERE") # flatAST.intermediate = [return_arguments; flatAST.intermediate] forward, backward = forward_backward(flatAST) registered_functions[f] = FunctionArguments( flatAST.variables, return_arguments, flatAST.intermediate) return quote $(esc(f)) = ConstraintFunction($(flatAST.variables), $(flatAST.intermediate), $(forward), $(backward), $(Meta.quot(forward)), $(Meta.quot(backward)), $(Meta.quot(ex)) ) end end function match_function(ex) try @capture ex begin ( (f_(args__) = body_) | (function f_(args__) body_ end) ) end return (f, args, rmlines(body)) # rmlines is from MacroTools package catch throw(ArgumentError("$ex does not have the form of a function")) end end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
129
function __init__() @require ModelingToolkit = "961ee093-0014-501f-94e3-6117800e7a78" include("init_ModelingToolkit.jl") end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
191
using .ModelingToolkit: Constant, Variable, Operation eval(_load_MT_flatten()) eval(_load_MT_parse()) eval(_load_MT_make_constraint()) eval(_load_MT_separator()) eval(_load_MT_contractor())
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
1264
const SubPaving{N,T} = Vector{IntervalBox{N,T}} struct Paving{N,T} separator::Separator # parametrize! inner::SubPaving{N,T} boundary::SubPaving{N,T} ฯต::Float64 end function setdiff(x::IntervalBox{N,T}, subpaving::SubPaving{N,T}) where {N,T} working = [x] new_working = IntervalBox{N,T}[] local have_split for y in subpaving for x in working have_split = false diff = setdiff(x, y) if diff != [x] have_split = true append!(new_working, diff) end end !have_split && push!(new_working, x) working = new_working new_working = IntervalBox{N,T}[] end return working end setdiff(X::SubPaving{N,T}, Y::SubPaving{N,T}) where {N,T} = vcat([setdiff(x, Y) for x in X]...) function setdiff(x::IntervalBox{N,T}, paving::Paving{N,T}) where {N,T} Y = setdiff(x, paving.inner) Z = setdiff(Y, paving.boundary) return Z end function show(io::IO, p::Paving{N,T}) where {N,T} print(io, """Paving: - tolerance ฯต = $(p.ฯต) - inner approx. of length $(length(p.inner)) - boundary approx. of length $(length(p.boundary))""" ) end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
10398
abstract type Separator end """ ConstraintSeparator is a separator that represents a constraint defined directly using `@constraint`. """ struct ConstraintSeparator{C, II, ex} <: Separator variables::Vector{Symbol} constraint::II # Interval or IntervalBox contractor::C expression::ex end ConstraintSeparator(constraint, contractor, expression) = ConstraintSeparator(contractor.variables, constraint, contractor, expression) """CombinationSeparator is a separator that is a combination (union, intersection, or complement) of other separators. """ struct CombinationSeparator{F, ex} <: Separator variables::Vector{Symbol} separator::F expression::ex end function (S::ConstraintSeparator)(X::IntervalBox) C = S.contractor a, b = S.constraint.lo, S.constraint.hi inner = C(IntervalBox(Interval(a, b)), X) local outer if a == -โˆž outer = C(IntervalBox(Interval(b, โˆž)), X) elseif b == โˆž outer = C(IntervalBox(Interval(-โˆž, a)), X) else outer1 = C(IntervalBox(Interval(-โˆž, a)), X) outer2 = C(IntervalBox(Interval(b, โˆž)), X) outer = outer1 โˆช outer2 end return (inner, outer) end """`parse_comparison` parses comparisons like `x >= 10` into the corresponding interval, expressed as `x โˆˆ [10,โˆž]` Returns the expression and the constraint interval TODO: Allow something like [3,4]' for the complement of [3,4] """ function parse_comparison(ex::Expr) expr, limits = @match ex begin ((a_ <= b_) | (a_ < b_) | (a_ โ‰ค b_)) => (a, (-โˆž, b)) ((a_ >= b_) | (a_ > b_) | (a_ โ‰ฅ b_)) => (a, (b, โˆž)) ((a_ == b_) | (a_ = b_)) => (a, (b, b)) ((a_ <= b_ <= c_) | (a_ < b_ < c_) | (a_ <= b_ < c) | (a_ < b_ <= c)) => (b, (a, c)) ((a_ >= b_ >= c_) | (a_ > b_ > c_) | (a_ >= b_ > c_) | (a_ > b_ >= c)) => (b, (c, a)) ((a_ โˆˆ [b_, c_]) | (a_ in [b_, c_]) | (a_ โˆˆ b_ .. c_) | (a_ in b_ .. c_)) => (a, (b, c)) _ => (ex, (-โˆž, โˆž)) end a, b = limits return (expr, a..b) # expr โˆˆ [a,b] end function _load_MT_parse() return quote function parse_comparison(ex::Operation) if isa(ex.args[1], Constant) if ex.op == < a = ex.args[1].value b = Inf elseif ex.op == > a = -Inf b = ex.args[1].value end return (ex.args[2], a..b) elseif isa(ex.args[2], Constant) if ex.op == > a = ex.args[2].value b = Inf elseif ex.op == < a = -Inf b = ex.args[2].value else a = ex.args[2].value b = ex.args[2].value end return (ex.args[1], a..b) end end end end function new_parse_comparison(ex) # @show ex if @capture ex begin (op_(a_, b_)) end #return (op, a, b) # @show op, a, b elseif ex.head == :comparison println("Comparison") symbols = ex.args[1:2:5] operators = ex.args[2:2:4] # @show symbols # @show operators end end function make_constraint(expr, constraint, var =[]) if isa(expr, Symbol) expr = :(1 * $expr) # make into an expression! end contractor_name = make_symbol(:C) full_expr = Meta.quot(:($expr โˆˆ $constraint)) contractor_code = make_contractor(expr, var) code = quote end push!(code.args, :($(esc(contractor_name)) = $(contractor_code))) push!(code.args, :(ConstraintSeparator($constraint, $(esc(contractor_name)), $full_expr))) code end function _load_MT_make_constraint() return quote make_constraint(expr::Variable, constraint) = make_constraint(Operation(expr), constraint) function make_constraint(expr::Operation, constraint, var=[]) C = Contractor(var, expr) ex = expr โˆˆ constraint ConstraintSeparator(constraint, C, ex) end end end """Create a separator from a given constraint expression, written as standard Julia code. e.g. `C = @constraint x^2 + y^2 <= 1` The variables (`x` and `y`, in this case) are automatically inferred. External constants can be used as e.g. `\$a`: ``` a = 3 C = @constraint x^2 + y^2 - \$a <= 0 ``` """ macro constraint(ex::Expr, variables = []) expr, constraint = parse_comparison(ex) isa(variables, Array) ? var = [] : var = variables.args make_constraint(expr, constraint, var) end function _load_MT_separator() return quote """ Create a separator without the use of macros using ModelingToolkit e.g ``` vars = @variables x y z S = Separator(vars, x^2+y^2<1) X= IntervalBox(-0.5..1.5, -0.5..1.5, -0.5..1.5) S(X) ``` """ function Separator(variables, ex::Operation) expr, constraint = parse_comparison(ex) make_constraint(expr, constraint, variables) end Separator(ex::Operation) = Separator([], ex) Separator(vars::Union{Vector{Operation}, Tuple{Vararg{Operation,N}}}, g::Function) where N = Separator(vars, g(vars...)) Separator(vars, f::Function) = Separator([Variable(Symbol(i))() for i in vars], f([Variable(Symbol(i))() for i in vars]...)) # if vars is not vector of variables end end function show(io::IO, S::Separator) println(io, "Separator:") print(io, " - variables: ") print(io, join(map(string, S.variables), ", ")) println(io) print(io, " - expression: ") print(io, S.expression) end (S::CombinationSeparator)(X) = S.separator(X) "Unify the variables of two separators" function unify_variables(vars1, vars2) variables = unique(sort(vcat(vars1, vars2))) numvars = length(variables) # total number of variables indices1 = indexin(vars1, variables) indices2 = indexin(vars2, variables) where1 = zeros(Int, numvars) # inverse of indices1 where2 = zeros(Int, numvars) for (i, which) in enumerate(indices1) where1[which] = i end for (i, which) in enumerate(indices2) where2[which] = i end return variables, indices1, indices2, where1, where2 end # TODO: when S1 and S2 have different variables -- amalgamate! """ โˆฉ(S1::Separator, S2::Separator) Separator for the intersection of two sets given by the separators `S1` and `S2`. Takes an iterator of intervals (`IntervalBox`, tuple, array, etc.), of length equal to the total number of variables in `S1` and `S2`; it returns inner and outer tuples of the same length """ function โˆฉ(S1::Separator, S2::Separator) #=variables, indices1, indices2, where1, where2 = unify_variables(S1.variables, S2.variables) numvars = length(variables)=# variables = S1.variables # as S1 and S2 have same variables f = X -> begin inner1, outer1 = S1(X) inner2, outer2 = S2(X) inner = inner1 โˆฉ inner2 outer = outer1 โˆช outer2 #= inner1, outer1 = S1(IntervalBox([X[i] for i in indices1]...)) inner2, outer2 = S2(IntervalBox([X[i] for i in indices2]...)) if any(isempty, inner1) inner1 = emptyinterval(IntervalBox(X)) else inner1 = [i โˆˆ indices1 ? inner1[where1[i]] : X[i] for i in 1:numvars] end if any(isempty, outer1) outer1 = emptyinterval(IntervalBox(X)) else outer1 = [i โˆˆ indices1 ? outer1[where1[i]] : X[i] for i in 1:numvars] end if any(isempty, inner2) inner2 = emptyinterval(IntervalBox(X)) else inner2 = [i โˆˆ indices2 ? inner2[where2[i]] : X[i] for i in 1:numvars] end if any(isempty, outer2) outer2 = emptyinterval(IntervalBox(X)) else outer2 = [i โˆˆ indices2 ? outer2[where2[i]] : X[i] for i in 1:numvars] end # Treat as if had X[i] in the other directions, except if empty inner = IntervalBox( [x โˆฉ y for (x,y) in zip(inner1, inner2) ]... ) outer = IntervalBox( [x โˆช y for (x,y) in zip(outer1, outer2) ]... ) =# return (inner, outer) end expression = :($(S1.expression) โˆฉ $(S2.expression)) return CombinationSeparator(variables, f, expression) end function โˆช(S1::Separator, S2::Separator) #=variables, indices1, indices2, where1, where2 = unify_variables(S1.variables, S2.variables) numvars = length(variables)=# variables = S1.variables # S1 and S2 have same variables f = X -> begin inner1, outer1 = S1(X) inner2, outer2 = S2(X) inner = inner1 โˆช inner2 outer = outer1 โˆฉ outer2 #= inner1, outer1 = S1(IntervalBox([X[i] for i in indices1]...)) inner2, outer2 = S2(IntervalBox([X[i] for i in indices2]...)) if any(isempty, inner1) inner1 = emptyinterval(IntervalBox(X)) else inner1 = [i โˆˆ indices1 ? inner1[where1[i]] : X[i] for i in 1:numvars] end if any(isempty, outer1) outer1 = emptyinterval(IntervalBox(X)) else outer1 = [i โˆˆ indices1 ? outer1[where1[i]] : X[i] for i in 1:numvars] end if any(isempty, inner2) inner2 = emptyinterval(IntervalBox(X)) else inner2 = [i โˆˆ indices2 ? inner2[where2[i]] : X[i] for i in 1:numvars] end if any(isempty, outer2) outer2 = emptyinterval(IntervalBox(X)) else outer2 = [i โˆˆ indices2 ? outer2[where2[i]] : X[i] for i in 1:numvars] end inner = IntervalBox( [x โˆช y for (x,y) in zip(inner1, inner2) ]... ) outer = IntervalBox( [x โˆฉ y for (x,y) in zip(outer1, outer2) ]... ) =# return (inner, outer) end expression = :($(S1.expression) โˆช $(S2.expression)) return CombinationSeparator(variables, f, expression) end function !(S::Separator) f = X -> begin inner, outer = S(X) return (outer, inner) end expression = :(!($(S.expression))) return CombinationSeparator(S.variables, f, expression) end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
1913
""" `pave` takes the given working list of boxes and splits them into inner and boundary lists with the given separator """ function pave(S::Separator, working::Vector{IntervalBox{N,T}}, ฯต, bisection_point=nothing) where {N,T} inner_list = SubPaving{N,T}() boundary_list = SubPaving{N,T}() while !isempty(working) X = pop!(working) inner, outer = S(X) # here inner and outer are reversed compared to Jaulin # S(X) returns the pair (contractor with respect to the inside of the constraing, contractor with respect to outside) #@show X, outer inside_list = setdiff(X, outer) if length(inside_list) > 0 append!(inner_list, inside_list) end boundary = inner โˆฉ outer if isempty(boundary) continue end if diam(boundary) < ฯต push!(boundary_list, boundary) else if isnothing(bisection_point) push!(working, bisect(boundary)...) else push!(working, bisect(boundary, bisection_point)...) end end end return inner_list, boundary_list end """ pave(S::Separator, domain::IntervalBox, eps)` Find the subset of `domain` defined by the constraints specified by the separator `S`. Returns (sub)pavings `inner` and `boundary`, i.e. lists of `IntervalBox`. """ function pave(S::Separator, X::IntervalBox{N,T}, ฯต = 1e-2, bisection_point=nothing) where {N,T} inner_list, boundary_list = pave(S, [X], ฯต, bisection_point) return Paving(S, inner_list, boundary_list, ฯต) end # """Refine a paving to tolerance ฯต""" # function refine!(P::Paving, ฯต = 1e-2) # if P.ฯต <= ฯต # already refined # return # end # # new_inner, new_boundary = pave(P.separator, P.boundary, ฯต) # # append!(P.inner, new_inner) # P.boundary = new_boundary # P.ฯต = ฯต # end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
855
import Base: +, show, * """N-dimensional Volume with lower and upper bounds""" struct Vol{N,T} bounds::Interval{T} end Vol_name(i::Integer) = i == 1 ? "length" : i == 2 ? "area" : i == 3 ? "Volume" : "hyper-Volume" show(io::IO, v::Vol{N,T}) where {N,T} = print(io, "$N-dimensional $(Vol_name(N)): $(v.bounds)") Vol(X::IntervalBox{N,T}) where {N,T} = Vol{N,T}(prod([Interval(x.hi) - Interval(x.lo) for x in X])) Vol(x::Interval{T}) where {T} = Vol(IntervalBox(x)) +(v::Vol{N,T}, w::Vol{N,T}) where {N,T} = Vol{N,T}(v.bounds + w.bounds) *(v::Vol{N1,T}, w::Vol{N2,T}) where {N1,N2,T} = Vol{N1+N2,T}(v.bounds * w.bounds) Vol(XX::SubPaving{N,T}) where {N,T} = sum([Vol(X) for X in XX]) function Vol(P::Paving{N,T}) where {N,T} Vin = Vol(P.inner) Vout = Vin + Vol(P.boundary) return Vol{N,T}(hull(Vin.bounds, Vout.bounds)) end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
2183
using ModelingToolkit @testset "BasicContractor" begin @variables x y C = BasicContractor(x^2 + y^2) @test C(-โˆž..1, IntervalBox(-โˆž..โˆž,2)) == IntervalBox(-1..1, -1..1) X =IntervalBox(-1..1,2) @test C(X) == 0..2 @test C((1,2)) == 5 end @testset "Contractor without using macro" begin @variables x y C = Contractor(x^2 + y^2) @test C(-โˆž..1, IntervalBox(-โˆž..โˆž, 2)) == IntervalBox(-1..1, -1..1) end @testset "Contractor (with macros and without macros) specifying variables explicitly" begin X =IntervalBox(0.5..1.5,3) A=-Inf..1 C1 = @contractor(x+y, [x,y,z]) @test C1(A,X) == IntervalBox(0.5..0.5, 0.5..0.5, 0.5..1.5) C2 = @contractor(y+z, [x,y,z]) @test C2(A,X) == IntervalBox(0.5..1.5, 0.5..0.5, 0.5..0.5) vars = @variables x y z C1 = Contractor(vars, x+y) @test C1(A,X) == IntervalBox(0.5..0.5, 0.5..0.5, 0.5..1.5) C2 = Contractor(vars, y+z) @test C2(A,X) == IntervalBox(0.5..1.5, 0.5..0.5, 0.5..0.5) C1 = Contractor([x, y, z], x+y) @test C1(A,X) == IntervalBox(0.5..0.5, 0.5..0.5, 0.5..1.5) C2 = Contractor([x, y, z], y+z) @test C2(A,X) == IntervalBox(0.5..1.5, 0.5..0.5, 0.5..0.5) vars = @variables x1 x3 x2 C = Contractor(vars, x1+x2) @test C(A, X) == IntervalBox(0.5..0.5, 0.5..1.5, 0.5..0.5) end @testset "Contractor is created by function name " begin vars = @variables x y g(x, y) = x + y C = Contractor(vars, g) @test C(-Inf..1, IntervalBox(0.5..1.5, 2)) == IntervalBox(0.5..0.5, 2) end @testset "Separators without using macros" begin II = -100..100 X = IntervalBox(II, II) vars = @variables x y S = Separator(vars, x^2 + y^2 < 1) inner, outer = S(X) @test inner == IntervalBox(-1..1, -1..1) @test outer == IntervalBox(II, II) X = IntervalBox(-โˆž..โˆž, -โˆž..โˆž) inner, outer = S(X) @test inner == IntervalBox(-1..1, -1..1) @test outer == IntervalBox(-โˆž..โˆž, -โˆž..โˆž) end @testset "Separator is created by function name " begin vars = @variables x y g(x, y) = x + y < 1 S = Separator(vars, g) @test S(IntervalBox(0.5..1.5, 2)) == (IntervalBox(0.5..0.5, 2), IntervalBox(0.5..1.5, 2)) end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
code
4921
using IntervalConstraintProgramming, Test using IntervalArithmetic @testset "Utilities" begin @test IntervalConstraintProgramming.unify_variables([:a, :c], [:c, :b]) == ([:a,:b,:c], [1,3], [3,2], [1,0,2], [0,2,1]) end @testset "Contractor" begin x = y = -โˆž..โˆž X = IntervalBox(x, y) C = @contractor x^2 + y^2 @test C(-โˆž..1, X) == IntervalBox(-1..1, -1..1) X =IntervalBox(-1..1,2) @test C(X) == 0..2 @test C((1,2)) == 5 end @testset "Separators" begin II = -100..100 X = IntervalBox(II, II) S = @constraint x^2 + y^2 <= 1 @test typeof(S) <: IntervalConstraintProgramming.ConstraintSeparator inner, outer = S(X) @test inner == IntervalBox(-1..1, -1..1) @test outer == IntervalBox(II, II) X = IntervalBox(-โˆž..โˆž, -โˆž..โˆž) inner, outer = S(X) @test inner == IntervalBox(-1..1, -1..1) @test outer == IntervalBox(-โˆž..โˆž, -โˆž..โˆž) end @testset "pave" begin S1a = @constraint(x > 0 , [x, y]) S1b = @constraint(y > 0 , [x, y]) S1 = S1a โˆฉ S1b paving = pave(S1, IntervalBox(-3..3, -3..3), 2.0, 0.5) @test Set(paving.inner) == Set([IntervalBox(1.5..3, 0..3), IntervalBox(0..1.5, 1.5..3)]) @test length(paving.inner) == 2 @test isempty(paving.boundary) == false S2 = S1a โˆช S1b paving = pave(S2, IntervalBox(-3..3, -3..3), 0.1) @test Set(paving.inner) == Set([IntervalBox(-3..0, 0..3), IntervalBox(0..3, -3..3)]) @test length(paving.inner) == 2 @test isempty(paving.boundary) == false S3 = @constraint x^2 + y^2 <= 1 X = IntervalBox(-โˆž..โˆž, -โˆž..โˆž) paving = pave(S3, X, 1.0, 0.5) @test Set(paving.inner) == Set([IntervalBox(Interval(0.0, 0.5), Interval(0.0, 0.8660254037844386)), IntervalBox(Interval(0.0, 0.5), Interval(-0.8660254037844386, 0.0)), IntervalBox(Interval(-0.5, 0.0), Interval(0.0, 0.8660254037844386)), IntervalBox(Interval(-0.5, 0.0), Interval(-0.8660254037844386, 0.0))]) @test Set(paving.boundary) == Set([ IntervalBox(Interval(0.5, 1.0), Interval(0.0, 0.8660254037844387)), IntervalBox(Interval(0.0, 0.5), Interval(0.8660254037844386, 1.0)), IntervalBox(Interval(0.5, 1.0), Interval(-0.8660254037844387, 0.0)), IntervalBox(Interval(0.0, 0.5), Interval(-1.0, -0.8660254037844386)), IntervalBox(Interval(-0.5, 0.0), Interval(0.8660254037844386, 1.0)), IntervalBox(Interval(-1.0, -0.5), Interval(0.0, 0.8660254037844387)), IntervalBox(Interval(-0.5, 0.0), Interval(-1.0, -0.8660254037844386)), IntervalBox(Interval(-1.0, -0.5), Interval(-0.8660254037844387, 0.0))]) @test length(paving.inner) == 4 @test length(paving.boundary) == 8 end # @testset "Constants" begin # x = y = -โˆž..โˆž # X = IntervalBox(x, y) # a = 3 # S4 = @constraint x^2 + y^2 - $a <= 0 # paving = pave(S4, X) # @test paving.ฯต == 0.01 # @test length(paving.inner) == 1532 # length(paving.boundary) == 1536 # end @testset "Paving a 3D torus" begin S5 = @constraint (3 - sqrt(x^2 + y^2))^2 + z^2 <= 1 x = y = z = -โˆž..โˆž X = IntervalBox(x, y, z) paving = pave(S5, X, 1.) @test typeof(paving) == IntervalConstraintProgramming.Paving{3, Float64} end @testset "Volume" begin x = 3..5 @test Vol(x).bounds == 2 V = Vol(IntervalBox(-1..1.5, 2..3.5)) @test typeof(V) == IntervalConstraintProgramming.Vol{2, Float64} @test V.bounds == 3.75 end @testset "Functions" begin @function f(x) = 4x; C1 = @contractor f(x); A = IntervalBox(0.5..1); x = IntervalBox(0..1); @test C1(A, x) == IntervalBox(0.125..0.25) # x such that 4x โˆˆ A=[0.5, 1] C2 = @constraint f(x) โˆˆ [0.5, 0.6] X = IntervalBox(0..1) paving = pave(C2, X) @test length(paving.inner) == 2 @test length(paving.boundary) == 2 C3 = @constraint f(f(x)) โˆˆ [0.4, 0.8] @test length(paving.inner) == 2 @test length(paving.boundary) == 2 end @testset "Nested functions" begin @function f(x) = 2x @function g(x) = ( a = f(x); a^2 ) @function g2(x) = ( a = f(f(x)); a^2 ) C = @contractor g(x) C2 = @contractor g2(x) A = IntervalBox(0.5..1) x = IntervalBox(0..1) @test C(A, x) == IntervalBox(sqrt(A[1] / 4)) @test C2(A, x) == IntervalBox(sqrt(A[1] / 16)) end @testset "Iterated functions" begin @function f(x) = 2x A = IntervalBox(0.5..1) x = IntervalBox(0..1) @function g3(x) = ( a = (fโ†‘2)(x); a^2 ) C3 = @contractor g3(x) @test C3(A, x) == IntervalBox(sqrt(A[1] / 16)) end @static if VERSION < v"1.9" # ModelingToolkit causes compilation problems with new Julia versions starting v1.9 include("ModelingToolkit.jl") end
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
docs
3918
# IntervalConstraintProgramming.jl # v0.11 ## Minimum Julia version - The minimum Julia version supported is now Julia 1.1 ## Functionality's are added - Contractor can be make by just function name only - New type of Contractor named as `BasicContractor` can be construct which only contain fields of useful data. # v0.10 ## Minimum Julia version - The minimum Julia version supported is now Julia 1.0. ## New Dependency added: `ModelingToolkit.jl` - By the help of `ModelingToolkit.jl` we can construct contractors and separators without the use of macros. # v0.9 ## Minimum Julia version - The minimum Julia version supported is now Julia 0.7. The package is fully compatible with Julia 1.0. ## Functionality removed - Pavings are now immutable, so `refine!` no longer works. # v0.8 ## Minimum Julia version - The minimum Julia version required has been bumped to 0.6; this will be the last release to support 0.6. # v0.7 ## New dependency: `IntervalContractors.jl` The reverse functions used for constraint propagation have been factored out into the `IntervalContractors.jl` package. # v0.6 ## Minimum Julia version - The minimum Julia version required has been bumped to 0.5 ## API change - Objects such as `Contractor` have been simplified by putting functions and the code that generated them inside a `GeneratedFunction` type ## Dependency change - The dependency on `ValidatedNumerics.jl` has been replaced by `IntervalArithmetic.jl` and `IntervalRootFinding.jl` # v0.5 - API change: Contractors now have their dimension as a type parameter - Refactoring for type stability - Removed reference to FixedSizeArrays; everything (including `bisect`) is now provided by `IntervalArithmetic` - Removed all functions acting directly on `Interval`s and `IntervalBox`es that should belong to `IntervalArithmetic` - Generated code uses simpler symbols - Example notebooks have been split out into a separate repository: https://github.com/dpsanders/IntervalConstraintProgrammingNotebooks # v0.4 - `@function f(x) = 4x` defines a function - Functions may be used inside constraints - Functions may be iterated - Functions may be multi-dimensional - Local variables may be introduced - Simple plotting solution for the results of `pave` using `Plots.jl` recipes (via `IntervalArithmetic.jl`): ``` using Plots gr() # preferred (fast) backed for `Plots.jl` plot(paving.inner) plot!(paving.boundary) ``` - Major internals rewrite - Unary minus and `power_rev` with odd powers now work correctly - Examples updated - Basic documentation using `Documenter.jl` # v0.3 - Renamed `setinverse` to `pave` - External constants may now be used in `@constraint`, e.g. ``` a, b = 1, 2 C = @constraint (x-$a)^2 + (y-$b)^2 ``` The constraint will *not* change if the constants are changed, but may be updated (changed) by calling the same `@constraint` command again. # v0.2 - `setinverse` now returns an object of type `Paving` [#17](https://github.com/dpsanders/IntervalConstraintProgramming.jl/pull/17) - `refine!` function added to refine an existing `Paving` to a lower tolerance [#17](https://github.com/dpsanders/IntervalConstraintProgramming.jl/pull/17) - `vol` has been renamed to `Vol`, and is applied directly to a `Paving` object. - Internal variable names in generated code are now of form `_z_1_` instead of `z1` to eliminate collisions with user-defined variables [#20](https://github.com/dpsanders/IntervalConstraintProgramming.jl/pull/20) # v0.1.1 - Add `sqrtRev` reverse-mode function - Add solid torus example, including 3D visualization with GLVisualize - Tests pass with Julia 0.5 # v0.1 - Basic functionality working (separators and `setinverse`) - `Vol` function calculates the Volume of the set produced by `setinverse`; returns objects of type `Vol` parametrised by the dimension $d$ of the set (i.e. $d$-dimensional Lebesgue measure), which are interval ranges
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
docs
2344
# IntervalConstraintProgramming.jl [![Build Status](https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl/workflows/CI/badge.svg)](https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl/actions/workflows/CI.yml) [![Docs](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliaintervals.github.io/pages/packages/intervalconstraintprogramming/) [![coverage](https://codecov.io/gh/JuliaIntervals/IntervalConstraintProgramming.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/JuliaIntervals/IntervalConstraintProgramming.jl) This Julia package allows us to specify a set of constraints on real-valued variables, given by inequalities, and rigorously calculate (inner and outer approximations to) the *feasible set*, i.e. the set that satisfies the constraints. The package is based on interval arithmetic using the [`IntervalArithmetic.jl`](https://github.com/JuliaIntervals/IntervalArithmetic.jl) package (co-written by the author), in particular multi-dimensional `IntervalBox`es (i.e. Cartesian products of one-dimensional intervals). ## Documentation Documentation for the package is available [here](https://juliaintervals.github.io/pages/packages/intervalconstraintprogramming/). The best way to learn how to use the package is to look at the tutorial, available in the organisation webpage [here](https://juliaintervals.github.io/pages/tutorials/tutorialConstraintProgramming/). ## Author - [David P. Sanders](http://sistemas.fciencias.unam.mx/~dsanders), Departamento de Fรญsica, Facultad de Ciencias, Universidad Nacional Autรณnoma de Mรฉxico (UNAM) ## References: - *Applied Interval Analysis*, Luc Jaulin, Michel Kieffer, Olivier Didrit, Eric Walter (2001) - Introduction to the Algebra of Separators with Application to Path Planning, Luc Jaulin and Benoรฎt Desrochers, *Engineering Applications of Artificial Intelligence* **33**, 141โ€“147 (2014) ## Acknowledements Financial support is acknowledged from DGAPA-UNAM PAPIME grants PE-105911 and PE-107114, and DGAPA-UNAM PAPIIT grant IN-117214, and from a CONACYT-Mexico sabbatical fellowship. The author thanks Alan Edelman and the Julia group for hospitality during his sabbatical visit. He also thanks Luc Jaulin and Jordan Ninin for the [IAMOOC](http://iamooc.ensta-bretagne.fr/) online course, which introduced him to this subject.
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
docs
95
# API ```@autodocs Modules = [IntervalConstraintProgramming] Order = [:type, :function] ```
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.13.0
aa88cc1284dc06dc9dd93e9c35fba59094f43130
docs
8150
# `IntervalConstraintProgramming.jl` This Julia package allows you to specify a set of **constraints** on real-valued variables, given by (in)equalities, and rigorously calculate inner and outer approximations to the *feasible set*, i.e. the set that satisfies the constraints. This uses interval arithmetic provided by the author's [`IntervalArithmetic.jl`](https://github.com/dpsanders/IntervalArithmetic.jl) package, in particular multi-dimensional `IntervalBox`es, i.e. Cartesian products of one-dimensional intervals. To do this, *interval constraint programming* is used, in particular the so-called "forward--backward contractor". This is implemented in terms of *separators*; see [Jaulin & Desrochers]. ```@meta DocTestSetup = quote using IntervalConstraintProgramming, IntervalArithmetic end ``` ## Usage Let's define a constraint, using the `@constraint` macro: ```jldoctest julia> using IntervalConstraintProgramming, IntervalArithmetic julia> S = @constraint x^2 + y^2 <= 1 Separator: - variables: x, y - expression: x ^ 2 + y ^ 2 โˆˆ [-โˆž, 1] ``` It works out automatically that `x` and `y` are variables. The macro creates a `Separator` object, in this case a `ConstraintSeparator`. We now create an initial interval box in the ``x``--``y`` plane: ```julia julia> x = y = -100..100 # notation for creating an interval with `IntervalArithmetic.jl` julia> X = IntervalBox(x, y) ``` The `@constraint` macro defines an object `S`, of type `Separator`. This is a function which, when applied to the box ``X = x \times y`` in the x--y plane, applies two *contractors*, an inner one and an outer one. The inner contractor tries to shrink down, or *contract*, the box, to the smallest subbox of ``X`` that contains the part of ``X`` that satisfies the constraint; the outer contractor tries to contract ``X`` to the smallest subbox that contains the region where the constraint is not satisfied. When `S` is applied to the box `X`, it returns the result of the inner and outer contractors: ```julia julia> inner, outer = S(X); julia> inner ([-1, 1],[-1, 1]) julia> outer ([-100, 100],[-100, 100]) ``` ### Without using macros We can also make an object `S`, of type `Separator` or `C`, of type `Contractor` without using Macros, for that you need to define variables using `ModelingToolkit.jl`. Example ```julia julia> using IntervalConstraintProgramming, IntervalArithmetic, ModelingToolkit julia> @variables x y (x(), y()) julia> S = Separator(x+y<1) Separator: - variables: x, y - expression: x() + y() == [-โˆž, 1] julia> C = Contractor(x+y) Contractor in 2 dimensions: - forward pass contracts to 1 dimensions - variables: Symbol[:x, :y] - expression: x() + y() ``` While making `Separator`or `Contractor`'s object we can also specify variables, like this ```julia julia> vars = @variables x y z (x(), y(), z()) julia> S = Separator(vars, x+y<1) Separator: - variables: x, y, z - expression: x() + y() == [-โˆž, 1] julia> C = Contractor(vars, y+z) Contractor in 3 dimensions: - forward pass contracts to 1 dimensions - variables: Symbol[:x, :y, :z] - expression: y() + z() ``` We can make objects (of type `Separator` or `Contractor`)by just using function name (Note: you have to specify variables explicitly as discussed above when you make objects by using function name). We can also use polynomial function to make objects. ```julia julia> vars=@variables x y (x(), y()) julia> f(a,b)= a+b f (generic function with 1 method) julia> C = Contractor(vars,f) Contractor in 2 dimensions: - forward pass contracts to 1 dimensions - variables: Symbol[:x, :y] - expression: x() + y() julia> f(a,b) = a+b <1 f (generic function with 1 method) julia> S=Separator(vars, f) Separator: - variables: x, y - expression: x() + y() == [-โˆž, 1] julia> using DynamicPolynomials #using polynomial functions julia> pvars = @polyvar x y (x, y) julia> f(a,b) = a + b < 1 p (generic function with 1 method) julia> S=Separator(pvars, f) Separator: - variables: x, y - expression: x() + y() == [-โˆž, 1] ``` #### BasicContractor Objects of type `Contractor` have four fields (variables, forward, backward and expression), among them data of two fields (forward, backward) are useful (i.e forward and backward functions) for further usage of that object, thats why it is preferred to use an object of type `BasicContractor` in place of `Contractor` which only contain these two fields for less usage of memory by unloading all the extra stuff.(Note: Like object of `Contractor` type,`BasicContractor`'s object will also have all the properties which are discussed above). ```julia julia> @variables x y (x(), y()) julia> C = BasicContractor(x^2 + y^2) Basic version of Contractor ``` ## Set inversion: finding the feasible set To make progress, we must recursively bisect and apply the contractors, keeping track of the region proved to be inside the feasible set, and the region that is on the boundary ("both inside and outside"). This is done by the `pave` function, that takes a separator, a domain to search inside, and an optional tolerance: ```julia julia> using Plots julia> x = y = -100..100 julia> S = @constraint 1 <= x^2 + y^2 <= 3 julia> paving = pave(S, X, 0.125); ``` `pave` returns an object of type `Paving`. This contains: the separator itself; an `inner` approximation, of type `SubPaving`, which is an alias for a `Vector` of `IntervalBox`es; a `SubPaving` representing the boxes on the boundary that could not be assigned either to the inside or outside of the set; and the tolerance. We may draw the result using a plot recipe from `IntervalArithmetic`. Either a single `IntervalBox`, or a `Vector` of `IntervalBox`es (which a `SubPaving` is) maybe be drawn using `plot` from `Plots.jl`: ```julia julia> plot(paving.inner, c="green") julia> plot!(paving.boundary, c="gray") ``` The output should look something like this: ![Ring](ring.png) The green boxes have been **rigorously** proved to be contained within the feasible set, and the white boxes to be outside the set. The grey boxes show those that lie on the boundary, whose status is unknown. ### 3D The package works in any number of dimensions, although it suffers from the usual exponential slowdown in higher dimensions ("combinatorial explosion"); in 3D, it is still relatively fast. There are sample 3D calculations in the `examples` directory, in particular in the [solid torus notebook](examples/Solid torus.ipynb), which uses [`GLVisualize.gl`](https://github.com/JuliaGL/GLVisualize.jl) to provide an interactive visualization that may be rotated and zoomed. The output for the solid torus looks like this: ![Coloured solid torus](solid_torus.png) ## Set operations Separators may be combined using the operators `!` (complement), `โˆฉ` and `โˆช` to make more complicated sets; see the [notebook](https://github.com/JuliaIntervals/IntervalConstraintProgrammingNotebooks/blob/master/Basic%20examples%20of%20separators.ipynb) for several examples. Further examples can be found in the repository [IntervalConstraintProgrammingNotebooks](https://github.com/JuliaIntervals/IntervalConstraintProgrammingNotebooks). ## Author - [David P. Sanders](http://sistemas.fciencias.unam.mx/~dsanders) - [Julia lab, MIT](http://julia.mit.edu/) - Departamento de Fรญsica, Facultad de Ciencias, Universidad Nacional Autรณnoma de Mรฉxico (UNAM) ## References: - *Applied Interval Analysis*, Luc Jaulin, Michel Kieffer, Olivier Didrit, Eric Walter (2001) - Introduction to the Algebra of Separators with Application to Path Planning, Luc Jaulin and Benoรฎt Desrochers, *Engineering Applications of Artificial Intelligence* **33**, 141โ€“147 (2014) ## Acknowledements Financial support is acknowledged from DGAPA-UNAM PAPIME grants PE-105911 and PE-107114, and DGAPA-UNAM PAPIIT grant IN-117214, and from a CONACYT-Mexico sabbatical fellowship. The author thanks Alan Edelman and the Julia group for hospitality during his sabbatical visit. He also thanks Luc Jaulin and Jordan Ninin for the [IAMOOC](http://iamooc.ensta-bretagne.fr/) online course, which introduced him to this subject.
IntervalConstraintProgramming
https://github.com/JuliaIntervals/IntervalConstraintProgramming.jl.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
448
using Documenter, Repotomata makedocs( sitename="Repotomata documentation", format=Documenter.HTML(prettyurls=get(ENV, "CI", nothing) == "true"), pages=[ "Home" => "index.md", "Repotomata" => "repotomata.md", "Rules" => "Rules.md", "Connection and GitHub" => "connection.md", "Image functions" => "image.md" ] ) deploydocs( repo="github.com/Nauss/Repotomata.git", devbranch="main" )
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
2895
module Repotomata using Random, Serialization, JSON, FileIO using ColorTypes, ImageAxes using ImageView include("utilities/constants.jl") include("Rule.jl") include("github/Repo.jl") include("image.jl") export repotomata, OutputType, open_viewer """ The different output types - `raw`: will return a Vector of the created images. - `viewer`: will open the result in a viewer. - `gif`: will create a gif file at the given `output_path`. See also: [`repotomata`](@ref) """ @enum OutputType raw viewer gif """ The different rules - `life`: the "game of life" rule. - `languages`: the languages rule. See also: [`repotomata`](@ref) """ @enum RuleType life chromatic """ repotomata(owner::AbstractString, name::AbstractString; <keyword arguments>) repotomata(ownername::AbstractString; kwargs...) Generates a cellular automata animation of the given GitHub repository. !!! note When using the second method, the format must be: "owner/name". # Arguments - `epochs::Int=10`: the number of generations to compute. - `width::Integer=500`: the output width (height will be automatically computed with the golden ratio). - `output::OutputType=raw`: the output type. - `output_path::String=""`: the output path when using OutputType.gif. - `rule::RuleType=chromatic`: the rule to use. - `seed_treshold::Real=0.58`: the threshold on the Perlin noise used as seed. - `background_color::Colorant=black`: the background color. """ function repotomata( owner::AbstractString, name::AbstractString; epochs::Int=250, width::Int=500, output::OutputType=raw, output_path::String="", rule::RuleType=chromatic, seed_treshold::Real=0.58, # Happens to be a good value for the Julia repository background_color::Colorant=black ) # Get the repo information repo = Repo(owner, name, background_color) image_parameters::Dict{String,Any} = Dict( "epochs" => epochs, "width" => width, "ruletype" => rule, "seed_treshold" => seed_treshold ) getparameters!(image_parameters, repo) images = generate_images(image_parameters) if output == viewer open_viewer(images); elseif output == gif save(output_path, cat(images..., dims=3), fps=25) else images; end end repotomata(ownername::AbstractString; kwargs...) = begin owner = split(ownername, "/")[1] name = split(ownername, "/")[2] repotomata(owner, name; kwargs...) end """ open_viewer(images) Display the `images` in an interactive window. """ function open_viewer(images::Array{Array{ColorTypes.RGB{Float64},2},1}) ImageView.closeall() epochs = size(images, 1) if epochs == 0 return end height, width = size(images[1]) result = AxisArray(reshape(cat(images..., dims=1), (height, epochs, width))) imshow(result, axes=(1, 3)) end end # module
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
1482
using PaddedViews """ An automata rule The rule is applied to all the image pixel for each epoch. # Fields - `neighbours`: the pixels (relative positions) observered when applying the contidtion. - `condition`: this function is called for each pixel and must return the new color. - `extent`: the image padding needed by the neighbours. """ struct Rule neighbours::Vector{<:Point} condition::Function extent::Tuple{Int,Int} @doc """ Rule(neighbours, condition) The rule constructor. It will automatically create the `extent`. """ function Rule(neighbours::Vector{<:Point}, condition::Function) extentx, extenty = 0, 0 for neighbour in neighbours x, y = abs(neighbour[1]), abs(neighbour[2]) if x > extentx extentx = x end if y > extenty extenty = y end end new(neighbours, condition, (extentx, extenty)) end end """ getcolor(rule, image, position) Computes the colors of the neighbours around `position`. Calls the `rule`'s condition function and return its result. """ function getcolor(rule::Rule, image::AbstractArray{<:Colorant,2}, position::Point)::Colorant # Get the neighbour's colors colors = map( neighbour -> getpixel(image, position + neighbour), rule.neighbours ) # Test the condition rule.condition(rule, getpixel(image, position), colors) end
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
4104
using Random, Colors, GeometryBasics, LinearAlgebra using Dates include("utilities/perlinnoise.jl") include("rules/game_of_life.jl") include("rules/chromatic.jl") export generate_images """ generate_images(input) Create the base image and runs the evolutions. Return a `Vector` of the created images. """ function generate_images(input::Dict) # Get the parameters parameters = copy(input) ruletype = parameters["ruletype"] epochs = parameters["epochs"] width = parameters["width"] height = floor(Int, width / MathConstants.golden) maincolor = parameters["color"] palette = parameters["palette"] stargazers = parameters["stargazers"] background_color = parameters["background_color"] middle_index = round(Int, size(palette, 1) / 2.0) # Create the Rule if ruletype == life rule = game_of_life(maincolor, background_color) elseif ruletype == chromatic rule = chromatic_rule(palette, background_color) end # Create the image image = create_image(width, height, parameters) # Evolution evolution = [image] for g = 1:epochs image = newgeneration(image, rule, background_color) push!(evolution, image) end return evolution end """ setpixel!(image, position, color) Set the `color` of the pixel at `position` in the `image`. """ function setpixel!(image::AbstractArray{<:Colorant,2}, position::Point, color::Colorant) # bounds check ? image[position[2], position[1]] = color end """ getpixel(image, position) Return the `color` of the pixel at `position` in the `image`. """ function getpixel(image::AbstractArray{<:Colorant,2}, position::Point)::Colorant # bounds check ? image[position[2], position[1]] end """ newgeneration(image, rule, background_color) Produce a new image by applying the `rule` to the given `image`. """ function newgeneration(image::AbstractArray{<:Colorant,2}, rule::Rule, background_color::Colorant) # Create a new image to apply the rules but test the current generation newimage = copy(image) # Pad the image for easy neighbours detection image_min = 1 .- rule.extent image_max = size(image) .+ 2 .* rule.extent padded = PaddedView(background_color, image, (image_min[1]:image_max[1], image_min[2]:image_max[2]) ) # Update every pixel Threads.@threads for x = 1:size(image, 2) for y = 1:size(image, 1) newimage[y, x] = getcolor(rule, padded, Point(x, y)) end end return newimage end """ create_image(width, height, parameters) Create the base image with the given `width` and `height`. The `parameters` will be used to generate the Perlin noise and the random points. """ function create_image(width::Int, height::Int, parameters::Dict) maincolor = parameters["color"] stargazers = parameters["stargazers"] forks_count = parameters["forks"] watchers_count = parameters["watchers"] udpatedat = parameters["updatedat"] threshold = parameters["seed_treshold"] background_color = parameters["background_color"] # Create an image with the background color image = fill(background_color, height, width) # Fill with perlin noise # area = width * height stargazer_ratio = 100 * stargazers / MAX_STARGAZERS forks_ratio = 100 * forks_count / MAX_FORKS watchers_ratio = 100 * watchers_count / MAX_WATCHERS colored_count = 0 for x = 1:width for y = 1:height noise = perlinsnoise( x * forks_ratio, y * watchers_ratio, stargazer_ratio ) if noise > threshold image[y, x] = maincolor colored_count += 1 else image[y, x] = background_color end end end # Add random points Random.seed!(Dates.datetime2epochms(udpatedat)) for s = 1:colored_count position = Point(rand(1:width), rand(1:height)) setpixel!(image, position, maincolor) end return image end
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
3167
using Diana, JSON, HTTP export GitHubError, Connection """ Error Simple error wrapper. # Fields - `name::String`: the error name. - `type::String`: the error type. - `message::String`: the error message. """ struct Error name::String type::String message::String end """ GitHubError Any error related to the repository connection. The error is created with either: - A `HTTP.ExceptionRequest.StatusError` - A failling `Diana.Result` - A string (for now only for the token error) # Fields - `errors::Vector{Error}`: a collection of [`Error`](@ref)s. """ struct GitHubError <: Exception errors::Vector{Error} function GitHubError(result::Diana.Result) jsondata = JSON.parse(result.Data) errors = Vector{Error}(undef, 0) if haskey(jsondata, "errors") for error in jsondata["errors"] push!(errors, Error("GitHub query error", error["type"], error["message"])) end end new(errors) end function GitHubError(error::HTTP.ExceptionRequest.StatusError) errors = fill( Error("GitHub query StatusError", string(error.status), string(error.response)), 1 ) new(errors) end function GitHubError(error::AbstractString) errors = fill( Error("GitHub token missing", "Env: GITHUB_TOKEN is missing", "Please provide your GitHub token via the GITHUB_TOKEN environment variable"), 1 ) new(errors) end end """ Connection Simple wrapper around `Diana.Client` with the current repository name and owner. # Fields - `owner::String`: the repository owner. - `name::String`: the repository name. - `client::Diana.Client`: the Diana.Client object. """ struct Connection owner::String name::String client::Diana.Client function Connection(owner::AbstractString, name::AbstractString) GITHUB_TOKEN = haskey(ENV, "GITHUB_TOKEN") ? ENV["GITHUB_TOKEN"] : "" if GITHUB_TOKEN == "" throw(GitHubError("token")) end client = GraphQLClient(GITHUB_URL, auth="Bearer $GITHUB_TOKEN") new(owner, name, client) end end """ query(connection::Connection, queryString) The base function to make the queries. It wraps the provided query in a "repository" query. It also handles connection and result errors. """ function query(connection::Connection, queryString::AbstractString) result = Diana.Result("", "") try result = connection.client.Query( """query A (\$owner:String!, \$name:String!){ repository(name:\$name, owner:\$owner) { $queryString } }""", vars=Dict("name" => connection.name, "owner" => connection.owner), operationName="A" ) catch error throw(GitHubError(error)) end jsondata = JSON.parse(result.Data) if result.Info.status != 200 || haskey(jsondata, "errors") throw(GitHubError(result)) end return jsondata end Base.showerror(io::IO, error::GitHubError) = begin for e in error.errors println(io, """$(e.name) Type: $(e.type) Message: $(e.message)""") end end
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
6178
using Base, Colors, Diana, JSON, Dates include("queries.jl") include("Connection.jl") export Repo, Language, create_palette """ Language When parsed from GitHub a `Language` has a `name`, `color` and the "usage" `size`. # Fields - `name::String`: the language name. - `color::Colorant`: the language color (provided by [github/linguist](https://github.com/github/linguist)). - `size::Int`: the relative usage of this [`Language`](@ref) in the repository. See also: [`Repo`](@ref) """ struct Language name::String color::Colorant size::Int """ Language(name, color, size) Language(name, Nothing, size) The `Language` constructor. """ function Language(name::String, color::String, size::Int) new(name, parse(RGB{Float64}, color), size) end Language(name::String, color::Nothing, size::Int) = Language(name, "#000000", size) end """ Repo Wrapper representing the GitHub Repository. # Fields - `owner::String`: the repository owner. - `name::String`: the repository name. - `languages::Vector{Language}`: the repository [`Language`](@ref)s. - `stargazer_count::UInt`: the repository stargazer count. - `forks_count::UInt`: the repository forks count. - `watchers_count::UInt`: the repository watchers count. - `updatedat::DateTime`: the repository last update time. - `background_color::Colorant`: the chosen background color See also: [`Language`](@ref) """ struct Repo owner::String name::String languages::Vector{Language} stargazer_count::UInt forks_count::UInt watchers_count::UInt updatedat::DateTime background_color::Colorant @doc """ Repo The `Repo` constructor will create a `Connection` with the given `owner/name` and query the needed information. See also: [`Connection`](@ref) """ function Repo(owner::AbstractString, name::AbstractString, background_color::Colorant) connection = Connection(owner, name) # Query information result = query(connection, """ $stargazer_count_query $forks_count_query $watchers_count_query $updatedat_query """) data = result["data"] repository = data["repository"] stargazer_count = repository["stargazerCount"] forks_count = repository["forkCount"] watchers_count = repository["watchers"]["totalCount"] updatedat = DateTime(repository["updatedAt"], GITHUB_DATE) languages = get_languages(connection) new(owner, name, languages, stargazer_count, forks_count, watchers_count, updatedat, background_color) end end Base.show(io::IO, repo::Repo) = print(io, """$(repo.owner)/$(repo.name) Languages: $(size(repo.languages, 1)) Stars: $(repo.stargazer_count) Forks: $(repo.forks_count) Watchers: $(repo.watchers_count) """) """ getparameters(parameters, repo) Dump the `repo` parameters into the given `parameters` Dict """ function getparameters!(parameters::Dict, repo::Repo) parameters["color"] = repo.languages[1].color parameters["stargazers"] = repo.stargazer_count parameters["forks"] = repo.forks_count parameters["updatedat"] = repo.updatedat parameters["watchers"] = repo.watchers_count parameters["background_color"] = repo.background_color parameters["palette"] = create_palette(repo) end """ get_languages(connection) Utility function used to query all the languages of the repository. Return a Vector of [`Language`](@ref)s sorted by size (bigger first). """ function get_languages(connection::Connection) result::Vector{Language} = Vector(undef, 0) pagesize = 2 has_next_page = true after = "" while has_next_page language_query = make_language_query(pagesize, after) query_result = query(connection, """ $language_query """) data = query_result["data"] repository = data["repository"] languages = repository["languages"] for language in languages["edges"] push!(result, Language( language["node"]["name"], language["node"]["color"], language["size"])) end has_next_page = languages["pageInfo"]["hasNextPage"] after = languages["pageInfo"]["endCursor"] end sort!(result, by=language -> language.size, rev=true) return result end """ create_palette(repo) Utility function used to create a color palette from the repositoty languages. """ function create_palette(repo::Repo) background_color = repo.background_color palette_size = PALETTE_SIZE palette = Vector(undef, 0) coeff_l, coeff_a, coeff_b = 50, 5, 5 total_size = sum(language -> language.size, repo.languages) for language in repo.languages if language.color == background_color # Ignore languages with the same color as the background continue end nbcolors = ceil(Int, language.size * palette_size / total_size) half_colors_index = round(Int, nbcolors / 2) labcolor = convert(Lab, language.color) colors_before = Vector(undef, half_colors_index) colors_after = Vector(undef, half_colors_index) for i = 1:half_colors_index a = (half_colors_index - i) / half_colors_index b = i / half_colors_index colors_before[i] = convert(RGB, Lab( labcolor.l - coeff_l * a, labcolor.a - coeff_a * a, labcolor.b - coeff_b * a )) colors_after[i] = convert(RGB, Lab( labcolor.l + coeff_l * b, labcolor.a + coeff_a * b, labcolor.b + coeff_b * b )) end if size(palette, 1) == 0 palette = [colors_before..., language.color, colors_after...] else palette = [colors_before..., palette..., colors_after...] end end # Make sure the palette does not contain the same color as the background return filter(color -> color โ‰  background_color, palette) end
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
668
""" make_language_query(pageSize, after) Provide access to all the languages from the repository given the correct `pageSize` and `after`. """ make_language_query(pageSize, after) = begin if after == "" query = "languages(first: $pageSize) {" else query = """languages(first: $pageSize, after: "$after") {""" end query * """ totalCount edges { node { name color } size } pageInfo { endCursor hasNextPage } }""" end stargazer_count_query = "stargazerCount" forks_count_query = """forkCount""" watchers_count_query = """watchers { totalCount }""" updatedat_query = """updatedAt"""
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
2267
""" chromatic_rule(palette, background_color) Create a "Chromatic rule" with the following condition: ``` if current == background_color 3 OR 4 neighbours โ‰  background_color > neighbours' color of the "smaller" in the palette else > background_color else 7 OR 8 neighbours โ‰  background_color > background_color 3 OR 4 neighbours โ‰  background_color > current 1 OR 2 neighbours โ‰  background_color > previous color in palette or reset to the middle 5 OR 6 neighbours โ‰  background_color > next color in palette or reset to the middle ``` """ chromatic_rule(palette::Vector{<:Colorant}, background_color::Colorant) = Rule( EIGHT_NEIGHBOURS, (rule::Rule, current::Colorant, colors::Vector{<:Colorant}) -> begin # Get current color index in palette index = findfirst(color -> color == current, palette) colored_neighbours = filter(color -> color โ‰  background_color, colors) nb_colored_neighbours = size(colored_neighbours, 1) # background_color if index === nothing # Lives if 3 or 4 neighbours if nb_colored_neighbours == 3 || nb_colored_neighbours == 4 sort( colored_neighbours, by=color -> findfirst(c -> c == color, palette), rev=true)[1] else background_color end else # Dies if 7 or 8 neighbours if nb_colored_neighbours >= 7 background_color elseif nb_colored_neighbours == 3 || nb_colored_neighbours == 4 # Do nothing current elseif nb_colored_neighbours == 1 || nb_colored_neighbours == 2 if index - 1 >= 1 # Update color "darker" palette[index - 1] else # Reset middle_index = round(Int, size(palette, 1) / 2.0) palette[middle_index] end else # 5, 6 if index + 1 <= size(palette, 1) # Update color "lighter" palette[index + 1] else # Reset middle_index = round(Int, size(palette, 1) / 2.0) palette[middle_index] end end end end )
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
765
""" game_of_life(color, background_color) Create a "Game of life rule" with the following condition: ``` if current = background_color && 3 neighbours โ‰  background_color > color if current โ‰  background_color && 2 OR 3 neighbours โ‰  background_color > color else > background_color ``` """ game_of_life(color::Colorant, background_color::Colorant) = Rule( EIGHT_NEIGHBOURS, (rule::Rule, current::Colorant, colors::Vector{<:Colorant}) -> begin # Count colored neighbours nb_black = count(color -> color == background_color, colors) if (current == background_color && nb_black == 5) || (current โ‰  background_color && (nb_black == 6 || nb_black == 5)) color else background_color end end )
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
597
using ColorTypes, GeometryBasics # Constants const PALETTE_SIZE = 100; const MAX_STARGAZERS = 500000; const MAX_FORKS = 300000; const MAX_WATCHERS = 30000; # GitHub const GITHUB_URL = "https://api.github.com/graphql" const GITHUB_DATE = "yyyy-mm-ddTHH:MM:SSZ" # Image const white = RGB(1.0, 1.0, 1.0) const black = RGB(0.0, 0.0, 0.0) # Relative positions const NORTH = Point(0, -1) const SOUTH = Point(0, 1) const EAST = Point(1, 0) const WEST = Point(-1, 0) # Default neighbours const EIGHT_NEIGHBOURS = Vector([NORTH, NORTH + EAST, SOUTH, SOUTH + WEST, EAST, EAST + SOUTH, WEST, WEST + NORTH])
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
2886
const permutation = UInt8[ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180] function grad(h::Integer, x, y, z) h &= 15 # CONVERT LO 4 BITS OF HASH CODE u = h < 8 ? x : y # INTO 12 GRADIENT DIRECTIONS. v = h < 4 ? y : h == 12 || h == 14 ? x : z (h & 1 == 0 ? u : -u) + (h & 2 == 0 ? v : -v) end function perlinsnoise(x, y, z) p = vcat(permutation, permutation) fade(t) = t * t * t * (t * (t * 6 - 15) + 10) lerp(t, a, b) = a + t * (b - a) floorb(x) = Int(floor(x)) & 0xff X, Y, Z = floorb(x), floorb(y), floorb(z) # FIND UNIT CUBE THAT CONTAINS POINT. x, y, z = x - floor(x), y - floor(y), z - floor(z) # FIND RELATIVE X,Y,Z OF POINT IN CUBE. u, v, w = fade(x), fade(y), fade(z) # COMPUTE FADE CURVES FOR EACH OF X,Y,Z. A = p[X + 1] + Y; AA = p[A + 1] + Z; AB = p[A + 2] + Z B = p[X + 2] + Y; BA = p[B + 1] + Z; BB = p[B + 2] + Z # HASH COORDINATES OF THE 8 CUBE CORNERS return lerp(w, lerp(v, lerp(u, grad(p[AA + 1], x, y, z), # AND ADD grad(p[BA + 1], x - 1, y, z)), # BLENDED lerp(u, grad(p[AB + 1], x, y - 1, z), # RESULTS grad(p[BB + 1], x - 1, y - 1, z))), # FROM 8 lerp(v, lerp(u, grad(p[AA + 2], x, y, z - 1), # CORNERS grad(p[BA + 2], x - 1, y, z - 1)), # OF CUBE. lerp(u, grad(p[AB + 2], x, y - 1, z - 1), grad(p[BB + 2], x - 1, y - 1, z - 1)))) end
Repotomata
https://github.com/Nauss/Repotomata.git
[ "MIT" ]
0.1.0
32e6d8d53512284b78dc0446061d3337ba4946a3
code
1480
using Colors, FixedPointNumbers, Dates include("../src/utilities/constants.jl") @testset "Repo" begin @testset "Construction" begin repo = Repo("JuliaLang", "Julia", RGB{Float64}(0.0, 0.0, 0.0)) @test repo.owner == "JuliaLang" @test repo.name == "Julia" @test size(repo.languages, 1) == 18 @test repo.languages[1].name == "Julia" @test repo.languages[1].color == RGB{Float64}(0.6352941176470588, 0.4392156862745098, 0.7294117647058823) @test repo.languages[1].size > 10000000 @test repo.stargazer_count > 30000 @test repo.forks_count > 4000 @test repo.watchers_count > 800 @test repo.updatedat >= DateTime("2020-11-15T14:15:25Z", GITHUB_DATE) end @testset "Construction fails" begin @test_throws GitHubError Repo("Paul", "Poule", RGB{Float64}(0.0, 0.0, 0.0)) end @testset "No token" begin # Remove the token token = ENV["GITHUB_TOKEN"] ENV["GITHUB_TOKEN"] = "" @test_throws GitHubError Repo("JuliaLang", "Julia", RGB{Float64}(0.0, 0.0, 0.0)) # Restore the token for other tests ENV["GITHUB_TOKEN"] = token end @testset "create_palette" begin repo = Repo("JuliaLang", "Julia", RGB{Float64}(0.0, 0.0, 0.0)) palette = create_palette(repo) @test size(palette, 1) == PALETTE_SIZE - 2 @test findfirst(color -> color โ‰ˆ repo.languages[1].color, palette) !== nothing end end
Repotomata
https://github.com/Nauss/Repotomata.git