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.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 647 | using NeighbourLists
using JuLIP
using BenchmarkTools
include("test_aux.jl")
print("N-body energy and forces benchmark: ")
println("# Threads = ", Base.Threads.nthreads())
at = bulk(:Cu, cubic=true) * 5
println("bulk :Cu with nat = $(length(at))")
r0 = rnn(:Cu)
rcut = 2.1 * r0
X = positions(at)
C = cell(at)
f, f_d = gen_fnbody(rcut, r0)
nlist = PairList(X, rcut, C, (false, false, false), sorted = true)
for M in [2, 3, 4, 5]
println("M = $M")
print(" energy: ")
@btime n_body($f, $M, $nlist)
print(" forces: ")
@btime grad_n_body($f_d, $M, $nlist)
end
lj = LennardJones(r0, 1.0) * C1Shift(cutoff)
@btime forces($lj, $at)
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 1945 | using NeighbourLists
using JuLIP
using BenchmarkTools
##
# using PyCall
# using ASE
# using ProfileView
# include("../test/test_aux.jl")
# @pyimport matscipy.neighbours as matscipy_neighbours
# matscipy_neighbours = pyimport("matscipy.neighbours")
# function matscipy_nlist(at, cutoff)
# pycall(matscipy_neighbours["neighbour_list"],
# NTuple{5, PyArray}, "ijdDS", at.po, cutoff)
# end
println("# Threads = ", Base.Threads.nthreads())
##
println("Neighbourlist assembly benchmark")
for L in [2, 4, 10, 30]
print("L = $L")
# si, non-cubic cell, mixed bc
at = bulk(:Si, cubic=true) * L
println(", N = $(length(at))")
set_pbc!(at, (true, true, true))
C = JMat(cell(at))
X = positions(at)
perbc = JVec(pbc(at))
cutoff = 3.5 * rnn(:Si)
# println("Julia Nlist")
@btime PairList($X, $cutoff, $C, $perbc)
# println("Matscipy Nlist")
# @btime matscipy_nlist($(ASEAtoms(at)), $cutoff)
println("------------------------------------------")
end
##
# at = bulk(:Si, cubic=true, pbc = true ) * 10
# rcut = 2.5 * rnn(:Si)
# C = JMat(cell(at))
# X = positions(at)
# perbc = JVec(pbc(at))
# # NeighbourLists._pairlist_(X, C, perbc, rcut, Int, false)
# clist = NeighbourLists._celllist_(X, C, perbc, rcut, Int)
# @btime NeighbourLists._celllist_($X, $C, $perbc, $rcut, Int)
# @btime NeighbourLists._pairlist_($clist)
# # @btime NeighbourLists._pairlist_($X, $C, $perbc, $rcut, Int, false)
# # clist = _celllist_(X, cell, pbc, cutoff, TI)
# # i, j, S = _pairlist_(clist)
# @code_warntype NeighbourLists._pairlist_(clist)
##
# @profview let clist = clist
# for _ = 1:100
# NeighbourLists._pairlist_(clist)
# end
# end
##
# at = bulk(:Si, cubic=true, pbc = true ) * 10
# rcut = 2.5 * rnn(:Si)
# @profview let C = JMat(cell(at)), X = positions(at), perbc = JVec(pbc(at)),
# rcut = rcut
# for _ = 1:30
# PairList(X, rcut, C, perbc)
# end
# end | NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 501 |
__precompile__()
module NeighbourLists
const MAX_THREADS = [1] # temporarily hard-coded single thread!
set_maxthreads!(n) = (NeighbourLists.MAX_THREADS[1] = n)
include("types.jl")
# this contains the cell-list data structures and assembly
include("cell_list.jl")
# this contains the different iterators over sites, bonds, etc
include("iterators.jl")
# alternative assembly protocol more akin to mapreduce
include("mapreduce.jl")
# AtomsBase interface
include("atoms_base.jl")
end # module
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 545 | using AtomsBase
using StaticArrays: SVector
using Unitful
function PairList(ab::AtomsBase.AbstractSystem, cutoff::Unitful.Length; length_unit=unit(cutoff))
cell = ustrip.(length_unit, hcat( bounding_box(ab)... )' )
pbc = periodicity(ab)
r = map( 1:length(ab) ) do i
# Need to have SVector here for PairList to work
# if position does not give SVector
SVector( ustrip.(length_unit, position(ab,i))...)
end
nlist = PairList(r, ustrip(length_unit, cutoff), cell, pbc; int_type=Int)
return nlist
end | NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 16246 | using Base.Threads, LinearAlgebra
export npairs, nsites, maxneigs, max_neighbours, neigs, neighbours, neigs!
PairList(X::Vector{SVec{T}}, cutoff::AbstractFloat, cell::AbstractMatrix, pbc;
int_type::Type = Int32, fixcell = true) where {T} =
_pairlist_(X, SMat{T}(cell), SVec{Bool}(pbc), T(cutoff), int_type,
fixcell)
PairList(X::Matrix{T}, args...; kwargs...) where {T} =
PairList(reinterpret(SVec{T}, X, (size(X,2),)), args...; varargs...)
npairs(nlist::PairList) = length(nlist.i)
nsites(nlist::PairList) = length(nlist.first) - 1
cutoff(nlist::PairList) = nlist.cutoff
# ====================== Cell Index Algebra =====================
"Map i back to the interval [0,n) by shifting by integer multiples of n"
@inline function bin_wrap(i::Integer, n::Integer)
while i <= 0; i += n; end
while i > n; i -= n; end
return i;
end
"apply bin_wrap only if periodic bdry"
@inline bin_wrap(i::Integer, pbc::Bool, n::Integer) = pbc ? bin_wrap(i, n) : i
"Map i back to the interval [0,n) by assigning edge value if outside interval"
@inline function bin_trunc(i::TI, n::TI) where {TI <: Integer}
if i <= 0; i = TI(1)
elseif i > n; i = n
end
return i
end
"apply bin_trunc only if open bdry"
@inline bin_trunc(i::TI, pbc::Bool, n::TI) where {TI <: Integer} =
pbc ? TI(i) : bin_trunc(i, n)
"applies bin_trunc to open bdry and bin_wrap to periodic bdry"
@inline bin_wrap_or_trunc(i::Integer, pbc::Integer, n::Integer) =
pbc ? bin_wrap(i, n) : bin_trunc(i, n)
"Map particle position to a (cartesian) cell index"
@inline position_to_cell_index(inv_cell::SMat{T}, x::SVec{T}, ns::SVec{TI}
) where {T, TI <: Integer} =
floor.(TI, ((inv_cell' * x) .* ns .+ 1))
# ------------ The next two functions are the only dimension-dependent
# parts of the code!
# an extension of sub2ind for the case when i is a vector (cartesian index)
# @inline Base.sub2ind(dims::NTuple{3,TI}, i::SVec{TI}) where {TI <: Integer} =
# sub2ind(dims, i[1], i[2], i[3])
# WARNING: this smells like a performance regression!
# WARNING: `LinearIndices` always returnsstores Int, not TI!!!
@inline _sub2ind(dims::NTuple{3,TI}, i::SVec{TI}) where {TI <: Integer} =
TI( (LinearIndices(dims))[i[1], i[2], i[3]] )
lengths(C::SMat{T}) where {T} =
det(C) ./ SVec{T}(norm(C[2,:]×C[3,:]), norm(C[3,:]×C[1,:]), norm(C[1,:]×C[2,:]))
# --------------------------------------------------------------------------
function analyze_cell(cell, cutoff, TI)
@assert TI <: Integer
# check the cell volume (allow only 3D volumes!)
volume = abs(det(cell))
if volume < 1e-12
@warn("zero volume detected - proceed at your own risk")
@show cell
@show volume
@show cutoff
end
# precompute inverse of cell matrix for coordiate transformation
inv_cell = inv(cell)
# Compute distance of cell faces
lens = abs.(lengths(cell))
# Number of cells for cell subdivision
_t = floor.(TI, lens / cutoff)
ns_vec = max.(_t, one(TI))
return inv_cell, ns_vec, lens
end
# multi-threading setup
function setup_mt(niter::TI, maxnt = MAX_THREADS[1]) where TI <: Integer
nt = minimum([6, nthreads(), ceil(TI, niter / 20), maxnt])
# nn = ceil.(TI, linspace(1, niter+1, nt+1))
# range(start, stop=stop, length=length)
nn = ceil.(TI, range(1, stop=niter+1, length=nt+1))
return nt, nn
end
# ==================== CellList Core ================
function _celllist_(X::Vector{<:SVec}, cell::SMat, pbc::SVec{Bool},
cutoff::T, TI) where {T <: Real}
@assert TI <: Integer
# ----- analyze cell -----
nat = length(X)
inv_cell, ns_vec, lens = analyze_cell(cell, cutoff, TI)
ns = ns_vec.data
if prod(BigInt.(ns_vec)) > typemax(TI)
error("""Ratio of simulation cell size to cutoff is very large.
Are you using a cell with lots of vacuum? To fix this
use a larger integer type (e.g. Int128), a
larger cut-off, or a smaller simulation cell.""")
end
# data structure to store a linked list for each bin
ncells = prod(ns_vec)
seed = fill(TI(-1), ncells)
last = Vector{TI}(undef, ncells)
next = Vector{TI}(undef, nat)
nats = zeros(TI, ncells)
for i = 1:nat
# Get cell index
c = position_to_cell_index(inv_cell, X[i], ns_vec)
# Periodic/non-periodic boundary conditions
c = bin_wrap_or_trunc.(c, pbc, ns_vec)
# linear cell index # (+1 due to 1-based indexing)
ci = _sub2ind(ns, c)
# Put atom into appropriate bin (list of linked lists)
if seed[ci] < 0 # ci contains no atom yet
next[i] = -1
seed[ci] = i
last[ci] = i
nats[ci] += 1
else
next[i] = -1
next[last[ci]] = i
last[ci] = i
nats[ci] += 1
end
end
return CellList(X, cell, inv_cell, pbc, cutoff, seed, last, next, nats)
end
function _pairlist_(clist::CellList{T, TI}) where {T, TI}
X, cell, pbc, cutoff, seed, last, next =
clist.X, clist.cell, clist.pbc, clist.cutoff,
clist.seed, clist.last, clist.next
nat = length(X)
inv_cell, ns_vec, lens = analyze_cell(cell, cutoff, TI)
# guess how many neighbours per atom
# atoms in cell x (8 cells) * (ball / cube)
max_nat_cell = maximum(clist.nats)
nneigs_guess = ceil(TI, 1.5 * max_nat_cell * (π^2/4))
# allocate arrays for the many threads
# set number of threads
nt, nn = setup_mt(nat)
# allocate arrays
first_t = Vector{TI}[ Vector{TI}() for n = 1:nt ] # i
secnd_t = Vector{TI}[ Vector{TI}() for n = 1:nt ] # j
shift_t = Vector{SVec{TI}}[ Vector{SVec{TI}}() for n = 1:nt ] # ~ X[i] - X[j]
# give size hints
sz = (nat ÷ nt + nt) * nneigs_guess
for n = 1:nt
sizehint!(first_t[n], sz)
sizehint!(secnd_t[n], sz)
sizehint!(shift_t[n], sz)
end
# We need the shape of the bin ( bins[:, i] = cell[i,:] / ns[i] )
# bins = cell' ./ ns_vec
bins = hcat( cell[1,:]/ns_vec[1], cell[2,:]/ns_vec[2], cell[3,:] / ns_vec[3] )
# Find out over how many neighbor cells we need to loop (if the box is small)
nxyz = ceil.(TI, cutoff * (ns_vec ./ lens))
# cxyz = CartesianIndex(nxyz.data)
# WARNING : 3D-specific hack; also potential performance regression
# WARNING: `CartesianIndices` always stores Int, not TI!!!
xyz_range = CartesianIndices((-nxyz[1]:nxyz[1],
-nxyz[2]:nxyz[2],
-nxyz[3]:nxyz[3]))
# Loop over threads
# @threads for it = 1:nt
for it = 1:nt
for i = nn[it]:(nn[it+1]-1)
# current atom position
_find_neighbours_!(i, clist, ns_vec, bins, xyz_range,
first_t[it], secnd_t[it], shift_t[it])
end # for i = 1:nat
end # @threads
# piece them back together
sz = sum( length(first_t[i]) for i = 1:nt )
first = first_t[1]; sizehint!(first, sz)
secnd = secnd_t[1]; sizehint!(secnd, sz)
shift = shift_t[1]; sizehint!(shift, sz)
for it = 2:nt
append!(first, first_t[it])
append!(secnd, secnd_t[it])
append!(shift, shift_t[it])
end
# Build return tuple
return first, secnd, shift
end
function _find_neighbours_!(i, clist, ns_vec::SVec{TI}, bins, xyz_range,
first, secnd, shift) where TI
inv_cell, X, pbc = clist.inv_cell, clist.X, clist.pbc
seed, last, next = clist.seed, clist.last, clist.next
xi = X[i]
# funnily testing with cutoff^2 actually makes a measurable difference
# which suggests we are pretty close to the performance limit
cutoff_sq = clist.cutoff^2
# cell index (cartesian) of xi
ci0 = position_to_cell_index(inv_cell, xi, ns_vec)
# Truncate if non-periodic and outside of simulation domain
# (here, we don't yet want to wrap the pbc as well)
ci = bin_trunc.(ci0, pbc, ns_vec)
# dxi is the position relative to the lower left corner of the bin
dxi = xi - bins * (ci .- 1)
# Apply periodic boundary conditions as well now
ci = bin_wrap_or_trunc.(ci0, pbc, ns_vec)
for ixyz in xyz_range # Integer
# convert cartesian index to SVector
xyz = SVec{TI}(ixyz.I)
# get the bin index
cj = bin_wrap.(ci + xyz, pbc, ns_vec)
# skip this bin if not inside the domain
all(TI(1) .<= cj .<= ns_vec) || continue
# linear cell index
ncj = _sub2ind(ns_vec.data, cj)
# Offset of the neighboring bins
off = bins * xyz
# Loop over all atoms in neighbouring bin (all potential
# neighbours in the bin with linear index cj1)
j = seed[ncj] # the first atom in the ncj cell
while j > 0
if i != j || any(xyz .!= 0)
xj = X[j] # position of current neighbour
# we need to find the cell index again, because this is
# not really the cell index, but it could be outside
# the domain -> i.e. this only makes a difference for pbc
cj = position_to_cell_index(inv_cell, xj, ns_vec)
cj = bin_trunc.(cj, pbc, ns_vec)
# drj is position relative to lower left corner of the bin
dxj = xj - bins * (cj .- 1)
# Compute distance between atoms
dx = dxj - dxi + off
norm_dx_sq = dot(dx, dx)
# append to the list
if norm_dx_sq < cutoff_sq
push!(first, i)
push!(secnd, j)
push!(shift, (ci0 - cj + xyz) .÷ ns_vec)
end
end # if i != j || any(xyz .!= 0)
# go to the next atom in the current cell
j = next[j];
end # while j > 0 (loop over atoms in current cell)
end # loop over neighbouring bins
end
function _pairlist_(X::Vector{SVec{T}}, cell::SMat{T}, pbc::SVec{Bool},
cutoff::T, TI, fixcell::Bool) where {T}
@assert TI <: Integer
# temporary (?) fix to make sure all atoms are within the cell
if fixcell
X, cell = _fix_cell_(X, cell, pbc)
end
clist = _celllist_(X, cell, pbc, cutoff, TI)
i, j, S = _pairlist_(clist)
first = get_first(i, length(X))
sort_neigs!(j, (S,), first)
return PairList(X, cell, cutoff, i, j, S, first)
end
# ==================== Post-Processing =========================
"""
`get_first(i::Vector{TI}, nat::Integer) -> first::Vector{TI}
where TI <: Integer`
Assumes that `i` is sorted in ascending order.
For `n = 1, . . ., nat`, `first[n]` will be the index to the first
element of `i` with value `n`. Further, `first[nat+1]` will be
`length(i) + 1`.
If `first[n] == first[n+1]` then this means that `i` contains no element `n`.
"""
function get_first(i::Vector{TI}, nat::Integer = i[end]) where {TI}
# compute the first index for each site
first = Vector{TI}(undef, nat + 1)
idx = 1
n = 1
while n <= nat && idx <= length(i)
first[n] = idx
while i[idx] == n
idx += 1
if idx > length(i)
break
end
end
n += 1
end
first[n:end] .= length(i)+1
return first
end
"""
`sort_neigs!(j, arrays, first)`
sorts each sub-range of `j` corresponding to one site in ascending order
and applies the same permutation to `r, R, S`.
"""
function sort_neigs!(j, arrays::Tuple, first)
nat = length(first) - 1
nt, nn = setup_mt(nat)
@threads for it = 1:nt
for n = nn[it]:(nn[it+1]-1)
if first[n+1] > first[n] + 1
rg = first[n]:first[n+1]-1
jrg = j[rg]
if !issorted(jrg)
I = sortperm(j[rg])
rg_perm = rg[I]
j[rg] = j[rg_perm]
for a in arrays
a[rg] .= a[rg_perm]
end
end
end
end
end
end
"""
`_fix_cell_(X::Vector{SVec{T}}, C::SMat{T}, pbc)`
produces new `X`, `C` such that PBC are respected, but all positions are
inside the cell. This Potentially involves
* wrapping atom positions in the pbc directions
* shifting atom positions in the non-pbc directions
* enlarging the cell
If either `X` or `C` are modified, then they will be copied.
"""
function _fix_cell_(X::Vector{SVec{T}}, C::SMat{T}, pbc) where {T}
invCt = inv(C)'
copy_X = false
min_lam = @MVector zeros(3)
max_lam = @MVector ones(3)
for (ix, x) in enumerate(X)
λ = Vector(invCt * x)
for i = 1:3
update_x = false
if !(0.0 <= λ[i] < 1.0)
if pbc[i]
λ[i] = mod(λ[i], 1.0)
update_x = true
else
min_lam[i] = min(min_lam[i], λ[i])
max_lam[i] = max(max_lam[i], λ[i])
end
end
if update_x
if !copy_X; X = copy(X); copy_X = true end
X[ix] = C' * SVec{T}(λ)
end
end
end
# check whether we need to adjust the non-PBC directions
if (minimum(min_lam) < 0.0) || (maximum(max_lam) > 1.0)
# shift vector:
if !copy_X; X = copy(X); copy_X = true end
t = - C' * min_lam
for n = 1:length(X)
X[n] += t
end
# the new min_lam is now zero and the new max_lam is max_lam - min_lam
max_lam -= min_lam
min_lam .= 0.0
# because of round-off we add a little extra in the non-pbc directions
# it doesn't affect any energies etc but creates weirdness otherwise.
for i = 1:3
if max_lam[i] > 1
max_lam[i] *= 1.01
end
end
# we need to multiply the cell by the correct lambda
C = hcat( max_lam[1] * C[1,:], max_lam[2] * C[2,:], max_lam[3] * C[3,:])'
end
return X, C
end
"""
`maxneigs(nlist::PairList) -> Integer`
returns the maximum number of neighbours that any atom in the
neighbourlist has.
"""
maxneigs(nlist::PairList) = maximum( nneigs(nlist, n) for n = 1:nsites(nlist) )
# retire max_neigs
const max_neigs = maxneigs
"""
`nneigs(nlist::PairList, i0::Integer) -> Integer` :
return number of neighbours of particle with index `i0`.
(within cutoff radius + buffer)
"""
nneigs(nlist::PairList, i0::Integer) = nlist.first[i0+1]-nlist.first[i0]
function _getR(nlist, idx)
i = nlist.i[idx]
j = nlist.j[idx]
return _getR(nlist.X[j] - nlist.X[i], nlist.S[idx], nlist.C)
end
_getR(dX::SVec, S::SVec, C::SMat) = dX + C' * S
"""
`neigs!(Rtemp, nlist, i) -> j, R`
For `nlist::PairList` this returns the interaction neighbourhood of
the atom indexed by `i`. E.g., in the standard loop approach one
would have
```
Rtemp = zeros(JVecF, maxneigs(nlist))
for (i, j, R) in sites(nlist)
(j, R) == neigs(nlist, i) == neigs!(Rtemp, nlist, i)
end
```
`R` is a view into `Rtemp` with the correct length, while `j` is a view
into `nlist.j`.
"""
function neigs!(Rs::AbstractVector{<: SVec}, nlist::PairList, i0::Integer)
n1, n2 = nlist.first[i0], nlist.first[i0+1]-1
_grow_array!(Rs, n2-n1+1)
J = (@view nlist.j[n1:n2])
for n = 1:length(J)
Rs[n] = _getR(nlist, n1+n-1)
end
return J, (@view Rs[1:length(J)])
end
function neigs!(Js::AbstractVector{<: SVec},
Rs::AbstractVector{<: SVec},
nlist::PairList, i0::Integer)
_grow_array!(Rs, n2-n1+1)
_grow_array!(Js, n2-n1+1)
j, Rs = neigs!(Rs, nlist, i0)
N = length(j)
copyto!(Js, j)
return (@view Js[1:length(j)]), Rs
end
function _grow_array!(A::Vector{T}, N) where {T}
if length(A) < N
append!(A, zeros(T, N-length(A)))
end
return A
end
"""
`neigss!(Rs, nlist, i0) -> j, R, S` : return neighbourhood as in
`neigs!` as well as the corresponding cell shifts.
(`R` is a view into `Rs` with the correct length)
"""
function neigss!(Rs::AbstractVector{<: SVec}, nlist::PairList, i0::Integer)
n1, n2 = nlist.first[i0], nlist.first[i0+1]-1
_grow_array!(Rs, n2-n1+1)
J = (@view nlist.j[n1:n2])
for n = 1:length(J)
Rs[n] = _getR(nlist, n1+n-1)
end
return J, (@view Rs[1:length(J)]), (@view nlist.S[n1:n2])
end
neigs(nlist::PairList{T}, i0::Integer) where {T} =
neigs!( zeros(SVec{T}, nneigs(nlist, i0)), nlist, i0 )
neigss(nlist::PairList{T}, i0::Integer) where {T} =
neigss!( zeros(SVec{T}, nneigs(nlist, i0)), nlist, i0 )
"""
alias for `neigs`
"""
neighbours = neigs
"""
alias for `max_neigs`
"""
max_neighbours = maxneigs
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 1132 |
import Base: iterate, length, pairs
export pairs, sites, site, nbodies
abstract type AbstractIterator end
inc(i::T) where {T <: Integer} = i + T(1)
# -------------- iterator over pairs ---------------
pairs(nlist::PairList) = PairIterator(nlist)
struct PairIterator{T,TI} <: AbstractIterator
nlist::PairList{T,TI}
end
_item(it::PairIterator, i::Integer) =
(it.nlist.i[i], it.nlist.j[i], _getR(it.nlist, i))
iterate(it::PairIterator{T,TI}) where {T,TI} =
npairs(it.nlist) > 0 ? (_item(it, 1), TI(1)) : nothing
iterate(it::PairIterator, i::Integer) =
i >= npairs(it.nlist) ? nothing : (_item(it, inc(i)), inc(i))
length(it::PairIterator) = npairs(it.nlist)
# -------------- iterator over sites ---------------
sites(nlist::PairList) = SiteIterator(nlist)
struct SiteIterator{T,TI} <: AbstractIterator
nlist::PairList{T,TI}
end
_item(it::SiteIterator, i::Integer) = (i, neigs(it.nlist, i)...)
iterate(it::SiteIterator{T,TI}) where {T,TI} = _item(it, 1), one(TI)
iterate(it::SiteIterator, i::Integer) =
i >= length(it) ? nothing : (_item(it, i+1), inc(i))
length(it::SiteIterator) = nsites(it.nlist)
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 2783 |
using Base.Threads
export maptosites!, maptosites_d!
function mt_split(niter::TI, maxthreads=MAX_THREADS[1]) where TI
nt = minimum([maxthreads, nthreads(), niter])
# nn = ceil.(TI, linspace(1, niter+1, nt+1))
nn = ceil.(TI, range(1, stop=niter+1, length=nt+1))
rgs = [nn[i]:(nn[i+1]-1) for i = 1:nt]
return nt, rgs
end
function mt_split_interlaced(niter::TI, maxthreads=MAX_THREADS[1]) where TI
nt = minimum([maxthreads, nthreads(), niter])
rgs = [ j:nt:niter for j = 1:nt ]
return nt, rgs
end
function _mt_map_!(f::FT, out, it, inner_loop) where FT
nt, rg = mt_split(length(it))
if nt == 1
inner_loop(f, out, it, 1:length(it))
else
OUT = [[out]; [zeros(out) for i = 2:nt]]
@threads for i = 1:nt
inner_loop(f, OUT[i], it, rg[i])
end
for it = 2:nt
out .+= OUT[it]
end
end
return out
end
maptosites!(f, out::AbstractVector, it::AbstractIterator) =
_mt_map_!(f, out, it, maptosites_inner!)
maptosites_d!(f, out::AbstractVector, it::AbstractIterator) =
_mt_map_!(f, out, it, maptosites_d_inner!)
# ============ assembly over pairs
"""
`mapreduce_sym!{S, T}(out::AbstractVector{S}, f, it::PairIterator{T})`
symmetric variant of `mapreduce!{S, T}(out::AbstractVector{S}, ...)`, summing only
over bonds (i,j) with i < j and adding f(R_ij) to both sites i, j.
"""
function maptosites_inner!(f::FT, out, it::PairIterator, rg) where FT
nlist = it.nlist
for n in rg
if nlist.i[n] < nlist.j[n]
f_ = f(nlist.r[n], nlist.R[n]) / 2
out[nlist.i[n]] += f_
out[nlist.j[n]] += f_
end
end
return out
end
"""
`mapreduce_antisym!{T}(out::AbstractVector{SVec{T}}, df, it::PairIterator{T})`
anti-symmetric variant of `mapreduce!{S, T}(out::AbstractVector{S}, ...)`, summing only
over bonds (i,j) with i < j and adding f(R_ij) to site j and
-f(R_ij) to site i.
"""
function maptosites_d_inner!(f::FT, out, it::PairIterator, rg) where FT
nlist = it.nlist
for n in rg
if nlist.i[n] < nlist.j[n]
f_ = f(nlist.r[n], nlist.R[n])
out[nlist.j[n]] += f_
out[nlist.i[n]] -= f_
end
end
return out
end
# ============ assembly over sites
function maptosites!(f::FT, out::AbstractVector, it::SiteIterator) where FT
@threads for i = 1:nsites(it.nlist)
_, R = neigs(it.nlist, i)
out[i] = f(R)
end
return out
end
function maptosites_d!(df::FT, out::AbstractVector, it::SiteIterator) where FT
nt = nthreads()
OUT = [out; [zeros(out) for n = 2:nt]]
@threads for i = 1:nsites(it.nlist)
j, R = neigs(it.nlist, i)
df_ = df(R)
OUT[threadid()][j] += df_
OUT[threadid()][i] -= sum(df_)
end
for it = 2:n
out .+= OUT[it]
end
return out
end
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 1624 |
using StaticArrays
const SVec{T} = SVector{3, T}
const SMat{T} = SMatrix{3, 3, T, 9}
export PairList
"""
`PairList` stores a neighbourlist as a list of pairs
```
PairList(X, cutoff, cell, pbc)
PairList(nlist::CellList)
```
where
* `X` : positions, either as 3 x N matrix or as `Vector{SVec}`
* `cutoff` : positive real value
* `cell` : 3 x 3 matrix, with rows denoting the cell vectors
* `pbc` : 3-tuple or array, storing periodicity information
### Kw-args:
* `int_type` : default is `Int`
* `store_first` : whether to store the array of first indices, default `true`
* `sorted` : whether to sort the `j` vector, default `false`
### PairList fields
`X, cutoff, i, j, r, R, first`, where
`(i[n], j[n])` denotes the indices of a neighbour pair, `r[n]` the distance
between those atoms, `R[n]` the vectorial distance, note this is identical to
`X[i[n]]-X[j[n]]` without periodic b.c.s, but with periodic boundary conditions
it is different. `first[m]` contains the index to the first `(i[n], j[n])` for
which `i[n] == first[m]`, i.e., `(j, first)` essentially defines a compressed
column storage of the adjacancy matrix.
"""
struct PairList{T <: Real, TI <: Integer}
X::Vector{SVec{T}}
C::SMat{T}
cutoff::T
i::Vector{TI}
j::Vector{TI}
S::Vector{SVec{TI}}
first::Vector{TI}
end
"""
`CellList` : store atoms in cells / bins. Mostly used internally
to construct PairLists.
"""
struct CellList{T <: Real, TI <: Integer}
X::Vector{SVec{T}}
cell::SMat{T}
inv_cell::SMat{T}
pbc::SVec{Bool}
cutoff::T
seed::Vector{TI}
last::Vector{TI}
next::Vector{TI}
nats::Vector{TI}
end
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 1263 |
using NearestNeighbors, Distances, LinearAlgebra
import Distances: evaluate
struct Periodic{T} <: Metric
L::SVec{T}
pbc::SVec{Bool}
end
function evaluate(d::Periodic{T}, x::AbstractVector, y::AbstractVector) where {T}
s = 0.0
for i = 1:3
if d.pbc[i]
m = mod(x[i]-y[i], d.L[i])
s += min( m, d.L[i]-m )^2
else
s += (x[i]-y[i])^2
end
end
return sqrt(s)
end
# function nn_list{T, TI}(X::Vector{SVec{T}}, cutoff::T,
# cell::SMat{T}, pbc::SVec{Bool}, _::TI)
function nn_list(X::Vector{SVec{Float64}}, cutoff, cell, pbc::SVec{Bool})
# WARNING: removed `const` here - will this slow down the code?
T = Float64
TI = Int
@assert cell == SMat{T}(diagm(0 => diag(cell))) # require cubic cell
# construct a periodic metric
d = Periodic(SVec{T}(diag(cell)), pbc)
# construct the ball tree
tree = BallTree(X, d)
i = TI[]
j = TI[]
r = T[]
R = SVec{T}[]
for n = 1:length(X)
neigs = inrange(tree, X[n], cutoff, true)
for a = 1:length(neigs)
if neigs[a] != n
push!(i, n)
push!(j, neigs[a])
push!(r, evaluate(d, X[n], X[neigs[a]]))
end
end
end
return i, j, r, R
end
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 756 | using NeighbourLists
using Test
# ---- FLAGS -----
# whether to run performance tests
performance = true
# check whether on CI
isCI = haskey(ENV, "CI")
notCI = !isCI
# TODO: switch the JuLIP test to an ASE test
# check whether we have JuLIP
# hasjulip = true
# try
# using JuLIP
# catch
# hasjulip = false
# end
# ----------------- TESTS -------------------
println("# threads = $(Base.Threads.nthreads())")
@testset "NeighbourLists" begin
@testset "Aux" begin include("test_aux.jl") end
@testset "CellList" begin include("test_celllist.jl") end
include("test_atoms_base.jl")
# pointless until we switch to comparing against ASE / matscipy
# if hasjulip
# @testset "JuLIP" begin include("test_julip.jl") end
# end
end
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 3158 |
using NeighbourLists
using JuLIP
# at = set_pbc!(bulk(:Si, cubic=true) * 3, true)
# length(at)
# cutoff = 3.1 * rnn(:Si)
# nlist = CellList(positions(at), cutoff, cell(at), pbc(at))
#
# f(r, R) = (exp(-8*(r-1)) - 2 * exp( - 4 * (r - 1))) * 1 / (1+r)
#
# out = zeros(length(at))
# mapreduce_sym!(out, f, pairs(nlist))
#
# @time mapreduce_sym!(out, f, pairs(nlist));
# @time NeighbourLists.tmapreduce_sym!(out, f, pairs(nlist));
macro symm(N, ex)
if N isa Symbol
N = eval(N)
end
@assert ex.head == :for
@assert length(ex.args) == 2
ex_for = ex.args[1]
ex_body = ex.args[2]
# iteration symbol
i = ex_for.args[1]
# lower and upper bound
a0 = ex_for.args[2].args[1]
a1 = ex_for.args[2].args[2]
# create the for-loop without body
loopstr = "for $(i)1 = ($a0):(($a1)-$(N-1))"
for n = 2:N
loopstr *= ", $i$n = $i$(n-1)+1:(($a1)-$(N-n))"
end
loopstr *= "\n $i = CartesianIndex($(i)1"
for n = 2:N
loopstr *= ", $i$n"
end
loopstr *= ") \n end"
loopex = Meta.parse(loopstr)
append!(loopex.args[2].args, ex_body.args)
# return the expression
esc(quote
$loopex
end)
end
@generated function t(b0, b1, Nval::Val{N}) where N
quote
@symm $N for j = b0:b1
println(j)
end
end
end
t(3, 8, Val(3))
M = 4
@symm M for j = 1:6
println(j)
end
getN(::Val{N}) where N = N::Int
getN(n::Integer) = n
getN(::Type{Val{N}}) where N = N::Int
macro mm(NN)
@show NN
@show getN(eval(NN))
end
@mm(4)
@mm(Val(4))
getN(Val{4})
M = 4
@mm 4
@mm M
function m1(::Val{N}) where N
@show N
@show typeof(N)
end
m1(Val(4))
@generated function m2(v::T)
@mm(T)
end
function simplex_lengths(I::SVector{N, TI}, X::AbstractVector{T}) where {
N, TI <: Integer, T <: AbstractFloat}
N2 = (N*(N-1))÷2
a = zeros(TI, N2)
b = zeros(TI, N2)
s = zeros(T, N2)
n = 0
for i = 1:N-1, j = i+1:N
n += 1
a[n] = I[i]
b[n] = I[j]
s[n] = abs(X[a[n]] - X[b[n]])
end
return s, a, b
end
I = SVector(3, 5, 7, 2)
X = rand(10)
simplex_lengths(I, X)
function statalloc(I::SVector{N, TI}) where {N, TI}
N2 = (N*(N-1)) ÷ 2
a = zero(MVector{N2, TI})
end
statalloc(I)
function simplex_lengths!(s, a, b, I::SVector{N, TI}, X) where {N, TI <: Integer}
n = 0
for i = 1:N-1, j = i+1:N
n += 1
a[n] = I[i]
b[n] = I[j]
s[n] = norm(X[a[n]] - X[b[n]])
end
return SVector(s), SVector(a), SVector(b)
end
function simplex_lengths2!(s, a, b, I::SVector{N, TI}, X) where {N, TI <: Integer}
n = 0
for i = 1:N-1, j = i+1:N
n += 1
a[n] = I[i]
b[n] = I[j]
s[n] = norm(X[a[n]] - X[b[n]])
end
return s, a, b
end
function test(slen, M)
I = SVector(3, 50, 74, 22, 10)
N = length(I)
N2 = (N*(N-1)) ÷ 2
X = rand(SVector{3, Float64}, 100)
s = zero(MVector{N2, Float64})
a = zero(MVector{N2, Int})
b = zero(MVector{N2, Int})
for m = 1:M
slen(s, a, b, I, X)
end
end
@btime test(simplex_lengths!, 10_000)
@btime test(simplex_lengths2!, 10_000)
# @btime simplex_lengths2!($s, $a, $b, $I, $X)
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 291 | using ASEconvert
using NeighbourLists
using Test
using Unitful
@testset "AtomsBase PairList" begin
cu = ase.build.bulk("Cu") * pytuple((4, 2, 3))
sys = pyconvert(AbstractSystem, cu)
nlist = PairList(sys, 3.5u"Å")
id, r = neigs(nlist,1)
@test length(id) == 12
end
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 2045 | # This file contains some code that is chared across several tests
using StaticArrays, Test, ForwardDiff
using NeighbourLists: SMat, SVec
using Test, StaticArrays, ForwardDiff
# ------ generate random configurations -------
function rand_config(N)
C = SMat( diagm(0 => 2.0 .+ 0.2 * rand(3)) * N )
X = [ C' * rand(SVec) for i = 1:ceil(Int, abs(det(C))) ÷ 4 + 2 ]
pbc = SVec(rand(Bool, 3))
return X, C, pbc
end
# --------- MANY BODY CODE THAT IS SHARED ACROSS TESTS ------------
sqrt1p(x) = expm1( 0.5 * log1p( x ) ) # sqrt(1 + x) - 1
sqrt1p_d(x) = 0.5 / sqrt(1+x)
function fnbody(r, r0, rcut)
E = sum( exp.(1.0 .- r./r0) )
F = prod( (r./rcut .- 1.0) .* (r .< rcut) )
return sqrt1p(E) * F^2
end
function fnbody_d(r, r0, rcut)
E = sum( exp.(1.0 .- r./r0) )
F = prod( (r./rcut .- 1.0) .* (r .< rcut) )
∇f = (- sqrt1p_d(E) * F^2 / r0) .* (exp.(1.0 .- r./r0))
∇f += (sqrt1p(E) * 2.0 / rcut * F^2) .* (r./rcut .- 1.0 .- 1e-14).^(-1)
return ∇f
end
# Generate a MODEL N-Body function
function gen_fnbody(rcut, r0=1.0)
return r->fnbody(r, r0, rcut), r -> fnbody_d(r, r0, rcut)
end
println("Checking that `fnbody` is correct...")
fnbody_ad(rs, r0, rcut) = ForwardDiff.gradient( t -> fnbody(t, r0, rcut), rs )
for n = 1:5
r = rand(SVector{3, Float64})
@test fnbody_d(r, 1.0, 2.0) ≈ fnbody_ad(r, 1.0, 2.0)
end
# global assembly of n-body energies and forces
n_body(X, f, M, rcut, C, pbc = (false, false, false),
nlist = PairList(X, rcut, C, pbc, sorted = true)) =
n_body(f, M, nlist)
n_body(f, M, nlist::PairList) =
NeighbourLists.maptosites!(f, zeros(nsites(nlist)),
NeighbourLists.nbodies(M, nlist)) |> sum
grad_n_body(X, df, M, rcut, C, pbc = (false, false, false),
nlist = PairList(X, rcut, C, pbc, sorted = true)) =
grad_n_body(df, M, nlist)
grad_n_body(df, M, nlist::PairList) =
NeighbourLists.maptosites_d!(df, zeros(SVec{Float64}, nsites(nlist)),
NeighbourLists.nbodies(M, nlist))
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 1301 | using NeighbourLists
using NeighbourLists: SMat, SVec
using Test
using LinearAlgebra
include("nn_list.jl")
Ns = [3, 3, 4, 4, 5, 5]
@info("Testing PairList Correctness: ")
for N in Ns
C = SMat( diagm(0 => (2.0 .+ 0.2 * rand(3))) * N )
X = [ C' * rand(SVec) for i = 1:ceil(Int, abs(det(C))) ÷ 4 + 2 ]
pbc = SVec(rand(Bool, 3))
cutoff = 2.0
# compute a cell list
nlist = PairList(X, cutoff, C, pbc)
@show typeof(nlist)
# compute a NearestNeighbors list
i, j, r, R = nn_list(X, cutoff, C, pbc)
R = X[j] - X[i]
first = NeighbourLists.get_first(i, length(X))
NeighbourLists.sort_neigs!(j, (r, R), first)
println(@test (nlist.i == i) && (nlist.j == j))
# check that they are sorted
print("sorted: ");
println(@test all( issorted(j) for (_i, j, _R) in NeighbourLists.sites(nlist) ))
# check that the neighbourhoods produced by `neigs` are correct
pass_neigs = true
for (i, j, R) in NeighbourLists.sites(nlist)
j_, R_ = NeighbourLists.neigs(nlist, i)
if j != j_ || !(R ≈ R_)
pass_neigs = false
break
end
js, Rs, Ss = NeighbourLists.neigss(nlist, i)
if j != js || !(R ≈ Rs)
pass_neigs = false
break
end
end
print("neigs: "); println(@test pass_neigs)
end
println()
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 5431 |
using JuLIP, ASE, StaticArrays, NeighbourLists
using Test
X_Ti = vecs([0.0 5.19374 2.59687 3.8953 1.29843 6.49217 7.7906 12.9843 10.3875 11.6859 9.08904 14.2828; 0.0 0.918131 1.83626 -1.11022e-16 0.918131 1.83626 -2.22045e-16 0.918131 1.83626 0.0 0.918131 1.83626; 0.0 0.0 0.0 2.24895 2.24895 2.24895 0.0 0.0 0.0 2.24895 2.24895 2.24895])
C_Ti = (@SMatrix [15.5812 2.47895 0.0; 0.0 2.75439 0.0; 0.0 0.0 4.49791])
# -------------- MatSciPy NeighbourList Patch -------------
using PyCall
import NeighbourLists
matscipy_neighbours = pyimport("matscipy.neighbours")
function asenlist(at::Atoms, rcut)
pyat = ASEAtoms(at).po
return matscipy_neighbours[:neighbour_list]("ijdD", pyat, rcut)
end
function matscipy_nlist(at::Atoms{T}, rcut::T; recompute=false, kwargs...) where T <: AbstractFloat
i, j, r, R = asenlist(at, rcut)
i = copy(i) .+ 1
j = copy(j) .+ 1
r = copy(r)
R = collect(vecs(copy(R')))
first = NeighbourLists.get_first(i, length(at))
NeighbourLists.sort_neigs!(j, r, R, first)
return NeighbourLists.PairList(positions(at), rcut, i, j, r, R, first)
end
# --------------------------------------------------------
pynlist(at, cutoff) = matscipy_nlist(at, cutoff)
jnlist(at, cutoff) = PairList(positions(at), cutoff, cell(at), pbc(at))
function test_nlist_julip(at, cutoff)
nlist = jnlist(at, cutoff)
py_nlist = pynlist(at, cutoff)
return ( (nlist.i == py_nlist.i) &&
(nlist.j == py_nlist.j) &&
(nlist.r ≈ py_nlist.r) &&
(nlist.R ≈ py_nlist.R) )
end
test_configs = [
#
( "si, cubic, cluster, short",
set_pbc!(bulk(:Si, cubic=true) * 3, false),
1.1 * rnn(:Si) ),
#
( "si, cubic, cluster, med",
set_pbc!(bulk(:Si, cubic=true) * 3, false),
2.1 * rnn(:Si) ),
#
( "si, non-cubic cell, cluster, med",
set_pbc!(bulk(:Si) * 5, false),
2.1 * rnn(:Si) ),
#
( "si, non-cubic cell, pbc",
set_pbc!(bulk(:Si) * 5, false),
2.1 * rnn(:Si) ),
#
( "si, non-cubic cell, mixed bc",
set_pbc!(bulk(:Si) * 5, false),
2.1 * rnn(:Si) ),
#
("Ti, non-symmetric elongated cell, pbc",
set_pbc!( set_cell!( Atoms(:Ti, X_Ti), C_Ti ), true ),
1.45 * rnn(:Ti) ),
#
("Ti (hcp?) canonical cell, pbc",
set_pbc!( bulk(:Ti) * 4, true ),
2.3 * rnn(:Ti) ),
]
# ----------- A FEW MORE COMPLEX TESTS THAT FAILED AT SOME POINT ---------------
# [1] a left-handed cell orientation
# the test that failed during Cas' experiments
X = [ 0.00000000e+00 0.00000000e+00 0.00000000e+00
1.92333044e+00 6.63816518e-17 -1.36000000e+00
1.92333044e+00 1.92333044e+00 -2.72000000e+00
3.84666089e+00 1.92333044e+00 -4.08000000e+00 ]'
C = [ 3.84666089 0. 0.
0. 3.84666089 0.
0. 0. -5.44 ]'
# X = [ 0.00000000e+00 0.00000000e+00 0.00000000e+00
# 1.92333044e+00 6.63816518e-17 1.36000000e+00
# 1.92333044e+00 1.92333044e+00 2.72000000e+00
# 3.84666089e+00 1.92333044e+00 4.08000000e+00 ]'
# C = [ 3.84666089 0. 0.
# 0. 3.84666089 0.
# 0. 0. 5.44 ]'
at = Atoms(:Si, collect(vecs(X)))
set_cell!(at, C)
set_pbc!(at, (true,true,true))
atlge = at * (1,1,10)
rcut = 2.3*rnn(:Si)
push!(test_configs, ("Si left-oriented", at, rcut))
push!(test_configs, ("Si left-oriented, large", atlge, rcut))
test_nlist_julip(at, rcut)
test_nlist_julip(atlge, rcut)
# # [2] vacancy in bulk Si
#
# using PyCall
# at = bulk(:Si, cubic=true)
# @pyimport ase.lattice.cubic as cubic
# at2py = cubic.Diamond(symbol = "Si", latticeconstant = 5.43)
# at2py[:get_positions]()
# @test at2py[:get_cell]() ≈ cell(at1)
# @test mat(positions(at1))' ≈ at2py[:get_positions]()[:,[3,2,1]]
#
# at = bulk(:Si, cubic=true)
# at1 = at * 3
# X = mat(positions(at1))
# at1 = deleteat!(at1, 1)
# at2 = deleteat!(set_positions!(at * 3, X[[3,2,1],:]), 1)
# rcut = 2.3 * rnn(:Si)
# test_nlist_julip(at1, rcut)
# test_nlist_julip(at2, rcut)
# [3] Two Ti configuration that seems to be causing problems
C1 = @SMatrix [5.71757 -1.81834e-15 9.74255e-41; -2.85879 4.95156 4.93924e-25; 4.56368e-40 9.05692e-25 9.05629]
X1 = vecs([0.00533847 2.85879 -1.42939 1.42939 0.0 2.85879 -1.42939 1.42939 -1.43e-6 2.85878 -1.42939 1.42939 -1.43e-6 2.85878 -1.42939 1.42939;
-0.0 -0.0 2.47578 2.47578 0.0 -0.0 2.47578 2.47578 1.65052 1.65052 4.1263 4.1263 1.65052 1.65052 4.1263 4.1263;
0.00845581 0.0 0.0 0.0 4.52815 4.52815 4.52815 4.52815 2.26407 2.26407 2.26407 2.26407 6.79222 6.79222 6.79222 6.79222]) |> collect
C2 = @SMatrix [5.71757 0.0 0.0; -2.85879 4.95156 0.0; 0.0 0.0 9.05629]
X2 = vecs([0.00534021 2.85879 -1.42939 1.42939 0.0 2.85879 -1.42939 1.42939 0.0 2.85879 -1.4294 1.4294 0.0 2.85879 -1.4294 1.4294;
0.0 0.0 2.47578 2.47578 0.0 0.0 2.47578 2.47578 1.65052 1.65052 4.1263 4.1263 1.65052 1.65052 4.1263 4.1263;
0.00845858 0.0 0.0 0.0 4.52815 4.52815 4.52815 4.52815 2.26407 2.26407 2.26407 2.26407 6.79222 6.79222 6.79222 6.79222]) |> collect
at1 = set_cell!(Atoms(:Ti, X1), C1)
at2 = set_cell!(Atoms(:Ti, X2), C2)
rcut = 2.5 * rnn(:Ti)
test_nlist_julip(at1, rcut)
test_nlist_julip(at2, rcut)
# --------------- ACTUALLY RUNNING THE TESTS ------------------
println("JuLIP Configuration tests:")
for (i, (descr, at, cutoff)) in enumerate(test_configs)
print("TEST $i: $descr => ")
println(@test test_nlist_julip(at, cutoff))
end
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 2645 | using ForwardDiff, StaticArrays, NeighbourLists
using Test, LinearAlgebra, Printf
# uncomment for testing from editor/file
# include("test_aux.jl")
let rcut = 3.0
fn, fn_d = gen_fnbody(rcut)
function naive_n_body(X::Vector{SVec{T}}, f, M, rcut) where {T}
N = length(X)
E = 0.0
cnt = 0
start = CartesianIndex(ntuple(_->1, M))
stop = CartesianIndex(ntuple(_->N, M))
for j in CartesianIndices(start, stop)
s = zeros(T, (M*(M-1))÷2); n = 0
for a = 1:M-1, b = a+1:M
n += 1
s[n] = norm(X[j[a]] - X[j[b]])
end
if 0 < minimum(s) && maximum(s) <= rcut
# each of these terms occur factorial(M) times, i.e. for
# every permutation of the indices!
E += f(s) / factorial(M)
end
end
return E
end
vecs(V::Vector{T}) where {T} = reinterpret(SVector{3,T}, V, (length(V) ÷ 3,))
mat(V::Vector{SVector{3,T}}) where {T} = reinterpret(T, V, (3, length(V)))
# NOT NEEDED - WE DO FINITE-DIFFERENCE TESTS INSTEAD!
# function grad_naive_n_body(X, f, M, rcut)
# x = mat(X)[:]
# g = ForwardDiff.gradient( y -> naive_n_body(vecs(y), f, M, rcut), x)
# return vecs(g)
# end
println("--------------------------------------")
println(" Testing NBodyIterator")
println("--------------------------------------")
println("Check that the energy is consistent with a naive implementation")
MM = [2,2,3,3,3,4,4,5] # body orders
println(" N Nat => |Emr-Enaive|")
for M in MM
# create a not-too-large copper cell
X, C, _ = rand_config(2)
nat = length(X)
# assemble energy via neighbourlist and map-reduce
Emr = n_body(X, fn, M, rcut, C)
# assemble energy naively
Enaive = naive_n_body(X, fn, M, rcut)
println(" $M $nat => $(abs(Emr - Enaive))")
@test Emr ≈ Enaive
end
println("--------------------------------------")
println("Finite-difference tests")
MM = [2,3,4,5] # body orders
for M in MM
println(" [M = $M]")
X, C, pbc = rand_config(2)
if M > 3
pbc = [false, false, false]
end
@show pbc
nat = length(X)
dE = grad_n_body(X, fn_d, M, rcut, C, pbc)
dE = mat(dE)[:]
E = n_body(X, fn, M, rcut, C, pbc)
@printf(" h | error \n")
@printf("---------|----------- \n")
x = mat(X)[:]
errors = []
for p = 2:11
h = 0.1^p
dEh = copy(dE)
for n = 1:length(dE)
x[n] += h
dEh[n] = (n_body(vecs(x), fn, M, rcut, C, pbc) - E) / h
x[n] -= h
end
push!(errors, vecnorm(dE - dEh, Inf))
@printf(" %1.1e | %4.2e \n", h, errors[end])
end
@test minimum(errors) <= 1e-3 * maximum(errors)
end
end # let block
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | docs | 1118 | # NeighbourLists.jl
A Julia port and restructuring of the neighbourlist implemented in
[matscipy](https://github.com/libAtoms/matscipy) (with the authors' permission).
Single-threaded, the Julia version is faster than matscipy for small systems,
probably due to the overhead of dealing with Python, but on large systems it is
tends to be slower (up to around a factor 2 for 100,000 atoms).
The package is can be used stand-alone, with
[JuLIP.jl](https://github.com/libAtoms/JuLIP.jl), or with [AtomsBase.jl](https://github.com/JuliaMolSim/AtomsBase.jl).
## Getting Started
```Julia
Pkg.add("NeighbourLists")
using NeighbourLists
?PairList
```
### Usage via `AtomsBase.jl`
```julia
using ASEconvert, NeighbourLists, Unitful
cu = ase.build.bulk("Cu") * pytuple((4, 2, 3))
sys = pyconvert(AbstractSystem, cu)
nlist = PairList(sys, 3.5u"Å")
neigs_1, Rs_1 = neigs(nlist, 1)
```
### Usage via `JuLIP.jl`
```julia
using JuLIP
at = bulk(:Cu) * (4, 2, 3)
nlist = neighbourlist(at, 3.5)
neigs_1, Rs_1 = neigs(nlist, 1)
```
Please also look at the tests on how to use this package. Or just open an issue and
ask.
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 812 | module ForestBiometrics
const K = 0.005454154
const KMETRIC = 0.00007854
struct Metric end
const metric = Metric()
include("tree.jl")
include("stand.jl")
include("density.jl")
include("charts.jl")
include("height.jl")
include("expansion.jl")
export Tree
export Stand
export basal_area, basal_area!
export trees_per_area, trees_per_area!
export qmd, qmd!
export sdi
export gingrich_chart
export reineke_chart
export HeightModel
export estimate_height, estimate_height!
export curtis,
michailoff,
meyer,
micment,
micment2,
naslund,
naslund2,
naslund3,
naslund4,
power,
wyckoff
#3 parameter equations, mainly from LMFOR R package
#sorted alphabetically
export chapman,
gompertz,
hossfeldIV,
korf,
logistic,
monserud,
prodan,
ratkowsky,
sibbesen,
weibull
export /,
collapse, collapse!,
expand, expand!
end | ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 2708 | #Gingrich stocking chart calculated using the original upland oak parameters
#for more information see:http://oak.snr.missouri.edu/silviculture/tools/gingrich.html
using RecipesBase
## eqs for gingrich chart
amd_convert(qmd) = -0.259 + 0.973qmd
get_tpa(j, i, a) = (1*j*10)/(a[1]+a[2]*amd_convert(i)+a[3]*i^2)
function stklines(stk, dia, a)
tpa = get_tpa.(stk', dia, Ref(a))
ba = pi * (dia ./ 24).^2 .* tpa
tpa, ba
end
@userplot gingrich_chart
@recipe function f(dat::gingrich_chart)
#define parameters
a = [-0.0507, 0.1698, 0.0317]
b = [0.175, 0.205, 0.06]
#QMD lines
dia = [7, 8, 10, 12, 14, 16, 18, 20, 22]
#stocking percent horizontal lines
stk_percent= 20:10:110
# plot attributes
xlabel --> "Trees Per Acre"
ylabel --> "Basal Area (sq ft./acre)"
xticks --> 0:50:450
yticks --> 0:20:200
legend := false
primary := false
tpa, ba = stklines(stk_percent, dia, a)
# horizontal lines
@series begin
linecolor := :black
tpa, ba
end
# vertical lines
@series begin
linecolor := :black
tpa', ba'
end
# upper red line
@series begin
linecolor := :red
stklines([100], dia, a)
end
# lower red line
@series begin
linecolor := :red
stklines([100], dia, b)
end
# the point and the annotations
@series begin
primary := true
seriestype := :scatter
annotations := (100:38:442, 20:10:110, ["$i%" for i in 20:10:110])
x,y = dat.args
[x], [y]
end
end
function gingrich_chart(s::Stand)
gingrich_chart(s.trees_per_area,s.basal_area)
end
##Reineke SDI chart
@userplot reineke_chart
@recipe function f(dat::reineke_chart ; maxsdi=450)
diarng = 1:1:50
#tparng = [1,1200] #unusued for now, TODO: figure out how to autoscale plot?
maxline() = maxsdi ./ (diarng ./ 10.0).^1.605
# plot attributes
xlabel --> "Trees Per Acre"
ylabel --> "Quadratic Mean Diameter"
xticks --> [1,5,10,50,100,500,1000]
yticks --> [1,2,5,10,20]
xscale --> :log10
yscale --> :log10
legend := false
primary := false
formatter --> x -> string(convert(Int,round(x,digits=2)))
title --> "Maximum SDI of $maxsdi"
#max SDI line
@series begin
linecolor := :black
maxline(), diarng
end
#competition induced mortality SDI line
@series begin
linecolor := :orange
maxline() * 0.55, diarng
end
#crown closure SDI line
@series begin
linecolor := :red
maxline() * 0.35, diarng
end
# the point and the annotations
@series begin
primary := true
seriestype := :scatter
#annotations := (100:38:442, 20:10:110, ["$i%" for i in 20:10:110])
x,y = dat.args
[x], [y]
end
end
function reineke_chart(s::Stand)
reineke_chart(s.trees_per_area, s.qmd)
end
| ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 1184 | #Reineke SDI calculation
function sdi(s::Stand)
return s.trees_per_area * ((s.qmd / 10.0) ^ 1.605)
end
function qmd(s::Stand)
sum_d2 = 0.0
@simd for i in eachindex(s.treelist)
@inbounds sum_d2 += (s.treelist[i].diameter ^ 2 * s.treelist[i].expansion)
end
qmd = ismissing(s.trees_per_area) ? sqrt(sum_d2 / s.trees_per_area) : sqrt(sum_d2 / trees_per_area(s))
return qmd
end
function qmd!(s::Stand)
s.qmd = qmd(s)
end
function basal_area(s::Stand)
ba = 0.0
@simd for i in eachindex(s.treelist)
@inbounds ba += basal_area(s.treelist[i]) * s.treelist[i].expansion
end
return ba
end
function basal_area!(s::Stand)
s.basal_area = basal_area(s)
end
function basal_area!(s::Stand,m::Metric)
s.basal_area = basal_area(s, metric)
end
function basal_area(t::Tree)
return ((t.diameter ^ 2) * K)
end
function basal_area(t::Tree,m::Metric)
return ((t.diameter ^ 2) * KMETRIC)
end
function trees_per_area(s::Stand)
tpa = 0.0
@simd for i in eachindex(s.treelist)
@inbounds tpa += s.treelist[i].expansion
end
return tpa
end
function trees_per_area!(s::Stand)
s.trees_per_area = trees_per_area(s)
end
| ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 1751 | using IterTools
#functions to collapse multiple tree records into a single tree record with sum of expansions
Base.isless(lhs::Tree, rhs::Tree) = isless((lhs.diameter, lhs.height, lhs.species), (rhs.diameter, rhs.height, rhs.species))
function collapse(ta::Array{Tree,1})
!issorted(ta) && sort(ta)
#group by diameter,height,species- needs to be sorted
tgroups = groupby(s -> (s.diameter,s.height,s.species),sort(ta))
# Extract the diameter,height,species from the group members
trees = imap(s ->(s[1].diameter,s[1].height,s[1].species), tgroups)
# Compute the sum of expansion
expans = sum.(imap(x -> getfield.(x, :expansion), tgroups))
#combine to new Array{Tree}
return [Tree((t...,s)...) for (t,s) in zip(trees,expans)]
end
function collapse!(s::Stand)
s.treelist = collapse(s.treelist)
end
#functions to split a single Tree instance into many depending on its expansion
function expand(t::Tree; min_exp = 1.0)
ch = Channel() do c
cnt = t.expansion
while cnt > 0.0
new_exp = cnt % min_exp != 0.0 ? cnt % min_exp : min_exp
put!(c, Tree(t.diameter, t.height, t.species, new_exp))
cnt -= new_exp
end
end
collect(ch)
end
function expand(ta::Array{Tree,1}; min_exp = 1.0)
ch = Channel() do c
for t in ta
cnt = t.expansion
while cnt > 0.0
new_exp = cnt % min_exp != 0.0 ? cnt % min_exp : min_exp
put!(c, Tree(t.diameter, t.height, t.species, new_exp))
cnt -= new_exp
end
end
end
collect(ch)
end
function expand!(s::Stand)
s.treelist= expand(s.treelist)
end
function Base.:/(t1::Tree, denom::Number)
expand(t1, min_exp =(t1.expansion/denom))
end
| ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 1396 | struct HeightModel <: Function
formula::Function
b
end
##named equations
#2 parameter equations, mainly from the LMFOR R package
#sorted alphabetically
curtis=(x,b)->4.5+b[1]*((x/1+x)^b[2])
michailoff=(x,b)->4.5+b[1]*exp(-b[2]*x^(-1))
meyer=(x,b)->4.5+b[1]*(1-exp(-b[2]*x))
micment=(x,b)->4.5+b[1]*x/(b[2]+x)
micment2=(x,b)-> 4.5+x/(b[1]+b[2]*x)
naslund=(x,b)->4.5+(x^2/(b[1]+b[2]*x)^2)
naslund2=(x,b)-> 4.5+x^2/(b[1]+exp(b[2])*x)^2
naslund3=(x,b)-> 4.5+x^2/(exp(b[1]) + b[2]*x)^2
naslund4=(x,b)-> 4.5+x^2/(exp(b[1]) +exp(b[2])*x)^2
power=(x,b)-> 4.5+b[1]*x^b[2]
wyckoff=(x,b)->4.5+exp(b[1]+(b[2]/(x+1)))
#3 parameter equations, mainly from LMFOR R package
#sorted alphabetically
chapman=(x,b)->4.5+b[1]*(1-exp(-b[2]*x))^b[3]
gompertz=(x,b)->4.5+b[1]*exp(-b[2]*exp(-b[3]*x))
hossfeldIV=(x,b)->4.5+b[1]/(1+1/(b[2]*x^b[3]))
korf=(x,b)->4.5+b[1]*exp(-b[2]*x^-b[3])
logistic=(x,b)->4.5+b[1]/(1+b[2]*exp(-b[3]*x))
monserud=(x,b)->4.5+exp(b[1]+(b[2]*x*b[3]))
prodan=(x,b)->4.5+x^2/(b[1]+b[2]*x+b[3]*x^2)
ratkowsky=(x,b)->4.5+b[1]*exp(-b[2]/(x+b[3]))
sibbesen=(x,b)->4.5+b[1]*x^(b[2]*x^(-b[3]))
weibull=(x,b)->4.5+b[1]*(1-exp(-b[2]*x^b[3]))
function estimate_height(t::Tree,hd::HeightModel)
hd.formula(t.diameter, hd.b[t.species])
end
function estimate_height!(t::Tree,hd::HeightModel)
t.height = ismissing(t.height) ? hd.formula(t.diameter, hd.b[t.species]) : t.height
end
| ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 219 | mutable struct Stand
treelist::Array{Tree,1}
basal_area::Union{Real,Missing}
trees_per_area::Union{Real,Missing}
qmd::Union{Real,Missing}
end
Stand(tl::Array{Tree,1}) = Stand(tl,missing,missing,missing) | ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 113 | struct Tree
diameter::Real
height::Union{Real,Missing}
species::Union{AbstractString,Real}
expansion::Real
end
| ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 12976 |
abstract type Log end
mutable struct LogSegment<:Log
small_end_diam
large_end_diam
length
#shape #?
end
abstract type Shape end
function area(diameter)
a=K * diameter^2
return a
end
#Table 6.1 form Kershaw et al Forest Mensuration
#Equations to compute Cubic Volume of Important Solids
# Equation 6.1
#V=AₗL where Aₗ is the area of the base(large end).
mutable struct Cylinder
length
large_end_diam
end
function volume(solid::Cylinder)
V = area(solid.large_end_diam)*solid.length
return V
end
#Equation 6.2
#V= 1/2(AₗH)
#Paraboloid
mutable struct Paraboloid
length
large_end_diam
end
function volume(solid::Paraboloid)
V = 1/2(area(solid.large_end_diam))*solid.length
V
end
#Equation 6.3
#V=1/3(AₗL)
#Cone
#PREDICT CUBIC FOOT VOLUME FOR A CONIC SEGMENT SUCH AS A STEM TIP
mutable struct Cone
length
large_end_diam
end
function volume(solid::Cone)
V = 1/3(area(solid.large_end_diam))*solid.length
return V
end
#Equation 6.4
#V=1/4(AₗL)
#Neiloid
mutable struct Neiloid
length
large_end_diam
end
function volume(solid::Neiloid)
V = 1/4(area(solid.large_end_diam))*solid.length
return V
end
#Equation 6.5- Smalian's formula
#V=L/2(Aₗ + Aₛ) where L is the length and Aₛ is the area of the upper end (or small end)
#Paraboloid frustrum
#Equation 6.6 - Huber's formula
#V=AₘL where Aₘ is the area at middle point
#Paraboloid frustrum
#Equation 6.9 - Newton's formula
#V=L/6(Aₗ + 4*Aₘ + Aₛ)
#Neiloid,Paraboloid or Conic Frustrum
mutable struct ParaboloidFrustrum
length
large_end_diam
mid_point_diam #can set to nothing ( or missing in 0.7.0+?)
small_end_diam
end
function volume(solid::ParaboloidFrustrum; huber=false, newton = false)
if huber == true
V = area(solid.mid_point_diam) * solid.length
elseif newton == true
V = (solid.length/6) * (area(solid.large_end_diam) + 4*area(solid.mid_point_diam) + area(solid.small_end_diam))
else
V = area(solid.large_end_diam) + area(solid.small_end_diam) * (solid.length/2)
end
return V
end
#Equation 6.7
#V=L/3(Aₗ + sqrt(Aₗ*Aₛ) + Aₛ)
mutable struct ConeFrustrum
length
large_end_diam
mid_point_diam #can set to nothing
small_end_diam
end
function volume(solid::ConeFrustrum; newton=false)
if newton == true
V = (solid.length/6) * (area(solid.large_end_diam) + 4*area(solid.mid_point_diam) + area(solid.small_end_diam))
else
V = area(solid.large_end_diam) + area(solid.small_end_diam) * (solid.length/2)
end
return V
end
#Equation 6.8
#V=L/4(Aₗ + cbrt(Aₗ²*Aₛ) + cbrt(Aₗ*Aₛ²) + Aₛ)
mutable struct NeiloidFrustrum
length
large_end_diam
mid_point_diam #can set to nothing
small_end_diam
end
function volume(solid::NeiloidFrustrum; newton=false)
if newton == true
V = (solid.length/6) * (area(solid.large_end_diam) + 4*area(solid.mid_point_diam) + area(solid.small_end_diam))
else
V = (solid.length/4) *
(cbrt(area(solid.large_end_diam)^2 * area(solid.small_end_diam)) +
cbrt((K * solid.large_end_diam^2) * area(solid.small_end_diam)^2) +
area(solid.small_end_diam))
end
return V
end
macro LogSegment(a,b,c,d,shape)
return :($shape($a,$b,$c,$d))
end
#@LogSegment(24,12,nothing,8,ParaboloidFrustrum)
#Function to calculate the Scribner scale volume
#for more info see: http://oak.snr.missouri.edu/forestry_functions/scribnerbfvolume.php
## Scribner Decimal C table
using OffsetArrays
scribner_decimal_c=OffsetArray([[5 5 5 5 5 5 10 10 10 10 10 10 20 20 20 20 20];
[5 5 5 5 5 5 10 10 10 10 10 10 20 20 20 20 20];
[5 5 5 10 10 10 10 20 20 20 20 20 30 30 30 30 30];
[5 10 10 10 10 10 20 20 20 20 20 20 30 30 30 30 30];
[10 10 10 20 20 20 30 30 30 30 30 30 40 40 40 40 40];
[10 10 20 20 30 30 30 30 30 40 40 50 60 60 60 60 70];
[10 20 20 20 30 30 40 40 40 50 50 60 70 70 80 80 80];
[20 20 30 30 40 40 50 50 60 60 70 70 80 80 90 100 100];
[20 30 40 40 50 50 60 70 70 80 80 90 100 100 110 120 120];
[30 40 40 50 60 60 70 80 90 90 100 110 110 120 130 140 140];
[40 40 50 60 70 80 90 100 110 120 120 130 140 150 160 170 180];
[40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200];
[50 60 70 80 90 100 120 130 140 150 160 170 180 200 210 220 230];
[50 70 80 90 110 120 130 150 160 170 190 200 210 230 240 260 270];
[60 80 90 100 120 130 150 160 180 190 210 220 240 250 270 280 300];
[70 90 110 120 140 160 170 190 210 230 240 260 280 300 310 330 350];
[80 100 120 130 150 170 190 210 230 250 270 280 300 320 340 360 380];
[80 100 130 150 170 190 210 230 250 270 290 310 330 350 380 400 420];
[90 120 140 160 190 210 230 260 280 310 330 350 380 400 420 440 470];
[100 130 150 180 210 230 250 280 300 330 350 380 400 430 450 480 500];
[110 140 170 200 230 260 290 310 340 370 400 430 460 490 520 540 570];
[120 160 190 220 250 280 310 340 370 410 440 470 500 530 560 590 620];
[140 170 210 240 270 310 340 380 410 440 480 510 550 580 620 650 680];
[150 180 220 250 290 330 360 400 440 470 510 540 580 620 650 690 730];
[150 190 230 270 310 350 380 420 460 490 530 570 610 650 680 720 760];
[160 210 250 290 330 370 410 450 490 530 570 620 660 700 740 780 820];
[180 220 270 310 360 400 440 490 530 580 620 670 710 750 800 840 890];
[180 230 280 320 370 410 460 510 550 600 640 690 740 780 830 880 920];
[200 240 290 340 390 440 490 540 590 640 690 730 780 830 880 930 980];
[200 250 300 350 400 450 500 550 600 650 700 750 800 850 900 950 1000];
[220 270 330 380 440 490 550 600 660 710 770 820 880 930 980 1040 1090];
[230 290 350 400 460 520 580 630 690 750 810 860 920 980 1040 1100 1150];
[260 320 390 450 510 580 640 710 770 840 900 960 1030 1090 1160 1220 1290];
[270 330 400 470 540 600 670 730 800 870 930 1000 1070 1130 1200 1260 1330];
[280 350 420 490 560 630 700 770 840 910 980 1050 1120 1190 1260 1330 1400];
[300 380 450 530 600 680 750 830 900 980 1050 1130 1200 1280 1350 1420 1500];
[320 390 480 560 640 720 790 870 950 1030 1110 1190 1270 1350 1430 1510 1590];
[330 420 500 590 670 760 840 920 1010 1090 1170 1260 1340 1430 1510 1600 1680];
[350 430 520 610 700 790 870 960 1050 1130 1220 1310 1400 1480 1570 1660 1740];
[370 460 560 650 740 830 930 1020 1110 1200 1290 1390 1480 1570 1660 1760 1850];
[380 470 570 660 760 850 950 1040 1140 1230 1330 1430 1520 1610 1710 1800 1900];
[390 490 590 690 790 890 990 1090 1190 1290 1390 1490 1590 1690 1780 1880 1980];
[410 520 620 720 830 930 1040 1140 1240 1340 1450 1550 1660 1760 1860 1960 2070];
[430 540 650 760 860 970 1080 1190 1300 1400 1510 1620 1730 1840 1940 2050 2160];
[450 560 670 790 900 1010 1120 1240 1350 1460 1570 1680 1800 1910 2020 2140 2250];
[470 580 700 820 940 1050 1170 1290 1400 1520 1640 1750 1870 1990 2110 2220 2340]],5:50,4:20)
function scribner_volume(small_end_diam,length;decimal_C=false)
if decimal_C==false
log_bf=((0.79*small_end_diam^2)-(2*small_end_diam)-4)*(length/16)
return log_bf
elseif decimal_C==true
# ROUND DIB TO NEAREST INTEGER, ROUND LOGFEET DOWN TO NEXT INTEGER
scale_dib=ceil(Int64,small_end_diam)
log_feet=floor(Int64,length)
println(scale_dib,log_feet)
if scale_dib > 5 && scale_dib < 50 && log_feet > 4 && log_feet < 20
#STANDARD SIZE LOG, USE LOOKUP TABLE
log_bf=scribner_decimal_c[scale_dib,log_feet]*1.0
else
#OVERSIZE LOG, I.E., DIB>50 AND/OR LOGLENGTH>20, USE FORMULA VERSION
log_bf=scribner_volume(scale_dib,log_feet,decimal_C=false)
return log_bf
end
end
end
#Function to calculate the Doyle scale volume
#for more info see: http://oak.snr.missouri.edu/forestry_functions/doylebfvolume.php
function doyle_volume(small_end_diam,length)
volume=((small_end_diam-4.0)/4.0)^2*length
return volume
end
#Function to calculate the International scale volume
#for more info see: http://oak.snr.missouri.edu/forestry_functions/int14bfvolume.php
function international_volume(small_end_diam,length)
if length == 4
volume = 0.22*small_end_diam^2-0.71*small_end_diam
elseif length == 8
volume = 0.44*small_end_diam^2-1.20*small_end_diam-0.30
elseif length == 12
volume = 0.66*small_end_diam^2 - 1.47 * small_end_diam - 0.79
elseif length == 16
volume = 0.88 * small_end_diam^2 - 1.52 * small_end_diam - 1.36
elseif length == 20
volume = 1.10 * small_end_diam^2 - 1.35 * small_end_diam - 1.90
elseif length == 24
volume = 1.10 * small_end_diam^2 - 1.35 * small_end_diam - 1.90 + 0.22 * small_end_diam^2 - 0.71 * small_end_diam
elseif length == 28
volume = 1.10 * small_end_diam^2 - 1.35 * small_end_diam - 1.90 + 0.44 * small_end_diam^2 - 1.20 * small_end_diam - 0.30
elseif length == 32
volume = 1.10 * small_end_diam^2 - 1.35 * small_end_diam - 1.90 + 0.66 * small_end_diam^2 - 1.47 * small_end_diam - 0.79
elseif length == 36
volume = 1.10 * small_end_diam^2 - 1.35 * small_end_diam - 1.90 + 0.88 * small_end_diam^2 - 1.52 * small_end_diam - 1.36
elseif length == 40
volume = (1.10 * small_end_diam^2 - 1.35 * small_end_diam - 1.90 )*2
return volume
end
end
####
#I don't know what a NVEL/Volume Equations API should look like?
#Various attempts below...
#introduce abstract super types
abstract type VolumeEquation end
abstract type MerchSpecs end
mutable struct Sawtimber<:MerchSpecs
std_length
trim
min_length
max_length
min_dib
stumpht
end
s=Sawtimber(16.0,0.5,8.0,20.0,6.0,1.0)
mutable struct Fiber<:MerchSpecs
min_length
std_length
min_dib
min_dbh
end
#Fiber(8.0,20.0,2.6,4.6)
mutable struct Pulp<:MerchSpecs
min_live_dib #pulp sawlogs
min_dead_dib #pulp sawlogs
end
#Pulp(6.0,6.0)
####work in progress
#bark thickness separate?
function dib_to_dob() end
#PREDICT DIAMETER INSIDE BARK AT ANY LOGICAL HEIGHT
function get_dib(species,dbh,tht,ht)
end
#PREDICT THE HEIGHT AT WHICH A SPECIFIED DIAMETER INSIDE BARK OCCURS
function get_height_to_dib(species,dbh,tht,dib)
end
#TO BREAK A SAWTIMBER BOLE INTO LOGS AND POPULATE THE SEGMENT LENGTH
function stem_buck(m::Sawtimber)
#DETERMINE LENGTH OF BOLE TO DIVIDE INTO LOGS
bole_length=52.9815
#bole_length=ht2sawdib-stumpht
#DETERMINE THE NUMBER OF FULL STANDARD LENGTH LOGS POSSIBLE
n_logs=floor(Int64,bole_length/(m.std_length+m.trim))
#POPULATE SEGLEN WITH STANDARD LOG LENGTHS TO START
seg_length=zeros(n_logs)
for i in 1:n_logs
seg_length[i]=m.std_length+m.trim
end
#ADJUST LOG LENGTHS ACCORDING TO BUCKING RULE AND AMOUNT OF SAWTIMBER EXCESS
saw_excess=bole_length-n_logs*(m.std_length+m.trim)
isaw_excess=floor(Int64,saw_excess/2.0)*2
if n_logs == floor(Int64,n_logs/2.0)*2
even=true
else
even=false
end
if isaw_excess >=2.0 && isaw_excess<6.0 #EXTRA SAWEXCESS IS 2' OR 4'
if even
if isaw_excess == 2.0
seg_length[n_logs-1]=seg_length[n_logs-1]+2.0 # Add 2' to last log
else
seg_length[n_logs-1]=seg_length[n_logs-1]+2.0 # Add 2' to top 2 logs
seg_length[n_logs]=seg_length[n_logs]+2.0
end
else
seg_length[n_logs]=seg_length[n_logs] + isaw_excess #Add 2' or 4' to top log
end
elseif isaw_excess>=6.0
if (saw_excess-m.trim) >= m.min_length
n_logs=n_logs+1 # Create whole new log
push!(seg_length,isaw_excess+m.trim)
#seg_length[n_logs]=isaw_excess+m.trim
else
n_logs=n_logs+1 # Create new log, split top
saw_excess=saw_excess+seg_length[n_logs-1]
seg_length[n_logs]=floor(Int64,saw_excess-(2.0*m.trim)/4.0)*2.0+m.trim
seg_length[n_logs-1]=floor(saw_excess-seg_length[n_logs]-m.trim/2.0)*2.0+m.trim
end
end
#FAILSAFE TO ENSURE LOGS ARE OF SUFFICIENT LENGTH (B/T MIN SCALE LEN AND MAXLEN)
sawtop=m.stumpht
for i in 1:n_logs
if seg_length[i]<(m.min_length+m.trim)
seg_length[i]=0
elseif seg_length[i] > (m.max_length+m.trim)
seg_length[i]=(m.max_length+m.trim)
end
#DETERMINE SAWTOP
sawtop=seg_length[i]
return seg_length
end
end
stem_buck(s)
function stem_buck(m::Fiber)
fiber_bole=30
#DETERMINE THE NUMBER OF FULL STANDARD LENGTH FIBER LOGS POSSIBLE
n_logs_fiber=floor(Int64,bole_length/m.std_length)
#POPULATE SEGLEN WITH STANDARD LOG LENGTHS TO START
for i in n_logs+1:n_logs+n_logs_fiber
seg_length[i]=m.std_length
end
#SEE IF ADDITIONAL FIBER ABOVE STANDARD LENGTH LOGS CONSTITUTES A FIBER LOG
fiber_excess=fiber_bole-(n_logs_fiber*m.std_length)
if fiber_excess>m.min_length
n_logs_fiber=n_logs_fiber+1
seg_length[n_logs+n_logs_fiber] = fiber_excess
end
end
#TO ASSIGN PRODUCT CLASSES TO EACH LOG SEGMENT IN A SINGLE TREE
function prod_classify()
end
#TO MERCHANDIZE AN INDIVIDUAL TREE WITH PREVIOUSLY BUCKED LOGS AND
#PRODUCTS ASSIGNED TO INDIVIDUAL LOGS INTO PIECES, AND DEVELOP THE NECESSARY PIECE INFORMATION (DIB,LEN,GRS,NET,NPCS)
function merchandize_tree() end
| ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 966 | using ForestBiometrics
using DelimitedFiles
using Test
using Plots
datapath = joinpath(@__DIR__, "data")
data = readdlm(joinpath(datapath,"StandExam_data.csv"),',',header=true)
tl = Tree[]
for i in eachrow(data[1])
push!(tl,Tree(i[7], i[8], i[6], i[9]))
end
stand = Stand(tl)
@test isapprox(basal_area(stand), 90.58823529)
basal_area!(stand)
@test isapprox(stand.basal_area, 90.58823529)
@test isapprox(trees_per_area(stand), 147.8593658)
trees_per_area!(stand)
@test isapprox(stand.trees_per_area, 147.8593658)
qmd!(stand)
@test isapprox(stand.qmd, 10.5985824)
@test isapprox(sdi(stand),162.3198113)
@test typeof(gingrich_chart(400, 80)) == Plots.Plot{Plots.GRBackend}
@test typeof(gingrich_chart(stand)) == Plots.Plot{Plots.GRBackend}
@test typeof(reineke_chart(500, 8)) == Plots.Plot{Plots.GRBackend}
@test typeof(reineke_chart(stand)) == Plots.Plot{Plots.GRBackend}
@test typeof(reineke_chart(500,8;maxsdi=600)) == Plots.Plot{Plots.GRBackend} | ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 812 | using ForestBiometrics
tl1 = [
Tree(10.0,65,"WO",1.0),
Tree(10.0,65,"WO",1.0),
Tree(10.0,65,"WO",1.0),
Tree(10.0,65,"WO",1.0)]
tl2 = [
Tree(10.0,65,"WO",1.0),
Tree(10.0,60,"WO",1.0),
Tree(10.0,65,"WO",1.0),
Tree(10.0,65,"WO",1.0)]
tl3 = [
Tree(10.0,65,"WO",1.0),
Tree(10.0,60,"WO",1.0),
Tree(10.0,60,"WO",1.0),
Tree(10.0,65,"WO",1.0),
Tree(10.0,70,"WO",1.0)]
@test length(collapse(tl1)) == 1
@test length(collapse(tl2)) == 2
@test length(collapse(tl3)) == 3
t1 = Tree(12.0,65,"WO",4.25)
t2 = Tree(12.0,65,"WO",10)
tl4 = [Tree(12.0,60,"WO",5),
Tree(10.0,65,"WO",5),
Tree(12.0,60,"WO",1),
Tree(10.0,65,"WO",1)]
@test length(expand(t1)) == 5
@test length(expand(t1, min_exp = 2)) == 3
@test length(expand(tl4)) == 12
@test length(t2 / 3.0) == 3
s1 = Stand(tl4)
expand!(s1)
@test length(s1.treelist) == 12
| ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 2325 | using ForestBiometrics
using DelimitedFiles
datapath = joinpath(@__DIR__, "data")
data=readdlm(joinpath(datapath,"IEsubset_Data_CSV.csv"),',',header=true)
tl = Tree[]
for i in eachrow(data[1])
push!(tl,Tree(i[10], missing, i[9], i[7]))
end
# 2 parameter Wyckoff coefficients. Default values for IE variant of FVS
FVS_IE=Dict{String,Array{Float64}}(
"WP"=>[5.19988 -9.26718],
"WL"=>[4.97407 -6.78347],
"DF"=>[4.81519 -7.29306],
"GF"=>[5.00233 -8.19365],
"WH"=>[4.97331 -8.19730],
"RC"=>[4.89564 -8.39057],
"LP"=>[4.62171 -5.32481],
"ES"=>[4.9219 -8.30289],
"AF"=>[4.76537 -7.61062],
"PP"=>[4.9288 -9.32795],
"MH"=>[4.77951 -9.31743],
"WB"=>[4.97407 -6.78347],
"LM"=>[4.19200 -5.16510],
"LL"=>[4.76537 -7.61062],
"PI"=>[3.20000 -5.00000],
"RM"=>[3.20000 -5.00000],
"PY"=>[4.19200 -5.16510],
"AS"=>[4.44210 -6.54050],
"CO"=>[4.44210 -6.54050],
"MM"=>[4.44210 -6.54050],
"PB"=>[4.44210 -6.54050],
"OH"=>[4.44210 -6.54050],
"OS"=>[4.77951 -9.31743] )
#using Wyckoff=(x,b)->4.5+exp(b[1]+(b[2]/(x+1)))
wyk = HeightModel(wyckoff,FVS_IE)
wyckoff_out= [estimate_height(i,wyk) for i in tl]
wyckoff_test=[
100.3704728
61.35043145
11.31948442
11.99184897
71.56773647
75.48849752
4.662859967
38.1318738
86.57926895
89.09331657
83.29702964
82.02991682
59.36359424
92.24130804
80.79924609
95.99589413
89.52703552
73.04225223
95.88342114
59.38502782
4.662859967
4.662859967
97.69440543
96.76176795
106.4984871
75.82474076
100.3704728
105.4603241
92.79168745
78.84582366
79.6182448
77.22661356
92.79168745
86.208065]
@test isapprox(wyckoff_out, wyckoff_test)
#test custom function
p2=HeightModel((x,b)->4.5+x^b[1]^b[2],FVS_IE)
user_eq_out = [estimate_height(i,p2) for i in tl]
user_eq_test=[
5.50000110437066
5.50000077727861
5.50000025616043
5.50000027222188
5.50000085504705
5.50000088557174
5.49997579696978
5.50000059480051
5.50000097615539
5.50000099792679
5.50000094851992
5.50002825335774
5.50002185801763
5.50003169790446
5.50000092800344
5.50003314012292
5.50000100174185
5.50000086646161
5.50003309510479
5.50000076242647
5.49997579696978
5.49997579696978
5.50003383536612
5.50003344996446
5.50000117082406
5.50000088821741
5.50000110437066
5.50000115899896
5.50003190202163
5.50002728005371
5.50002751279364
5.50002679851972
5.50003190202163
5.50002959423972]
@test isapprox(user_eq_out, user_eq_test)
#end test 2
| ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | code | 81 | include("density_test.jl")
include("height_test.jl")
include("expansion_test.jl") | ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 0.3.0 | a6ba6fb67518ba83b5dcc2f24b2e89d558e2a8cb | docs | 4148 | 
[](https://coveralls.io/github/Crghilardi/ForestBiometrics.jl?branch=master)
# ForestBiometrics.jl
A package for various forest mensuration and biometrics functions in Julia
ForestBiometrics.jl is a package for working with forest measurements data and growth and yield modeling.
This package was inspired by its R counterpart, the [lmfor package](https://CRAN.R-project.org/package=lmfor) with the addition of equations from the western US. For more info on lmfor, please see http://cs.uef.fi/~lamehtat/rcodes.htm
It is my hope that the package not only ports existing functionality from other languages, but also showcases the abilities of Julia as a programming language and how concepts like multiple dispatch and metaprogramming can be used to solve domain-specific problems.
## Installation
`] add https://github.com/Crghilardi/ForestBiometrics.jl`
If you are interested in this package and would like to contribute, feel free to submit an issue or pull request.
## Design
`ForestBiometrics` exports a `Tree` type and a `Stand` type for dispatch. The package was designed with fully expanded treelists in mind and makes no effort to accomodate plot data and plot compilation.
A `Tree` is a minimalistic container of fields that are absolutely needed for basic measurements. Future work will focus on the ability to add arbitrary fields as needed.
```julia
struct Tree
diameter::Real
height::Union{Real,Missing}
species::Union{AbstractString,Real}
expansion::Real
end
```
Likewise a `Stand` is mainly an Array of `Tree` objects with some very minimal summary info fields
```julia
mutable struct Stand
treelist::Array{Tree,1}
basal_area::Union{Real,Missing}
trees_per_area::Union{Real,Missing}
qmd::Union{Real,Missing}
end
```
## Example Usage
```julia
using ForestBiometrics
using DelimitedFiles
using Plots
#read csv with tree data (upland HW stand from northeast USA)
datapath = joinpath(dirname(pathof(ForestBiometrics)), "..", "test/StandExam_data.csv")
data = readdlm(datapath,',',header=true)
tl = Tree[]
#read data and create array of Tree
for i in eachrow(data[1])
push!(tl,Tree(i[7], i[8], i[6], i[9]))
end
#create a Stand from the array of Tree
stand = Stand(tl)
```
If just given a treelist, stand basal area, trees per area and qmd are intialized as missing. Once we have `Tree`s and a `Stand` created we can calculate a number of summary information including:
```julia
#basal area of a single tree or the entire stand
basal_area(tl[1])
basal_area(stand)
#if the diameters are in cm
basal_area(tl[1],metric)
trees_per_area(stand)
qmd(stand)
sdi(stand)
```
We can update the Stand object summary field by using the bang version (!) of the functions
```julia
basal_area!(stand)
trees_per_area!(stand)
qmd!(stand)
```
The package also exports a `HeightModel` that generalizes the process of estimating height from diameter using arbitrary model forms and parameters
```julia
#create Tree with diameter but no height
t1 = Tree(10.0,missing,"DF",1)
#make dictionary of species specific parameters
FVS_IE=Dict{String,Array{Float64}}(
"WP"=>[5.19988 -9.26718],
"WL"=>[4.97407 -6.78347],
"DF"=>[4.81519 -7.29306],
"GF"=>[5.00233 -8.19365])
#create HeightModel object using an named model form (exported by package) and the parameter dict above.
#See src/height.jl for full list of existing #model forms.
wyk = HeightModel(wyckoff,FVS_IE)
estimate_height(t1, wyk)
```
## Example outputs
Gingrich stocking guides
`gingrich_chart(stand)`
<img src="https://raw.githubusercontent.com/Crghilardi/ForestBiometrics.jl/master/examples/Gingrich_chart_example.png" align="middle" />
SDI chart with lines at 100%, 55% and 35% max SDI
`reineke_chart(stand)`
`#or can define a max sdi explicity reineke_chart(stand; maxsdi = 250)`
<img src="https://raw.githubusercontent.com/Crghilardi/ForestBiometrics.jl/master/examples/SDI_chart_example.png" align="middle" />
| ForestBiometrics | https://github.com/Crghilardi/ForestBiometrics.jl.git |
|
[
"MIT"
] | 1.0.0 | fa3f5f18fc4f7867ed9c92a06b38aac0311bbf95 | code | 4330 | module SimpleBoids
struct BoidState
positions::Vector{Vector{Float64}}
orientations::Vector{Vector{Float64}}
end
function norm(v1,v2)
return sqrt(sum(x->x^2,v1-v2))
end
function ruleOrientations!(orientations::Vector{Vector{Float64}},positions::Vector{Vector{Float64}},paramMaxRad::Float64,paramVelWeight::Float64)
for i in eachindex(orientations)
temp=[0.,0.]
for j in eachindex(orientations)
if i==j
continue
end
if norm(positions[i],positions[j])>paramMaxRad
continue
end
temp.+=orientations[j]
end
if temp[1]^2+temp[2]^2==0.
continue
end
orientations[i][1]+=(temp[1]/sqrt(temp[1]^2+temp[2]^2)-orientations[i][1])*paramVelWeight
orientations[i][2]+=(temp[2]/sqrt(temp[1]^2+temp[2]^2)-orientations[i][2])*paramVelWeight
orientations[i]/=sqrt(orientations[i][1]^2+orientations[i][2]^2)
end
end
function rulePosition!(orientations::Vector{Vector{Float64}},positions::Vector{Vector{Float64}},paramMaxRad::Float64,paramMinRad::Float64,paramPosWeight::Float64,paramRepWeight::Float64)
for i in eachindex(orientations)
temp=[0.,0.]
N=0
temprepulse=[0.,0.]
Nr=0
for j in eachindex(positions)
if i==j
continue
end
if norm(positions[i],positions[j])>paramMaxRad
continue
end
if norm(positions[i],positions[j])<paramMinRad
temprepulse.+=positions[j]
Nr+=1
continue
end
temp.+=positions[j]
N+=1
end
if temp[1]^2+temp[2]^2!=0.
temp/=N
temp.-=positions[i]
orientations[i][1]+=temp[1]/sqrt(temp[1]^2+temp[2]^2)*paramPosWeight
orientations[i][2]+=temp[2]/sqrt(temp[1]^2+temp[2]^2)*paramPosWeight
orientations[i]/=sqrt(orientations[i][1]^2+orientations[i][2]^2)
end
if temprepulse[1]^2+temprepulse[2]^2!=0.
temprepulse/=Nr
temprepulse.-=positions[i]
orientations[i][1]-=temprepulse[1]/sqrt(temprepulse[1]^2+temprepulse[2]^2)*paramRepWeight
orientations[i][2]-=temprepulse[2]/sqrt(temprepulse[1]^2+temprepulse[2]^2)*paramRepWeight
orientations[i]/=sqrt(orientations[i][1]^2+orientations[i][2]^2)
end
end
end
function updateBoidState(state::BoidState,size::Float64,vel::Float64,paramMaxRad::Float64,paramMinRad::Float64,paramPosWeight::Float64,paramRepWeight::Float64,paramVelWeight::Float64)
newstate=deepcopy(state)
ruleOrientations!(newstate.orientations,newstate.positions,paramMaxRad,paramVelWeight)
rulePosition!(newstate.orientations,newstate.positions,paramMaxRad,paramMinRad,paramPosWeight,paramRepWeight)
for i in eachindex(newstate.positions)
newstate.positions[i].+=newstate.orientations[i]*vel
if newstate.positions[i][1]>size
newstate.positions[i][1]=2*size-newstate.positions[i][1]
newstate.orientations[i][1]*=-1
end
if newstate.positions[i][1]<0
newstate.positions[i][1]*=-1
newstate.orientations[i][1]*=-1
end
if newstate.positions[i][2]>size
newstate.positions[i][2]=2*size-newstate.positions[i][2]
newstate.orientations[i][2]*=-1
end
if newstate.positions[i][2]<0
newstate.positions[i][2]*=-1
newstate.orientations[i][2]*=-1
end
end
return newstate
end
function randomOrientation()
th=rand(Float64)*2*π
return [cos(th),sin(th)]
end
function initializeRandomBoidState(numboids::Int64,size::Float64)
return BoidState([[rand(Float64)*size,rand(Float64)*size] for i in 1:numboids],[randomOrientation() for i in 1:numboids])
end
function runBoids(numboids::Int64,steps::Int64,size::Float64,vel::Float64,paramMaxRad::Float64,paramMinRad::Float64,paramPosWeight::Float64,paramRepWeight::Float64,paramVelWeight::Float64)
out=[initializeRandomBoidState(numboids,size)]
for i in 1:steps
push!(out,updateBoidState(out[i],size,vel,paramMaxRad,paramMinRad,paramPosWeight,paramRepWeight,paramVelWeight))
end
return out
end
end
| SimpleBoids | https://github.com/jeanfdp/SimpleBoids.jl.git |
|
[
"MIT"
] | 1.0.0 | fa3f5f18fc4f7867ed9c92a06b38aac0311bbf95 | code | 114 | using SimpleBoids
using Test
@testset "SimpleBoids.jl" begin
@test SimpleBoids.norm([1.,0.],[1.,0.])==0.
end
| SimpleBoids | https://github.com/jeanfdp/SimpleBoids.jl.git |
|
[
"MIT"
] | 1.0.0 | fa3f5f18fc4f7867ed9c92a06b38aac0311bbf95 | docs | 319 | # SimpleBoids
A simple, unoptimized implementation of the Boids algorithim. Visualization has to be done seperately.
[](https://github.com/jeanfdp/SimpleBoids.jl/actions/workflows/CI.yml?query=branch%3Amaster)
| SimpleBoids | https://github.com/jeanfdp/SimpleBoids.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | code | 845 | push!(LOAD_PATH, "../src/")
using Documenter, MahjongTiles
makedocs(
sitename="MahjongTiles.jl Documentation",
format=Documenter.HTML(
prettyurls=get(ENV, "CI", nothing) == "true"
),
modules=[MahjongTiles],
pages=[
"Home" => "index.md",
"Mahjong Rules" => "rules_resources.md",
"Anatomy of a Game" => [
"Building the Wall" => "building_wall.md",
"Dealing the Hands" => "dealing.md",
"Rounds of Gameplay" => "gameplay.md",
"Scoring Hands" => "scoring.md",
],
"API Reference" => [
"Tiles" => "tiles.md",
"Decks/TilePiles" => "decks.md",
"Hands" => "hands.md",
],
],
)
deploydocs(
repo = "github.com/tmthyln/MahjongTiles.jl.git",
devbranch = "main",
devurl="latest",
)
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | code | 328 | module MahjongTiles
export
character, bamboo, circle, wind, dragon, flower, season
# in addition, all the tiles are programmatically exported in tiles.jl
# define the suits and all the tiles
include("tiles.jl")
# from the tiles, create decks of tiles for games
include("decks.jl")
# check "hands"
include("hands.jl")
end
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | code | 4149 | using Random
"""
A pile of tiles.
An abstraction for a collection of Mahjong tiles, similar to a deque.
Some properties:
- ordered and unsorted
- size only strictly decreases once created
"""
struct TilePile
tiles::Vector{SuitedTile}
end
@doc """
TilePile(tiles)
TilePile(name)
Create a particular predefined/standard `TilePile` given the `name`, or
create the `TilePile` from a specific list of tiles.
## Supported Names
### `:standard`
4 of each numbered tile from the 3 suits, plus 4 of each wind, 4 of each dragon, and the 8 flowers/seasons
"""
function TilePile(type::Symbol)
if type == :standard
tiles = [
SuitedTile(suit, i)
for suit in all_suits
for i in 1:max_number(suit)
for _ in 1:typical_duplication(suit)
]
else
@warn "Not a recognized type of Mahjong game (don't know how to create a pile for it)"
tiles = []
end
return TilePile(tiles)
end
Base.:(==)(this::TilePile, that::TilePile) = this.tiles == that.tiles
Base.hash(tp::TilePile, h::UInt) = hash(tp.tiles, h)
Base.length(tp::TilePile) = length(tp.tiles)
Base.first(tp::TilePile) = first(tp.tiles)
Base.first(tp::TilePile, n::Integer) = first(tp.tiles, n)
Base.last(tp::TilePile) = last(tp.tiles)
Base.last(tp::TilePile, n::Integer) = last(tp.tiles, n)
Base.iterate(tilepile::TilePile) = iterate(tilepile.tiles)
Base.iterate(tilepile::TilePile, state) = iterate(tilepile.tiles, state)
"""
popfirst!(tilepile)
Remove the "first" tile from the tile pile.
Removing from this end is intended to be used for flower/four-of-a-kind replacement
(this is to improve average performance).
"""
Base.popfirst!(tp::TilePile) = popfirst!(tp.tiles)
"""
popfirst!(tilepile, num_tiles)
Remove the "first" `num_tiles` tiles from the tile pile as an array.
Removing from this end is intended to be used for flower/four-of-a-kind replacement
(this is to improve average performance).
"""
function Base.popfirst!(tp::TilePile, n::Integer)
n < 0 && throw("cannot pop fewer than 0 tiles")
return splice!(tp.tiles, 1:min(n, lastindex(tp.tiles)))
end
"""
pop!(tilepile)
Remove a tile from the end of the tile pile.
Removing from this end is used for the usual pickup of tiles from the deck
(not for flower/four-of-a-kind replacement).
"""
Base.pop!(tp::TilePile) = pop!(tp.tiles)
"""
pop!(tilepile, num_tiles)
Remove `num_tiles` tiles from the end of the tile pile as an array.
Removing from this end is used for the usual pickup of tiles from the deck
(not for flower/four-of-a-kind replacement).
"""
function Base.pop!(tp::TilePile, n::Integer)
n < 0 && throw("cannot pop fewer than 0 tiles")
return splice!(tp.tiles, max(1, lastindex(tp.tiles) - n + 1):lastindex(tp.tiles))
end
Random.shuffle!(tp::TilePile) = (shuffle!(tp.tiles); tp)
Random.shuffle!(rng, tp::TilePile) = (shuffle!(rng, tp.tiles); tp)
Base.circshift(tp::TilePile, shift) = TilePile(circshift(tp.tiles, shift))
function Base.circshift!(tp::TilePile, shift)
shift %= length(tp.tiles)
shift == 0 && return tp
shift < 0 && (shift += length(tp.tiles))
@assert shift > 0 && shift < length(tp.tiles)
@inbounds begin
temp = tp.tiles[end-shift+1:end]
tp.tiles[shift+1:end] = tp.tiles[begin:end-shift]
tp.tiles[begin:shift] = temp
end
return tp
end
function Base.show(io::IO, mime::MIME"text/plain", tilepile::TilePile)
for tile in tilepile.tiles
show(io, mime, tile)
end
end
function Base.show(io::IO, tilepile::TilePile)
print(io, "TilePile([")
for (index, tile) in enumerate(tilepile)
print(io, tile)
index != length(tilepile) && print(io, ", ")
end
print(io, "])")
end
function deal_tiles(tp::TilePile; quadruple_rounds=3, single_rounds=1)
player_hands = [SuitedTile[] for _ in 1:4]
for _ in 1:quadruple_rounds, player in 1:4
append!(player_hands[player], pop!(tp, 4))
end
for _ in 1:single_rounds, player in 1:4
push!(player_hands[player], pop!(tp))
end
push!(first(player_hands), pop!(tp))
return Hand.(player_hands)
end
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | code | 3896 | using DataStructures
"""
Represents the tiles in a single player's hand.
"""
struct Hand
tiles::Vector{SuitedTile}
hidden::Vector{SuitedTile}
exposed::Vector{SuitedTile}
@doc """
Hand()
Hand(tiles)
Create an empty hand, or one that starts off with the `tiles` given (all hidden).
## Example
```jldoctest
julia> using MahjongTiles: character, wind, bamboo, Hand
julia> Hand([character(1), character(2), wind(:north), bamboo(5)])
🀃🀇🀈🀔
```
"""
function Hand(initial_tiles::AbstractVector{<: Tile} = [])
hidden_tiles = sort!(initial_tiles)
return new(hidden_tiles, hidden_tiles, SuitedTile[])
end
end
@doc """
push_hidden!(hand, tiles...)
Base.push!(hand, tiles...)
Add a tile or `tiles` to the hidden part of the hand.
"""
function push_hidden!(hand::Hand, tile...)
push!(hand.hidden, tile...)
push!(hand.tiles, tile...)
sort!(hand.hidden, alg=InsertionSort())
sort!(hand.tiles, alg=InsertionSort())
return hand
end
Base.push!(hand::Hand, tile...) = push_hidden!(hand, tile)
@doc """
push_exposed!(hand, tiles...)
Add a tile or `tiles` to the open/exposed part of the hand.
"""
function push_exposed!(hand::Hand, tile...)
push!(hand.exposed, tile...)
push!(hand.tiles, tile...)
sort!(hand.exposed, alg=InsertionSort())
sort!(hand.tiles, alg=InsertionSort())
return hand
end
@doc """
expose!(hand, tiles...)
Expose/make open the tiles from the hand.
"""
function expose!(hand::Hand, tiles...)
end
Base.first(hand::Hand) = first(hand.tiles)
Base.first(hand::Hand, num::Integer) = first(hand.tiles, num)
Base.iterate(hand::Hand) = iterate(hand.tiles)
Base.iterate(hand::Hand, state) = iterate(hand.tiles, state)
function Base.show(io::IO, mime::MIME"text/plain", hand::Hand)
for tile in hand.tiles
show(io, mime, tile)
end
end
@doc """
is_pure(hand)
Determine whether the hand is pure (清).
A hand is considered pure if there are no winds or dragons.
## Example
```jldoctest
julia> using MahjongTiles: wind, character, dragon, bamboo, circle, Hand, is_pure
julia> is_pure(Hand([wind(:east), character(3)]))
false
julia> is_pure(Hand([character(3), dragon(:green)]))
false
julia> is_pure(Hand([bamboo(8), character(3), circle(1)]))
true
```
"""
function is_pure(hand::Hand)
return all(!is_suit(tile, Wind) && !is_suit(tile, Dragon) for tile in hand)
end
@doc """
is_single_suit(hand)
Determine whether the hand consists of a single suit (一色),
which can include non-suits like winds or flowers.
To determine if the hand is only exactly a single suit,
excluding winds, dragons, and flowers/seasons,
combine this function with `is_pure`.
## Example
```jldoctest
julia> using MahjongTiles: wind, flower, character, circle, bamboo, Hand, is_single_suit
julia> is_single_suit(Hand([character(1), character(4), character(8), flower(3)]))
true
julia> is_single_suit(Hand([character(5), circle(5), bamboo(5)]))
false
julia> is_single_suit(Hand([circle(1), circle(7), wind(:north), wind(:east)]))
true
```
"""
function is_single_suit(hand::Hand)
only_suit = suit(first(hand))
return all(suit(tile) == only_suit || suit(tile) in (Wind, Dragon, Flower, Season) for tile in hand)
end
@doc """
has_dragon_triple(hand)
Determine whether the hand has a triple of any one of the three dragon tiles.
## Example
```jldoctest
julia> using MahjongTiles: dragon, wind, bamboo, Hand, has_dragon_triple
julia> has_dragon_triple(Hand([dragon(:red), dragon(:red), dragon(:red), bamboo(2), wind(:east)]))
true
julia> has_dragon_triple(Hand([dragon(:red), dragon(:red), dragon(:green), dragon(:white)]))
false
```
"""
function has_dragon_triple(hand::Hand)
counts = counter(hand.tiles)
return counts[dragon(:red)] >= 3 || counts[dragon(:green)] >= 3 || counts[dragon(:white)] >= 3
end
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | code | 7523 |
#=================================== SUITS ===================================#
"""
The root abstract type for suit types.
This is also used to represent "pseudo-suit" types, like the winds, dragons, flowers, etc.
"""
abstract type Suit end
abstract type Character <: Suit end
abstract type Bamboo <: Suit end
abstract type Circle <: Suit end
abstract type Wind <: Suit end
abstract type Dragon <: Suit end
abstract type Flower <: Suit end
abstract type Season <: Suit end
@doc """
is_sequential(suit_type)
Check whether this suit type (or pseudo-suit) is a sequential one (for the purposes of hands).
For example, typically the characters suit is sequential, but the winds suit is not.
"""
is_sequential(::Type{<:Suit}) = false
is_sequential(s::Suit) = is_sequential(typeof(s))
is_sequential(::Type{Character}) = true
is_sequential(::Type{Bamboo}) = true
is_sequential(::Type{Circle}) = true
@doc """
max_number(suit_type)
The maximum ("index") number for this suit type (or pseudo-suit).
For example, the traditional suited tiles (characters, bamboo, circle)
have a max of 9 (starting at 1),
whereas the winds pseudo-suit has a max of 4.
"""
max_number(::Type{<:Suit}) = 1
max_number(s::Suit) = max_number(typeof(s))
max_number(::Type{Character}) = 9
max_number(::Type{Bamboo}) = 9
max_number(::Type{Circle}) = 9
max_number(::Type{Wind}) = 4
max_number(::Type{Dragon}) = 3
max_number(::Type{Flower}) = 4
max_number(::Type{Season}) = 4
@doc """
first_char(suit_type)
The character for the first tile in this suit (in Unicode).
## Examples
```julia-repl
julia> first_char(Character)
🀇
```
"""
first_char(::Type{<:Suit}) = throw("not implemented")
first_char(::Type{Character}) = '🀇'
first_char(::Type{Bamboo}) = '🀐'
first_char(::Type{Circle}) = '🀙'
first_char(::Type{Wind}) = '🀀'
first_char(::Type{Dragon}) = '🀄'
first_char(::Type{Flower}) = '🀢'
first_char(::Type{Season}) = '🀦'
@doc """
typical_duplication(suit_type)
The number of duplicate tiles usually used for this suit type
(this is usually 1 or 4).
"""
typical_duplication(::Type{<:Suit}) = 1
typical_duplication(::Type{Character}) = 4
typical_duplication(::Type{Bamboo}) = 4
typical_duplication(::Type{Circle}) = 4
typical_duplication(::Type{Wind}) = 4
typical_duplication(::Type{Dragon}) = 4
Base.isless(x::Type{<:Suit}, y::Type{<:Suit}) = first_char(x) < first_char(y)
#=================================== TILES ===================================#
"""
The root tile type for Mahjong tiles.
However, the contract for what the Tile interface entails is not well-defined,
so most functions dispatch on the `SuitedTile` and not on `Tile`.
"""
abstract type Tile end
"""
A tile with a suit (or pseudo-suit).
"""
struct SuitedTile{SuitType <: Suit} <: Tile
number::Int8
"""
SuitedTile(suit_type, number=1)
Create a tile of a particular suit `suit_type` and `number`
(use the default `1` for a "suit" that has only 1 tile).
"""
function SuitedTile(SuitType::Type{<:Suit}, number::Integer = 1)
number < 1 && throw("number must be positive")
number > max_number(SuitType) && throw("number is greater than the max allowed for this suit")
return new{SuitType}(number)
end
end
suit(::SuitedTile{T}) where T = T
number(tile::SuitedTile) = tile.number
is_suit(::SuitedTile{T}, suit_type::Type{<:Suit}) where T = T == suit_type
is_number(tile::SuitedTile, num::Integer) = tile.number == num
function Base.:(==)(x::SuitedTile{T}, y::SuitedTile{S}) where {T, S}
return T == S && x.number == y.number
end
Base.hash(tile::SuitedTile{SuitType}, h::UInt) where SuitType = hash(SuitType, hash(tile.number, h))
function Base.isless(left::SuitedTile{LeftSuit}, right::SuitedTile{RightSuit}) where {LeftSuit, RightSuit}
if LeftSuit != RightSuit
return isless(LeftSuit, RightSuit)
else
return left.number < right.number
end
end
function Base.show(io::IO, ::MIME"text/plain", tile::SuitedTile{T}) where T
print(io, first_char(T) + tile.number - 1)
end
function Base.show(io::IO, tile::SuitedTile{T}) where T
show(io::IO, MIME"text/plain"(), tile)
end
#============================== TILE CONSTANTS ===============================#
"""
List of the "normal" suits: character, bamboo, circles.
```@repl
using MahjongTiles
MahjongTiles.suits
```
"""
const suits = [Character, Bamboo, Circle]
"""
List of all suits, including "pseudo-suits" like the winds and flowers.
"""
const all_suits = [suits..., Wind, Dragon, Flower, Season]
for suit in [Character, Bamboo, Circle, Wind, Dragon, Flower, Season], i in 1:max_number(suit)
tile_name = Symbol(first_char(suit) + i - 1)
@eval MahjongTiles, const $tile_name = SuitedTile($suit, $i)
@eval MahjongTiles, export $tile_name
end
@doc """
character(index)
Creates a tile of the character suit with the particular number.
## Example
```jldoctest
julia> character(5)
🀋
```
"""
character(index::Integer) = SuitedTile(Character, index)
@doc """
bamboo(index)
Creates a tile of the bamboo suit with the particular number.
## Example
```jldoctest
julia> bamboo(2)
🀑
```
"""
bamboo(index::Integer) = SuitedTile(Bamboo, index)
@doc """
circle(index)
Creates a tile of the circle suit with the particular number.
## Example
```jldoctest
julia> circle(9)
🀡
```
"""
circle(index::Integer) = SuitedTile(Circle, index)
@doc """
wind(index)
wind(direction)
Creates a wind tile.
If an integer is used,
the standard Chinese ordering of the cardinal directions is used
(i.e. `1` -> east, `2` -> south, `3` -> west, `4` -> north).
Otherwise, symbols can also be used for the names of the directions
(e.g. `:east`, `:north`).
## Example
```jldoctest
julia> wind(:north)
🀃
julia> wind(2)
🀁
```
"""
wind(index::Integer) = SuitedTile(Wind, index)
function wind(name::Symbol)
if name === :east
return SuitedTile(Wind, 1)
elseif name === :south
return SuitedTile(Wind, 2)
elseif name === :west
return SuitedTile(Wind, 3)
elseif name === :north
return SuitedTile(Wind, 4)
else
throw("unrecognized cardinal direction")
end
end
@doc """
dragon(index)
dragon(name)
Creates a wind tile.
If an integer is used,
the standard ordering is used
(i.e. `1` -> red dragon, `2` -> green dragon, `3` -> white dragon).
Otherwise, symbols can also be used for their names/colors
(e.g. `:red`, `:green`).
## Example
```jldoctest
julia> dragon(:red)
🀄
julia> dragon(2)
🀅
```
"""
dragon(index::Integer) = SuitedTile(Dragon, index)
function dragon(name::Symbol)
if name === :red
return SuitedTile(Dragon, 1)
elseif name === :green
return SuitedTile(Dragon, 2)
elseif name === :white
return SuitedTile(Dragon, 3)
else
throw("unrecognized dragon color")
end
end
@doc """
flower(index)
Creates a flower tile with the particular number.
!!! note
While this function (and the `season` function) don't allow using the flower (season) names,
they may have this functionality in the future.
## Example
```jldoctest
julia> flower(2)
🀣
```
"""
flower(index::Integer) = SuitedTile(Flower, index)
@doc """
season(index)
Creates a season (flower) tile with the particular number.
!!! note
While this function (and the `flower` function) don't allow using the season (flower) names,
they may have this functionality in the future.
## Example
```jldoctest
julia> season(4)
🀩
```
"""
season(index::Integer) = SuitedTile(Season, index)
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | code | 128 | using MahjongTiles
using Test
@testset "unit tests" begin
include("tile_identities.jl")
include("tilepiles.jl")
end
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | code | 433 | using Test
using MahjongTiles
@testset "tile function aliases" begin
@test all([🀇, 🀈, 🀉, 🀊, 🀋, 🀌, 🀍, 🀎, 🀏] .== character.(1:9))
@test all([🀐, 🀑, 🀒, 🀓, 🀔, 🀕, 🀖, 🀗, 🀘] .== bamboo.(1:9))
@test all([🀙, 🀚, 🀛, 🀜, 🀝, 🀞, 🀟, 🀠, 🀡] .== circle.(1:9))
@test all([🀀, 🀁, 🀂, 🀃] .== wind.(1:4))
@test all([🀄, 🀅, 🀆] .== dragon.(1:3))
@test all([🀢, 🀣, 🀤, 🀥] .== flower.(1:4))
@test all([🀦, 🀧, 🀨, 🀩] .== season.(1:4))
end
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | code | 2677 | using Test
using MahjongTiles
using MahjongTiles: TilePile
@testset "equality" begin
@test TilePile(:standard) !== TilePile(:standard)
@test TilePile(:standard) == TilePile(:standard)
end
@testset "circular shifting" begin
create_tilepile() = TilePile([character(4), wind(2), circle(7), bamboo(9), dragon(2), flower(1)])
# test non-mutating circshift
@test circshift(create_tilepile(), 0) == create_tilepile()
@test circshift(create_tilepile(), 1) == TilePile([flower(1), character(4), wind(2), circle(7), bamboo(9), dragon(2)])
@test circshift(create_tilepile(), -1) == TilePile([wind(2), circle(7), bamboo(9), dragon(2), flower(1), character(4)])
@test circshift(create_tilepile(), 7) == TilePile([flower(1), character(4), wind(2), circle(7), bamboo(9), dragon(2)])
@test circshift(create_tilepile(), -7) == TilePile([wind(2), circle(7), bamboo(9), dragon(2), flower(1), character(4)])
@test circshift(create_tilepile(), 2) == TilePile([dragon(2), flower(1), character(4), wind(2), circle(7), bamboo(9)])
@test circshift(create_tilepile(), -2) == TilePile([circle(7), bamboo(9), dragon(2), flower(1), character(4), wind(2)])
@test circshift(create_tilepile(), 8) == TilePile([dragon(2), flower(1), character(4), wind(2), circle(7), bamboo(9)])
@test circshift(create_tilepile(), -8) == TilePile([circle(7), bamboo(9), dragon(2), flower(1), character(4), wind(2)])
# test mutating circshift
@test circshift!(create_tilepile(), 0) == create_tilepile()
@test circshift!(create_tilepile(), 1) == TilePile([flower(1), character(4), wind(2), circle(7), bamboo(9), dragon(2)])
@test circshift!(create_tilepile(), -1) == TilePile([wind(2), circle(7), bamboo(9), dragon(2), flower(1), character(4)])
@test circshift!(create_tilepile(), 7) == TilePile([flower(1), character(4), wind(2), circle(7), bamboo(9), dragon(2)])
@test circshift!(create_tilepile(), -7) == TilePile([wind(2), circle(7), bamboo(9), dragon(2), flower(1), character(4)])
@test circshift!(create_tilepile(), 2) == TilePile([dragon(2), flower(1), character(4), wind(2), circle(7), bamboo(9)])
@test circshift!(create_tilepile(), -2) == TilePile([circle(7), bamboo(9), dragon(2), flower(1), character(4), wind(2)])
@test circshift!(create_tilepile(), 8) == TilePile([dragon(2), flower(1), character(4), wind(2), circle(7), bamboo(9)])
@test circshift!(create_tilepile(), -8) == TilePile([circle(7), bamboo(9), dragon(2), flower(1), character(4), wind(2)])
# test that the tilepile itself is returned as the modified tilepile
tilepile = create_tilepile()
@test circshift!(tilepile, 3) == tilepile
end
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 2533 | # MahjongTiles.jl
[](https://github.com/tmthyln/MahjongTiles.jl/actions/workflows/docs.yml)
[](https://github.com/tmthyln/MahjongTiles.jl/actions/workflows/tests.yml)
[](https://github.com/tmthyln/MahjongTiles.jl/actions/workflows/nightly.yml)
Basic utilities for representing and working with Mahjong tiles, hands, and decks
(works in a similar way to
[PlayingCards.jl](https://juliahub.com/ui/Packages/PlayingCards/I6MLG/0.3.0)).
To get started, you can install from the Julia General repository in the usual way:
```julia
(env) pkg> add MahjongTiles
```
See the [full documentation](https://tmthyln.github.io/MahjongTiles.jl/latest/) for more details.
## Components
### Tiles
Each of the 42 unique standard tiles is represented as a object.
To access an individual tile, you can reference the "symbolic" constants
that are exported by the package:
```julia
julia> using MahjongTiles
julia> 🀛
🀛
julia> 🀥
🀥
```
However, it's hard to type these out without already knowing how to type them,
so there are a few convenience functions that can create specific tiles:
```julia
julia> using MahjongTiles: character, season, wind, dragon
julia> character(3)
🀉
julia> season(4)
🀩
julia> wind(2)
🀁
julia> dragon(1) == dragon(:red)
🀄
```
### Decks
Depending on the specific variety of Mahjong being played,
a deck is composed of 4 of each tile from the 3 standard "suits",
plus 4 of each of the winds, 4 of each of the dragons, and
sometimes the 8 flowers/seasons.
In the code, these are called `TilePile`s.
The easiest way to create one is to just use the standard constructor:
```julia
using MahjongTiles: TilePile
deck = TilePile(:standard)
```
### Hands
Again, depending on the specific variety being played,
a hand is usually composed of 13+1 or 16+1 tiles from a game deck.
There are also functions to test if hands contain certain arrangements;
these are used to count points
(for gambling, sure, but also for bragging rights).
## Related
There's also a similar project [MahjongEnvironment](https://github.com/coldinjection/MahjongEnvironment);
however, this package differs in
- more broad scope beyond just reinforcement learning
- registered
- supporting different variants of Mahjong in a more general way
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 1528 | # Building the Wall
The first step before the game can be played is that the four "walls" need to be built.
Physically, this involves shuffling the deck and stacking the tiles into four rows of a certain length and 2 tiles tall.
In code, this is broken up into a few steps:
## Determine the size of the deck
Depending on the variation, some of the "suits" are excluded.
In the standard variation, there are the following tile quantities:
| Suit | Examples | Quantity of Each Tile |
| ---------------:|:-------- |:--------------------- |
| Character | 🀉🀍🀏 | 4 per number |
| Bamboo | 🀐🀑🀗 | 4 per number |
| Circle | 🀙🀝🀟 | 4 per number |
| Winds | 🀀🀁🀂🀃 | 4 of each |
| Dragons | 🀄🀅🀆 | 4 of each |
| Flowers/Seasons | 🀢🀤🀦🀩 | 1 of each |
## Create and shuffle the deck
For the standard deck, there's a single argument constructor that automatically creates a deck with the correct number of tiles.
```@example deck
using MahjongTiles: TilePile
deck = TilePile(:standard)
```
Then, we shuffle the deck.
```@example deck
using Random
shuffle!(deck)
```
In a physical game of Mahjong,
dice are rolled to determine where to start distributing tiles.
However, this is mostly an anti-cheat measure
and doesn't meaningfully affect the game itself.
We could roll some dice and then use `circshift!` to adjust the deck,
but that's mostly for show (e.g. in a GUI implementation).
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 1195 | # Dealing the Hands
Having [built the wall](building_wall.md),
next we need to deal tiles to each player.
## Distributing tiles to player hands
Starting from the **east** seat,
sets of 4 tiles are distributed to each seat,
and then single tiles are distributed.
The **east** seat gets one extra tile to start
(effectively, they're just starting their turn early).
Depending on the style of Mahjong,
there are different numbers of sets of tiles distributed.
For example, in 13-tile variants,
all seats get 3 sets of 4 tiles and then 1 set of 1 tile.
```@example deal
using MahjongTiles: TilePile, deal_tiles
using Random
deck = TilePile(:standard)
shuffle!(deck)
hands = deal_tiles(deck, quadruple_rounds=3, single_rounds=1) # default
```
In 16-tile variants,
all seats get 4 sets of 4 tiles and no sets of 1 tile.
```@example deal
deck = TilePile(:standard)
shuffle!(deck)
hands16 = deal_tiles(deck, quadruple_rounds=4, single_rounds=0)
```
Note how the first hand (the one for the **east** hand) has an extra tile to start.
## Replacing flowers
When playing with flowers,
flowers for all players are replaced at the beginning of each game
before the first tile is thrown out.
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 1175 | # Decks (TilePiles)
Tiles can also be collected into an abstract idea of a "pile of tiles."
For example, this is intended to be used to represent the four walls of tiles in the game.
Decks (called `TilePile`s in code) have several properties:
- Ordered (but not sorted)
- Size strictly decreases
- Removal occurs strictly at the two ends of the pile
In this way, a `TilePile` is like a deque that can only be removed from once it's been created.
```@docs
MahjongTiles.TilePile
MahjongTiles.TilePile(::Symbol)
```
`TilePile`s support a limited set of operations that reflect allowable actions in the game,
e.g. shuffling tiles, `circshift` for determining where the ends of the pile are.
## Removing from a `TilePile`
```@docs
Base.pop!(::MahjongTiles.TilePile)
Base.pop!(::MahjongTiles.TilePile, ::Integer)
Base.popfirst!(::MahjongTiles.TilePile)
Base.popfirst!(::MahjongTiles.TilePile, ::Integer)
```
## Other Operations
These are other functions supported for the `TilePile` type,
which behave similar to the way they do in Julia Base.
- `length`
- `first`
- `last`
- `circshift`
- `circshift!` (this has a slightly different signature than in Base)
- `shuffle!`
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 63 | # Playing the Game
At this point, the game starts properly.
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 1243 |
# Hands
A `Hand` represents the set of tiles that a particular player has
(varies in number, depending on the variety of Mahjong being played).
```@docs
MahjongTiles.Hand
```
## Supported Operations
```@docs
MahjongTiles.push_hidden!
MahjongTiles.push_exposed!
MahjongTiles.expose!
```
`Hand`s also support the following operations that behave similarly to how they do in Julia Base:
- iteration
- `first`
## Scoring Functions
`Hand`s can be checked for whether they have certain configurations/arrangements of tiles
(e.g. contain no winds, contain only tiles that are completely green, contain all threes-of-a-kind).
There are roughly 2 kinds:
- those that describe a property of the entire hand (e.g. all sets must include the number 5), and
- those that describe a smaller arrangement of tiles that must be present somewhere in the hand (e.g. two threes-in-a-row of different suits, the other tiles are not considered).
The former are generally prefixed with `is_` and the latter with `has_`.
In a way, these are not "scoring" functions,
as they don't assign a score for each configuration,
but only whether the configuration applies.
```@docs
MahjongTiles.is_pure
MahjongTiles.is_single_suit
MahjongTiles.has_dragon_triple
```
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 1399 | # MahjongTiles.jl Documentation
This is a library package for working with Mahjong games and its primitives,
such as tiles, decks, and hands.
It's designed to be useful for both simulation or gameplay.
## Getting Started
To install, you can use the Julia package manager:
```julia-repl
(env) pkg> add MahjongTiles
```
The "Anatomy of a Game" walks through the phases of a typical Mahjong game
(using a particular set of rules)
and how it would be implemented using this package.
For specific structs and function calls available,
see the "API" section of the docs.
!!! note
When tiles are printed (to the console) or shown in the docs,
usually (although depending on your setup),
the tiles will be very small,
which means they can sometimes be difficult to see.
In addition, because of the weird position of the "red dragon" tile (🀄),
it often appears more emoji-like in many fonts,
making it stand out and messing up fixed-width spacing.
## Related
There's also a similar project [MahjongEnvironment.jl](https://github.com/coldinjection/MahjongEnvironment);
however, this package differs in
- having a broader scope than just reinforcement learning
- being registered
- supporting different variants of Mahjong in a more general way
- is not intended to provide the full Mahjong game environment, just a set of useful primitives for potentially doing so
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 851 |
# Mahjong Rules & Other Resources
This is a list of resources for different variants of the game.
Of course, even within a variant, there are variations.
Feel free to submit a PR with other useful references!
## Cantonese/Hong Kong (most common variant)
- [Hong Kong Mahjong, the authentic Chinese mahjong game](https://web.archive.org/web/20160323155914/http://ninedragons.com/mahjong/scoring.html)
## Taiwanese
- [Taiwan 16-Tile Mahjong Rules (archive link only)](https://web.archive.org/web/20160422004911/http://www.rag.com/~steve/mahjong/index.html)
- [Taiwanese Rules](https://mahjongtime.com/mahjong-taiwanese-rules.html)
- [Essence of Taiwanese Mahjong – Introduction](https://www.jiyuulife.net/taiwanese-mahjong-introduction/)
## American
- [National Mah Jongg League | The Game](https://www.nationalmahjonggleague.org/game.aspx)
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 594 | # Scoring Hands
Now that someone has won (or claimed to have won),
we need to "score" two parts:
- determine whether they've actually won; this is just checking that their hand "works"
- if counting points, determine the number of points they have and whether they've reached the win threshold of points
It turns out, this is not *that* straightforward,
because we need to search through all possible ways to arrange the tiles in a valid way.
In general, we also want to combine this with the scoring
so that we find the arrangement with the highest point score,
and rules can be complex.
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.1.0 | 10068b287d714f4b968dfbd2aa5809282f38ab19 | docs | 2639 | # Tile API
Tiles are sorted in "suits" or "pseudo-suits."
Generally speaking, the usual "suited tiles" belong to the character, bamboo, or circle suits.
The other tiles are not really in suits,
but they can be treated programmatically as if they were.
The normal suits are considered *sequential* suits;
the other suits are considered *non-sequential* suits.
```@setup mahjong
using MahjongTiles
```
## Suits
!!! info
This is an internal implementation detail and is subject to change in future versions.
This is the current way that suits are implemented. All suit types inherit from a single abstract type
```@docs
MahjongTiles.Suit
```
which has the following interface:
| Function | Default | Description |
| -------------------------------: | :-----: | :------------------------------------------------------------------------- |
| `is_sequential(suit_type)` | `false` | Whether this suit can be scored sequentially |
| `max_number(suit_type)` | `1` | The max number that this suit has |
| `first_char(suit_type)` | - | The Unicode character associated with the number 1 (required) |
| `typical_duplication(suit_type)` | `1` | The typical number of tiles included in a deck with each tile in this suit |
Note that the `first_char` method is required for printing,
and if a new suit has `max_number(suit_type) > 1`,
it is assumed that they are consecutive in Unicode.
The way that these are currently implemented,
each suit type is another `abstract type` that inherits from `Suit`.
The required methods operate on the *type* and not instances of the type.
```@docs
MahjongTiles.is_sequential
MahjongTiles.max_number
MahjongTiles.first_char
MahjongTiles.typical_duplication
```
There are also 2 additional constants that list all of the implemented suits.
```@docs
MahjongTiles.suits
MahjongTiles.all_suits
```
## Tiles
```@docs
MahjongTiles.Tile
MahjongTiles.SuitedTile
```
### Accessing Specific Tiles
All of the standard tiles are exported as constants from the MahjongTiles module,
so they can be directly accessed (e.g. for comparisons).
```@repl mahjong
🀘
🀛 < 🀞
```
However, this means that it is difficult to type these without already knowing how to type them.
To mitigate this, there are helper functions to create tiles of each suit.
```@docs
MahjongTiles.character
MahjongTiles.bamboo
MahjongTiles.circle
MahjongTiles.wind
MahjongTiles.dragon
MahjongTiles.flower
MahjongTiles.season
```
| MahjongTiles | https://github.com/tmthyln/MahjongTiles.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 18583 | #==
= DomainColoringToy
=
= Copyright (c) 2023 Evert Provoost. See LICENSE.
=
= Provided functionality is partially inspired by
=
= Wegert, Elias. Visual Complex Functions:
= An Introduction with Phase Portraits.
= Birkhäuser Basel, 2012.
=#
module DomainColoringToy
using Reexport
@reexport using GLMakie
import DomainColoring as DC
"""
DomainColoringToy.shadedplot(
f :: "Complex -> Complex",
shader :: "Complex -> Color",
limits = (-1, 1, -1, 1),
pixels = (480, 480);
kwargs...
)
Takes a complex function and a shader and produces a GLMakie plot with
auto updating.
# Arguments
- **`f`** is the complex function to plot.
- **`shader`** is the shader function to compute a pixel.
- **`limits`** are the initial limits of the plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
- **`pixels`** is the size of the output in pixels, respectively, the
number of pixels along the real and imaginary axis, taking the same
for both if only one number is provided. If either is `:auto`, the
viewport resolution is used.
Keyword arguments are passed to GLMakie.
"""
function shadedplot(
f,
shader,
limits = (-1, 1, -1, 1),
pixels = (480, 480);
kwargs...
)
# sanitize input
pixels == :auto && (pixels = (:auto, :auto))
length(pixels) == 1 && (pixels = (pixels, pixels))
limits = DC._expandlimits(limits)
# parse Makie options
defaults = Attributes(
interpolate = true,
axis = (autolimitaspect = 1,)
)
attr = merge(Attributes(; kwargs...), defaults)
# setup observables to be used by update
img = Observable(
# tiny render to catch errors and setup type
DC.renderimage(f, shader, limits, (2, 2))
)
xl = Observable([limits[1], limits[2]])
yl = Observable([limits[3], limits[4]])
# setup plot
# transpose as x and y are swapped in images
# reverse as y is reversed in images
plt = heatmap(xl, lift(reverse, yl), lift(adjoint, img);
attr...)
# set default limits
xlims!(plt.axis, limits[1], limits[2])
ylims!(plt.axis, limits[3], limits[4])
# update loop
function update(lims, res)
# set render limits to viewport
axs = (lims.origin[1], lims.origin[1] + lims.widths[1],
lims.origin[2], lims.origin[2] + lims.widths[2])
xl[] = [axs[1], axs[2]]
yl[] = [axs[3], axs[4]]
# get resolution if needed
px = map((p, r) -> p == :auto ? ceil(Int, 1.1r) : p,
pixels, tuple(res...))
# render new image reusing buffer if possible
if size(img.val) != px
img.val = DC.renderimage(f, shader, axs, px)
else
DC.renderimage!(img.val, f, shader, axs)
end
notify(img)
end
# initial render
lims = plt.axis.finallimits
res = plt.axis.scene.camera.resolution
update(lims[], res[])
# observe updates
onany(update, lims, res)
return plt
end
"""
DomainColoringToy.@shadedplot(
basename,
shaderkwargs,
shader
)
Macro emitting an implementation of **`fname`** in a similar fashion to
the other plotting routines in this library, see for instance
[`domaincolor`](@ref).
**`shaderkwargs`** is a named tuple setting keyword arguments used in
the expression **`shader`**. The result of **`shader`** should be a
function `Complex -> Color` and is used to shade the resulting plot.
See the source for examples.
"""
macro shadedplot(fname, shaderkwargs, shader)
# interpret shaderkwargs as keyword arguments
skwargs = [Expr(:kw, p...) for
p in pairs(__module__.eval(shaderkwargs))]
@eval __module__ begin
function $fname(
f :: Function,
limits = (-1, 1, -1, 1);
pixels = (480, 480),
$(skwargs...),
kwargs...
)
DomainColoringToy.shadedplot(
f, $shader, limits, pixels; kwargs...)
end
end
end
export domaincolor
"""
domaincolor(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (480, 480),
abs = false,
grid = false,
color = true,
all = false,
box = nothing,
kwargs...
)
Takes a complex function and produces its domain coloring plot as an
interactive GLMakie plot.
Red corresponds to phase ``0``, yellow to ``\\frac{\\pi}{3}``, green
to ``\\frac{2\\pi}{3}``, cyan to ``\\pi``, blue to
``\\frac{4\\pi}{3}``, and magenta to ``\\frac{5\\pi}{3}``.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the size of the output in pixels, respectively, the
number of pixels along the real and imaginary axis, taking the same
for both if only one number is provided. If either is `:auto`, the
viewport resolution is used.
- **`abs`** toggles the plotting of the natural logarithm of the
magnitude as lightness ramps between level curves. If set to a number,
this will be used as base of the logarithm instead, if set to `Inf`,
zero magnitude will be colored black and poles white. Further granular
control can be achieved by passing a named tuple with any of the
parameters `base`, `transform`, or `sigma`. `base` changes the base of
the logarithm, as before. `transform` is the function applied to the
magnitude (`m -> log(base, m)` by default), and `sigma` changes the
rate at which zeros and poles are colored and implies `base = Inf`.
- **`grid`** plots points with integer real or imaginary part as black
dots. More complicated arguments can be passed as a named tuple in a
similar fashion to [`checkerplot`](@ref).
- **`color`** toggles coloring of the phase angle. Can also be set to
either the name of, or a `ColorScheme`, or a function `θ -> Color`.
If set to `:print` a desaturated version of the default is used.
- **`all`** is a shortcut for `abs = true`, `grid = true`, and
`color = true`.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
Remaining keyword arguments are passed to the plotting backend.
"""
domaincolor
@shadedplot(domaincolor,
(abs = false,
grid = false,
color = true,
all = false,
box = nothing),
begin
# issue warning if everything is inactive
if Base.all(b -> b isa Bool && !b, (abs, grid, color, all))
@warn "angle, abs, and grid are all false, domain coloring will be a constant color."
end
w -> DC.domaincolorshader(w; abs, grid, color, all, box)
end)
export checkerplot
"""
checkerplot(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (480, 480),
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
hicontrast = false,
kwargs...
)
Takes a complex function and produces a checker plot as an interactive
GLMakie plot.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the size of the output in pixels, respectively, the
number of pixels along the real and imaginary axis, taking the same
for both if only one number is provided. If either is `:auto`, the
viewport resolution is used.
If none of the below options are set, the plot defaults to `rect = true`.
- **`real`** plots black and white stripes orthogonal to the real axis
at a rate of one stripe per unit increase. If set to a number this
will be used as width instead.
- **`imag`** plots black and white stripes orthogonal to the imaginary
axis at a rate of one stripe per unit increase. If set to a number
this will be used as width instead.
- **`rect`** is a shortcut for `real = true` and `imag = true`.
- **`angle`** plots black and white stripes orthogonal to the phase
angle at a rate of eight stripes per full rotation. Can be set to an
integer to specify a different rate.
- **`abs`** plots black and white stripes at a rate of one stripe per
unit increase of the natural logarithm of the magnitude. If set to
a number this is used as the base of the logarithm. When set to a
function, unit increases of its output are used instead.
- **`polar`** is a shortcut for `angle = true` and `abs = true`. Can
also be set to the basis to use for `abs`, then a suitable rate for
`angle` will be selected.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
- **`hicontrast`** uses black and white instead of the softer defaults.
Remaining keyword arguments are passed to the plotting backend.
"""
checkerplot
@shadedplot(checkerplot,
(real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
hicontrast = false),
begin
# set carthesian grid if no options given
if all(b -> b isa Bool && !b,
(real, imag, rect, angle, abs, polar))
rect = true
end
w -> DC.checkerplotshader(
w; real, imag, rect, angle, abs, polar, box, hicontrast
)
end)
export sawplot
"""
sawplot(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (480, 480),
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
color = false,
box = nothing,
kwargs...
)
Takes a complex function and produces a saw plot as an interactive
GLMakie plot.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the size of the output in pixels, respectively, the
number of pixels along the real and imaginary axis, taking the same
for both if only one number is provided. If either is `:auto`, the
viewport resolution is used.
If none of the below options are set, the plot defaults to `rect = true`.
- **`real`** plots black to white ramps orthogonal to the real axis at a
rate of one ramp per unit increase. If set to a number this will be
used as width instead.
- **`imag`** plots black to white ramps orthogonal to the imaginary axis
at a rate of one ramp per unit increase. If set to a number this will
be used as width instead.
- **`rect`** is a shortcut for `real = true` and `imag = true`.
- **`angle`** plots black to white ramps orthogonal to the phase angle
at a rate of eight ramps per full rotation. Can be set to an integer
to specify a different rate.
- **`abs`** plots black to white ramps at a rate of one ramp per unit
increase of the natural logarithm of the magnitude. If set to a number
this is used as the base of the logarithm. When set to a function,
unit increases of its output are used instead.
- **`polar`** is a shortcut for `angle = true` and `abs = true`. Can
also be set to the basis to use for `abs`, then a suitable rate for
`angle` will be selected.
- **`color`** toggles coloring of the phase angle. Can also be set to
either the name of, or a `ColorScheme`, or a function `θ -> Color`.
If set to `:print` a desaturated version of the default is used.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
Remaining keyword arguments are passed to the plotting backend.
"""
sawplot
@shadedplot(sawplot,
(real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
color = false,
box = nothing),
begin
# set carthesian grid if no options given
if all(b -> b isa Bool && !b,
(real, imag, rect, angle, abs, polar))
rect = true
end
w -> DC.sawplotshader(
w; real, imag, rect, angle, abs, polar, color, box
)
end)
export pdphaseplot
"""
pdphaseplot(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (480, 480),
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
kwargs...
)
Takes a complex valued function and produces a phase plot using
[ColorCET](https://colorcet.com)'s CBC1 cyclic color map for protanopic
and deuteranopic viewers as an interactive GLMakie plot.
Yellow corresponds to phase ``0``, white to ``\\frac{\\pi}{2}``, blue
to ``\\pi``, and black to ``\\frac{3\\pi}{2}``.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the size of the output in pixels, respectively, the
number of pixels along the real and imaginary axis, taking the same
for both if only one number is provided. If either is `:auto`, the
viewport resolution is used.
- **`real`** plots black to white ramps orthogonal to the real axis at a
rate of one ramp per unit increase. If set to a number this will be
used as width instead.
- **`imag`** plots black to white ramps orthogonal to the imaginary axis
at a rate of one ramp per unit increase. If set to a number this will
be used as width instead.
- **`rect`** is a shortcut for `real = true` and `imag = true`.
- **`angle`** plots black to white ramps orthogonal to the phase angle
at a rate of eight ramps per full rotation. Can be set to an integer
to specify a different rate.
- **`abs`** plots black to white ramps at a rate of one ramp per unit
increase of the natural logarithm of the magnitude. If set to a number
this is used as the base of the logarithm. When set to a function,
unit increases of its output are used instead.
- **`polar`** is a shortcut for `angle = true` and `abs = true`. Can
also be set to the basis to use for `abs`, then a suitable rate for
`angle` will be selected.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
Remaining keyword arguments are passed to the plotting backend.
"""
pdphaseplot
@shadedplot(pdphaseplot,
(real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing),
w -> DC.sawplotshader(
w; real, imag, rect, angle, abs, polar, color=:CBC1, box
))
export tphaseplot
"""
tphaseplot(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (480, 480),
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
kwargs...
)
Takes a complex valued function and produces a phase plot using
[ColorCET](https://colorcet.com)'s CBTC1 cyclic color map for titranopic
viewers as an interactive GLMakie plot.
Red corresponds to phase ``0``, white to ``\\frac{\\pi}{2}``, cyan to
``\\pi``, and black to ``\\frac{3\\pi}{2}``.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the size of the output in pixels, respectively, the
number of pixels along the real and imaginary axis, taking the same
for both if only one number is provided. If either is `:auto`, the
viewport resolution is used.
- **`real`** plots black to white ramps orthogonal to the real axis at a
rate of one ramp per unit increase. If set to a number this will be
used as width instead.
- **`imag`** plots black to white ramps orthogonal to the imaginary axis
at a rate of one ramp per unit increase. If set to a number this will
be used as width instead.
- **`rect`** is a shortcut for `real = true` and `imag = true`.
- **`angle`** plots black to white ramps orthogonal to the phase angle
at a rate of eight ramps per full rotation. Can be set to an integer
to specify a different rate.
- **`abs`** plots black to white ramps at a rate of one ramp per unit
increase of the natural logarithm of the magnitude. If set to a number
this is used as the base of the logarithm. When set to a function,
unit increases of its output are used instead.
- **`polar`** is a shortcut for `angle = true` and `abs = true`. Can
also be set to the basis to use for `abs`, then a suitable rate for
`angle` will be selected.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
Remaining keyword arguments are passed to the plotting backend.
"""
tphaseplot
@shadedplot(tphaseplot,
(real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing),
w -> DC.sawplotshader(
w; real, imag, rect, angle, abs, polar, color=:CBTC1, box
))
end
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 686 | using Pkg
cd(@__DIR__)
Pkg.activate(".")
pkg"dev .. ../DomainColoringToy"
Pkg.instantiate()
Pkg.precompile()
using Documenter, DomainColoring
import DomainColoringToy
makedocs(
sitename = "DomainColoring.jl",
authors = "Evert Provoost",
pages = [
"Home" => "index.md",
"Usage" => [
"usage/tutorial.md",
"usage/general.md",
"usage/cvd.md",
"usage/custom.md",
],
"Library" => "lib.md",
"DomainColoringToy" => "dct.md",
"Design Choices" => [
"design/phasewheel.md",
],
]
)
deploydocs(
repo = "github.com/eprovst/DomainColoring.jl.git",
push_preview = true,
versions = ["stable" => "v^", "v1.#", "dev" => "dev"],
)
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 175 | using Images
import DomainColoring as DC
fig = DC.renderimage(z -> im*(z+.1im)^3-1,
w -> DC.domaincolorshader(w; all=true), 2.5)
save("logo.png", fig)
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 631 | #==
= DomainColoring.jl
=
= Copyright (c) 2023 Evert Provoost. See LICENSE.
=
= Provided functionality is partially inspired by
=
= Wegert, Elias. Visual Complex Functions:
= An Introduction with Phase Portraits.
= Birkhäuser Basel, 2012.
=#
module DomainColoring
using Requires
# load relevant backend
include("backends/stub.jl")
function __init__()
@require MakieCore="20f20a25-4f0e-4fdf-b5d1-57303727442b" include("backends/makie.jl")
@require Plots="91a5bcdd-55d7-5caf-9e0b-520d859cae80" include("backends/plots.jl")
end
include("render.jl")
include("shaders.jl")
include("plots.jl")
end
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 15285 | """
DomainColoring.@shadedplot(basename, shaderkwargs, shader)
Macro emitting implementations of **`basename`** and **`basename!`** in
a similar fashion to the other plotting routines in this library, see
for instance [`domaincolor`](@ref) and [`domaincolor!`](@ref).
**`shaderkwargs`** is a named tuple setting keyword arguments used in
the expression **`shader`**. The result of **`shader`** should be a
function `Complex -> Color` and is used to shade the resulting plot.
See the source for examples.
"""
macro shadedplot(basename, shaderkwargs, shader)
modifname = Symbol(basename, '!')
# interpret sargs as keyword arguments
skwargs = [Expr(:kw, p...) for
p in pairs(__module__.eval(shaderkwargs))]
for (fname, sname, target) in
((basename, :shadedplot, ()),
(modifname, :shadedplot!, ()),
(modifname, :shadedplot!, (:target,)))
@eval __module__ begin
function $fname(
$(target...),
f :: Function,
limits = (-1, 1, -1, 1);
pixels = (720, 720),
$(skwargs...),
kwargs...
)
DomainColoring.$sname($(target...), f, $shader,
limits, pixels; kwargs...)
end
end
end
end
export domaincolor, domaincolor!
"""
domaincolor(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (720, 720),
abs = false,
grid = false,
color = true,
all = false,
box = nothing,
kwargs...
)
Takes a complex function and produces its domain coloring plot.
Red corresponds to phase ``0``, yellow to ``\\frac{\\pi}{3}``, green
to ``\\frac{2\\pi}{3}``, cyan to ``\\pi``, blue to
``\\frac{4\\pi}{3}``, and magenta to ``\\frac{5\\pi}{3}``.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the number of pixels to compute in, respectively, the
real and imaginary axis, taking the same for both if only one number
is provided.
- **`abs`** toggles the plotting of the natural logarithm of the
magnitude as lightness ramps between level curves. If set to a number,
this will be used as base of the logarithm instead, if set to `Inf`,
zero magnitude will be colored black and poles white. Further granular
control can be achieved by passing a named tuple with any of the
parameters `base`, `transform`, or `sigma`. `base` changes the base of
the logarithm, as before. `transform` is the function applied to the
magnitude (`m -> log(base, m)` by default), and `sigma` changes the
rate at which zeros and poles are colored and implies `base = Inf`.
- **`grid`** plots points with integer real or imaginary part as black
dots. More complicated arguments can be passed as a named tuple in a
similar fashion to [`checkerplot`](@ref).
- **`color`** toggles coloring of the phase angle. Can also be set to
either the name of, or a `ColorScheme`, or a function `θ -> Color`.
If set to `:print` a desaturated version of the default is used.
- **`all`** is a shortcut for `abs = true`, `grid = true`, and
`color = true`.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
Remaining keyword arguments are passed to the plotting backend.
"""
domaincolor, domaincolor!
@shadedplot(domaincolor,
(abs = false,
grid = false,
color = true,
all = false,
box = nothing),
begin
# issue warning if everything is inactive
if Base.all(b -> b isa Bool && !b, (abs, grid, color, all))
@warn "angle, abs, and grid are all false, domain coloring will be a constant color."
end
w -> domaincolorshader(w; abs, grid, color, all, box)
end)
export checkerplot, checkerplot!
"""
checkerplot(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (720, 720),
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
hicontrast = false,
kwargs...
)
Takes a complex function and produces a checker plot.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the number of pixels to compute in, respectively, the
real and imaginary axis, taking the same for both if only one number
is provided.
If none of the below options are set, the plot defaults to `rect = true`.
- **`real`** plots black and white stripes orthogonal to the real axis
at a rate of one stripe per unit increase. If set to a number this
will be used as width instead.
- **`imag`** plots black and white stripes orthogonal to the imaginary
axis at a rate of one stripe per unit increase. If set to a number
this will be used as width instead.
- **`rect`** is a shortcut for `real = true` and `imag = true`.
- **`angle`** plots black and white stripes orthogonal to the phase
angle at a rate of eight stripes per full rotation. Can be set to an
integer to specify a different rate.
- **`abs`** plots black and white stripes at a rate of one stripe per
unit increase of the natural logarithm of the magnitude. If set to
a number this is used as the base of the logarithm. When set to a
function, unit increases of its output are used instead.
- **`polar`** is a shortcut for `angle = true` and `abs = true`. Can
also be set to the basis to use for `abs`, then a suitable rate for
`angle` will be selected.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
- **`hicontrast`** uses black and white instead of the softer defaults.
Remaining keyword arguments are passed to the plotting backend.
"""
checkerplot, checkerplot!
@shadedplot(checkerplot,
(real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
hicontrast = false),
begin
# set carthesian grid if no options given
if all(b -> b isa Bool && !b,
(real, imag, rect, angle, abs, polar))
rect = true
end
w -> checkerplotshader(
w; real, imag, rect, angle, abs, polar, box, hicontrast
)
end)
export sawplot, sawplot!
"""
sawplot(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (720, 720),
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
color = false,
box = nothing,
kwargs...
)
Takes a complex function and produces a saw plot.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the number of pixels to compute in, respectively, the
real and imaginary axis, taking the same for both if only one number
is provided.
If none of the below options are set, the plot defaults to `rect = true`.
- **`real`** plots black to white ramps orthogonal to the real axis at a
rate of one ramp per unit increase. If set to a number this will be
used as width instead.
- **`imag`** plots black to white ramps orthogonal to the imaginary axis
at a rate of one ramp per unit increase. If set to a number this will
be used as width instead.
- **`rect`** is a shortcut for `real = true` and `imag = true`.
- **`angle`** plots black to white ramps orthogonal to the phase angle
at a rate of eight ramps per full rotation. Can be set to an integer
to specify a different rate.
- **`abs`** plots black to white ramps at a rate of one ramp per unit
increase of the natural logarithm of the magnitude. If set to a number
this is used as the base of the logarithm. When set to a function,
unit increases of its output are used instead.
- **`polar`** is a shortcut for `angle = true` and `abs = true`. Can
also be set to the basis to use for `abs`, then a suitable rate for
`angle` will be selected.
- **`color`** toggles coloring of the phase angle. Can also be set to
either the name of, or a `ColorScheme`, or a function `θ -> Color`.
If set to `:print` a desaturated version of the default is used.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
Remaining keyword arguments are passed to the plotting backend.
"""
sawplot, sawplot!
@shadedplot(sawplot,
(real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
color = false,
box = nothing),
begin
# set carthesian grid if no options given
if all(b -> b isa Bool && !b,
(real, imag, rect, angle, abs, polar))
rect = true
end
w -> sawplotshader(
w; real, imag, rect, angle, abs, polar, color, box
)
end)
export pdphaseplot, pdphaseplot!
"""
pdphaseplot(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (720, 720),
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
kwargs...
)
Takes a complex valued function and produces a phase plot using
[ColorCET](https://colorcet.com)'s CBC1 cyclic color map for protanopic
and deuteranopic viewers.
Yellow corresponds to phase ``0``, white to ``\\frac{\\pi}{2}``, blue
to ``\\pi``, and black to ``\\frac{3\\pi}{2}``.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the number of pixels to compute in, respectively, the
real and imaginary axis, taking the same for both if only one number
is provided.
- **`real`** plots black to white ramps orthogonal to the real axis at a
rate of one ramp per unit increase. If set to a number this will be
used as width instead.
- **`imag`** plots black to white ramps orthogonal to the imaginary axis
at a rate of one ramp per unit increase. If set to a number this will
be used as width instead.
- **`rect`** is a shortcut for `real = true` and `imag = true`.
- **`angle`** plots black to white ramps orthogonal to the phase angle
at a rate of eight ramps per full rotation. Can be set to an integer
to specify a different rate.
- **`abs`** plots black to white ramps at a rate of one ramp per unit
increase of the natural logarithm of the magnitude. If set to a number
this is used as the base of the logarithm. When set to a function,
unit increases of its output are used instead.
- **`polar`** is a shortcut for `angle = true` and `abs = true`. Can
also be set to the basis to use for `abs`, then a suitable rate for
`angle` will be selected.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
Remaining keyword arguments are passed to the plotting backend.
"""
pdphaseplot, pdphaseplot!
@shadedplot(pdphaseplot,
(real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing),
w -> sawplotshader(
w; real, imag, rect, angle, abs, polar, color=:CBC1, box
))
export tphaseplot, tphaseplot!
"""
tphaseplot(
f :: "Complex -> Complex",
limits = (-1, 1, -1, 1);
pixels = (720, 720),
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
kwargs...
)
Takes a complex valued function and produces a phase plot using
[ColorCET](https://colorcet.com)'s CBTC1 cyclic color map for titranopic
viewers.
Red corresponds to phase ``0``, white to ``\\frac{\\pi}{2}``, cyan to
``\\pi``, and black to ``\\frac{3\\pi}{2}``.
# Arguments
- **`f`** is the complex function to plot.
- **`limits`** are the limits of the rectangle to plot, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
# Keyword Arguments
- **`pixels`** is the number of pixels to compute in, respectively, the
real and imaginary axis, taking the same for both if only one number
is provided.
- **`real`** plots black to white ramps orthogonal to the real axis at a
rate of one ramp per unit increase. If set to a number this will be
used as width instead.
- **`imag`** plots black to white ramps orthogonal to the imaginary axis
at a rate of one ramp per unit increase. If set to a number this will
be used as width instead.
- **`rect`** is a shortcut for `real = true` and `imag = true`.
- **`angle`** plots black to white ramps orthogonal to the phase angle
at a rate of eight ramps per full rotation. Can be set to an integer
to specify a different rate.
- **`abs`** plots black to white ramps at a rate of one ramp per unit
increase of the natural logarithm of the magnitude. If set to a number
this is used as the base of the logarithm. When set to a function,
unit increases of its output are used instead.
- **`polar`** is a shortcut for `angle = true` and `abs = true`. Can
also be set to the basis to use for `abs`, then a suitable rate for
`angle` will be selected.
- **`box`** if set to `(a, b, s)` shades the area where the output is
within the box `a` and `b` in the color `s` when set to `(f, s)` the
colored domain is defined by `f(w) == true`. Can also be a list of
multiple boxes.
Remaining keyword arguments are passed to the plotting backend.
"""
tphaseplot, tphaseplot!
@shadedplot(tphaseplot,
(real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing),
w -> sawplotshader(
w; real, imag, rect, angle, abs, polar, color=:CBTC1, box
))
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 2379 | using ColorTypes
# Implements the `limits` expansion typical of the functions in this
# module, additionally normalizes to tuples.
function _expandlimits(limits)
if length(limits) == 1
return Float64.(tuple(-limits, limits, -limits, limits))
elseif length(limits) == 2
return Float64.(tuple(-limits[1], limits[1], -limits[2], limits[2]))
else
return Float64.(Tuple(limits))
end
end
"""
DomainColoring.renderimage!(
out :: Matrix{<: Color},
f :: "Complex -> Complex",
shader :: "Complex -> Color",
limits = (-1, 1, -1, 1),
)
# Arguments
- **`out`** is the output image buffer.
- **`f`** is the complex function to turn into an image.
- **`shader`** is the shader function to compute a pixel.
- **`limits`** are the limits of the rectangle to render, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
"""
function renderimage!(
img::Matrix{C},
f,
shader,
limits = (-1, 1, -1, 1),
) where C
limits = _expandlimits(limits)
r = range(limits[1], limits[2], length=size(img, 2))
i = range(limits[4], limits[3], length=size(img, 1))
shd(w) = isnan(w) ? zero(C) : convert(C, shader(w))
broadcast!((r, i) -> shd(f(r + im*i)), img, r', i)
end
"""
DomainColoring.renderimage(
f :: "Complex -> Complex",
shader :: "Complex -> Color",
limits = (-1, 1, -1, 1),
pixels = (720, 720),
)
# Arguments
- **`f`** is the complex function to turn into an image.
- **`shader`** is the shader function to compute a pixel.
- **`limits`** are the limits of the rectangle to render, in the format
`(minRe, maxRe, minIm, maxIm)`, if one or two numbers are provided
instead they are take symmetric along the real and imaginary axis.
- **`pixels`** is the size of the output in pixels, respectively, the
number of pixels along the real and imaginary axis, taking the same
for both if only one number is provided.
"""
function renderimage(
f,
shader,
limits = (-1, 1, -1, 1),
pixels = (720, 720),
)
length(pixels) == 1 && (pixels = (pixels, pixels))
img = Matrix{RGBA{Float64}}(undef, pixels[1], pixels[2])
renderimage!(img, f, shader, limits)
return img
end
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 8797 | using ColorTypes, ColorSchemes
"""
DomainColoring.labsweep(θ)
Maps a phase angle **`θ`** to a color in CIE L\\*a\\*b\\* space by
taking
```math
\\begin{aligned}
L^* &= 67 - 12 \\cos(3\\theta), \\\\
a^* &= 46 \\cos(\\theta + .4) - 3, \\quad\\text{and} \\\\
b^* &= 46 \\sin(\\theta + .4) - 16.
\\end{aligned}
```
See [Phase Wheel](@ref) for more information.
"""
function labsweep(θ)
θ = mod(θ, 2π)
Lab(67 - 12cos(3θ),
46cos(θ + .4) - 3,
46sin(θ + .4) + 16)
end
# Grid types supported by _grid
@enum GridType begin
CheckerGrid
LineGrid
SawGrid
end
# Logic for grid like plotting elements, somewhat ugly, but it works.
# `w` is the complex value, `type` is the type of grid to make
# `checkerplot`.
function _grid(
type,
w;
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
)
# carthesian checker plot
if rect isa Bool
if rect
real = true
imag = true
end
elseif length(rect) > 1
real = rect[1]
imag = rect[2]
else
real = rect
imag = rect
end
# polar checker plot
if polar isa Bool
if polar
angle = true
abs = true
end
elseif polar isa Function
angle = true
abs = polar
elseif length(polar) > 1
angle = polar[1]
abs = polar[2]
else
angle = 2max(round(π/log(polar)), 4)
abs = polar
end
# set defaults
(real isa Bool && real) && (real = 1)
(imag isa Bool && imag) && (imag = 1)
(angle isa Bool && angle) && (angle = 8)
(abs isa Bool && abs) && (abs = ℯ)
# set the transform
saw(x) = mod(x, 1)
if type == SawGrid
trf = saw
else
trf = sinpi
end
g = 1.0
if real > 0
r = Base.real(w) / real
isfinite(r) && (g *= trf(r))
end
if imag > 0
i = Base.imag(w) / imag
isfinite(i) && (g *= trf(i))
end
if angle > 0
@assert mod(angle, 1) ≈ 0 "Rate of angle has to be an integer."
angle = round(angle)
(type == CheckerGrid) && @assert iseven(angle) "Rate of angle has to be even."
a = angle * Base.angle(w) / 2π
isfinite(a) && (g *= trf(a))
end
if abs isa Function
m = abs(Base.abs(w))
isfinite(m) && (g *= trf(m))
elseif abs > 0
m = log(abs, Base.abs(w))
isfinite(m) && (g *= trf(m))
end
if type == CheckerGrid
float(g > 0)
elseif type == LineGrid
Base.abs(g)^0.06
else
g
end
end
_grid(type, w, args::NamedTuple) = _grid(type, w; args...)
_grid(type, w, arg) = _grid(type, w; rect=arg)
# Implements the angle coloring logic for shaders.
_color_angle(w, arg::Bool) = arg ? labsweep(angle(w)) : Lab(80.0, 0.0, 0.0)
_color_angle(w, arg::Function) = arg(mod(angle(w), 2π))
_color_angle(w, arg::ColorScheme) = get(arg, mod(angle(w) / 2π, 1))
function _color_angle(w, arg::Symbol)
if arg == :print
c = labsweep(angle(w))
Lab(c.l + 5, .7c.a, .7c.b)
elseif arg == :CBC1 || arg == :pd
get(ColorSchemes.cyclic_protanopic_deuteranopic_bwyk_16_96_c31_n256,
mod(-angle(w) / 2π + .5, 1))
elseif arg == :CBTC1 || arg == :t
get(ColorSchemes.cyclic_tritanopic_cwrk_40_100_c20_n256,
mod(-angle(w) / 2π + .5, 1))
else
_color_angle(w, ColorSchemes.colorschemes[arg])
end
end
# Implements the magnitude logic for `domaincolorshader`
# isnothing(transform) gives the default log, and saves us
# from compiling an anonymous function each call. See `domaincolor`
# for further argument description.
function _add_magnitude(
w,
c;
base = ℯ,
transform = nothing,
sigma = nothing,
)
# add magnitude if requested
if base > 0
if isfinite(base) && isnothing(sigma)
if isnothing(transform)
m = log(base, abs(w))
else
m = transform(abs(w))
end
isfinite(m) && (c = Lab(c.l + 20mod(m, 1) - 10, c.a, c.b))
else
isnothing(sigma) && (sigma = 0.02)
m = log(abs(w))
t = isfinite(m) ? exp(-sigma*m^2) : 0.0
g = 100.0(m > 0)
c = Lab((1 - t)g + t*c.l, t*c.a, t*c.b)
end
end
return c
end
_add_magnitude(w, c, args::NamedTuple) = _add_magnitude(w, c; args...)
_add_magnitude(w, c, arg::Bool) = arg ? _add_magnitude(w, c) : c
_add_magnitude(w, c, arg::Function) = _add_magnitude(w, c; transform=arg)
_add_magnitude(w, c, arg) = _add_magnitude(w, c; base=arg)
# draw a colored box in a specified area
function _add_box(w, c, sqs)
if isnothing(sqs)
return c
end
for sq in sqs
c = _add_box(w, c, sq)
end
return c
end
# domain function
function _add_box(w, c::C, sq::Tuple{<:Function, <:Color}) where C <: Color
f, s = sq
f(w) ? convert(C, s) : c
end
function _add_box(w, c::C, sq::Tuple{<:Function, <:Any}) where C <: Color
f, s = sq
_add_box(w, c, (f, parse(C, s)))
end
# normal box
function _add_box(w, c::C, sq::Tuple{<:Number, <:Number, <:Color}) where C <: Color
a, b, s = sq
mr, Mr = minmax(real(a), real(b))
mi, Mi = minmax(imag(a), imag(b))
r, i = reim(w)
(mr <= r <= Mr) && (mi <= i <= Mi) ? convert(C, s) : c
end
function _add_box(w, c::C, sq::Tuple{<:Number, <:Number, <:Any}) where C <: Color
a, b, s = sq
_add_box(w, c, (a, b, parse(C, s)))
end
"""
DomainColoring.domaincolorshader(
w :: Complex;
abs = false,
grid = false,
color = true,
all = false,
box = nothing,
)
Takes a complex value **`w`** and shades it as in a domain coloring.
For documentation of the remaining arguments see [`domaincolor`](@ref).
"""
function domaincolorshader(
w;
abs = false,
grid = false,
color = true,
all = false,
box = nothing,
)
# user wants full domain coloring
if all
(abs isa Bool) && (abs = true)
(grid isa Bool) && (grid = true)
(color isa Bool) && (color = true)
end
# short circuit conversions
if (abs isa Bool) && !abs && (grid isa Bool) && !grid
return _add_box(w, _color_angle(w, color), box)
end
# phase color
c = convert(Lab, _color_angle(w, color))
# add magnitude
c = _add_magnitude(w, c, abs)
# add integer grid if requested
if !(grid isa Bool) || grid
# slightly overattenuate to compensate global darkening
g = 1.06_grid(LineGrid, w, grid)
c = mapc(x -> g*x, c)
end
# add boxs
c = _add_box(w, c, box)
return c
end
"""
DomainColoring.checkerplotshader(
w :: Complex;
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
hicontrast = false,
)
Takes a complex value **`w`** and shades it as in a checker plot.
For documentation of the remaining arguments see [`checkerplot`](@ref).
"""
function checkerplotshader(
w;
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
box = nothing,
hicontrast = false,
)
g = _grid(CheckerGrid, w; real, imag, rect, angle, abs, polar)
if hicontrast
c = Gray(g)
else
c = Gray(0.9g + 0.08)
end
# add boxs
isnothing(box) ? c : _add_box(w, convert(RGB, c), box)
end
"""
DomainColoring.sawplotshader(
w :: Complex;
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
color = false,
box = nothing,
)
Takes a complex value **`w`** and shades it as in a saw plot.
For documentation of the remaining arguments see [`sawplot`](@ref).
"""
function sawplotshader(
w;
real = false,
imag = false,
rect = false,
angle = false,
abs = false,
polar = false,
color = false,
box = nothing,
)
# shortcut if there is no grid to add
if all(b -> (b isa Bool) && !b,
(real, imag, rect, angle, abs, polar))
return _add_box(w, _color_angle(w, color), box)
end
g = _grid(SawGrid, w; real, imag, rect, angle, abs, polar)
if color isa Bool && !color
c = Gray(0.6g + 0.3)
isnothing(box) ? c : _add_box(w, convert(RGB, c), box)
else
c = convert(Lab, _color_angle(w, color))
_add_box(w, Lab(c.l + 20g - 10, c.a, c.b), box)
end
end
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 1356 | import .MakieCore as MC
# Makie specific version of `shadedplot` and `shadedplot!`
for (modifying, target) in
((false, ()),
(true, ()),
(true, (:target,)))
fname = modifying ? :shadedplot! : :shadedplot
hname = modifying ? :heatmap! : :heatmap
@eval begin
function $fname(
$(target...),
f :: Function,
shader :: Function,
limits = (-1, 1, -1, 1),
pixels = (720, 720);
kwargs...
)
limits = _expandlimits(limits)
# parse Makie options
$(if !modifying
:(defaults = MC.Attributes(;
interpolate = true,
axis = (autolimitaspect = 1,
aspect = (limits[2] - limits[1]) /
(limits[4] - limits[3]))))
else
:(defaults = MC.Attributes(; interpolate = true))
end)
attr = merge(MC.Attributes(; kwargs...), defaults)
# images have inverted y and flip x and y in their storage
r = [limits[1], limits[2]]
i = [limits[4], limits[3]]
MC.$hname($(target...), r, i,
renderimage(f, shader, limits, pixels)'; attr...)
end
end
end
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 1036 | import .Plots
# Plots.jl specific version of `shadedplot` and `shadedplot!`
for (modifying, target) in
((false, ()),
(true, ()),
(true, (:target,)))
fname = modifying ? :shadedplot! : :shadedplot
pname = modifying ? :plot! : :plot
@eval begin
function $fname(
$(target...),
f :: Function,
shader :: Function,
limits = (-1, 1, -1, 1),
pixels = (720, 720);
kwargs...
)
limits = _expandlimits(limits)
r = [limits[1], limits[2]]
i = [limits[3], limits[4]]
# set attributes
$(if !modifying
:(attr = merge((yflip=false, xlims=r, ylims=i),
kwargs))
else
:(attr = kwargs)
end)
Plots.$pname($(target...), r, i,
reverse(renderimage(f, shader, limits, pixels), dims=1);
attr...)
end
end
end
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | code | 608 | """
DomainColoring.shadedplot(
f :: "Complex -> Complex",
shader :: "Complex -> Color",
limits = (-1, 1, -1, 1),
pixels = (720, 720);
kwargs...
)
Takes a complex function **`f`** and a **`shader`** and produces a plot.
For documentation of the remaining arguments see [`renderimage`](@ref).
Keyword arguments are passed to the backend.
"""
shadedplot, shadedplot!
shadedplot(args...) = @error "`shadedplot` is used in an unusual way; did you load a backend?"
shadedplot!(args...) = @error "`shadedplot!` is used in an unusual way; did you load a backend?"
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 484 | <div align="center">
<img src="docs/src/assets/logo.png" width=210/>
<h1>DomainColoring.jl</h1>
</div>
<p>
<a href="https://eprovst.github.io/DomainColoring.jl/stable">
<img src="https://img.shields.io/badge/docs-stable-green.svg"/>
</a>
<a href="https://eprovst.github.io/DomainColoring.jl/dev">
<img src="https://img.shields.io/badge/docs-dev-blue.svg"/>
</a>
</p>
<p>
Domain colorings and checker plots of complex functions in Julia using smooth colors.
</p>
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 477 | <h1>DomainColoringToy</h1>
<p>
<a href="https://eprovst.github.io/DomainColoring.jl/stable/dct">
<img src="https://img.shields.io/badge/docs-stable-green.svg"/>
</a>
<a href="https://eprovst.github.io/DomainColoring.jl/dev/dct">
<img src="https://img.shields.io/badge/docs-dev-blue.svg"/>
</a>
</p>
<p>
Interactive domain colorings and checker plots of complex functions in Julia using smooth colors,
based on <a href="https://makie.org/">GLMakie</a>.
</p>
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 986 | # DomainColoringToy
`DomainColoringToy` is an auxiliary package building on
`DomainColoring.jl` which preloads `GLMakie` and rerenders the plot when
the user zooms in or pans around.
The exported functions and arguments are identical to
`DomainColoring.jl` with the addition of the acceptance of `:auto` in
place of an integer in the `pixels` keyword argument. A direction
which is set to `:auto` will use the viewport resolution to determine
the number of samples. Note that this can make plotting very slow.
Finally, in a similar fashion to `DomainColoring.@shadedplot`, one can
use `DomainColoringToy.@shadedplot` to create custom plots.
## Installation
`DomainColoringToy` is a different package and hence has to be installed
separately. Installation is as usual:
```
]add DomainColoringToy
```
## Library
### Public Interface
```@autodocs
Modules = [DomainColoringToy]
Private = false
```
### Package Internals
```@autodocs
Modules = [DomainColoringToy]
Public = false
```
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 710 | # DomainColoring.jl: Smooth Complex Plotting
Welcome to the documentation of the `DomainColoring.jl` package, a small
collection of various ways to plot complex functions, supporting
[Plots.jl](https://docs.juliaplots.org) and [Makie](https://makie.org).
```@raw html
<div align="center">
<img src="assets/logo.png" width=300 />
</div>
```
The plots implemented here are inspired by the wonderful book by
Wegert[^1], yet using a smooth (technically analytic) curve
through CIE L\*a\*b\* space, yielding a more perceptually uniform
representation of the phase (see [Phase Wheel](@ref)).
[^1]:
Wegert, Elias. Visual Complex Functions: An Introduction with Phase
Portraits. Birkhäuser Basel, 2012.
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 174 | # Library
## Public Interface
```@autodocs
Modules = [DomainColoring]
Private = false
```
## Package Internals
```@autodocs
Modules = [DomainColoring]
Public = false
```
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 1839 | # Phase Wheel
Creating a perceptually smooth color wheel is in general a difficult
task, and comes with inherent compromises. This document serves to list
the design decisions taken for the phase wheel used in our
implementation of domain coloring. We carefully selected the following
analytical sweep through CIE L\*a\*b\* space:
```math
\begin{aligned}
L^* &= 67 - 12 \cos(3\theta),\\
a^* &= 46 \cos(\theta + .4) - 3,\quad\text{and}\\
b^* &= 46 \sin(\theta + .4) - 16.
\end{aligned}
```
This is implemented by the internal function [`DomainColoring.labsweep`](@ref),
giving the following phase wheel.
```@example
using DomainColoring, Colors #hide
showable(::MIME"text/plain", ::AbstractVector{C}) where {C<:Colorant} = false #hide
DomainColoring.labsweep.(0:.01:2π)
```
The main problem in the usually used HSV map is the erratic nature of everything,
creating false detail, making certain parts of the phase look longer than others,
etc. Unlike, HSV our peaks and troughs are equispaced, and smooth.
Lightnesswise the entire range is separated into six equal parts. For usual
data analysis it would be better to minimise the number of oscillations,
however for our purposes the turning points serve as visual anchors dividing
the phase range. Note that some lightness variation is wanted, as our eyes
mainly rely on lightness to discern higher frequency information[^1].
The target color space is sRGB, so adding dips in lightness near its red,
green, and blue primaries buys us more range in additional lightness variation
to show magnitude in more complicated plots. This way we have only slight
clipping in sRGB space when adding the lightness variations used to show
magnitude changes in [`domaincolor`](@ref).
[^1]:
Kovesi, Peter. (2015). "Good Colour Maps: How to Design Them."
arXiv:abs/1509.03700.
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 1769 | # Creating Custom Plots
The underlying architecture of DomainColoring is fairly straightforward.
A shader function (a map from complex numbers to colors) is applied to
the input function `f` applied to some grid.
The specification of this grid, the `pixels` option, the axis limiting
and the interface with Plots and Makie are identical throughout
DomainColoring and stem from the internal macro `@shadedplot`.
An example makes this clear. Let's say we want a plot where integer grid
lines of the real part and the imaginary part in different colors. A
shader implementing this could be:
```julia
using DomainColoring, Colors
function shader(w, realcol, imagcol)
r, i = reim(w)
c = weighted_color_mean(abs(sinpi(r))^.06, colorant"white", realcol)
weighted_color_mean(abs(sinpi(i))^.06, c, imagcol)
end
```
Turning this into a plotting function is then as simple as:
```julia
import DomainColoring: @shadedplot
@shadedplot(cgridplot,
(realcol = colorant"red", imagcol = colorant"blue"),
w -> shader(w, realcol, imagcol))
```
This produces functions `cgridplot` and `cgridplot!`. Which give plots
like:
```@example
using CairoMakie
using DomainColoring, Colors # hide
function shader(w, realcol, imagcol) # hide
r, i = reim(w) # hide
c = colorant"white" # hide
c = weighted_color_mean(abs(sinpi(r))^.06, c, realcol) # hide
weighted_color_mean(abs(sinpi(i))^.06, c, imagcol) # hide
end # hide
import DomainColoring: @shadedplot # hide
@shadedplot(cgridplot, # hide
(realcol = colorant"red", imagcol = colorant"blue"), # hide
w -> shader(w, realcol, imagcol)) # hide
cgridplot(z -> im*z^3-1, 2.5)
resize!(current_figure(), 620, 600) #hide
save("example.png", current_figure()) # hide
nothing # hide
```

| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 1852 | # Plotting for Color Vision Deficiency
To distinguish phase values without introducing a discontinuity we need
to use two stimuli. The shading used by [`domaincolor`](@ref) uses
green-magenta and blue-yellow color opponents (i.e. a full rainbow),
with only slight variation in lightness to enhance local contrast. This
leaves lightness to display contour lines of the magnitude, but is
problematic for viewers with color vision deficiency. For them, these
color opponents are not (fully) distinguishable and hence the plot is
rendered unreadable.
`DomainColoring.jl` hence provides alternative phase plots that are
clearly readable to them, based on color maps developed by
[Peter Kovesi](https://peterkovesi.com/papers/ColourMapsForColourBlindIAMG2017.pdf).
!!! note
These color maps can also be used in the other plots as
`:pd`/`:CBC1` and `:t`/`:CBTC1`, respectively. However do note that
their use of black and white might interfere with other plotting
elements.
## Phase plots for protanopia and deuteranopia
For these viewers it is difficult to distinguish red and green hues. The
method [`pdphaseplot`](@ref) hence uses lightness and a yellow-blue
sweep to display phase instead.
```@example
using CairoMakie, DomainColoring # hide
pdphaseplot(z -> exp(1/z), 0.5)
resize!(current_figure(), 620, 600) #hide
save("pdphaseexample.png", current_figure()) # hide
nothing # hide
```

## Phase plots for titranopia
For these viewers it is difficult to distinguish blue and yellow hues.
The method [`tphaseplot`](@ref) hence uses lightness and a red-cyan
sweep to display phase instead.
```@example
using CairoMakie, DomainColoring # hide
tphaseplot(z -> exp(1/z), 0.5)
resize!(current_figure(), 620, 600) #hide
save("tphaseexample.png", current_figure()) # hide
nothing # hide
```

| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 12239 | # General Overview
!!! note
`DomainColoring.jl` provides plots on top of either the
[Plots.jl](https://docs.juliaplots.org) or
[Makie](https://makie.org) frameworks, thus a user will have to
additionally install and load a backend.
## Common options
All plotting functions require a function ``\mathbb{C} \to \mathbb{C}``
as first argument and accept optionally axis limits as a second.
If no limits are provided by default unit length is taken in all four
directions. If a list of two numbers is provided the first is used as
both limit in the real direction and the second in the imaginary
direction. A list of four elements are interpreted as
``({\rm Re}_{\rm min}, {\rm Re}_{\rm max}, {\rm Im}_{\rm min},
{\rm Im}_{\rm max})``.
All plots have a keyword argument `pixels` by which one can specify the
number of samples in respectively the real and imaginary direction. If
only one number is provided it is used for both.
Additionally there is also the option to fill in a box, or list of boxes
in the output space using the option `box`, which is illustrated in the
section on [`checkerplot`](@ref) and [`sawplot`](@ref).
Finally, any remaining keywords are passed to the backend. This,
together with the modifying variants (`domaincolor!`, `checkerplot!`,
etc.), makes the plotting routines in this library behave similarly to
other plot types. For more information we refer to the
[Plots.jl](https://docs.juliaplots.org) and
[Makie](https://docs.makie.org) documentation.
The remainder of this page gives a quick overview of the main plotting
functions of `DomainColoring.jl`.
## The [`domaincolor`](@ref) function
!!! note
The phase output of [`domaincolor`](@ref) is generally not suited
for those with color vision deficiency, refer to [Plotting for Color
Vision Deficiency](@ref) instead.
By default [`domaincolor`](@ref) produces a phase plot such as the
following.
```@example
using CairoMakie, DomainColoring # hide
domaincolor(sinc, (3, 1.5))
resize!(current_figure(), 620, 340) #hide
save("dcsincphase.png", current_figure()) # hide
nothing # hide
```

One can additionally superimpose contour lines of the magnitude as
sweeps of increasing lightness by setting `abs = true`. Where this
increase of lightness is taken proportional to the fractional part of
``\log|f(z)|``.
```@example
using CairoMakie, DomainColoring # hide
domaincolor(sinc, (3, 1.5), abs=true)
resize!(current_figure(), 620, 340) #hide
save("dcsincabs.png", current_figure()) # hide
nothing # hide
```

Finally, one can also add a dark grid where the imaginary or real part
of ``f(z)`` is integer by setting `grid = true`.
```@example
using CairoMakie, DomainColoring # hide
domaincolor(sinc, (3, 1.5), grid=true)
resize!(current_figure(), 620, 340) #hide
save("dcsincgrid.png", current_figure()) # hide
nothing # hide
```

Of course these options can be combined, the common combination of
`abs = true` and `grid = true` even has an abbreviation `all = true`.
```@example
using CairoMakie, DomainColoring # hide
domaincolor(sinc, (3, 1.5), all=true)
resize!(current_figure(), 620, 340) #hide
save("dcsincall.png", current_figure()) # hide
nothing # hide
```

The argument interface contains many further options, but we will delay
their discussion until after introducing the [`checkerplot`](@ref) and
[`sawplot`](@ref) functions.
## The [`checkerplot`](@ref) and [`sawplot`](@ref) functions
A checker plot shows limited information and is useful to detect
patterns in certain contexts. By default a checker board pattern is used
with one stripe for an unit increase in either direction. A
checkerplot of the identity function makes this clearer.
```@example
using CairoMakie, DomainColoring # hide
checkerplot(z -> z, 5)
resize!(current_figure(), 620, 600) #hide
save("cprect.png", current_figure()) # hide
nothing # hide
```

A saw plot is similar but shows ramps instead of solid stripes, to get
an idea of the direction of increase. Their interface is almost
identical, so we'll use them interchangeably for most examples.
The previous example as a saw plot would be:
```@example
using CairoMakie, DomainColoring # hide
sawplot(z -> z, 5)
resize!(current_figure(), 620, 600) #hide
save("sprect.png", current_figure()) # hide
nothing # hide
```

You can limit the stripes to only show increase in the real or imaginary
part by setting `real = true` or `imag = true`, respectively. Again the
previous example.
```@example
using CairoMakie, DomainColoring # hide
checkerplot(z -> z, 5, real=true)
resize!(current_figure(), 620, 600) #hide
save("cpreal.png", current_figure()) # hide
nothing # hide
```

Setting `real = true` and `imag = true` can be abbreviated to
`rect = true`, which is identical to the default behaviour.
Alternatively one can also display a polar grid by setting
`polar = true`, giving one band per unit increase of ``\log|f(z)|`` and
eight bands per ``2\pi`` increase of ``\arg(f(z))``.
```@example
using CairoMakie, DomainColoring # hide
sawplot(z -> z, 5, polar=true)
resize!(current_figure(), 620, 600) #hide
save("cppolar.png", current_figure()) # hide
nothing # hide
```

As with `rect = true`, `polar = true` is an abbreviation for
`abs = true` and `angle = true`, showing magnitude and phase
respectively. Now is a good time to mention that most arguments
discussed so far also accept numbers, modifying the width or rate of the
stripes. For example, we can change the basis of the logarithm used for
the magnitude (alternatively one can also pass a function as in
[`domaincolor`](@ref), see next section):
```@example
using CairoMakie, DomainColoring # hide
checkerplot(z -> z, 5, abs=1.1)
resize!(current_figure(), 620, 600) #hide
save("cpabs.png", current_figure()) # hide
nothing # hide
```

and for phase:
```@example
using CairoMakie, DomainColoring # hide
sawplot(z -> z, 5, angle=10)
resize!(current_figure(), 620, 600) #hide
save("cpangle.png", current_figure()) # hide
nothing # hide
```

Note, that for a [`checkerplot`](@ref) the latter we needs to be an even
number. If we set `phase` to a number, this will be used for `abs` and a
suitable integer rate will be chosen for `angle`, for instance:
```@example
using CairoMakie, DomainColoring # hide
checkerplot(sin, (5, 2), polar=1.5)
resize!(current_figure(), 620, 280) #hide
save("cppolarsin.png", current_figure()) # hide
nothing # hide
```

As mentioned before regions of the output plane can be colored using the
`box` option, for example:
```@example
using CairoMakie, DomainColoring # hide
checkerplot(z -> z^2, 2, box=[(1,1im,:red), (-1-2im,-2-1im,:blue)])
resize!(current_figure(), 620, 600) #hide
save("cpboxes.png", current_figure()) # hide
nothing # hide
```

Finally, `hicontrast = true` can be used in [`checkerplot`](@ref) to
plot in black and white instead of the slightly softer defaults, and
`color = true` mixes phase coloring into a [`sawplot`](@ref) (further
possibilities of this option are identical to [`domaincolor`](@ref), as
discussed at the end of the next section).
## The [`domaincolor`](@ref) function, revisited
Like [`checkerplot`](@ref) and [`sawplot`](@ref), `abs` and `grid` also
accept numbers. Respectively, changing the basis of the used logarithm
and the rate of the grid. Additionally, we can pass named tuples to open
up even more options.
For `grid` these options are identical to `checkerplot`, for example an
analogous example to the penultimate one of last section, is given by:
```@example
using CairoMakie, DomainColoring # hide
domaincolor(sin, (5, 2), grid=(polar=1.5,))
resize!(current_figure(), 620, 280) #hide
save("dcpolarsin.png", current_figure()) # hide
nothing # hide
```

(Note: unlike before, the rate of `angle` need not be even for grids.)
The `abs` argument accepts a different basis from the default ``e``, if
we for instance wanted to see orders of magnitude, we could look at:
```@example
using CairoMakie, DomainColoring # hide
domaincolor(z -> z^3, 5, abs=10)
resize!(current_figure(), 620, 600) #hide
save("dcordermag.png", current_figure()) # hide
nothing # hide
```

If one does not want to look at the logarithm of the magnitude, but the
magnitude itself, they can use the `transform` option, or pass a
function directly to `abs`, for instance:
```@example
using CairoMakie, DomainColoring # hide
domaincolor(sqrt, (-1, 19, -4, 4), abs=z->z)
resize!(current_figure(), 620, 280) #hide
save("dclinmag.png", current_figure()) # hide
nothing # hide
```

Finally, if we set the base to `Inf`, the magnitude is colored from
black at zero to white at infinity, which we can use to illustrate the
Casorati–Weierstrass theorem:
```@example
using CairoMakie, DomainColoring # hide
domaincolor(z -> exp(1/z), .1, abs=Inf)
resize!(current_figure(), 620, 600) #hide
save("cwthm.png", current_figure()) # hide
nothing # hide
```

The harshness of these white an black areas can be changed using the
`sigma` parameter, try for instance:
```julia
domaincolor(z -> exp(1/z), .1, abs=(sigma=0.001,))
```
If one wants to change the coloring of the phase angle, they can pass a
`ColorScheme` (as an object or by name, see [their
documentation](https://juliagraphics.github.io/ColorSchemes.jl/stable/catalogue/))
or a function `θ -> Color`, to `color`. As an example of the latter, we
can add a discretization effect:
```@example
using CairoMakie, DomainColoring # hide
discrangle(θ) = DomainColoring.labsweep(π/10 * floor(10/π * θ))
domaincolor(tan, π/2, color=discrangle)
resize!(current_figure(), 620, 600) #hide
save("dsccolor.png", current_figure()) # hide
nothing # hide
```

There is also a `:print` option that uses a desaturated version of the
default color scheme, which is more suitable for consumer grade printers.
```@example
using CairoMakie, DomainColoring # hide
domaincolor(tan, π/2, color=:print)
resize!(current_figure(), 620, 600) #hide
save("dscprint.png", current_figure()) # hide
nothing # hide
```

Finally, if no coloring of the phase is wanted, we can set
`color = false`.
## The Riemann sphere
To close, let us demonstrate how you can combine plots in the Makie
framework to plot the two hemispheres of the Riemann sphere side to
side.
Separately these would be for some function `f`, say `sin`
```@example
using CairoMakie, DomainColoring # hide
f = sin
domaincolor(z -> abs(z) <= 1 ? f(z) : NaN)
resize!(current_figure(), 620, 600) #hide
current_figure() #hide
```
and
```@example
using CairoMakie, DomainColoring # hide
f = sin #hide
domaincolor(z -> abs(z) <= 1 ? f(1/z) : NaN)
resize!(current_figure(), 620, 600) #hide
current_figure() #hide
```
where we used that `NaN` is shown transparent by the plots of this
package.
In Makie a layout of `Axis` objects is collected in a `Figure`, we can
position them by indexing the figure. Two axes side by side would for
instance be:
```@example
using CairoMakie
fig = Figure()
ax11 = Axis(fig[1,1])
ax12 = Axis(fig[1,2])
resize!(fig, 620, 400) #hide
fig
```
As a final complication, `domaincolor!` can't change the aspect ratio
of a plot, hence we have to set it to square at the time of creation,
giving finally the function (where we also pass keyword arguments):
```julia
function riemann(f; kwargs...)
fig = Figure()
ax11 = Axis(fig[1,1], aspect=1)
domaincolor!(ax11, z -> abs(z) <= 1 ? f(z) : NaN; kwargs...)
ax12 = Axis(fig[1,2], aspect=1)
domaincolor!(ax12, z -> abs(z) <= 1 ? f(1/z) : NaN; kwargs...)
fig
end
```
For the sine function this for instance gives:
```@example
using DomainColoring, CairoMakie # hide
function riemann(f; kwargs...) # hide
fig = Figure() # hide
ax11 = Axis(fig[1,1], aspect=1) # hide
domaincolor!(ax11, z -> abs(z) <= 1 ? f(z) : NaN; kwargs...) # hide
ax12 = Axis(fig[1,2], aspect=1) # hide
domaincolor!(ax12, z -> abs(z) <= 1 ? f(1/z) : NaN; kwargs...) # hide
fig # hide
end # hide
riemann(sin, abs=true)
resize!(current_figure(), 620, 300) #hide
current_figure() #hide
```
| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 1.0.1 | 034b43b4a93702047f2c91670e8df0372d725aca | docs | 5023 | # Basic Tutorial
!!! note
If you're experienced with Julia and phase plots, this document
might be fairly basic. Continue to the [General Overview](@ref)
instead.
## Installation, loading, Makie and Plots.jl
`DomainColoring.jl` provides plotting routines for complex functions.
These require either the [Makie](https://makie.org/) or
[Plots.jl](https://docs.juliaplots.org) plotting libraries. In this
tutorial we will use the former.
Makie supports multiple backends, one of which has to be loaded to
display the resulting plot. There are two main options:
- `GLMakie` for interactive plots, and
- `CairoMakie` for publication quality plots.
In this tutorial we will use `CairoMakie` to provide output for the
documentation, but whilst following along you might want to use
`GLMakie` instead.
To install `DomainColoring.jl` and either of these packages, enter
```
]add DomainColoring GLMakie
```
or
```
]add DomainColoring CairoMakie
```
into the Julia REPL. (To return to the Julia REPL after this, simply
press backspace.)
After installation your session should in general start with either
```julia
using GLMakie, DomainColoring
```
for interactive work, or for publication graphics with
```julia
using CairoMakie, DomainColoring
```
## Plotting our first few phase plots
Julia supports the passing of functions as arguments, even better, it
supports the creation of so called 'anonymous' functions. We can for
instance write the function that maps an argument ``z`` to ``2z + 1`` as
```julia
z -> 2z + 1
```
Let us now see how the phase of this function behaves in the complex
plane. First, if you haven't already, we need to load
`DomainColoring.jl` and an appropriate backend (our suggestion is
`GLMakie` if you're experimenting from the Julia REPL):
```@example
using CairoMakie, DomainColoring
```
Then a simple phase plot can be made using
```@example
using CairoMakie, DomainColoring # hide
domaincolor(z -> 2z + 1)
resize!(current_figure(), 620, 600) #hide
save("simplephaseexample.png", current_figure()) # hide
nothing # hide
```

As expected we see a zero of multiplicity one at ``-0.5``,
furthermore we see that `domaincolor` defaults to unit axis limits in
each direction.
Something useful to know about phase plots, the order of the colors
tells you more about the thing you are seeing:
- red, green and blue (anticlockwise) is a zero; and
- red, blue and green is a pole.
The number of times you go through these colors gives you the
multiplicity. A pole of multiplicity two gives for instance:
```@example
using CairoMakie, DomainColoring # hide
domaincolor(z -> 1 / z^2)
resize!(current_figure(), 620, 600) #hide
save("simplepoleexample.png", current_figure()) # hide
nothing # hide
```

We've now looked at poles and zeroes, another interesting effect to see
on a phase plot are
[branch cuts](https://en.wikipedia.org/wiki/Branch_point). Julia's
implementation of the square root has a branch cut on the negative real
axis, as we can see on the following figure.
```@example
using CairoMakie, DomainColoring # hide
domaincolor(sqrt, [-10, 2, -2, 2])
resize!(current_figure(), 620, 250) #hide
save("sqrtexample.png", current_figure()) # hide
nothing # hide
```

There are a couple of things of note here. First, Julia allows us to
simply pass `sqrt`, which here is equivalent to `z -> sqrt(z)`. Second,
`domaincolor` accepts axis limits as an optional second argument
(for those familiar with Julia: any indexable object will work).
Finally, branch cuts give discontinuities in the phase plot (identifying
these is greatly helped by the perceptual uniformity of the
[Phase Wheel](@ref) used).
We conclude by mentioning that you do not always need to specify all
limits explicitly. If you want to take the same limit in all four
directions you can simply pass that number. When you pass a vector with
only two elements, these will be taken symmetric in the real and
imaginary direction respectively. This way we can zoom in on the beauty
of the essential singularity of ``e^\frac{1}{z}``.
```@example
using CairoMakie, DomainColoring # hide
domaincolor(z -> exp(1/z), 0.5)
resize!(current_figure(), 620, 600) #hide
save("essentialsingexample.png", current_figure()) # hide
nothing # hide
```

## Plotting the `DomainColoring.jl` logo
As a final example, let us show off a few more capabilities of the
[`domaincolor`](@ref) function by plotting the `DomainColoring.jl` logo.
This is a plot of ``f(z) = z^3i - 1`` with level curves of the logarithm
of the magnitude and an integer grid. You can continue by reading the
[General Overview](@ref) to learn more about these and other additional
options, and the other provided plotting functions.
```@example
using CairoMakie, DomainColoring # hide
domaincolor(z -> im*z^3-1, 2.5, all=true)
resize!(current_figure(), 620, 600) #hide
save("logoexample.png", current_figure()) # hide
nothing # hide
```

| DomainColoring | https://github.com/eprovst/DomainColoring.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 604 | using Documenter, Ekztazy
makedocs(;
modules=[Ekztazy],
format=Documenter.HTML(),
pages=[
"Home" => "index.md",
"Types" => "types.md",
"Client" => "client.md",
"REST API" => "rest.md",
"Helpers" => "helpers.md",
"Events" => "events.md"
],
repo="https://github.com/Humans-of-Julia/Ekztazy.jl/blob/{commit}{path}#L{line}",
sitename="Ekztazy.jl",
authors="Xh4H <[email protected]>, christopher-dG <[email protected]> Kyando <[email protected]>",
)
deploydocs(;
repo="github.com/Humans-of-Julia/Ekztazy.jl",
)
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 327 | module Eval
using Ekztazy
c = Client()
g = ENV["TESTGUILD"]
command!(c, g, "eval", "evaluates a string as julia code", legacy=false, options=Options(
[String, "str", "the string to evaluate"]
)) do ctx, str::String
@info "$str"
reply(c, ctx, content="```julia\n$(eval(Meta.parse(str)))\n```")
end
start(c)
end | Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 1915 | module Ekztazy
using Dates
using Distributed
using HTTP
using InteractiveUtils
using JSON3
using StructTypes
using OpenTrick
using Setfield
using TimeToLive
const D1ZKORD_JL_VERSION = v"0.6.1"
const API_VERSION = 9
const DISCORD_API = "https://discordapp.com/api"
# Shortcuts for common unions.
const Optional{T} = Union{T, Missing}
const Nullable{T} = Union{T, Nothing}
const OptionalNullable{T} = Union{T, Missing, Nothing}
const StringOrChar = Union{AbstractString, AbstractChar}
# Shortcut functions .
jsonify(x) = JSON3.write(x)
# Constant functions.
donothing(args...; kwargs...) = nothing
alwaystrue(args...; kwargs...) = true
alwaysfalse(args...; kwargs...) = false
# Run a function with an acquired semaphore.
function withsem(f::Function, s::Base.Semaphore)
Base.acquire(s)
try f() finally Base.release(s) end
end
# Precompile all methods of a function, running it if force is set.
function compile(f::Function, force::Bool; kwargs...)
for m in methods(f)
types = Tuple(m.sig.types[2:end])
precompile(f, types)
force && try f(mock.(types; kwargs...)...) catch end
end
end
function method_argnames(m::Method)
argnames = ccall(:jl_uncompress_argnames, Vector{Symbol}, (Any,), m.slot_syms)
isempty(argnames) && return argnames
return argnames[2:m.nargs]
end
function method_argtypes(m::Method)
return m.sig.types[2:end]
end
"""
method_args(m::Method) -> Vector{Tuple{Symbol, Type}}
"""
function method_args(m::Method)
n, t, v = method_argnames(m), method_argtypes(m), []
for x = 1:length(n)
push!(v, (n[x], t[x]))
end
v
end
include(joinpath("utils", "consts.jl"))
include(joinpath("types", "types.jl"))
include(joinpath("client", "client.jl"))
include(joinpath("client", "handlers.jl"))
include(joinpath("gateway", "gateway.jl"))
include(joinpath("rest", "rest.jl"))
include(joinpath("utils", "helpers.jl"))
end | Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 11316 | export Client,
me,
enable_cache!,
disable_cache!,
start,
add_handler!
include("limiter.jl")
include("state.jl")
# Messages are created regularly, and lose relevance quickly.
const DEFAULT_STRATEGIES = Dict{DataType, CacheStrategy}(
Guild => CacheForever(),
DiscordChannel => CacheForever(),
User => CacheForever(),
Member => CacheForever(),
Presence => CacheForever(),
Message => CacheTTL(Hour(6)),
)
# A versioned WebSocket connection.
mutable struct Conn
io
v::Int
end
"""
Client(
token::String
application_id::Snowflake
intents::Int;
presence::Union{Dict, NamedTuple}=Dict(),
strategies::Dict{DataType, <:CacheStrategy}=Dict(),
version::Int=$API_VERSION,
) -> Client
A Discord bot. `Client`s can connect to the gateway, respond to events, and make REST API
calls to perform actions such as sending/deleting messages, kicking/banning users, etc.
### Bot Token
A bot token can be acquired by creating a new application
[here](https://discordapp.com/developers/applications). Make sure not to hardcode the token
into your Julia code! Use an environment variable or configuration file instead.
### Application ID
The application id for your bot can be found [here](https://discordapp.com/developers/applications).
Make sure not to hardcode the application id into your Julia code!
Use an environment variable or configuration file instead.
### Intents
Integer representing intents. More information [here](https://discord.com/developers/docs/topics/gateway#gateway-intents).
### Presence
The `presence` keyword sets the bot's presence upon connection. It also sets defaults
for future calls to [`set_game`](@ref). The schema
[here](https://discordapp.com/developers/docs/topics/gateway#update-status-gateway-status-update-structure)
must be followed.
### Cache Control
By default, most data that comes from Discord is cached for later use. However, to avoid
memory leakage, not all of it is kept forever. The default setings are to keep everything
but [`Message`](@ref)s, which are deleted after 6 hours, forever. Although the default
settings are sufficient for most workloads, you can specify your own strategies per type
with the `strategies` keyword. Keys can be any of the following:
- [`Guild`](@ref)
- [`DiscordChannel`](@ref)
- [`Message`](@ref)
- [`User`](@ref)
- [`Member`](@ref)
- [`Presence`](@ref)
For potential values, see [`CacheStrategy`](@ref).
The cache can also be disabled/enabled permanently and temporarily as a whole with
[`enable_cache!`](@ref) and [`disable_cache!`](@ref).
### API Version
The `version` keyword chooses the Version of the Discord API to use. Using anything but
`$API_VERSION` is not officially supported by the Ekztazy.jl developers.
### Sharding
Sharding is handled automatically. The number of available processes is the number of
shards that are created. See the
[sharding example](https://github.com/Xh4H/Discord.jl/blob/master/examples/sharding.jl)
for more details.
"""
mutable struct Client
token::AbstractString # Bot token
application_id::Snowflake # Application ID for Interactions
commands::Vector{ApplicationCommand} # Commands
guild_commands::Dict{Snowflake, Vector{ApplicationCommand}} # Guild commands
intents::Int # Intents value
handlers::Dict{Symbol, Vector{Handler}} # Handlers for each event
hb_interval::Int # Milliseconds between heartbeats.
hb_seq::Nullable{Int} # Sequence value sent by Discord for resuming.
last_hb::DateTime # Last heartbeat send.
last_ack::DateTime # Last heartbeat ack.
version::Int # Discord API version.
state::State # Client state, cached data, etc.
shards::Int # Number of shards in use.
shard::Int # Client's shard index.
limiter::Limiter # Rate limiter.
ready::Bool # Client is connected and authenticated.
use_cache::Bool # Whether or not to use the cache.
presence::Dict # Default presence options.
conn::Conn # WebSocket connection.
p_guilds::Dict{Snowflake, String} # Command prefix overrides.
no_auto_ack::Vector{String} # No auto ack custom ids.
auto_update_ack::Vector{String} # Auto ack for deferred message update custom ids.
function Client(
token::String,
application_id::Snowflake,
intents::Int;
# kwargs
presence::Union{Dict, NamedTuple}=Dict(),
strategies::Dict{DataType, <:CacheStrategy}=Dict{DataType, CacheStrategy}(),
version::Int=API_VERSION,
)
token = startswith(token, "Bot ") ? token : "Bot $token"
state = State(merge(DEFAULT_STRATEGIES, strategies))
app_id = application_id
conn = Conn(nothing, 0)
presence = merge(Dict(
"since" => nothing,
"game" => nothing,
"status" => "online", # Should make a const out of statuses
"afk" => false,
), Dict(string(k) => v for (k, v) in Dict(pairs(presence))))
c = new(
token, # token
app_id, # application_id
Vector(), # Commands
Dict(), # Guild commands
intents, # intents
Dict(), # handlers
0, # hb_interval
nothing, # hb_seq
DateTime(0), # last_hb
DateTime(0), # last_ack
version, # version
state, # state
nprocs(), # shards
myid() - 1, # shard
Limiter(), # limiter
false, # ready
true, # use_cache
presence, # presence
conn, # conn
Dict(), # p_guilds
[], # no_auto_ack
[] # auto_update_ack
)
return c
end
end
Client(token::String, appid::Int, intents::Int, args...) = Client(token, UInt(appid), intents, args...)
Client(in::Int) = Client(
ENV["DISCORD_TOKEN"],
ENV["APPLICATION_ID"] isa Number ? ENV["APPLICATION_ID"] : parse(UInt, ENV["APPLICATION_ID"]),
in
)
Client() = Client(intents(GUILDS, GUILD_MESSAGES))
add!(d::Dict{U, Union{Vector{T}}}, k::U, v::T) where T where U = haskey(d, k) ? push!(d[k], v) : d[k] = [v]
"""
add_handler!(c::Client, handler::Handler)
Adds a handler to the client.
"""
add_handler!(c::Client, handler::Handler) = add!(c.handlers, handlerkind(handler), handler)
"""
add_handler!(c::Client, handler::Handler)
Bulk adds handlers to the client.
"""
add_handler!(c::Client, args...) = map(h -> add_handler!(c, h), args)
add_command!(c::Client; kwargs...) = add_command!(c, ApplicationCommand(; application_id=c.application_id, kwargs...))
add_command!(c::Client, cmd::ApplicationCommand) = push!(c.commands, cmd)
add_command!(c::Client, args...) = map(cmd -> add_command!(c, cmd), args)
add_command!(c::Client, g::Snowflake; kwargs...) = add_command!(c, g, ApplicationCommand(; application_id=c.application_id, kwargs...))
add_command!(c::Client, g::Snowflake, cmd::ApplicationCommand) = add!(c.guild_commands, g, cmd)
add_command!(c::Client, g::Snowflake, args...) = map(cmd -> add_command!(c, g, cmd), args)
mock(::Type{Client}; kwargs...) = Client("token")
function Base.show(io::IO, c::Client)
print(io, "Discord.Client(shard=$(c.shard + 1)/$(c.shards), api=$(c.version), ")
isopen(c) || print(io, "not ")
print(io, "logged in)")
end
"""
me(c::Client) -> Nullable{User}
Get the [`Client`](@ref)'s bot user.
"""
me(c::Client) = c.state.user
"""
enable_cache!(c::Client)
enable_cache!(f::Function c::Client)
Enable the cache. `do` syntax is also accepted.
"""
enable_cache!(c::Client) = c.use_cache = true
enable_cache!(f::Function, c::Client) = set_cache(f, c, true)
"""
disable_cache!(c::Client)
disable_cache!(f::Function, c::Client)
Disable the cache. `do` syntax is also accepted.
"""
disable_cache!(c::Client) = c.use_cache = false
disable_cache!(f::Function, c::Client) = set_cache(f, c, false)
# Compute some contextual keywords for log messages.
function logkws(c::Client; kwargs...)
kws = Pair[:time => now()]
c.shards > 1 && push!(kws, :shard => c.shard)
c.conn.io === nothing || push!(kws, :conn => c.conn.v)
for kw in kwargs
if kw.second === undef # Delete any keys overridden with undef.
filter!(p -> p.first !== kw.first, kws)
else
# Replace any overridden keys.
idx = findfirst(p -> p.first === kw.first, kws)
if idx === nothing
push!(kws, kw)
else
kws[idx] = kw
end
end
end
return kws
end
# Parse some data (usually a Dict from JSON), or return the thrown error.
function Base.tryparse(c::Client, T::Type, data)
return try
T <: Vector ? eltype(T).(data) : T(data), nothing
catch e
kws = logkws(c; T=T, exception=(e, catch_backtrace()))
@error "Parsing failed" kws...
nothing, e
end
end
# Run some function with the cache enabled or disabled.
function set_cache(f::Function, c::Client, use_cache::Bool)
old = c.use_cache
c.use_cache = use_cache
try
f()
finally
# Usually the above function is going to be calling REST endpoints. The cache flag
# is checked asynchronously, so by the time it happens there's a good chance we've
# already returned and set the cache flag back to its original value.
sleep(Millisecond(1))
c.use_cache = old
end
end
"""
start(c::Client)
Creates a handler to generate [`ApplicationCommand`](@ref)s.\n
Creates handlers for GuildCreate events.\n
Calls `open` then `wait` on the [`Client`](@ref).
"""
function start(c::Client)
hcreate = OnGuildCreate() do (ctx)
put!(c.state, ctx.guild)
end
hupdate = OnGuildUpdate() do (ctx)
put!(c.state, ctx.guild)
end
hready = OnReady() do (ctx)
c.state.user = ctx.user
for (g, cmds) in c.guild_commands
create(c, Vector{ApplicationCommand}, g, cmds)
end
create(c, Vector{ApplicationCommand}, c.commands)
end
add_handler!(c, hcreate, hupdate, hready)
try
open(c)
wait(c)
catch err
if err isa InterruptException
close(c)
end
rethrow(err)
return
end
end | Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 8209 | export command!,
component!,
modal!,
select!
"""
command!(
f::Function
c::Client
name::AbstractString
description::AbstractString;
kwargs...
)
Adds a handler for INTERACTION CREATE gateway events where the InteractionData's `name` field matches `name`.
Adds this command to `c.commands` or `c.guild_commands` based on the presence of `guild`.
The `f` parameter signature should be:
```
(ctx::Context, args...) -> Any
```
Where args is a list of all the Command Options
For example a command that takes a user u and a number n as input should have this signature:
```
(ctx::Context, u::User, n::Int) -> Any
```
and the arguments would automatically get converted.
**Note:** The argument names **must** match the Option names. The arguments can be ordered in any way. If no type is specified, no conversion will be performed, so Discord objects will be `Snowflake`s.
"""
function command!(c::Client, f::Function, name::AbstractString, desc::AbstractString, legacy::Bool; auto_ack=true, kwargs...)
haskey(kwargs, :options) && check_option.(kwargs[:options])
namecheck(name, r"^[\w-]{1,32}$", 32, "ApplicationCommand Name")
namecheck(name, 100, "ApplicationCommand Description")
if !auto_ack push!(c.no_auto_ack, name) end
legacy ? add_handler!(c, OnInteractionCreate(f; name=name)) : add_handler!(c, OnInteractionCreate(generate_command_func(f); name=name))
end
function command!(f::Function, c::Client, name::AbstractString, description::AbstractString; legacy::Bool=true, auto_ack=true, kwargs...)
command!(c, f, name, description, legacy; auto_ack=auto_ack, kwargs...)
add_command!(c; name=name, description=description, kwargs...)
end
function command!(f::Function, c::Client, g::Number, name::AbstractString, description::AbstractString; legacy::Bool=true, auto_ack=true, kwargs...)
command!(c, f, name, description, legacy; auto_ack=auto_ack, kwargs...)
add_command!(c, Snowflake(g); name=name, description=description, kwargs...)
end
command!(f::Function, c::Client, g::String, name::AbstractString, description::AbstractString; kwargs...) = command!(f, c, parse(Int, g), name, description; kwargs...)
function modal!(f::Function, c::Client, custom_id::String, int::Interaction; kwargs...)
add_handler!(c, OnInteractionCreate(generate_command_func(f), custom_id=custom_id))
push!(c.no_auto_ack, custom_id)
respond_to_interaction_with_a_modal(c, int.id, int.token; custom_id=custom_id, kwargs...)
end
modal!(f::Function, c::Client, custom_id::String, ctx::Context; kwargs...) = modal!(f, c, custom_id, ctx.interaction; compkwfix(; kwargs...)...)
function check_option(o::ApplicationCommandOption)
namecheck(o.name, r"^[\w-]{1,32}$", 32, "ApplicationCommandOption Name")
namecheck(o.description, 100, "ApplicationCommandOption Description")
end
namecheck(val::String, patt::Regex, len::Int, of::String) = (!occursin(patt, val) || length(val) > len) && throw(NamingError(val, of))
namecheck(val::String, patt::Regex, of::String) = namecheck(val, patt, 32, of)
namecheck(val::String, len::Int, of::String) = namecheck(val, r"", len, of)
namecheck(val::String, of::String) = namecheck(val, 32, of)
function generate_command_func(f::Function)
args = handlerargs(f)
@debug "Generating typed args" args=args
g = (ctx::Context) -> begin
a = makeargs(ctx, args)
f(ctx, a...)
end
g
end
function generate_select_command_func(f::Function)
g = (ctx::Context) -> begin
f(ctx, ctx.interaction.data.values)
end
g
end
function makeargs(ctx::Context, args)
v = []
args = args[2:end]
if length(args) == 0
return v
end
o = opt(ctx)
for x = args
t = last(x)
arg = get(o, string(first(x)), :ERR)
push!(v, conv(t, arg, ctx))
end
v
end
function conv(::Type{T}, arg, ctx::Context) where T
if T in [String, Int, Bool, Any]
return arg
end
id = snowflake(arg)
if T == User
return ctx.interaction.data.resolved.users[id]
elseif T == Member
u = ctx.interaction.data.resolved.users[id]
m = ctx.interaction.data.resolved.members[id]
m.user = u
return m
elseif T == Role
return ctx.interaction.data.resolved.roles[id]
elseif T == DiscordChannel
return ctx.interaction.data.resolved.channels[id]
end
arg
end
"""
component!(
f::Function
c::Client
custom_id::AbstractString
kwargs...
)
Adds a handler for INTERACTION CREATE gateway events where the InteractionData's `custom_id` field matches `custom_id`.
The `f` parameter signature should be:
```
(ctx::Context) -> Any
```
"""
function component!(f::Function, c::Client, custom_id::AbstractString; auto_ack::Bool=true, auto_update_ack::Bool=true, kwargs...)
add_handler!(c, OnInteractionCreate(f; custom_id=custom_id))
if !auto_ack push!(c.no_auto_ack, custom_id) end
if auto_update_ack push!(c.auto_update_ack, custom_id) end
return Component(custom_id=custom_id; kwargs...)
end
"""
select!(
f::Function
c::Client
custom_id::AbstractString
args::Vector{Tuple}
kwargs...
)
Adds a handler for INTERACTION CREATE gateway events where the InteractionData's `custom_id` field matches `custom_id`.
The `f` parameter signature should be:
```
(ctx::Context, choices::Vector{String}) -> Any
```
"""
function select!(f::Function, c::Client, custom_id::AbstractString, args...; auto_ack::Bool=true, auto_update_ack::Bool=true, kwargs...)
add_handler!(c, OnInteractionCreate(generate_select_command_func(f); custom_id=custom_id))
if !auto_ack push!(c.no_auto_ack, custom_id) end
if auto_update_ack push!(c.auto_update_ack, custom_id) end
if length(args) == 0 throw(FieldRequired("options", "SelectOption")) end
return Component(custom_id=custom_id; options=[SelectOption(a...) for a in args], type=3, kwargs...)
end
"""
handle(
c::Client
handlers,
data
)
Determines whether handlers are appropriate to call and calls them if so.
Creates an `AbstractContext` based on the event using the `data` provided and passes it to the handler.
"""
function handle(c::Client, handlers::Vector{Handler}, data::Dict, t::Symbol)
ctx = context(t, data::Dict)
hasproperty(ctx, :interaction) && handle_ack(c, ctx)
isvalidcommand = (h) -> return (!hasproperty(h, :name) || (!ismissing(ctx.interaction.data.name) && h.name == ctx.interaction.data.name))
isvalidcomponent = (h) -> return (!hasproperty(h, :custom_id) || (!ismissing(ctx.interaction.data.custom_id) && h.custom_id == ctx.interaction.data.custom_id))
isvalid = (h) -> return isvalidcommand(h) && isvalidcomponent(h)
@debug "$(repr.(handlers))" currrent = repr(ctx)
for hh in handlers
isvalid(hh) && (runhandler(c, hh, ctx, t))
end
end
function handle_ack(c::Client, ctx::Context)
iscomp = !ismissing(ctx.interaction.data.custom_id)
!ismissing(ctx.interaction.data.type) && ctx.interaction.data.type == 5 && return
if !iscomp || !(ctx.interaction.data.custom_id in c.no_auto_ack)
@debug "Acking interaction" name=ctx.interaction.data.name custom_id=ctx.interaction.data.custom_id
if iscomp && (ctx.interaction.data.custom_id in c.auto_update_ack)
update_ack_interaction(c, ctx.interaction.id, ctx.interaction.token)
elseif (!ismissing(ctx.interaction.data.name) && !(ctx.interaction.data.name in c.no_auto_ack)) || iscomp
ack_interaction(c, ctx.interaction.id, ctx.interaction.token)
end
end
end
"""
Runs a handler with given context
"""
function runhandler(c::Client, h::Handler, ctx::Context, t::Symbol)
@debug "Running handler" h=Handler type=t
@spawn begin try h.f(ctx) catch e
kws = logkws(c; handler=t, exception=(e, catch_backtrace()))
@warn "Handler errored" kws...
end end
end
"""
Calls handle with a list of all found handlers.
"""
function handle(c::Client, t::Symbol, data::Dict)
haskey(c.handlers, t) ? handle(c, c.handlers[t], data, t) : return nothing
end | Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 4545 | const MESSAGES_REGEX = r"^/channels/\d+/messages/\d+$"
const ENDS_MAJOR_ID_REGEX = r"(?:channels|guilds|webhooks)/\d+$"
const ENDS_ID_REGEX = r"/\d+$"
const EXCEPT_TRAILING_ID_REGEX = r"(.*?)/\d+$"
# A rate limited job queue for one endpoint.
mutable struct JobQueue
remaining::Nullable{Int}
reset::Nullable{DateTime} # UTC.
jobs::Channel{Function} # These functions must return an HTTP response.
retries::Channel{Function} # Jobs which must be retried (higher priority).
function JobQueue(endpoint::AbstractString, limiter)
q = new(nothing, nothing, Channel{Function}(Inf), Channel{Function}(Inf))
@spawn while true
# Get a job, prioritizing retries. This is really ugly.
local f = nothing
while true
if isready(q.retries)
f = take!(q.retries)
break
elseif isready(q.jobs)
f = take!(q.jobs)
break
end
sleep(Millisecond(10))
end
# Wait for any existing rate limits.
# TODO: Having the shard index would be nice for logging here.
n = now(UTC)
if limiter.reset !== nothing && n < limiter.reset
time = limiter.reset - n
@debug "Waiting for global rate limit" time=now() sleep=time
sleep(time)
end
n = now(UTC)
if q.remaining == 0 && q.reset !== nothing && n < q.reset
time = q.reset - n
@debug "Waiting for rate limit" time=now() endpoint=endpoint sleep=time
sleep(time)
end
# Run the job, and get the HTTP response.
r = f()
@debug "Ran the job!"
if r === nothing
# Exception from the HTTP request itself, nothing to do.
@debug "Got an error"
@async put!(q.retries, f)
elseif r.status == 429
# Update the rate limiter with the response body.
@warn "Rate limited"
@async begin
n = now(UTC)
d = JSON3.read(String(copy(r.body)))
reset = n + Millisecond(get(d, "retry_after", 0))
if get(d, "global", false)
limiter.reset = reset
else
q.remaining = 0
q.reset = reset
end
end
# Requeue the job with high priority.
put!(q.retries, f)
else
# Update the rate limiter with the response headers.
@debug "Updated limiter"
rem = HTTP.header(r, "X-RateLimit-Remaining")
isempty(rem) || (q.remaining = parse(Int, rem))
res = HTTP.header(r, "X-RateLimit-Reset")
@async begin
if !isempty(res)
tim = parse(Int, res)
q.reset = unix2datetime(tim)
end
end
end
@debug "Finished rate limit job handling"
end
return q
end
end
# A rate limiter for all endpoints.
mutable struct Limiter
reset::Nullable{DateTime} # API-wide limit.
queues::Dict{String, JobQueue}
sem::Base.Semaphore
Limiter() = new(nothing, Dict(), Base.Semaphore(1))
end
# Schedule a job.
function enqueue!(f::Function, l::Limiter, method::Symbol, endpoint::AbstractString)
endpoint = parse_endpoint(endpoint, method)
withsem(l.sem) do
haskey(l.queues, endpoint) || (l.queues[endpoint] = JobQueue(endpoint, l))
end
put!(l.queues[endpoint].jobs, f)
end
# Get the endpoint which corresponds to its own rate limit.
function parse_endpoint(endpoint::AbstractString, method::Symbol)
return if method === :DELETE && match(MESSAGES_REGEX, endpoint) !== nothing
# Special case 1: Deleting messages has its own rate limit.
first(match(EXCEPT_TRAILING_ID_REGEX, endpoint).captures) * " $method"
elseif startswith(endpoint, "/invites/")
# Special case 2: Invites are identified by a non-numeric code.
"/invites"
elseif match(ENDS_MAJOR_ID_REGEX, endpoint) !== nothing
endpoint
elseif match(ENDS_ID_REGEX, endpoint) !== nothing
first(match(EXCEPT_TRAILING_ID_REGEX, endpoint).captures)
else
endpoint
end
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 12019 | export CacheForever,
CacheNever,
CacheTTL,
CacheLRU,
CacheFilter
# TODO: Strategy composition, e.g. TTL eviction with filtered insertion.
"""
A method of handling cache insertion and eviction.
"""
abstract type CacheStrategy end
"""
CacheForever() -> CacheForever
Store everything and never evict items from the cache.
"""
struct CacheForever <: CacheStrategy end
"""
CacheNever() -> CacheNever
Don't store anything in the cache.
"""
struct CacheNever <: CacheStrategy end
"""
CacheTTL(ttl::Period) -> CacheTTL
Evict items from the cache after `ttl` has elapsed.
"""
struct CacheTTL <: CacheStrategy
ttl::Period
end
"""
CacheLRU(size::Int) -> CacheLRU
Evict the least recently used item from the cache when there are more than `size` items.
"""
struct CacheLRU <: CacheStrategy
size::Int
end
"""
CacheFilter(f::Function) -> CacheFilter
Only store value `v` at key `k` if `f(v) === true` (`k` is always `v.id`).
"""
struct CacheFilter <: CacheStrategy
f::Function
end
# A dict-like object with a caching strategy.
struct Store{D <: AbstractDict, S <: CacheStrategy}
data::D
strat::S
Store(d::D, s::CacheStrategy) where D = new{D, typeof(s)}(d, s)
end
Store(::CacheForever, V::Type) = Store(Dict{Snowflake, V}(), CacheForever())
Store(::CacheNever, V::Type) = Store(Dict{Snowflake, V}(), CacheNever())
Store(s::CacheTTL, V::Type) = Store(TTL{Snowflake, V}(s.ttl), s)
Store(s::CacheLRU, V::Type) = Store(LRU{Snowflake, V}(s.size), s)
Store(s::CacheFilter, V::Type) = Store(Dict{Snowflake, V}(), s)
Base.eltype(s::Store) = eltype(s.data)
Base.get(s::Store, key, default) = get(s.data, key, default)
Base.getindex(s::Store, key) = s.data[key]
Base.haskey(s::Store, key) = haskey(s.data, key)
Base.isempty(s::Store) = isempty(s.data)
Base.keys(s::Store) = keys(s.data)
Base.values(s::Store) = values(s.data)
Base.length(s::Store) = length(s.data)
Base.iterate(s::Store) = iterate(s.data)
Base.iterate(s::Store, i) = iterate(s.data, i)
Base.touch(s::Store, k) = nothing
Base.delete!(s::Store, key) = (delete!(s.data, key); s)
Base.empty!(s::Store) = (empty!(s.data); s)
Base.filter!(f, s::Store) = (filter!(s.data); s)
Base.setindex!(s::Store, value, key) = (setindex!(s.data, value, key); s)
Base.touch(s::Store{<:AbstractDict, CacheTTL}, key) = touch(s.data, key)
Base.setindex!(s::Store{<:AbstractDict, CacheNever}, value, key) = s
function Base.setindex!(s::Store{<:AbstractDict, CacheFilter}, value, key)
try
s.strat.f(value) === true && setindex!(s.data, value, key)
catch
# TODO: Log this?
end
return s
end
# Container for all client state.
mutable struct State
v::Int # Discord API version.
session_id::String # Gateway session ID.
_trace::Vector{String} # Servers (not guilds) connected to.
user::Nullable{User} # Bot user.
guilds::Store # Guild ID -> guild.
channels::Store # Channel ID -> channel.
users::Store # User ID -> user.
messages::Store # Message ID -> message.
presences::Dict{Snowflake, Store} # Guild ID -> user ID -> presence.
members::Dict{Snowflake, Store} # Guild ID -> member ID -> member.
sem::Base.Semaphore # Internal mutex.
strats::Dict{DataType, CacheStrategy} # Caching strategies per type.
end
function State(strats::Dict{DataType, <:CacheStrategy})
return State(
0, # v
"", # session_id
[], # _trace
nothing, # user
Store(strats[Guild], AbstractGuild), # guilds
Store(strats[DiscordChannel], DiscordChannel), # channels
Store(strats[User], User), # users
Store(strats[Message], Message), # messages
Dict(), # presences
Dict(), # members
Base.Semaphore(1), # sem
strats, # strats
)
end
Store(s::State, T::Type) = Store(get(s.strats, T, CacheForever()), T)
# Base.get retrieves a value of a given type from the cache, or returns nothing.
Base.get(s::State, ::Type; kwargs...) = nothing
Base.get(s::State, ::Type{User}; kwargs...) = get(s.users, kwargs[:user], nothing)
Base.get(s::State, ::Type{Message}; kwargs...) = get(s.messages, kwargs[:message], nothing)
# Get a single channel.
function Base.get(s::State, ::Type{DiscordChannel}; kwargs...)
return get(s.channels, kwargs[:channel], nothing)
end
# Get all the channels of a guild.
function Base.get(s::State, ::Type{Vector{DiscordChannel}}; kwargs...)
guild = kwargs[:guild]
haskey(s.guilds, guild) || return nothing
channels = map(
i -> s.channels[i],
Iterators.filter(i -> haskey(s.channels, i), collect(s.guilds[guild].djl_channels)),
)
return isempty(channels) ? nothing : channels
end
function Base.get(s::State, ::Type{Presence}; kwargs...)
guild = kwargs[:guild]
haskey(s.presences, guild) || return nothing
return get(s.presences[guild], kwargs[:user], nothing)
end
function Base.get(s::State, ::Type{Guild}; kwargs...)
haskey(s.guilds, kwargs[:guild]) || return nothing
g = s.guilds[kwargs[:guild]]
# Guilds are stored with missing channels, members, and presences.
g = @set g.channels = map(
ch -> s.channels[ch],
Iterators.filter(ch -> haskey(s.channels, ch), collect(g.djl_channels)),
)
g = @set g.djl_channels = missing
ms = get(s.members, g.id, Dict())
g = @set g.members = map(
i -> get(s, Member; guild=g.id, user=i),
Iterators.filter(i -> haskey(ms, i), collect(coalesce(g.djl_users, Member[]))),
)
ps = get(s.presences, g.id, Dict())
g = @set g.presences = map(
i -> get(s, Presence; guild=g.id, user=i),
Iterators.filter(i -> haskey(ps, i), collect(coalesce(g.djl_users, Presence[]))),
)
g = @set g.djl_users = missing
return g
end
function Base.get(s::State, ::Type{Member}; kwargs...)
# Members are stored with missing user.
haskey(s.members, kwargs[:guild]) || return nothing
guild = s.members[kwargs[:guild]]
haskey(guild, kwargs[:user]) || return nothing
member = guild[kwargs[:user]]
haskey(s.users, kwargs[:user]) || return member # With a missing user field.
user = s.users[kwargs[:user]]
return @set member.user = user
end
function Base.get(s::State, ::Type{Role}; kwargs...)
haskey(s.guilds, kwargs[:guild]) || return nothing
roles = coalesce(s.guilds[kwargs[:guild]].roles, Role[])
idx = findfirst(r -> r.id == kwargs[:role], roles)
return idx === nothing ? nothing : roles[idx]
end
# Base.put! inserts a value into the cache, and returns the updated value.
Base.put!(s::State, val; kwargs...) = val
Base.put!(s::State, g::UnavailableGuild; kwargs...) = insert_or_update!(s.guilds, g)
Base.put!(s::State, ms::Vector{Member}; kwargs...) = map(m -> put!(s, m; kwargs...), ms)
Base.put!(s::State, u::User; kwargs...) = insert_or_update!(s.users, u)
function Base.put!(s::State, m::Message; kwargs...)
if ismissing(m.guild_id) && haskey(s.channels, m.channel_id)
m = @set m.guild_id = s.channels[m.channel_id].guild_id
end
insert_or_update!(s.messages, m)
touch(s.channels, m.channel_id)
touch(s.guilds, m.guild_id)
return m
end
function Base.put!(s::State, g::Guild; kwargs...)
# Replace members and presences with IDs that can be looked up later.
ms = coalesce(g.members, Member[])
ps = coalesce(g.presences, Presence[])
users = map(m -> m.user.id, Iterators.filter(m -> m.user !== nothing, ms))
unique!(append!(users, map(p -> p.user.id, ps)))
g = @set g.members = missing
g = @set g.presences = missing
g = @set g.djl_users = Set(users)
chs = coalesce(g.channels, DiscordChannel[])
channels = map(ch -> ch.id, chs)
g = @set g.djl_channels = Set(channels)
g = @set g.channels = missing
insert_or_update!(s.guilds, g)
put!(s, chs; kwargs..., guild=g.id)
foreach(m -> put!(s, m; kwargs..., guild=g.id), ms)
foreach(p -> put!(s, p; kwargs..., guild=g.id), ps)
return get(s, Guild; guild=g.id)
end
function Base.put!(s::State, ms::Vector{Message}; kwargs...)
return map(m -> put!(s, m; kwargs...), ms)
end
function Base.put!(s::State, ch::DiscordChannel; kwargs...)
if ismissing(ch.guild_id) && get(kwargs, :guild, nothing) !== nothing
ch = @set ch.guild_id = kwargs[:guild]
end
foreach(u -> put!(s, u; kwargs...), coalesce(ch.recipients, User[]))
haskey(s.guilds, ch.guild_id) && push!(s.guilds[ch.guild_id].djl_channels, ch.id)
return insert_or_update!(s.channels, ch)
end
function Base.put!(s::State, chs::Vector{DiscordChannel}; kwargs...)
return map(ch -> put!(s, ch; kwargs...), chs)
end
function Base.put!(s::State, p::Presence; kwargs...)
guild = coalesce(get(kwargs, :guild, missing), p.guild_id)
ismissing(guild) && return p
if haskey(s.guilds, guild)
g = s.guilds[guild]
g isa Guild && push!(g.djl_users, p.user.id)
end
haskey(s.presences, guild) || (s.presences[guild] = Store(s, Presence))
return insert_or_update!(s.presences[guild], p.user.id, p)
end
function Base.put!(s::State, m::Member; kwargs...)
ismissing(m.user) && return m
guild = kwargs[:guild]
# Members are stored with a missing user field to save memory.
user = m.user
m = @set m.user = missing
# This is a bit ugly, but basically we're updating the member as usual but then
# filling in its user field at the same time as the user sync.
haskey(s.members, guild) || (s.members[guild] = Store(s, Member))
m = insert_or_update!(s.members[guild], user.id, m)
m = @set m.user = insert_or_update!(s.users, user)
if haskey(s.guilds, guild)
g = s.guilds[guild]
g isa Guild && push!(g.djl_users, user.id)
end
return m
end
function Base.put!(s::State, r::Role; kwargs...)
guild = kwargs[:guild]
haskey(s.guilds, guild) || return r
g = s.guilds[guild]
g isa Guild || return r
return if ismissing(g.roles)
s.guilds[guild] = @set g.roles = [r]
r
else
insert_or_update!(g.roles, r)
end
end
# This handles emojis being added to a guild.
function Base.put!(s::State, es::Vector{Emoji}; kwargs...)
guild = kwargs[:guild]
haskey(s.guilds, guild) || return es
g = s.guilds[guild]
g isa Guild || return es
s.guilds[guild] = @set g.emojis = es
return es
end
# This handles a single emoji being added as a reaction.
function Base.put!(s::State, e::Emoji; kwargs...)
message = kwargs[:message]
user = kwargs[:user]
haskey(s.messages, message) || return e
withsem(s.sem) do
m = s.messages[message]
isclient = !ismissing(s.user) && s.user.id == user
if ismissing(m.reactions)
s.messages[message] = @set m.reactions = [Reaction(1, isclient, e)]
else
idx = findfirst(r -> r.emoji.name == e.name, m.reactions)
if idx === nothing
push!(m.reactions, Reaction(1, isclient, e))
else
r = m.reactions[idx]
r = @set r.count += 1
r = @set r.me |= isclient
r = @set r.emoji = merge(r.emoji, e)
m.reactions[idx] = r
end
end
end
return e
end
# Insert or update a value in the cache.
insert_or_update!(d, k, v; kwargs...) = d[k] = haskey(d, k) ? merge(d[k], v) : v
function insert_or_update!(d::Vector, k, v; key::Function=x -> x.id)
idx = findfirst(x -> key(x) == k, d)
return if idx === nothing
push!(d, v)
v
else
d[idx] = merge(d[idx], v)
end
end
function insert_or_update!(d, v; key::Function=x -> x.id)
insert_or_update!(d, key(v), v; key=key)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 12424 | export request_guild_members,
update_voice_status,
update_status,
update_presence
const conn_properties = Dict(
"\$os" => string(Sys.KERNEL),
"\$browser" => "Discord.jl",
"\$device" => "Discord.jl",
)
const OPCODES = Dict(
0 => :DISPATCH,
1 => :HEARTBEAT,
2 => :IDENTIFY,
3 => :STATUS_UPDATE,
4 => :VOICE_STATUS_UPDATE,
6 => :RESUME,
7 => :RECONNECT,
8 => :REQUEST_GUILD_MEMBERS,
9 => :INVALID_SESSION,
10 => :HELLO,
11 => :HEARTBEAT_ACK,
)
struct Empty <: Exception end
# Connection.
"""
open(c::Client; delay::Period=Second(7))
Connect a [`Client`](@ref) to the Discord gateway.
The `delay` keyword is the time between shards connecting. It can be increased from its
default if you are using multiple shards and frequently experiencing invalid sessions upon
connection.
"""
function Base.open(c::Client; resume::Bool=false, delay::Period=Second(7))
isopen(c) && throw(ArgumentError("Client is already connected"))
c.ready = false
# Clients can only identify once per 5 seconds.
resume || sleep(c.shard * delay)
@debug "Requesting gateway URL" logkws(c; conn=undef)...
resp = try
HTTP.get("$DISCORD_API/v$(c.version)/gateway")
catch e
kws = logkws(c; conn=undef, exception=(e, catch_backtrace()))
@error "Getting gateway URL failed" kws...
rethrow(e)
end
data = JSON3.read(String(resp.body))
url = "$(data["url"])?v=$(c.version)&encoding=json"
c.conn.v += 1
@debug "Connecting to gateway" logkws(c; conn=c.conn.v, url=url)...
c.conn.io = opentrick(HTTP.WebSockets.open, url)
@debug "Receiving HELLO" logkws(c)...
data, e = readjson(c.conn.io)
op = get(OPCODES, data[:op], data[:op])
if op !== :HELLO
msg = "Expected opcode HELLO, received $op"
@error msg logkws(c)...
error(msg)
end
hello(c, data)
data = if resume
Dict("op" => 6, "d" => Dict(
"token" => c.token,
"intents" => c.intents,
"session_id" => c.state.session_id,
"seq" => c.hb_seq,
))
else
d = Dict("op" => 2, "s" => c.hb_seq, "d" => Dict(
"token" => c.token,
"intents" => c.intents,
"properties" => conn_properties,
))
isempty(c.presence) || (d["d"]["presence"] = c.presence)
c.shards > 1 && (d["d"]["shard"] = [c.shard, c.shards])
d
end
op = resume ? :RESUME : :IDENTIFY
@debug "Writing $op" logkws(c)...
try
writejson(c.conn.io, data)
catch e
kws = logkws(c; exception=(e, catch_backtrace()))
@error "Writing $op failed" kws...
rethrow(e)
end
@debug "Starting background maintenance tasks" logkws(c)...
@spawn heartbeat_loop(c)
@spawn read_loop(c)
c.ready = true
end
"""
isopen(c::Client) -> Bool
Determine whether the [`Client`](@ref) is connected to the gateway.
"""
Base.isopen(c::Client) = c.ready && c.conn.io !== nothing && isopen(c.conn.io)
"""
close(c::Client)
Disconnect the [`Client`](@ref) from the gateway.
"""
function Base.close(c::Client; statuscode::Int=1000, zombie::Bool=false)
isopen(c) || return
c.ready = false
if zombie
# It seems that Discord doesn't send a closing frame for zombie connections
# (which makes sense). However, close waits for one forever (see HTTP.jl#350).
@async close(c.conn.io; statuscode=statuscode)
sleep(1)
else
close(c.conn.io; statuscode=statuscode)
end
end
"""
wait(c::Client)
Wait for an open [`Client`](@ref) to close.
"""
function Base.wait(c::Client)
while isopen(c)
wait(c.conn.io.cond)
# This is an arbitrary amount of time to wait,
# but we want to wait long enough to potentially reconnect.
sleep(10)
end
end
# Gateway commands.
"""
request_guild_members(
c::Client,
guilds::Union{Integer, Vector{<:Integer};
query::AbstractString="",
limit::Int=0,
) -> Bool
Request offline guild members of one or more [`Guild`](@ref)s. [`on_guild_members_chunk!`](@ref)
events are sent by the gateway in response.
More details [here](https://discordapp.com/developers/docs/topics/gateway#request-guild-members).
"""
function request_guild_members(
c::Client,
guild::Integer;
query::AbstractString="",
limit::Int=0,
)
return request_guild_members(c, [guild]; query=query, limit=limit)
end
function request_guild_members(
c::Client,
guilds::Vector{<:Integer};
query::AbstractString="",
limit::Int=0,
)
e, bt = trywritejson(c.conn.io, Dict("op" => 8, "d" => Dict(
"guild_id" => guilds,
"query" => query,
"limit" => limit,
)))
show_gateway_error(c, e, bt)
return e === nothing
end
"""
update_voice_state(
c::Client,
guild::Integer,
channel::Nullable{Integer},
mute::Bool,
deaf::Bool,
) -> Bool
Join, move, or disconnect from a voice channel. A `VoiceStateUpdate` event is sent
by the gateway in response.
More details [here](https://discordapp.com/developers/docs/topics/gateway#update-voice-state).
"""
function update_voice_state(
c::Client,
guild::Integer,
channel::Nullable{Integer},
mute::Bool,
deaf::Bool,
)
e, bt = trywritejson(c.conn.io, Dict("op" => 4, "d" => Dict(
"guild_id" => guild,
"channel_id" => channel,
"self_mute" => mute,
"self_deaf" => deaf,
)))
show_gateway_error(c, e, bt)
return e === nothing
end
"""
update_status(
c::Client,
since::Nullable{Int},
activity::Nullable{Activity},
status::Union{PresenceStatus, AbstractString},
afk::Bool,
) -> Bool
Indicate a presence or status update. A `PresenceUpdate` event is sent by the
gateway in response.
More details [here](https://discordapp.com/developers/docs/topics/gateway#update-status).
"""
function update_status(
c::Client,
since::Nullable{Int},
game::Union{Dict, NamedTuple, Activity, Nothing},
status::Union{Int, AbstractString},
afk::Bool,
)
# Update defaults for future calls to set_game.
c.presence["since"] = since
c.presence["game"] = game
c.presence["status"] = status
c.presence["afk"] = afk
e, bt = trywritejson(c.conn.io, Dict("op" => 3, "d" => Dict(
"since" => since,
"game" => game,
"status" => status,
"afk" => afk,
)))
show_gateway_error(c, e, bt)
return e === nothing
end
# Client maintenance.
# Continuously send the heartbeat.
function heartbeat_loop(c::Client)
v = c.conn.v
try
sleep(rand(1:round(Int, c.hb_interval / 1000)))
heartbeat(c) || (isopen(c) && @error "Writing HEARTBEAT failed" logkws(c)...)
while c.conn.v == v && isopen(c)
sleep(c.hb_interval / 1000)
if c.last_hb > c.last_ack && isopen(c) && c.conn.v == v
@debug "Encountered zombie connection" logkws(c)...
reconnect(c; zombie=true)
elseif !heartbeat(c) && c.conn.v == v && isopen(c)
@error "Writing HEARTBEAT failed" logkws(c)...
end
end
@debug "Heartbeat loop exited" logkws(c; conn=v)...
catch e
kws = logkws(c; conn=v, exception=(e, catch_backtrace()))
@warn "Heartbeat loop exited unexpectedly" kws...
end
end
# Continuously read and respond to messages.
function read_loop(c::Client)
v = c.conn.v
try
while c.conn.v == v && isopen(c)
data, e = readjson(c.conn.io)
if e !== nothing
if c.conn.v == v
handle_read_exception(c, e)
else
@debug "Read failed, but the connection is outdated" logkws(c; error=e)...
end
elseif haskey(HANDLERS, data[:op])
HANDLERS[data[:op]](c, data)
else
@warn "Unkown opcode" logkws(c; op=data[:op])...
end
end
@debug "Read loop exited" logkws(c; conn=v)...
catch e
kws = logkws(c; conn=v, exception=(e, catch_backtrace()))
@warn "Read loop exited unexpectedly" kws...
c.ready && reconnect(c; zombie=true)
end
end
# Dispatch an event to its handlers.
function dispatch(c::Client, data::Dict)
T = get(EVENT_TYPES, data[:t], :UnknownEvent)
handle(c::Client, Symbol("On"*String(T))::Symbol, data[:d]::Dict)
end
dispatch(c::Client; kwargs...) = dispatch(c::Client, Dict(kwargs))
# Send a heartbeat.
function heartbeat(c::Client, ::Dict=Dict())
isopen(c) || return false
e, bt = trywritejson(c.conn.io, Dict("op" => 1, "d" => c.hb_seq))
show_gateway_error(c, e, bt)
ok = e === nothing
ok && (c.last_hb = now())
return ok
end
# Reconnect to the gateway.
function reconnect(c::Client, ::Dict=Dict(); resume::Bool=true, zombie::Bool=false)
@info "Reconnecting" logkws(c; resume=resume, zombie=zombie)...
try
close(c; zombie=zombie, statuscode=resume ? 4000 : 1000)
catch ex
@warn "Unable to close existing connection" ex
end
open(c; resume=resume)
end
# React to an invalid session.
function invalid_session(c::Client, data::Dict)
@warn "Received INVALID_SESSION" logkws(c; resumable=data[:d])...
sleep(rand(1:5))
reconnect(c; resume=data[:d])
end
# React to a hello message.
hello(c::Client, data::Dict) = c.hb_interval = data[:d][:heartbeat_interval]
# React to a heartbeack ack.
heartbeat_ack(c::Client, ::Dict) = c.last_ack = now()
# Gateway opcodes => handler function.
const HANDLERS = Dict(
0 => dispatch,
1 => heartbeat,
7 => reconnect,
9 => invalid_session,
10 => hello,
11 => heartbeat_ack,
)
# Error handling.
const CLOSE_CODES = Dict(
1000 => :NORMAL,
4000 => :UNKNOWN_ERROR,
4001 => :UNKNOWN_OPCODE,
4002 => :DECODE_ERROR, # Probably a library bug.
4003 => :NOT_AUTHENTICATED, # Probably a library bug.
4004 => :AUTHENTICATION_FAILED,
4005 => :ALREADY_AUTHENTICATED,
4007 => :INVALID_SEQ, # Probably a library bug.
4008 => :RATE_LIMITED, # Probably a library bug.
4009 => :SESSION_TIMEOUT,
4010 => :INVALID_SHARD,
4011 => :SHARDING_REQUIRED,
)
# Deal with an error from reading a message.
function handle_read_exception(c::Client, e::Exception)
@debug "Handling a $(typeof(e))" logkws(c; error=e)...
c.ready && handle_specific_exception(c, e)
end
handle_specific_exception(::Client, ::Empty) = nothing
handle_specific_exception(c::Client, ::EOFError) = reconnect(c)
function handle_specific_exception(c::Client, e::HTTP.WebSockets.WebSocketError)
err = get(CLOSE_CODES, e.status, :UNKNOWN_ERROR)
if err === :NORMAL
close(c)
elseif err === :AUTHENTICATION_FAILED
@error "Authentication failed" logkws(c)...
close(c)
elseif err === :INVALID_SHARD
@error "Invalid shard" logkws(c)...
close(c)
elseif err === :SHARDING_REQUIRED
@error "Sharding required" logkws(c)...
close(c)
else
@debug "Gateway connection was closed" logkws(c; code=e.status, error=err)...
reconnect(c)
end
end
function handle_specific_exception(c::Client, e::Exception)
@error sprint(showerror, e) logkws(c)...
isopen(c) || reconnect(c)
end
# Read a JSON message.
function readjson(io)
data = readavailable(io)
if isempty(data)
nothing, Empty()
else
k , v = JSON3.read(String(data), Dict), nothing
symk = symbolize(k)
return symk, v
end
end
# Write a JSON message.
writejson(::Nothing, body) = error("Tried to write to an uninitialized connection")
writejson(io, body) = write(io, jsonify(body))
# Write a JSON message, but don't throw an exception.
function trywritejson(io, body)
return try
writejson(io, body)
nothing, nothing
catch e
e, catch_backtrace()
end
end
# Display a gateway error.
show_gateway_error(c::Client, ::Nothing, ::Nothing) = nothing
function show_gateway_error(c::Client, e::Exception, bt)
kws = logkws(c; exception=(e, bt))
if isopen(c)
@error "Gateway error" kws...
else
@debug "Gateway error" kws...
end
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 6302 | export fetchval
const SHOULD_SEND = Dict(:PATCH => true, :POST => true, :PUT => true)
"""
A wrapper around a response from the REST API. Every function which wraps a Discord REST
API endpoint returns a `Future` which will contain a value of this type. To retrieve the
`Response` from the `Future`, use `fetch`. See also: [`fetchval`](@ref).
## Fields
- `val::Nullable{T}`: The object contained in the HTTP response. For example, for a
call to [`get_channel_message`](@ref), this value will be a [`Message`](@ref).
- `ok::Bool`: The state of the request. If `true`, then it is safe to access `val`.
- `http_response::Nullable{HTTP.Messages.Response}`: The underlying HTTP response, if
a request was made.
- `exception::Nullable{Exception}`: The caught exception, if one is thrown.
## Examples
Multiple API calls which immediately return `Future`s and can be awaited:
```julia
futures = map(i -> create_message(c, channel_id; content=string(i)), 1:10);
other_work_here()
resps = fetch.(futures)
```
Skipping error checks and returning the value directly:
```julia
guild = fetchval(create_guild(c; name="foo"))
```
"""
struct Response{T}
val::Nullable{T}
ok::Bool
http_response::Nullable{HTTP.Messages.Response}
exception::Nullable{Exception}
end
# HTTP response with no body.
function Response{Nothing}(r::HTTP.Messages.Response)
return Response{Nothing}(nothing, r.status < 300, r, nothing)
end
# HTTP response with body (maybe).
function Response{T}(c::Client, r::HTTP.Messages.Response) where T
if T == Nothing
return Response{Nothing}(r)
end
r.status == 204 && return Response{T}(nothing, true, r, nothing)
r.status >= 300 && return Response{T}(nothing, false, r, nothing)
val = if HTTP.header(r, "Content-Type") == "application/json"
symbolize(JSON3.read(String(copy(r.body)), T))
else
copy(r.body)
end
return Response{T}(val, true, r, nothing)
end
# HTTP request with no expected response body.
function Response(
c::Client,
method::Symbol,
endpoint::AbstractString;
body="",
kwargs...
)
return Response{Nothing}(c, method, endpoint; body=body, kwargs...)
end
# HTTP request.
function Response{T}(
c::Client,
method::Symbol,
endpoint::AbstractString,
cachetest::Function=alwaystrue;
headers=Dict(),
body=HTTP.nobody,
kwargs...
) where T
f = Future()
@spawn begin
kws = (
channel=cap("channels", endpoint),
guild=cap("guilds", endpoint),
message=cap("messages", endpoint),
user=cap("users", endpoint),
)
# Retrieve the value from the cache, maybe.
@debug "Preparing Request: Looking in cache" Time=now()
if c.use_cache && method === :GET
val = get(c.state, T; kws...)
if val !== nothing
try
# Only use the value if it satisfies the cache test.
if cachetest(val) === true
put!(f, Response{T}(val, true, nothing, nothing))
return
end
catch
# TODO: Log this?
end
end
end
# Prepare the request.
url = "$DISCORD_API/v$(c.version)$endpoint"
@debug "Preparing Request: Did not find in cache, preparing request" Time=now()
isempty(kwargs) || (url *= "?" * HTTP.escapeuri(kwargs))
headers = merge(Dict(
"User-Agent" => "Discord.jl $D1ZKORD_JL_VERSION",
"Content-Type" => "application/json",
"Authorization" => c.token,
), Dict(headers))
args = [method, url, headers]
@debug "Preparing Request: Type of request: $T" Time=now()
if get(SHOULD_SEND, method, false)
push!(args, headers["Content-Type"] == "application/json" ? JSON3.write(body) : body)
end
@debug "Preparing Request: Enqueuing request" Time=now()
# Queue a job to be run within the rate-limiting constraints.
enqueue!(c.limiter, method, endpoint) do
@debug "Enqueued job running"
http_r = nothing
try
# Make an HTTP request, and generate a Response.
# If we hit an upstream rate limit, return the response immediately.
http_r = HTTP.request(args...; status_exception=false)
@debug "Sent http request" Time=now()
if http_r.status - 200 >= 100
@warn "Got an unexpected response" To=args[2] Code=http_r.status Body=http_r Sent=args[4]
end
http_r.status == 429 && return http_r
r = Response{T}(c, http_r)
if r.ok && r.val !== nothing
# Cache the value, and also replace any missing data
# in the response with data from the cache.
r = @set r.val = put!(c.state, r.val; kws...)
end
# Store the successful Response to the Future.
put!(f, r)
@debug "Got response"
catch e
kws = logkws(c; conn=undef, exception=(e, catch_backtrace()))
@error "Creating response failed" kws...
put!(f, Response{T}(nothing, false, http_r, e))
end
@debug "Request completed" url=args[2]
return http_r
end
end
@debug "Returning future" Time=now()
return f
end
Base.eltype(::Response{T}) where T = T
Base.eltype(::Type{Response{T}}) where T = T
"""
fetchval(f::Future{Response{T}}) -> Nullable{T}
Shortcut for `fetch(f).val`: Fetch a [`Response`](@ref) and return its value. Note that
there are no guarantees about the response's success and the value being returned, and it
discards context that can be useful for debugging, such as HTTP responses and caught
exceptions.
"""
fetchval(f::Future) = fetch(f).val
# Capture an ID from a string.
function cap(path::AbstractString, s::AbstractString)
m = match(Regex("/$path/(\\d+)"), s)
return m === nothing ? nothing : parse(Snowflake, first(m.captures))
end
include(joinpath("endpoints", "endpoints.jl"))
include(joinpath("crud", "crud.jl"))
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 131 | function retrieve(c::Client, ::Type{AuditLog}, g::AbstractGuild; kwargs...)
return get_guild_audit_log(c, g.id; kwargs...)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 433 | function create(c::Client, ::Type{Ban}, g::AbstractGuild, u::User; kwargs...)
return create_guild_ban(c, g.id, u.id; kwargs...)
end
function retrieve(c::Client, ::Type{Ban}, g::AbstractGuild, u::User)
return get_guild_ban(c, g.id, u.id)
end
retrieve(c::Client, ::Type{Ban}, g::AbstractGuild) = get_guild_bans(c, g.id)
function delete(c::Client, b::Ban, g::AbstractGuild)
return remove_guild_ban(c, g.id, b.user.id)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 600 | function create(c::Client, ::Type{DiscordChannel}, g::AbstractGuild; kwargs...)
return create_guild_channel(c, g.id; kwargs...)
end
function create(c::Client, ::Type{DiscordChannel}, u::User; kwargs...)
return create_dm(c; kwargs..., recipient_id=u.id)
end
retrieve(c::Client, ::Type{DiscordChannel}, channel::Integer) = get_channel(c, channel)
retrieve(c::Client, ::Type{DiscordChannel}, g::AbstractGuild) = get_guild_channels(c, g.id)
update(c::Client, ch::DiscordChannel; kwargs...) = modify_channel(c, ch.id; kwargs...)
delete(c::Client, ch::DiscordChannel) = delete_channel(c, ch.id)
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 2759 | export create,
retrieve,
update,
delete,
obtain
"""
create(c::Client, ::Type{T}, args...; kwargs...) -> Future{Response}
Create, add, send, etc.
## Examples
Sending a [`Message`](@ref):
```julia
create(c, Message, channel; content="foo")
```
Creating a new [`DiscordChannel`](@ref):
```julia
create(c, DiscordChannel, guild; name="bar")
```
Banning a [`Member`](@ref):
```julia
create(c, Ban, guild, member; reason="baz")
```
"""
function create end
"""
retrieve(c::Client, ::Type{T}, args...; kwargs...) -> Future{Response{T}}
Retrieve, get, list, etc.
## Examples
Getting the [`Client`](@ref)'s [`User`](@ref):
```julia
retrieve(c, User)
```
Getting a [`Guild`](@ref)'s [`DiscordChannel`](@ref)s:
```julia
retrieve(c, DiscordChannel, guild)
```
Getting an [`Invite`](@ref) to a [`Guild`](@ref) by code:
```julia
retrieve(c, Invite, "abcdef")
```
"""
function retrieve end
"""
obtain(c::Client, ::Type{T}, args...; kwargs...) -> T
Equivalent to retrieve, but blocks and returns the object of type T
"""
obtain(args...; kwargs...) = fetch(retrieve(args...; kwargs...)).val
"""
update(c::Client, x::T, args...; kwargs...) -> Future{Response}
Update, edit, modify, etc.
## Examples
Editing a [`Message`](@ref):
```julia
update(c, message; content="foo2")
```
Modifying a [`Webhook`](@ref):
```julia
update(c, webhook; name="bar2")
```
Updating a [`Role`](@ref):
```julia
update(c, role, guild; permissions=8)
```
"""
function update end
"""
delete(c::Client, x::T, args...) -> Future{Response}
Delete, remove, discard, etc.
## Examples
Kicking a [`Member`](@ref):
```julia
delete(c, member)
```
Unbanning a [`Member`](@ref):
```julia
delete(c, ban, guild)
```
Deleting all [`Reaction`](@ref)s from a [`Message`](@ref) (note: this is the only
update/delete method which takes a type parameter):
```julia
delete(c, Reaction, message)
```
"""
function delete end
include("audit_log.jl")
include("ban.jl")
include("channel.jl")
include("emoji.jl")
include("guild_embed.jl")
include("guild.jl")
include("integration.jl")
include("invite.jl")
include("member.jl")
include("message.jl")
include("overwrite.jl")
include("reaction.jl")
include("role.jl")
include("user.jl")
include("voice_region.jl")
include("webhook.jl")
include("interaction.jl")
#=
Functions not covered here:
- trigger_typing_indicator
- group_dm_add_recipient
- group_dm_remove_recipient
- modify_guild_channel_positions
- modify_current_user_nick
- modify_guild_role_positions
- get_guild_prune_count
- begin_guild_prune
- sync_guild_integration (combine with update?)
- get_guild_vanity_url
- get_guild_widget_image
- leave_guild (combine with delete?)
- execute_webhook
- execute_slack_compatible_webhook
- execute_github_compatible_webhook
=#
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 580 | function create(c::Client, ::Type{Emoji}, g::AbstractGuild; kwargs...)
return create_guild_emoji(c, g.id; kwargs...)
end
function retrieve(c::Client, ::Type{Emoji}, g::AbstractGuild, e::Emoji)
return get_guild_emoji(c, g.id, e.id)
end
function retrieve(c::Client, ::Type{Emoji}, g::AbstractGuild)
return list_guild_emojis(c, g.id)
end
function update(c::Client, e::Emoji, g::AbstractGuild; kwargs...)
return modify_guild_emoji(c, g.id, e.id; kwargs...)
end
function delete(c::Client, e::Emoji, g::AbstractGuild)
return delete_guild_emoji(c, g.id, e.id)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 377 | create(c::Client, ::Type{Guild}; kwargs...) = create_guild(c; kwargs...)
retrieve(c::Client, ::Type{Guild}, guild::Integer) = get_guild(c, guild)
retrieve(c::Client, ::Type{Guild}; kwargs...) = get_current_user_guilds(c; kwargs...)
update(c::Client, g::AbstractGuild; kwargs...) = modify_guild(c, g.id; kwargs...)
delete(c::Client, g::AbstractGuild) = delete_guild(c, g.id)
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 210 | retrieve(c::Client, ::Type{GuildEmbed}, g::AbstractGuild) = get_guild_embed(c, g.id)
function update(c::Client, ::GuildEmbed, g::AbstractGuild; kwargs...)
return modify_guild_embed(c, g.id; kwargs...)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 487 | function create(c::Client, ::Type{Integration}, g::AbstractGuild; kwargs...)
return create_guild_integration(c, g.id; kwargs...)
end
retrieve(c::Client, ::Type{Integration}, g::AbstractGuild) = get_guild_integrations(c, g.id)
function update(c::Client, i::Integration, g::AbstractGuild; kwargs...)
return modify_guild_integration(c, g.id, i.id; kwargs...)
end
function delete(c::Client, i::Integration, g::AbstractGuild)
return delete_guild_integration(c, g.id, i.id)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 1388 | create(c::Client, ::Type{ApplicationCommand}, name::AbstractString, description::AbstractString; kwargs...) = create_application_command(c; name=name, description=description, kwargs...)
create(c::Client, ::Type{ApplicationCommand}, name::AbstractString, description::AbstractString, g::Snowflake; kwargs...) = create_application_command(c, g; name=name, description=description, kwargs...)
create(c::Client, ::Type{Message}, interaction::Interaction; kwargs...) = create_followup_message(c, interaction.id, interaction.token; compkwfix(; kwargs...)...)
create(c::Client, ::Type{Vector{ApplicationCommand}}, cmds::Vector{ApplicationCommand}) = bulk_overwrite_application_commands(c, cmds)
create(c::Client, ::Type{Vector{ApplicationCommand}}, g::Snowflake, cmds::Vector{ApplicationCommand}) = bulk_overwrite_application_commands(c, g, cmds)
retrieve(c::Client, ::Type{Vector{ApplicationCommand}}) = get_application_commands(c)
retrieve(c::Client, ::Type{Vector{ApplicationCommand}}, g::Snowflake) = get_application_commands(c, g)
update(c::Client, ctx::Context, m::Message; kwargs...) = edit_interaction(c, ctx.interaction.token, m.id; compkwfix(; kwargs...)...)
update(c::Client, ctx::Context; kwargs...) = hasproperty(ctx, :interaction) ? update_message_int(c, ctx.interaction.id, ctx.interaction.token; compkwfix(; kwargs...)...) : update(c, ctx.message; compkwfix(; kwargs...)...)
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 489 | function create(c::Client, ::Type{Invite}, ch::DiscordChannel; kwargs...)
return create_channel_invite(c, ch.id; kwargs...)
end
retrieve(c::Client, ::Type{Invite}, g::AbstractGuild) = get_guild_invites(c, g.id)
retrieve(c::Client, ::Type{Invite}, ch::DiscordChannel) = get_channel_invites(c, ch.id)
function retrieve(c::Client, ::Type{Invite}, invite::AbstractString; kwargs...)
return get_invite(c, invite; kwargs...)
end
delete(c::Client, i::Invite) = delete_invite(c, i.code)
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 870 | function create(c::Client, ::Type{Member}, g::AbstractGuild, u::User; kwargs...)
return add_guild_member(c, g.id, u.id; kwargs...)
end
function retrieve(c::Client, ::Type{Member}, g::AbstractGuild, u::User)
return get_guild_member(c, g.id, u.id)
end
function retrieve(c::Client, ::Type{Member}, g::AbstractGuild)
return list_guild_members(c, g.id)
end
function update(c::Client, m::Member, g::AbstractGuild; kwargs...)
return modify_guild_member(c, g.id, m.user.id; kwargs...)
end
function update(c::Client, m::Member, r::Role, g::AbstractGuild)
return add_guild_member_role(c, g.id, m.user.id, r.id)
end
function delete(c::Client, m::Member, g::AbstractGuild)
return remove_guild_member(c, g.id, m.user.id)
end
function delete(c::Client, m::Member, r::Role, g::AbstractGuild)
return remove_guild_member_role(c, g.id, m.user.id, r.id)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 965 | function create(c::Client, ::Type{Message}, ch::DiscordChannel; kwargs...)
return create_message(c, ch.id; compkwfix(; kwargs...)...)
end
function retrieve(c::Client, ::Type{Message}, ch::DiscordChannel, message::Integer)
return get_channel_message(c, ch.id, message)
end
function retrieve(
c::Client,
::Type{Message},
ch::DiscordChannel;
pinned::Bool=false,
kwargs...,
)
return if pinned
get_pinned_messages(c, ch.id)
else
get_channel_messages(c, ch.id; kwargs...)
end
end
update(c::Client, m::Message; kwargs...) = edit_message(c, m.channel_id, m.id; kwargs...)
function delete(c::Client, m::Message; pinned::Bool=false)
return if pinned
delete_pinned_channel_message(c, m.channel_id, m.id)
else
delete_message(c, m.channel_id, m.id)
end
end
function delete(c::Client, ms::Vector{Message})
return bulk_delete_messages(c, ms[1].channel_id; messages=map(m -> m.id, ms))
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 608 | function create(c::Client, ::Type{Overwrite}, ch::DiscordChannel, r::Role; kwargs...)
return edit_channel_permissions(c, ch.id, r.id; kwargs..., type=OT_ROLE)
end
function create(c::Client, ::Type{Overwrite}, ch::DiscordChannel, u::User; kwargs...)
return edit_channel_permissions(c, ch.id, u.id; kwargs..., type=OT_MEMBER)
end
function update(c::Client, o::Overwrite, ch::DiscordChannel; kwargs...)
return edit_channel_permissions(c, ch.id, o.id; kwargs..., type=o.type)
end
function delete(c::Client, o::Overwrite, ch::DiscordChannel)
return delete_channel_permission(c, ch.id, o.id)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 1102 | function create(c::Client, ::Type{Reaction}, m::Message, emoji::StringOrChar)
return create_reaction(c, m.channel_id, m.id, emoji)
end
function create(c::Client, ::Type{Reaction}, m::Message, e::Emoji)
emoji = e.id === nothing ? e.name : "$(e.name):$(e.id)"
return create_reaction(c, m.channel_id, m.id, emoji)
end
function retrieve(c::Client, ::Type{Reaction}, m::Message, emoji::StringOrChar)
return get_reactions(c, m.channel_id, m.id, emoji)
end
retrieve(c::Client, ::Type{Reaction}, m::Message, e::Emoji) = get(Reaction, c, m, e.name)
function delete(c::Client, ::Type{Reaction}, m::Message)
return delete_all_reactions(c, m.channel_id, m.id)
end
function delete(c::Client, emoji::StringOrChar, m::Message, u::User)
return if c.state.user !== nothing && u.id == c.state.user.id
delete_own_reaction(c, m.channel_id, m.id, emoji)
else
delete_user_reaction(c, m.channel_id, m.id, emoji, u.id)
end
end
function delete(c::Client, e::Emoji, m::Message, u::User)
emoji = e.id === nothing ? e.name : "$(e.name):$(e.id)"
delete(c, emoji, m, u)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 409 | function create(c::Client, ::Type{Role}, g::AbstractGuild; kwargs...)
return create_guild_role(c, g.id; kwargs...)
end
retrieve(c::Client, ::Type{Role}, g::AbstractGuild) = get_guild_roles(c, g.id)
function update(c::Client, r::Role, g::AbstractGuild; kwargs...)
return modify_guild_role(c, g.id, r.id; kwargs...)
end
delete(c::Client, r::Role, g::AbstractGuild) = delete_guild_role(c, g.id, r.id)
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 307 | function retrieve(c::Client, ::Type{User}, user::Integer)
return if me(c) !== nothing && me(c).id == user
get_current_user(c)
else
get_user(c, user)
end
end
retrieve(c::Client, ::Type{User}) = get_current_user(c)
update(c::Client; kwargs...) = modify_current_user(c; kwargs...)
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 181 | function retrieve(c::Client, ::Type{VoiceRegion}, g::AbstractGuild)
return get_guild_voice_regions(c, g.id)
end
retrieve(c::Client, ::Type{VoiceRegion}) = list_voice_regions(c)
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 923 | function create(c::Client, ::Type{Webhook}, ch::DiscordChannel; kwargs...)
return create_webhook(c, ch.id; kwargs...)
end
retrieve(c::Client, ::Type{Webhook}, ch::DiscordChannel) = get_channel_webhooks(c, ch.id)
retrieve(c::Client, ::Type{Webhook}, g::AbstractGuild) = get_guild_webhooks(c, g.id)
retrieve(c::Client, ::Type{Webhook}, webhook::Integer) = get_webhook(c, webhook)
function retrieve(c::Client, ::Type{Webhook}, webhook::Integer, token::AbstractString)
return get_webhook_with_token(c, webhook, token)
end
update(c::Client, w::Webhook; kwargs...) = modify_webhook(c, w.id; kwargs...)
function update(c::Client, w::Webhook, token::AbstractString; kwargs...)
return modify_webhook_with_token(c, w.id, token; kwargs...)
end
delete(c::Client, w::Webhook) = delete_webhook(c, w.id)
function delete(c::Client, w::Webhook, token::AbstractString)
return delete_webhook_with_token(c, w.id, token)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 406 | export get_guild_audit_log
"""
get_guild_audit_log(c::Client, guild::Integer; kwargs...) -> AuditLog
Get a [`Guild`](@ref)'s [`AuditLog`](@ref).
More details [here](https://discordapp.com/developers/docs/resources/audit-log#get-guild-audit-log).
"""
function get_guild_audit_log(c::Client, guild::Integer; kwargs...)
return Response{AuditLog}(c, :GET, "/guilds/$guild/audit-logs"; kwargs...)
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
|
[
"MIT"
] | 0.8.0 | da36639322f6789ee33aa2d4c55186f6b2bccdd2 | code | 8802 | export encode_emoji,
get_channel,
modify_channel,
delete_channel,
get_channel_messages,
get_channel_message,
create_message,
create_reaction,
delete_own_reaction,
delete_user_reaction,
get_reactions,
delete_all_reactions,
edit_message,
delete_message,
bulk_delete_messages,
edit_channel_permissions,
get_channel_invites,
create_channel_invite,
delete_channel_permission,
trigger_typing_indicator,
get_pinned_messages,
add_pinned_channel_message,
delete_pinned_channel_message
encode_emoji(emoji::AbstractString) = HTTP.escapeuri(emoji)
encode_emoji(emoji::AbstractChar) = encode_emoji(string(emoji))
"""
get_channel(c::Client, channel::Integer) -> DiscordChannel
Get a [`DiscordChannel`](@ref).
"""
function get_channel(c::Client, channel::Integer)
return Response{DiscordChannel}(c, :GET, "/channels/$channel")
end
"""
modify_channel(c::Client, channel::Integer; kwargs...) -> DiscordChannel
Modify a [`DiscordChannel`](@ref).
More details [here](https://discordapp.com/developers/docs/resources/channel#modify-channel).
"""
function modify_channel(c::Client, channel::Integer; kwargs...)
return Response{DiscordChannel}(c, :PATCH, "/channels/$channel"; body=kwargs)
end
"""
delete_channel(c::Client, channel::Integer) -> DiscordChannel
Delete a [`DiscordChannel`](@ref).
"""
function delete_channel(c::Client, channel::Integer)
return Response{DiscordChannel}(c, :DELETE, "/channels/$channel")
end
"""
get_channel_messages(c::Client, channel::Integer; kwargs...) -> Vector{Message}
Get a list of [`Message`](@ref)s from a [`DiscordChannel`](@ref).
More details [here](https://discordapp.com/developers/docs/resources/channel#get-channel-messages).
"""
function get_channel_messages(c::Client, channel::Integer; kwargs...)
return Response{Vector{Message}}(c, :GET, "/channels/$channel/messages"; kwargs...)
end
"""
get_channel_message(c::Client, channel::Integer, message::Integer) -> Message
Get a [`Message`](@ref) from a [`DiscordChannel`](@ref).
"""
function get_channel_message(c::Client, channel::Integer, message::Integer)
return Response{Message}(c, :GET, "/channels/$channel/messages/$message")
end
"""
create_message(c::Client, channel::Integer; kwargs...) -> Message
Send a [`Message`](@ref) to a [`DiscordChannel`](@ref).
More details [here](https://discordapp.com/developers/docs/resources/channel#create-message).
"""
function create_message(c::Client, channel::Integer; kwargs...)
endpoint = "/channels/$channel/messages"
return if haskey(kwargs, :file) # We have to use multipart/form-data for file uploads.
d = Dict(pairs(kwargs))
file = pop!(d, :file)
form = HTTP.Form(Dict("file" => file, "payload_json" => jsonify(d)))
headers = Dict(HTTP.content_type(form))
Response{Message}(c, :POST, endpoint; headers=headers, body=form)
else
Response{Message}(c, :POST, endpoint; body=kwargs)
end
end
"""
create_reaction(c::Client, channel::Integer, message::Integer, emoji::StringOrChar)
React to a [`Message`](@ref). If `emoji` is a custom [`Emoji`](@ref), it should be
formatted "name:id".
"""
function create_reaction(c::Client, channel::Integer, message::Integer, emoji::StringOrChar)
return Response(
c,
:PUT,
"/channels/$channel/messages/$message/reactions/$(encode_emoji(emoji))/@me",
)
end
"""
delete_own_reaction(c::Client, channel::Integer, message::Integer, emoji::StringOrChar)
Delete the [`Client`](@ref) user's reaction to a [`Message`](@ref).
"""
function delete_own_reaction(
c::Client,
channel::Integer,
message::Integer,
emoji::StringOrChar,
)
return Response(
c,
:DELETE,
"/channels/$channel/messages/$message/reactions/$(encode_emoji(emoji))/@me",
)
end
"""
delete_user_reaction(
c::Client,
channel::Integer,
message::Integer,
emoji::StringOrChar,
user::Integer,
)
Delete a [`User`](@ref)'s reaction to a [`Message`](@ref).
"""
function delete_user_reaction(
c::Client,
channel::Integer,
message::Integer,
emoji::StringOrChar,
user::Integer,
)
return Response(
c,
:DELETE,
"/channels/$channel/messages/$message/reactions/$(encode_emoji(emoji))/$user",
)
end
"""
get_reactions(
c::Client,
channel::Integer,
message::Integer,
emoji::StringOrChar,
) -> Vector{User}
Get the [`User`](@ref)s who reacted to a [`Message`](@ref) with an [`Emoji`](@ref).
"""
function get_reactions(c::Client, channel::Integer, message::Integer, emoji::StringOrChar)
return Response{Vector{User}}(
c,
:GET,
"/channels/$channel/messages/$message/reactions/$(encode_emoji(emoji))",
)
end
"""
delete_all_reactions(c::Client, channel::Integer, message::Integer)
Delete all reactions from a [`Message`](@ref).
"""
function delete_all_reactions(c::Client, channel::Integer, message::Integer)
return Response(c, :DELETE, "/channels/$channel/messages/$message/reactions")
end
"""
edit_message(c::Client, channel::Integer, message::Integer; kwargs...) -> Message
Edit a [`Message`](@ref).
More details [here](https://discordapp.com/developers/docs/resources/channel#edit-message).
"""
function edit_message(c::Client, channel::Integer, message::Integer; kwargs...)
return Response{Message}(c, :PATCH, "/channels/$channel/messages/$message"; body=kwargs)
end
"""
delete_message(c::Client, channel::Integer, message::Integer)
Delete a [`Message`](@ref).
"""
function delete_message(c::Client, channel::Integer, message::Integer)
return Response(c, :DELETE, "/channels/$channel/messages/$message")
end
"""
bulk_delete_messages(c::Client, channel::Integer; kwargs...)
Delete multiple [`Message`](@ref)s.
More details [here](https://discordapp.com/developers/docs/resources/channel#bulk-delete-messages).
"""
function bulk_delete_messages(c::Client, channel::Integer; kwargs...)
return Response(c, :POST, "/channels/$channel/messages/bulk-delete"; body=kwargs)
end
"""
edit_channel_permissions(
c::Client,
channel::Integer,
overwrite::Integer;
kwargs...,
)
Edit permissions for a [`DiscordChannel`](@ref).
More details [here](https://discordapp.com/developers/docs/resources/channel#edit-channel-permissions).
"""
function edit_channel_permissions(
c::Client,
channel::Integer,
overwrite::Integer;
kwargs...,
)
return Response(c, :PUT, "/channels/$channel/permissions/$overwrite"; body=kwargs)
end
"""
get_channel_invites(c::Client, channel::Integer) -> Vector{Invite}
Get the [`Invite`](@ref)s for a [`DiscordChannel`](@ref).
"""
function get_channel_invites(c::Client, channel::Integer)
return Response{Vector{Invite}}(c, :GET, "/channels/$channel/invites")
end
"""
create_channel_invite(c::Client, channel::Integer; kwargs...) -> Invite
Create an [`Invite`](@ref) to a [`DiscordChannel`](@ref).
More details [here](https://discordapp.com/developers/docs/resources/channel#create-channel-invite).
"""
function create_channel_invite(c::Client, channel::Integer, kwargs...)
return Response{Invite}(c, :POST, "/channels/$channel/invites"; body=kwargs)
end
"""
delete_channel_permission(c::Client, channel::Integer, overwrite::Integer)
Delete an [`Overwrite`](@ref) from a [`DiscordChannel`](@ref).
"""
function delete_channel_permission(c::Client, channel::Integer, overwrite::Integer)
return Response(c, :DELETE, "/channels/$channel/permissions/$overwrite")
end
"""
trigger_typing_indicator(c::Client, channel::Integer)
Trigger the typing indicator in a [`DiscordChannel`](@ref).
"""
function trigger_typing_indicator(c::Client, channel::Integer)
return Response(c, :POST, "/channels/$channel/typing")
end
"""
get_pinned_messages(c::Client, channel::Integer) -> Vector{Message}
Get the pinned [`Message`](@ref)s in a [`DiscordChannel`](@ref).
"""
function get_pinned_messages(c::Client, channel::Integer)
return Response{Vector{Message}}(c, :GET, "/channels/$channel/pins")
end
"""
add_pinned_channel_message(c::Client, channel::Integer, message::Integer)
Pin a [`Message`](@ref) in a [`DiscordChannel`](@ref).
"""
function add_pinned_channel_message(c::Client, channel::Integer, message::Integer)
return Response(c, :PUT, "/channels/$channel/pins/$message")
end
"""
delete_pinned_channel_message(c::Client, channel::Integer, message::Integer)
Unpin a [`Message`](@ref) from a [`DiscordChannel`](@ref).
"""
function delete_pinned_channel_message(c::Client, channel::Integer, message::Integer)
return Response(c, :DELETE, "/channels/$channel/pins/$message")
end
| Ekztazy | https://github.com/Humans-of-Julia/Ekztazy.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.