text
stringlengths 5
1.02M
|
---|
# Author: Ritchie Lee, [email protected]
# Date: 12/15/2014
# Correlated Encounter Model for Cooperative Aircraft in the National Airspace
# exposed as DBN. Samples are generated at runtime at each step.
module CorrAEMDBNImpl
export
AddObserver,
getInitialState,
initialize,
update,
get,
CorrAEMDBN
import Compat.ASCIIString
using AbstractEncounterDBNImpl
using AbstractEncounterDBNInterfaces
using CommonInterfaces
using Util
using Encounter
using CorrAEMImpl
using RLESUtils, Observers
import CommonInterfaces.addObserver
import CommonInterfaces.initialize
import CommonInterfaces.update
import AbstractEncounterDBNInterfaces.get
import AbstractEncounterDBNInterfaces.getInitialState
import Base.convert
include(Pkg.dir("SISLES/src/Encounter/CorrAEMImpl/corr_aem_sample.jl"))
type CorrAEMDBN <: AbstractEncounterDBN
number_of_aircraft::Int64
encounter_file::ASCIIString
initial_sample_file::ASCIIString
transition_sample_file::ASCIIString
encounter_number::Int64
command_method::Symbol #:ENC = read from encounter file, :DBN = generate from DBN on-the-fly
aem::CorrAEM
dirichlet_transition
#initial states
init_aem_dstate::Vector{Int64} #discrete current state
init_aem_dyn_cstate::Vector{Float64} #continuous of current dynamic variables
#current states
t::Int64
aem_dstate::Vector{Int64} #discrete current state
aem_dyn_cstate::Vector{Float64} #continuous of current dynamic variables
#caching and reuse
dynamic_variables0::Vector{Int64}
dynamic_variables1::Vector{Int64}
parents_cache::Dict{Int64, Vector{Bool}}
weights_cache::Dict{Tuple{Int64, Int64}, Vector{Float64}}
cumweights_cache::Dict{Tuple{Int64, Int64}, Vector{Float64}}
#pre-allocated output to avoid repeating reallocations
output_commands::Vector{CorrAEMCommand}
logProb::Float64 #log probability of output
function CorrAEMDBN(number_of_aircraft::Int, encounter_file::AbstractString, initial_sample_file::AbstractString,
transition_sample_file::AbstractString,
encounter_number::Int, encounter_seed::UInt64, command_method::Symbol)
dbn = new()
@assert number_of_aircraft == 2 #need to revisit the code if this is not true
dbn.number_of_aircraft = number_of_aircraft
dbn.encounter_file = encounter_file
dbn.initial_sample_file = initial_sample_file
dbn.transition_sample_file = transition_sample_file
dbn.encounter_number = encounter_number
dbn.command_method = command_method
dbn.aem = CorrAEM(encounter_file, initial_sample_file, transition_sample_file)
dbn.t = 0
srand(encounter_seed) #There's a rand inside generateEncounter
generateEncounter(dbn.aem, sample_number=encounter_number) #To optimize: This allocates a lot of memory
#compute initial states of variables
p = dbn.aem.parameters
dbn.dynamic_variables0 = p.temporal_map[:,1]
dbn.dynamic_variables1 = p.temporal_map[:,2]
aem_initial_unconverted = unconvertUnitsAemState(dbn.aem.initial)
aem_initial_dstate = Int64[ val2ind(p.boundaries[i], p.r_transition[i], val)
for (i, val) in enumerate(aem_initial_unconverted)]
dbn.init_aem_dstate = [aem_initial_dstate; aem_initial_dstate[dbn.dynamic_variables0]] #bins, [11:14] are updated with time, append space for t+1 variables
dbn.init_aem_dyn_cstate = dbn.aem.initial[dbn.dynamic_variables0] #continuous variables.
dbn.dirichlet_transition = bn_dirichlet_prior(p.N_transition)
dbn.aem_dstate = deepcopy(dbn.init_aem_dstate)
dbn.aem_dyn_cstate = deepcopy(dbn.init_aem_dyn_cstate)
#precompute and cache these quantities
dbn.parents_cache = Dict{Int64,Vector{Bool}}()
dbn.weights_cache = Dict{Tuple{Int64,Int64}, Vector{Float64}}()
dbn.cumweights_cache = Dict{Tuple{Int64,Int64}, Vector{Float64}}()
for i = 1:length(p.N_transition)
dbn.parents_cache[i] = p.G_transition[:, i]
for j = 1:1:size(dbn.dirichlet_transition[i], 2)
dbn.weights_cache[(i, j)] = p.N_transition[i][:, j] + dbn.dirichlet_transition[i][:, j]
dbn.weights_cache[(i, j)] /= sum(dbn.weights_cache[(i, j)])
dbn.cumweights_cache[(i, j)] = cumsum(dbn.weights_cache[(i, j)])
end
end
dbn.output_commands = CorrAEMCommand[ CorrAEMCommand(0.0, 0.0, 0.0, 0.0) for i = 1:number_of_aircraft ]
dbn.logProb = 0.0
return dbn
end
end
addObserver(dbn::CorrAEMDBN, f::Function) = add_observer(aem.observer, f)
addObserver(dbn::CorrAEMDBN, tag::AbstractString, f::Function) = add_observer(aem.observer, tag, f)
function initialize(dbn::CorrAEMDBN)
#reset to initial state
copy!(dbn.aem_dstate, dbn.init_aem_dstate)
copy!(dbn.aem_dyn_cstate, dbn.init_aem_dyn_cstate)
dbn.t = 0
#reset aem indices
initialize(dbn.aem)
end
function getInitialState(dbn::CorrAEMDBN, index::Int)
return Encounter.getInitialState(dbn.aem, index)
end
function update(dbn::CorrAEMDBN)
if dbn.command_method == :DBN
logProb = step_dbn(dbn)
elseif dbn.command_method == :ENC
logProb = step_enc(dbn)
else
error("CorrAEMDBNImpl::Step: No such command method")
end
dbn.t += 1
return logProb
end
function step_dbn(dbn::CorrAEMDBN)
p = dbn.aem.parameters
aem_dstate = dbn.aem_dstate #entire state, discrete bins
aem_dyn_cstate = dbn.aem_dyn_cstate #dynamic states, continuous
logProb = 0.0
for (o,i) in enumerate(dbn.dynamic_variables1)
if !isempty(find(dbn.parents_cache[i]))
dims = tuple(p.r_transition[dbn.parents_cache[i]]...)
j = sub2ind(dims, aem_dstate[dbn.parents_cache[i]]...)
aem_dstate[i] = select_random_cumweights(dbn.cumweights_cache[(i,j)])
logProb += log(dbn.weights_cache[(i,j)][aem_dstate[i]])
#Resampling and dediscretizing process
i_t = dbn.dynamic_variables0[o]
if (aem_dstate[i] != aem_dstate[i_t]) || #compare to state at last time step, #Different bin, do resample
(aem_dstate[i] == aem_dstate[i_t] && rand() < p.resample_rates[i_t]) #Same bin but meets resample rate
aem_dyn_cstate[o],_ = dediscretize(aem_dstate[i],p.boundaries[i_t],p.zero_bins[i_t])
if in(i,[17,18]) #these need unit conversion
aem_dyn_cstate[o] /= 60 #convert units
end
end
#Else same bin and does not meet rate, just set equal to previous (no update)
end
end
# copy over x(t+1) to x(t)
aem_dstate[dbn.dynamic_variables0] = aem_dstate[dbn.dynamic_variables1]
#Just a reminder, this will break if number_of_aircraft != 2
@assert dbn.number_of_aircraft == 2
dbn.output_commands[1].t = dbn.t
dbn.output_commands[1].v_d = getInitialSample(dbn.aem, :v1d)
dbn.output_commands[1].h_d = dbn.aem_dyn_cstate[1]
dbn.output_commands[1].psi_d = dbn.aem_dyn_cstate[3]
dbn.output_commands[2].t = dbn.t
dbn.output_commands[2].v_d = getInitialSample(dbn.aem, :v2d)
dbn.output_commands[2].h_d = dbn.aem_dyn_cstate[2]
dbn.output_commands[2].psi_d = dbn.aem_dyn_cstate[4]
return dbn.logProb = logProb
end
#TODO: remove hardcoding
convert_units(x::AbstractFloat, i::Int) = in(i, [17,18]) ? x / 60 : x
convert(::Type{Vector{Float64}}, command_1::CorrAEMCommand, command_2::CorrAEMCommand) =
[ command_1.h_d, command_2.h_d, command_1.psi_d, command_2.psi_d ]
function step_enc(dbn::CorrAEMDBN)
aem = dbn.aem
p = aem.parameters
for i = 1:dbn.number_of_aircraft
cmd = Encounter.update(aem, i)
if cmd != nothing
dbn.output_commands[i] = cmd
end
end
#Just a reminder, this will break if number_of_aircraft != 2
#@assert dbn.number_of_aircraft == 2
#= FIXME: skip probability calc for now...
#prepare t+1 from encounter commands
aem_dyn_cstate = convert(Vector{Float64}, dbn.output_commands[1], dbn.output_commands[2])
aem_dstate = dbn.aem_dstate #only copies pointer
#load into the (t+1) slots
#boundaries are specified at t
aem_dyn_cstate_unconverted = unconvertUnitsDynVars(aem_dyn_cstate) #need to unconvert units
aem_dstate[dbn.dynamic_variables1] = Int64[ val2ind(p.boundaries[i], p.r_transition[i], aem_dyn_cstate_unconverted[o])
for (o, i) in enumerate(dbn.dynamic_variables0) ]
# compute the probability of this transition
logProb = 0.0
for (o, i) in enumerate(dbn.dynamic_variables1)
j = 1
parents = dbn.parents_cache[i]
if !isempty(find(parents))
dims = tuple(p.r_transition[parents]...)
indices = aem_dstate[parents]
j = sub2ind(dims, indices...)
end
weights = dbn.weights_cache[(i, j)]
logProb += log(weights[aem_dstate[i]])
#probability from continuous sampling process
#two components: resample prob, dediscretize prob
i_prev = dbn.dynamic_variables0[o]
if aem_dstate[i] != aem_dstate[i_prev] #not the same bin, resample wp 1
logProb += dediscretize_prob(aem_dyn_cstate[o], aem_dstate[i], p.boundaries[i_prev], p.zero_bins[i_prev])
elseif isapprox(aem_dyn_cstate[o], dbn.aem_dyn_cstate[o], atol=0.0001) #same bin same value, did not resample
logProb += log(1.0 - p.resample_rates[i_prev])
else #Same bin different value, got resampled
logProb += log(p.resample_rates[i_prev])
logProb += dediscretize_prob(aem_dyn_cstate[o], aem_dstate[i], p.boundaries[i_prev], p.zero_bins[i_prev])
end
end
# copy over x(t+1) to x(t)
aem_dstate[dbn.dynamic_variables0] = aem_dstate[dbn.dynamic_variables1]
#push to sim
dbn.aem_dstate = aem_dstate
dbn.aem_dyn_cstate = aem_dyn_cstate
#return
dbn.logProb = logProb
=#
dbn.logProb = 0.0 #for now... FIXME
end
function get(dbn::CorrAEMDBN, aircraft_number::Int)
return dbn.output_commands[aircraft_number]
end
function val2ind(boundariesi, ri, value)
if !isempty(boundariesi)
index = findfirst(x -> (x > value), boundariesi) - 1
if index == -1
index = ri
end
else
index = value
end
return index
end
function dediscretize(dval::Int64, boundaries::Vector{Float64}, zero_bin::Int64)
val_min = boundaries[dval]
val_max = boundaries[dval + 1]
if dval == zero_bin
val = 0.0
prob = 1.0
elseif val_max == val_min
val = val_min
prob = 1.0
else
val = val_min + rand() * (val_max - val_min)
prob = 1.0 / (val_max - val_min)
#this is a density so it won't be normalized to [0,1]
end
return (val, prob)
end
function dediscretize_prob(val::Float64, dval::Int64, boundaries::Vector{Float64}, zero_bin::Int64)
val_min = boundaries[dval]
val_max = boundaries[dval + 1]
if dval == zero_bin
@assert val == 0.0
prob = 1.0
elseif val_max == val_min
@assert val == val_min
prob = 1.0
else
@assert val_min <= val <= val_max
prob = 1.0 / (val_max - val_min)
#this is a density so it won't be normalized to [0,1]
end
return prob
end
function unconvertUnitsDynVars(v)
return [v[1:2] * 60.0, v[3:end]]
end
function unconvertUnitsAemState(state_) #from CorrAEM
state = deepcopy(state_)
state[7] /= 1.68780
state[8] /= 1.68780
state[9] /= 1.68780
state[10] /= 1.68780
state[11] *= 60
state[12] *= 60
state[15] /= 6076.12
return state
end
function select_random_cumweights(cweights::Vector{Float64})
#select randomly according to cumulative weights vector
r = cweights[end] * rand()
return findfirst(x -> (x >= r), cweights)
end
end #module
|
function isprerelease(version::VersionNumber)::Bool
prerelease = version.prerelease
isempty(prerelease) && return false
for x in prerelease
if !isempty(strip(x))
return true
end
end
return false
end
function _calculate_increment(before::VersionNumber,
after::VersionNumber)::VersionNumber
before_first3 = VersionNumber(before.major,
before.minor,
before.patch)
after_first3 = VersionNumber(after.major,
after.minor,
after.patch)
# @debug("before: ", before)
# @debug("before_first3: ", before_first3)
# @debug("after:", after)
# @debug("after_first3:", after_first3)
always_assert(after > before, "after > before")
always_assert(after_first3 >= before_first3,
"after_first3 >= before_first3")
if before.major == after.major
if before.minor == after.minor
always_assert(after.patch >= before.patch,
"after.patch >= before.patch")
return VersionNumber(0, 0, after.patch - before.patch)
else
always_assert(after.minor >= before.minor,
"after.minor >= before.minor")
return VersionNumber(0,
after.minor - before.minor,
after.patch - 0)
end
else
always_assert(after.major >= before.major,
"after.major >= before.major")
return VersionNumber(after.major - before.major,
after.minor - 0,
after.patch - 0)
end
end
function check_version_increment(master_version::VersionNumber,
head_version::VersionNumber;
allow_skipping_versions::Bool,
gh_set_output::Bool = get(ENV, "GITHUB_ACTIONS", "") == "true",
gh_set_output_io::IO = stdout)::Nothing
always_assert(head_version > master_version, "head_version > master_version")
_gh_set_output_println(gh_set_output, gh_set_output_io, "compare_versions", "success")
@info("Version number has increased")
increment = _calculate_increment(master_version, head_version)
if increment in (v"0.0.0", v"0.0.1", v"0.1.0", v"1.0.0")
@info("Increment is good",
master_version,
head_version,
increment)
else
if allow_skipping_versions
@warn("Increment is bad, but `allow_skipping_versions` is true, so we will allow it",
master_version,
head_version,
increment,
allow_skipping_versions)
else
@error("Increment is bad",
master_version,
head_version,
increment,
allow_skipping_versions)
error("Bad increment")
end
end
return nothing
end
function compare_versions(master_version::VersionNumber,
head_version::VersionNumber;
allow_unchanged_prerelease::Bool,
allow_skipping_versions::Bool,
gh_set_output::Bool = get(ENV, "GITHUB_ACTIONS", "") == "true",
gh_set_output_io::IO = stdout)::Nothing
if head_version > master_version
check_version_increment(master_version,
head_version;
allow_skipping_versions = allow_skipping_versions,
gh_set_output = gh_set_output,
gh_set_output_io = gh_set_output_io)
elseif head_version == master_version
if isprerelease(head_version) && isprerelease(master_version) && allow_unchanged_prerelease
_gh_set_output_println(gh_set_output, gh_set_output_io, "compare_versions", "success")
@info("Version number did not change, but it is a prerelease so this is allowed")
else
_gh_set_output_println(gh_set_output, gh_set_output_io, "compare_versions", "failure")
throw(ErrorException("Version number is unchanged, which is not allowed"))
end
else
_gh_set_output_println(gh_set_output, gh_set_output_io, "compare_versions", "failure")
throw(ErrorException("Version number decreased, which is not allowed"))
end
return nothing
end
|
##Operators
# TODO: REMOVE!
for op in (:Derivative,:Integral)
@eval begin
function ($op)(d::AbstractVector{T}) where T<:IntervalOrSegment
n=length(d)
R=zeros(Operator{mapreduce(eltype,promote_type,d)},n,n)
for k=1:n
R[k,k]=$op(d[k])
end
R
end
end
end
function Evaluation(d::AbstractVector{T},x...) where T<:IntervalOrSegment
n=length(d)
R=zeros(Operator{mapreduce(eltype,promote_type,d)},n,n)
for k=1:n
R[k,k]=Evaluation(d[k],x...)
end
R
end
## Construction
function diagm_container(kv::Pair{<:Integer,<:AbstractVector{O}}...) where O<:Operator
T = mapreduce(x -> mapreduce(eltype,promote_type,x.second),
promote_type, kv)
n = mapreduce(x -> length(x.second) + abs(x.first), max, kv)
zeros(Operator{T}, n, n)
end
##TODO: unify with other blockdiag
function blockdiag(d1::AbstractVector{T},d2::AbstractVector{T}) where T<:Operator
if isempty(d1)&&isempty(d2)
error("Empty blockdiag")
end
if isempty(d1)
TT=mapreduce(eltype,promote_type,d2)
elseif isempty(d2)
TT=mapreduce(eltype,promote_type,d1)
else
TT=promote_type(mapreduce(eltype,promote_type,d1),
mapreduce(eltype,promote_type,d2))
end
D=zeros(Operator{TT},length(d1)+length(d2),2)
D[1:length(d1),1]=d1
D[length(d1)+1:end,2]=d2
D
end
blockdiag(a::Operator,b::Operator) = blockdiag(Operator{promote_type(eltype(a),eltype(b))}[a],
Operator{promote_type(eltype(a),eltype(b))}[b])
## broadcase
broadcast(::typeof(*),A::AbstractArray{N},D::Operator) where {N<:Number} =
Operator{promote_type(N,eltype(D))}[A[k,j]*D for k=1:size(A,1),j=1:size(A,2)]
broadcast(::typeof(*),D::Operator,A::AbstractArray{N}) where {N<:Number}=A.*D
|
using Test
using SpinMonteCarlo
const SEED = 137
const SEED2 = 19937
const MCS = 10000
const Therm = MCS
const alpha = 0.001
@testset begin
filenames = [
"classical.jl",
"quantum.jl",
"checkpoint.jl",
]
for filename in filenames
t = @elapsed include(filename)
println("$(filename): $t sec")
end
end
|
"""
ListBasedNonProjective()
Transition system for list-based non-projective dependency parsing.
Described in Nivre 2008, "Algorithms for Deterministic Incremental Dependency Parsing."
"""
struct ListBasedNonProjective <: AbstractTransitionSystem end
initconfig(s::ListBasedNonProjective, graph::DependencyTree) =
ListBasedNonProjectiveConfig(graph)
initconfig(s::ListBasedNonProjective, deptype, words) =
ListBasedNonProjectiveConfig{deptype}(words)
projective_only(::ListBasedNonProjective) = false
transition_space(::ListBasedNonProjective, labels=[]) =
isempty(labels) ? [LeftArc(), RightArc(), NoArc(), Shift()] :
[LeftArc.(labels)..., RightArc.(labels)..., NoArc(), Shift()]
struct ListBasedNonProjectiveConfig{T} <: AbstractParserConfiguration{T}
λ1::Vector{Int} # right-headed
λ2::Vector{Int} # left-headed
β::Vector{Int}
A::Vector{T}
end
function ListBasedNonProjectiveConfig{T}(words::Vector{String}) where {T}
λ1 = [0]
λ2 = Int[]
β = 1:length(words)
A = [unk(T, id, w) for (id,w) in enumerate(words)]
ListBasedNonProjectiveConfig{T}(λ1, λ2, β, A)
end
function ListBasedNonProjectiveConfig{T}(gold::DependencyTree) where {T}
λ1 = [0]
λ2 = Int[]
β = 1:length(gold)
A = [dep(token, head=-1) for token in gold]
ListBasedNonProjectiveConfig{T}(λ1, λ2, β, A)
end
ListBasedNonProjectiveConfig(gold::DependencyTree) =
ListBasedNonProjectiveConfig{eltype(gold)}(gold)
buffer(cfg::ListBasedNonProjectiveConfig) = cfg.β
token(cfg::ListBasedNonProjectiveConfig, i) = iszero(i) ? root(deptype(cfg)) :
i == -1 ? noval(deptype(cfg)) :
cfg.A[i]
tokens(cfg::ListBasedNonProjectiveConfig) = cfg.A
tokens(cfg::ListBasedNonProjectiveConfig, is) = [token(cfg, i) for i in is]
function leftarc(cfg::ListBasedNonProjectiveConfig, args...; kwargs...)
λ1, i = cfg.λ1[1:end-1], cfg.λ1[end]
j, β = cfg.β[1], cfg.β[2:end]
A = copy(cfg.A)
i != 0 && (A[i] = dep(A[i], args...; head=j, kwargs...))
ListBasedNonProjectiveConfig(λ1, [i ; cfg.λ2], [j ; β], A)
end
function rightarc(cfg::ListBasedNonProjectiveConfig, args...; kwargs...)
λ1, i = cfg.λ1[1:end-1], cfg.λ1[end]
j, β = cfg.β[1], cfg.β[2:end]
A = copy(cfg.A)
A[j] = dep(A[j], args...; head=i, kwargs...)
ListBasedNonProjectiveConfig(λ1, [i ; cfg.λ2], [j ; β], A)
end
function noarc(cfg::ListBasedNonProjectiveConfig)
λ1, i = cfg.λ1[1:end-1], cfg.λ1[end]
λ2, β, A = cfg.λ2, cfg.β, cfg.A
ListBasedNonProjectiveConfig(λ1, [i ; λ2], β, A)
end
function shift(cfg::ListBasedNonProjectiveConfig)
λ1, λ2 = cfg.λ1, cfg.λ2
i, β = cfg.β[1], cfg.β[2:end]
ListBasedNonProjectiveConfig([λ1 ; λ2 ; i], Int[], β, cfg.A)
end
function isfinal(cfg::ListBasedNonProjectiveConfig)
return all(a -> head(a) != -1, tokens(cfg)) && length(cfg.λ1) == length(cfg.A) + 1 &&
length(cfg.λ2) == 0 && length(cfg.β) == 0
end
"""
static_oracle(::ListBasedNonProjectiveConfig, tree)
Return a training oracle function which returns gold transition
operations from a parser configuration with reference to `graph`.
"""
function static_oracle(cfg::ListBasedNonProjectiveConfig, tree, arc=untyped)
l = i -> arc(tree[i])
if length(cfg.λ1) >= 1 && length(cfg.β) >= 1
i, λ1 = cfg.λ1[end], cfg.λ1[1:end-1]
j, β = cfg.β[1], cfg.β[2:end]
if !iszero(i) && head(tree, i) == j
return LeftArc(l(i)...)
elseif head(tree, j) == i
return RightArc(l(j)...)
end
j_deps = dependents(tree, j)
if (!(any(x -> x < j, j_deps) && j_deps[1] < i)) && !(head(tree, j) < i)
return Shift()
end
end
if length(cfg.λ1) == 0
return Shift()
end
return NoArc()
end
# todo?
possible_transitions(cfg::ListBasedNonProjectiveConfig, graph::DependencyTree, arc=untyped) =
TransitionOperator[static_oracle(cfg, graph, arc)]
==(cfg1::ListBasedNonProjectiveConfig, cfg2::ListBasedNonProjectiveConfig) =
cfg1.λ1 == cfg2.λ1 && cfg1.λ2 == cfg2.λ2 && cfg1.β == cfg2.β && cfg1.A == cfg2.A
function Base.show(io::IO, c::ListBasedNonProjectiveConfig)
λ1 = join(c.λ1, ",")
λ2 = join(c.λ2, ",")
β = join(c.β, ",")
print(io, "ListBasedNonProjectiveConfig([$λ1],[$λ2],[$β])\n$(join([join([id(t),form(t),head(t)],'\t') for t in tokens(c)],'\n'))")
end
|
# Basic test script - generates the file sample_uam_traj.csv containing one uam trajectory
# Include the files
include("UAMTrajectoryGenerator.jl")
# Set the random seed
Random.seed!(1)
# Generate the trajectory file
generate_trajectory_file("output/uam_traj.csv") |
using FunctionalCollections: PersistentSet, PersistentHashMap, dissoc, assoc, conj, disj
using Gen
#########################################
# compiling a trace into a factor graph #
#########################################
struct Latent{T,U}
domain::Vector{T}
parent_addrs::Vector{U}
end
struct Observation{U}
parent_addrs::Vector{U} # only include addrs that are selected
end
parent_addrs(info::Union{Latent,Observation}) = info.parent_addrs
function get_domain_to_idx(domain::Vector{T}) where {T}
domain_to_idx = Dict{T,Int}()
for (i, value) in enumerate(domain)
domain_to_idx[value] = i
end
return domain_to_idx
end
function cartesian_product(value_lists)
tuples = Vector{Tuple}()
for value in value_lists[1]
if length(value_lists) > 1
append!(tuples,
[(value, rest...) for rest in cartesian_product(value_lists[2:end])])
else
append!(tuples, [(value,)])
end
end
return tuples
end
# addr could be latent or obserrved...
# latent_addrs is the set of latent variables that are involved, which may or
# may not include the actual addr itself..
function create_factor(
trace, addr,
latents::Dict{Any,Latent}, observations::Dict{Any,Observation},
all_latent_addrs::Vector{Any})
N = length(all_latent_addrs)
in_factor = Vector{Bool}(undef, N)
if haskey(latents, addr)
for (i, a) in enumerate(all_latent_addrs)
in_factor[i] = (a == addr || a in parent_addrs(latents[addr]))
end
num_vars = length(parent_addrs(latents[addr]))+1
elseif haskey(observations, addr)
for (i, a) in enumerate(all_latent_addrs)
in_factor[i] = (a in parent_addrs(observations[addr]))
end
num_vars = length(parent_addrs(observations[addr]))
end
dims = map(i -> in_factor[i] ? length(latents[all_latent_addrs[i]].domain) : 1, 1:N)
log_factor = Array{Float64,N}(undef, dims...)
view_inds = map(i -> in_factor[i] ? Colon() : 1, 1:N)
log_factor_view = view(log_factor, view_inds...)
var_addrs = Vector{Any}(undef, num_vars)
value_idx_lists = Vector{Any}(undef, num_vars)
j = 1
for i in 1:N
if in_factor[i]
a = all_latent_addrs[i]
var_addrs[j] = a
value_idx_lists[j] = collect(1:length(latents[a].domain))
j += 1
end
end
@assert j == num_vars + 1
# populate factor with values by probing trace with update
# the key idea is that this scales exponentially in maximum number of
# parents of a variable, not the total number of variables
cprod = cartesian_product(value_idx_lists)
for value_idx_tuple in cprod
choices = choicemap()
for (a, value_idx) in zip(var_addrs, value_idx_tuple)
choices[a] = latents[a].domain[value_idx]
end
(tmp_trace, _, _, _) = update(trace, get_args(trace), map((_)->NoChange(),get_args(trace)), choices)
# NOTE: technically, the generative function of trace can use any
# internal proposal, not only forward sampling, but this code is only
# correct if the internal proposal uses forward sampling. enhancing the
# trace interface with some more methods that specifically assume a
# dependency graph would resolve this
weight = project(tmp_trace, select(addr))
log_factor_view[value_idx_tuple...] = weight
end
log_factor = log_factor .- logsumexp(log_factor[:])
return (log_factor, var_addrs)
end
function compile_trace_to_factor_graph(
trace, latents::Dict{Any,Latent}, observations::Dict{Any,Observation})
# choose order of addresses (note, this is NOT the elimination order)
# TODO does the order in which the addresses are indexed matter for e.g. cache performance? maybe?
all_latent_addrs = collect(keys(latents))
latent_addr_to_idx = Dict{Any,Int}()
for (idx, addr) in enumerate(all_latent_addrs)
latent_addr_to_idx[addr] = idx
end
# construct factor nodes, one for each latent and downstream variable
N = length(all_latent_addrs)
addr_to_factor_node = Dict{Any,FactorNode{N}}()
factor_id = 1
for addr in Iterators.flatten((keys(latents), keys(observations)))
(log_factor, var_addrs) = create_factor(
trace, addr, latents, observations, all_latent_addrs)
addr_to_factor_node[addr] = FactorNode{N}(factor_id, Int[latent_addr_to_idx[a] for a in var_addrs], log_factor)
factor_id += 1
end
num_factors = factor_id - 1
# for each latent address, the set of addresses for factors that it is involved in
children_and_self = [Set{Any}([all_latent_addrs[i]]) for i in 1:N]
for (addr, addr_info) in Iterators.flatten((latents, observations))
for parent_addr in parent_addrs(addr_info)
push!(children_and_self[latent_addr_to_idx[parent_addr]], addr)
end
end
# construct factor graph
var_nodes = PersistentHashMap{Int,VarNode}()
for (addr, addr_info) in latents
i = latent_addr_to_idx[addr]
factor_nodes = PersistentSet{FactorNode{N}}(
[addr_to_factor_node[addr] for addr in children_and_self[i]])
var_node = VarNode(addr, factor_nodes, addr_info.domain, get_domain_to_idx(addr_info.domain))
var_nodes = assoc(var_nodes, latent_addr_to_idx[addr], var_node)
end
return FactorGraph{N}(num_factors, var_nodes, latent_addr_to_idx)
end
|
#MAIN ENTRY POINT
#final columns for the decompressed file
#merges crsp and compustat
# note refresh merge will be automatically run if any of the other two are run
function loadccm(;
datapath::String=DATA_PATH,
ccmname::String = CCM_NAME,
incsvstream::Function = IN_CSV_STREAM,
csvextension::String = CSV_EXTENSION)
local ccm::DataFrame
#makes a serialization object so we don't have to keep parsing the CSV
ccm = incsvstream("$datapath\\$ccmname.$csvextension") |> CSV.File |> DataFrame
return ccm
end
function mergecompccm!(comp::DataFrame;
testoutput::Bool = TEST_OUTPUT,
months2stale::Int = MONTHS_2_STALE_LONG)
#first
local ccm::DataFrame = loadccm()
ccm = preprocessccm!(ccm)
testoutput && CSV.write("output\\ccm.csv", ccm)
select!(ccm, Not([:cusip]))
#println("Comp rows before merge: $(size(comp, 1))")
comp = innerjoin(comp, ccm, on=[:gvkey])
comp.keep = trues(size(comp,1))
comp.keep = (r::DataFrameRow->
r.adate ∈ r.linkeffdate:Day(1):r.linkenddate).(eachrow(comp))
comp = comp[comp.keep,:]
select!(comp, Not(:keep))
println("Comp rows after merge, post-filter: $(size(comp, 1))")
#Note: we still will have overlapping lineffdates and linkenddates, which will be corrected
#with the below method
comp = reconcilecompccmintervals!(comp)
# lagwithin!(comp, :fdate, :gvkey, :fyear)
sort!(comp, [:lpermno, :fdate])
issorted(comp, [:lpermno, :adate]) || error("I thought comp was sorted by [:lpermno, :adate]")
period2stale::Month = Month(months2stale)
lagwithin2!(comp, [:fdate, :fyrmonth], :lpermno, date=:fdate, maxnotstale = period2stale)
lagwithin2!(comp, [:Lfdate, :Lfyrmonth], :lpermno, date=:fdate, maxnotstale = period2stale)
for r ∈ eachrow(comp)
ismissing(r.Lfdate) && continue
(r.Lfdate < r.fdate - period2stale) && error("failed date check $r")
end
@info "past date validatation check"
#=
NOTE: we accept dup fyears due to changing fiscal years
function testfordups(df::AbstractDataFrame, groupfields::Vector{Symbol})
for sdf ∈ groupby(df, groupfields)
if size(sdf,1) > 1
println(sdf[!, [:gvkey, :lpermno, :fdate,
:Lfdate, :adate, :Nadate, :linkeffdate, :linkenddate, :begindate, :enddate, :fyear]])
error("duplicate fyear found")
end
end
@info "passed dedup fyear test"
end
testfordups(comp, [:lpermno, :fyear])=#
return comp
end
#formats the ccm table in a reasonable way
function preprocessccm!(ccm::DataFrame;
retainedcolsccm::Vector{Symbol} = RETAINED_COLS_CCM,
lastdatestring::String = LAST_DATE_STRING,
testoutput::Bool = TEST_OUTPUT)
#names ot lower case
cleannames::Vector{String} = (s::String->lowercase(s)).(names(ccm))
rename!(ccm, ((oldn, newn)->oldn=>newn).(names(ccm), cleannames))
#fix the end date
ccm.linkenddt .= (s::MString->
coalesce(s,"")=="E" ? lastdatestring : s).(ccm.linkenddt)
#below didn't work for some reason
#filter!(r::DataFrameRow->((!ismissing(r.gvkey)) && (!ismissing(r.lpermno))), ccm)
ccm = ccm[(r::DataFrameRow->(
(!ismissing(r.gvkey)) && (!ismissing(r.lpermno)))).(eachrow(ccm)),:]
ccm.linkprim = (s::String->length(s)==1 ? s[1] : error("invalid linkprim in ccm")).(ccm.linkprim)
filter!(r::DataFrameRow->r.linkprim =='P' || r.linkprim =='C', ccm)
#parse the dates
ccm.linkeffdate = (s->parseccm(Date, s)).(ccm.linkdt)
ccm.linkenddate = (s->parseccm(Date, s)).(ccm.linkenddt)
#dedup if possible
ccm.tokeep = trues(size(ccm,1))
ccm.dateranges = ((linkeffdate::Date,linkenddate::Date)->
linkeffdate:Day(1):linkenddate).(ccm.linkeffdate,ccm.linkenddate)
gccm::GroupedDataFrame = groupby(ccm, [:gvkey, :lpermno])
@mpar for i ∈ 1:length(gccm)
sccm::SubDataFrame = gccm[i]
Nsccm::Int = size(sccm,1)
#construct the union of all of the date sets
if Nsccm > 1
local periodrange::StepRange{Date,Day} = minimum(
sccm.linkeffdate):Day(1):maximum(sccm.linkenddate)
local dateunionlength::Int = length(unique([sccm.dateranges...;]))
if dateunionlength == length(periodrange)
sccm.linkeffdate[1] = minimum(periodrange)
sccm.linkenddate[1] = maximum(periodrange)
sccm.tokeep[2:end] .= false
end
end
end
println("ccm size pre-dedup $(size(ccm))")
ccm = ccm[ccm.tokeep,:]
println("ccm size post-dedup $(size(ccm))")
if testoutput
testoutput && CSV.write("output\\ccm_preproc.csv", ccm)
end
#rename!(ccm, :indfmt=>:indfmtold)
#ccm.indfmt = (s::MString->parsecomp(Symbol, s)).(ccm.indfmtold)
#only need some of the fields
ccm = select!(ccm, retainedcolsccm)
return ccm
end
#this function reconciles the link intervals with the announcement intervals
#NOTE: A weird situation can arise if gvkey changes. The the linkenddate finishes too soon,
#we end up with a gap . Considering the laternatives, it seems like the lesser evil
#to extending the record beyond the linkenddate
function reconcilecompccmintervals!(comp::DataFrame)
#subtract one day since the effective interval is inclusive of the
#first date while the begin-end date is exclusve of the first date
comp.begindate .= (max).(comp.begindate, comp.linkeffdate .- Day(1))
comp.enddate .= (min).(comp.enddate, comp.linkenddate)
#this gets rid of one day records
#(this assumes the previous effective record is the current record)
#not many of these ~140
#println("records before interval reconciliation: $(size(comp,1))")
#println(comp[comp.begindate .≥ comp.enddate,
# [:gvkey, :adateq, :begindate, :enddate, :linkeffdate, :linkenddate]])
comp = comp[comp.begindate .< comp.enddate, :]
println("records after interval reconciliation: $(size(comp,1))")
return comp
end
function parseccm(::Type{T}, s::String;
#=parsedmissings = CCM_PARSED_MISSINGS=#) where T
#if it doesn't parse to the right type, set to missing
v::Union{T,Missing} = something(tryparse(T, s), missing)
#check against the list of missing codes
#(!ismissing(v)) && (v ∈ parsedmissings) && (v=missing)
return v
end
#the date case
parseccm(::Type{Date}, s::String;
ccmdateformat::DateFormat = CCM_DATE_FORMAT) = Dates.Date(s, ccmdateformat)
#helper methods and special cases
parseccm(::Type{<:Any}, v::Missing) = missing
parseccm(::Type{Date}, i::Int) = parseccm(Date, "$i")
parseccm(::Type{Symbol}, s::String) = Symbol(s)
|
module ComradeSoss
#Turn off precompilations because of GG bug https://github.com/cscherrer/Soss.jl/issues/267
__precompile__(false)
using HypercubeTransform
using Reexport
@reexport using Soss
@reexport using Comrade
import Distributions
const Dists = Distributions
using MeasureTheory
using NamedTupleTools
using NestedTuples
using MacroTools
using PyCall
using Random
using Requires
using ParameterHandling
using StatsBase: median
using StatsBase
using StructArrays
using TupleVectors
# This is a hack for MeasureTheory since it wants the type to output
Base.rand(rng::AbstractRNG, ::Type{Float64}, d::Dists.ContinuousDistribution) = rand(rng, d)
const rad2μas = 180.0/π*3600*1e6
#These hold the pointers to the PyObjects that will store dynesty and ehtim
#and are loaded at initialization
const dynesty = PyNULL()
export ObsChar, scandata,
create_joint,
DynestyStatic,
sample, optimize,
threaded_optimize,
chi2, ehtim
#include("ehtim.jl")
include("utility.jl")
include("hypercube.jl")
include("inference.jl")
include("dists.jl")
include("models.jl")
#include("grads.jl")
#include("nlopt.jl")
#include("hmc.jl")
function __init__()
copy!(dynesty, pyimport("dynesty"))
@require UltraNest="6822f173-b0be-4018-9ee2-28bf56348d09" include("ultranest.jl")
@require NestedSamplers="41ceaf6f-1696-4a54-9b49-2e7a9ec3782e" include("nested.jl")
@require BlackBoxOptim="a134a8b2-14d6-55f6-9291-3336d3ab0209" include("bboptim.jl")
@require Metaheuristics="bcdb8e00-2c21-11e9-3065-2b553b22f898" include("metaheuristics.jl")
end
end #end ComradeSoss
|
#############################################################################
# Joulia
# A Large-Scale Spatial Power System Model for Julia
# See https://github.com/JuliaEnergy/Joulia.jl
#############################################################################
# This file contains functions and structs for nodes
mutable struct Nodes
id
load
exchange
function Nodes(nodes_df::DataFrame, load_df::DataFrame, exchange_df::DataFrame)
N = Symbol.(nodes_df[1])
load_dict = df_to_dict(load_df)
insert_default!(load_dict, fill(0.0, 8760), N)
exchange_dict = df_to_dict(exchange_df)
insert_default!(exchange_dict, fill(0.0, 8760), N)
return new(N, load_dict, exchange_dict)
end
end
|
@with_kw type Body2D <: Body
name::String = "None"
parent::Body = ground2D()
connection::connection2D = free2D("None")
mass::SymFloat = SymFloat(symbols("m_None",nonnegative=true,real=true))
inertia::SymFloat = SymFloat(symbols("I_None",nonnegative=true,real=true))
end
function ==(b1::Body2D,b2::Body2D)
f = fieldnames(b1)
for i in f
if getfield(b1,i) != getfield(b2,i)
return false
end
end
return true
end
|
"""
child = replace(parent, query => replacement)
Generates a `child` crystal structure by (i) searches the `parent` crystal structure for subgraphs that match the `query` then
(ii) replaces the substructures of the `parent` matching the `query` fragment with the `replacement` fragment.
Equivalent to calling `substructure_replace(query ∈ parent, replacement)`.
Accepts the same keyword arguments as [`substructure_replace`](@ref).
"""
replace(p::Crystal, pair::Pair; kwargs...) = substructure_replace(pair[1] ∈ p, pair[2]; kwargs...)
"""
alignment = Alignment(rot::Matrix{Float64}, shift_1::Vector{Float64}, shift_2::Vector{Float64}, err::Float64)
Data structure for tracking alignment in substructure find/replace operations.
"""
struct Alignment
rot::Matrix{Float64}
# before rotation
shift_1::Vector{Float64}
# after rotation
shift_2::Vector{Float64}
# error
err::Float64
end
struct Installation
aligned_replacement::Crystal
q2p::Dict{Int, Int}
r2p::Dict{Int, Int}
end
function get_r2p_alignment(replacement::Crystal, parent::Crystal, r2p::Dict{Int, Int}, q2p::Dict{Int, Int})
center = (X::Matrix{Float64}) -> sum(X, dims=2)[:] / size(X, 2)
# when both centered to origin
@assert replacement.atoms.n ≥ 3 && parent.atoms.n ≥ 3 "Parent and replacement must each be at least 3 atoms for SVD alignment."
###
# compute centered Cartesian coords of the atoms of
# replacement fragment involved in alignment
###
atoms_r = Cart(replacement.atoms[[r for (r, p) in r2p]], replacement.box)
X_r = atoms_r.coords.x
x_r_center = center(X_r)
X_r = X_r .- x_r_center
###
# compute centered Cartesian coords of the atoms of
# parent involved in alignment
###
# handle fragments cut across the PB using the parent subset isomorphic to query
parent_substructure = deepcopy(parent[[p for (q, p) in q2p]])
conglomerate!(parent_substructure) # must do this for when replacement fragment is disconnected
# prepare parent substructure having correspondence with replacement
p2ps = Dict([p => i for (i, p) in enumerate([p for (q, p) in q2p])]) # parent to parent subset map
parent_substructure_to_align_to = parent_substructure[[p2ps[p] for p in [p for (r, p) in r2p]]]
atoms_p = Cart(parent_substructure_to_align_to.atoms, parent.box)
X_p = atoms_p.coords.x
x_p_center = center(X_p)
X_p = X_p .- x_p_center
# solve the orthogonal procrustes probelm via SVD
F = svd(X_r * X_p')
# optimal rotation matrix
rot = F.V * F.U'
err = norm(rot * X_r - X_p)
return Alignment(rot, - x_r_center, x_p_center, err)
end
function conglomerate!(parent_substructure::Crystal)
# snip the cross-PB bonds
bonds = deepcopy(parent_substructure.bonds)
if length(connected_components(bonds)) > 1
@warn "# connected components in parent substructure > 1. assuming the substructure does not cross the periodic boundary..."
return
end
drop_cross_pb_bonds!(bonds)
# find connected components of bonding graph without cross-PB bonds
# these are the components split across the boundary
conn_comps = connected_components(bonds)
# if substructure is entireline in the unit cell, it's already conglomerated :)
if length(conn_comps) == 1
return
end
# we wish to shift all connected components to a reference component,
# defined to be the largest component for speed.
conn_comps_shifted = [false for c = 1:length(conn_comps)]
ref_comp_id = argmax(length.(conn_comps))
conn_comps_shifted[ref_comp_id] = true # consider it shifted.
# has atom p been shifted?
function shifted_atom(p::Int)
# loop over all connected components that have been shifted
for conn_comp in conn_comps[conn_comps_shifted]
# if parent substructure atom in this, yes!
if p in conn_comp
return true
end
end
# reached this far, atom p is not in component that has been shifted.
return false
end
# to which component does atom p belong?
function find_component(p::Int)
for c = 1:length(conn_comps)
if p in conn_comps[c]
return c
end
end
end
# until all components have been shifted to the reference component...
while ! all(conn_comps_shifted)
# loop over cross-PB edges in the parent substructure
for ed in edges(parent_substructure.bonds)
if get_prop(parent_substructure.bonds, ed, :cross_boundary)
# if one edge belongs to unshifted component and another belogs to any component that has been shifted...
if shifted_atom(ed.src) && ! shifted_atom(ed.dst)
p_ref, p = ed.src, ed.dst
elseif shifted_atom(ed.dst) && ! shifted_atom(ed.src)
p_ref, p = ed.dst, ed.src
else
continue # both are shifted or both are unshifted. ignore this cross-PB edge
end
# here's the unshifted component we will shift next, to be next to the shifted components.
comp_id = find_component(p)
# find displacement vector for this cross-PB edge.
dx = parent_substructure.atoms.coords.xf[:, p_ref] - parent_substructure.atoms.coords.xf[:, p]
# get distance to nearest image
n_dx = copy(dx)
nearest_image!(n_dx)
# shift all atoms in this component by this vector.
for atom_idx in conn_comps[comp_id]
parent_substructure.atoms.coords.xf[:, atom_idx] .+= dx - n_dx
end
# mark that we've shifted this component.
conn_comps_shifted[comp_id] = true
end
end
end
return
end
function aligned_replacement(replacement::Crystal, parent::Crystal, r2p_alignment::Alignment)
# put replacement into cartesian space
atoms_r = Cart(replacement.atoms, replacement.box)
# rotate replacement to align with parent_subset
atoms_r.coords.x[:, :] = r2p_alignment.rot * (atoms_r.coords.x .+ r2p_alignment.shift_1) .+ r2p_alignment.shift_2
# cast atoms back to Frac
return Crystal(replacement.name, parent.box, Frac(atoms_r, parent.box), Charges{Frac}(0), replacement.bonds, replacement.symmetry)
end
function effect_replacements(search::Search, replacement::Crystal, configs::Vector{Tuple{Int, Int}}, name::String)::Crystal
nb_not_masked = sum(.! occursin.(rc[:r_tag], String.(search.query.atoms.species)))
if replacement.atoms.n > 0
q_unmasked_in_r = substructure_search(search.query[1:nb_not_masked], replacement)
q2r = Dict([q => q_unmasked_in_r.isomorphisms[1][1][q] for q in 1:nb_not_masked])
else
q2r = Dict{Int, Int}()
end
installations = [optimal_replacement(search, replacement, q2r, loc_id, [ori_id]) for (loc_id, ori_id) in configs]
child = install_replacements(search.parent, installations, name)
# handle `missing` values in edge :cross_boundary attribute
for edge in edges(child.bonds) # loop over edges
# check if cross-boundary info is missing
if ismissing(get_prop(child.bonds, edge, :cross_boundary))
# check if bond crosses boundary
distance_e = get_prop(child.bonds, edge, :distance) # distance in edge property
dxa = Cart(Frac(child.atoms.coords.xf[:, src(edge)] - child.atoms.coords.xf[:, dst(edge)]), child.box) # Cartesian displacement
distance_a = norm(dxa.x) # current euclidean distance by atom coords
set_prop!(child.bonds, edge, :cross_boundary, !isapprox(distance_e, distance_a, atol=0.1))
end
end
return child
end
function install_replacements(parent::Crystal, replacements::Vector{Installation}, name::String)::Crystal
# create child w/o symmetry rules for sake of crystal addition
child = Crystal(name, parent.box, parent.atoms, parent.charges, parent.bonds, Xtals.SymmetryInfo())
obsolete_atoms = Int[] # to delete at the end
# loop over replacements to install
for installation in replacements
replacement, q2p, r2p = installation.aligned_replacement, installation.q2p, installation.r2p
#add into parent
if replacement.atoms.n > 0
child = +(child, replacement, check_overlap=false)
end
# reconstruct bonds
for (r, p) in r2p # p is in parent_subst
p_nbrs = neighbors(parent.bonds, p)
for p_nbr in p_nbrs
if ! (p_nbr in values(q2p)) # p_nbr not in parent_subst
# need bond nbr => r in child, where r is in replacement
e = (p_nbr, child.atoms.n - replacement.atoms.n + r)
# create edge
add_edge!(child.bonds, e)
# copy edge attributes from parent (:cross_boundary will need to be reassessed later)
set_props!(child.bonds, e[1], e[2], props(parent.bonds, p, p_nbr))
set_prop!(child.bonds, e[1], e[2], :cross_boundary, missing)
end
end
end
# accumulate atoms to delete
obsolete_atoms = vcat(obsolete_atoms, values(q2p)...)
end
# delete obsolete atoms
obsolete_atoms = unique(obsolete_atoms)
keep_atoms = [p for p = 1:child.atoms.n if ! (p in obsolete_atoms)]
child = child[keep_atoms]
# restore symmetry rules
child = Crystal(name, child.box, child.atoms, child.charges, child.bonds, parent.symmetry)
# return result
return child
end
function optimal_replacement(search::Search, replacement::Crystal, q2r::Dict{Int,Int}, loc_id::Int, ori_ids::Vector{Int})
# unpack search arg
isomorphisms, parent = search.isomorphisms, search.parent
if q2r == Dict{Int, Int}() # "replace-with-nothing" operation
q2p = isomorphisms[loc_id][1]
r2p = Dict([0 => p for p in values(q2p)])
return Installation(replacement, q2p, r2p)
end
if ori_ids == [0]
ori_ids = [1:nb_ori_at_loc(search)[loc_id]...]
end
# loop over ori_ids to find best r2p_alignment
r2p_alignment = Alignment(zeros(1,1), [0.], [0.], Inf)
best_ori = 0
best_r2p = Dict{Int, Int}()
for ori_id in ori_ids
# find r2p isom
q2p = isomorphisms[loc_id][ori_id]
r2p = Dict([r => q2p[q] for (q, r) in q2r])
# calculate alignment
test_alignment = get_r2p_alignment(replacement, parent, r2p, q2p)
# keep best alignment and generating ori_id
if test_alignment.err < r2p_alignment.err
r2p_alignment = test_alignment
best_ori = ori_id
best_r2p = r2p
end
end
opt_aligned_replacement = aligned_replacement(replacement, parent, r2p_alignment)
# return the replacement modified according to r2p_alignment
@assert ne(opt_aligned_replacement.bonds) == ne(replacement.bonds)
return Installation(opt_aligned_replacement, isomorphisms[loc_id][best_ori], best_r2p)
end
@doc raw"""
child = substructure_replace(search, replacement; random=false, nb_loc=0, loc=Int[], ori=Int[], name="new_xtal", verbose=false, remove_duplicates=false, periodic_boundaries=true)
Replace the substructures of `search.parent` matching the `search.query` fragment with the `replacement` fragment,
at locations and orientations specified by the keyword arguments `random`, `nb_loc`, `loc`, and `ori`.
Default behavior is to effect replacements at all "hit" locations in the parent structure and, at each location,
choose the orientation giving the optimal (lowest error) spatial aligment.
Returns a new `Crystal` with the specified modifications (returns `search.parent` if no replacements are made).
# Arguments
- `search::Search` the `Search` for a substructure moiety in the parent crystal
- `replacement::Crystal` the moiety to use for replacement of the searched substructure
- `random::Bool` set `true` to select random replacement orientations
- `nb_loc::Int` assign a value to select random replacement at `nb_loc` random locations
- `loc::Array{Int}` assign value(s) to select specific locations for replacement. If `ori` is not specified, replacement orientation is random.
- `ori::Array{Int}` assign value(s) when `loc` is assigned to specify exact configurations for replacement. `0` values mean the configuration at that location should be selected for optimal alignment with the parent.
- `name::String` assign to give the generated `Crystal` a name ("new_xtal" by default)
- `verbose::Bool` set `true` to print console messages about the replacement(s) being performed
- `remove_duplicates::Bool` set `true` to automatically combine overlapping atoms of the same species in generated structures.
- `reinfer_bonds::Bool` set `true` to re-infer bonds after producing a structure
- `periodic_boundaries::Bool` set `false` to disable periodic boundary conditions when checking for atom duplication or re-inferring bonds
"""
function substructure_replace(search::Search, replacement::Crystal; random::Bool=false,
nb_loc::Int=0, loc::Array{Int}=Int[], ori::Array{Int}=Int[], name::String="new_xtal", verbose::Bool=false,
remove_duplicates::Bool=false, periodic_boundaries::Bool=true, reinfer_bonds::Bool=false, wrap::Bool=true)::Crystal
# replacement at all locations (default)
if nb_loc == 0 && loc == Int[] && ori == Int[]
nb_loc = nb_locations(search)
loc = [1:nb_loc...]
if random
ori = [rand(1:nb_ori_at_loc(search)[i]) for i in loc]
if verbose
@info "Replacing" q_in_p=search r=replacement.name mode="random ori @ all loc"
end
else
ori = zeros(Int, nb_loc)
if verbose
@info "Replacing" q_in_p=search r=replacement.name mode="optimal ori @ all loc"
end
end
# replacement at nb_loc random locations
elseif nb_loc > 0 && ori == Int[] && loc == Int[]
loc = sample([1:nb_locations(search)...], nb_loc, replace=false)
if random
ori = [rand(1:nb_ori_at_loc(search)[i]) for i in loc]
if verbose
@info "Replacing" q_in_p=search r=replacement.name mode="random ori @ $nb_loc loc"
end
else
ori = zeros(Int, nb_loc)
if verbose
@info "Replacing" q_in_p=search r=replacement.name mode="optimal ori @ $nb_loc loc"
end
end
# specific replacements
elseif ori ≠ Int[] && loc ≠ Int[]
@assert length(loc) == length(ori) "one orientation per location"
nb_loc = length(ori)
if verbose
@info "Replacing" q_in_p=search r=replacement.name mode="loc: $loc\tori: $ori"
end
# replacement at specific locations
elseif loc ≠ Int[]
nb_loc = length(loc)
if random
ori = [rand(1:nb_ori_at_loc(search)[i]) for i in loc]
if verbose
@info "Replacing" q_in_p=search r=replacement.name mode="random ori @ loc: $loc"
end
else
ori = zeros(Int, nb_loc)
if verbose
@info "Replacing" q_in_p=search r=replacement.name mode="optimal ori @ loc: $loc"
end
end
end
# remove charges from parent
if search.parent.charges.n > 0
@warn "Dropping charges from parent."
p = search.parent
search = Search(
Crystal(p.name, p.box, p.atoms, Charges{Frac}(0), p.bonds, p.symmetry),
search.query,
search.isomorphisms
)
end
# generate configuration tuples (location, orientation)
configs = Tuple{Int,Int}[(loc[i], ori[i]) for i in 1:nb_loc]
# process replacements
child = effect_replacements(search, replacement, configs, name)
if remove_duplicates
child = Crystal(child.name, child.box,
Xtals.remove_duplicates(child.atoms, child.box, periodic_boundaries),
Xtals.remove_duplicates(child.charges, child.box, periodic_boundaries)
)
end
if wrap
# throw error if installed replacement fragment spans the unit cell
if any(abs.(child.atoms.coords.xf) .> 2.0)
error("installed replacement fragment too large for the unit cell; replicate the parent and try again.")
end
# wrap coordinates
wrap!(child.atoms.coords)
# check :cross_boundary edge attributes
for edge in edges(child.bonds) # loop over edges
distance_e = get_prop(child.bonds, edge, :distance) # distance in edge property
dxa = Cart(Frac(child.atoms.coords.xf[:, src(edge)] - child.atoms.coords.xf[:, dst(edge)]), child.box) # Cartesian displacement
distance_a = norm(dxa.x) # current euclidean distance by atom coords
set_prop!(child.bonds, edge, :cross_boundary, !isapprox(distance_e, distance_a, atol=0.1))
end
end
if reinfer_bonds
remove_bonds!(child)
infer_bonds!(child, periodic_boundaries)
end
return child
end
substructure_replace(search::Search, replacement::Nothing; kwargs...) = substructure_replace(search, moiety(nothing); kwargs...)
|
# AUTO GENERATED FILE - DO NOT EDIT
export 'feffery'_antdalert
"""
'feffery'_antdalert(;kwargs...)
An AntdAlert component.
Keyword arguments:
- `id` (String; optional)
- `className` (String; optional)
- `closable` (Bool; optional)
- `description` (String; optional)
- `loading_state` (optional): . loading_state has the following type: lists containing elements 'is_loading', 'prop_name', 'component_name'.
Those elements have the following types:
- `is_loading` (Bool; optional): Determines if the component is loading or not
- `prop_name` (String; optional): Holds which property is loading
- `component_name` (String; optional): Holds the name of the component that is loading
- `message` (String | Array of Strings; optional)
- `messageRenderMode` (a value equal to: 'default', 'loop-text', 'marquee'; optional)
- `showIcon` (Bool; optional)
- `style` (Dict; optional)
- `type` (a value equal to: 'success', 'info', 'warning', 'error'; optional)
"""
function 'feffery'_antdalert(; kwargs...)
available_props = Symbol[:id, :className, :closable, :description, :loading_state, :message, :messageRenderMode, :showIcon, :style, :type]
wild_props = Symbol[]
return Component("'feffery'_antdalert", "AntdAlert", "feffery_antd_components", available_props, wild_props; kwargs...)
end
|
module ATI
import GetC.@getCFun
typealias GLenum Cuint
typealias GLboolean Cuchar
typealias GLbitfield Cuint
typealias GLvoid Void
typealias GLbyte Cuchar
typealias GLshort Cshort
typealias GLint Cint
typealias GLubyte Cuchar
typealias GLushort Cushort
typealias GLuint Cuint
typealias GLsizei Csize_t
typealias GLfloat Cfloat
typealias GLclampf Cfloat
typealias GLdouble Cdouble
typealias GLclampd Cdouble
typealias GLchar Cchar
typealias GLint64 Clonglong
typealias GLuint64 Culonglong
typealias GLhalf Cushort
typealias GLhalfARB Cushort
typealias GLhalfNV Cushort
typealias GLsync Ptr{Void}
typealias Pointer Ptr{Void}
typealias GLsizeiptr Cint
typealias GLintptr Cptrdiff_t
const DRAW_BUFFER0_ATI = 0x8825
export DRAW_BUFFER0_ATI
const DRAW_BUFFER10_ATI = 0x882F
export DRAW_BUFFER10_ATI
const DRAW_BUFFER11_ATI = 0x8830
export DRAW_BUFFER11_ATI
const DRAW_BUFFER12_ATI = 0x8831
export DRAW_BUFFER12_ATI
const DRAW_BUFFER13_ATI = 0x8832
export DRAW_BUFFER13_ATI
const DRAW_BUFFER14_ATI = 0x8833
export DRAW_BUFFER14_ATI
const DRAW_BUFFER15_ATI = 0x8834
export DRAW_BUFFER15_ATI
const DRAW_BUFFER1_ATI = 0x8826
export DRAW_BUFFER1_ATI
const DRAW_BUFFER2_ATI = 0x8827
export DRAW_BUFFER2_ATI
const DRAW_BUFFER3_ATI = 0x8828
export DRAW_BUFFER3_ATI
const DRAW_BUFFER4_ATI = 0x8829
export DRAW_BUFFER4_ATI
const DRAW_BUFFER5_ATI = 0x882A
export DRAW_BUFFER5_ATI
const DRAW_BUFFER6_ATI = 0x882B
export DRAW_BUFFER6_ATI
const DRAW_BUFFER7_ATI = 0x882C
export DRAW_BUFFER7_ATI
const DRAW_BUFFER8_ATI = 0x882D
export DRAW_BUFFER8_ATI
const DRAW_BUFFER9_ATI = 0x882E
export DRAW_BUFFER9_ATI
const MAX_DRAW_BUFFERS_ATI = 0x8824
export MAX_DRAW_BUFFERS_ATI
const ELEMENT_ARRAY_ATI = 0x8768
export ELEMENT_ARRAY_ATI
const ELEMENT_ARRAY_POINTER_ATI = 0x876A
export ELEMENT_ARRAY_POINTER_ATI
const ELEMENT_ARRAY_TYPE_ATI = 0x8769
export ELEMENT_ARRAY_TYPE_ATI
const BUMP_ENVMAP_ATI = 0x877B
export BUMP_ENVMAP_ATI
const BUMP_NUM_TEX_UNITS_ATI = 0x8777
export BUMP_NUM_TEX_UNITS_ATI
const BUMP_ROT_MATRIX_ATI = 0x8775
export BUMP_ROT_MATRIX_ATI
const BUMP_ROT_MATRIX_SIZE_ATI = 0x8776
export BUMP_ROT_MATRIX_SIZE_ATI
const BUMP_TARGET_ATI = 0x877C
export BUMP_TARGET_ATI
const BUMP_TEX_UNITS_ATI = 0x8778
export BUMP_TEX_UNITS_ATI
const DU8DV8_ATI = 0x877A
export DU8DV8_ATI
const DUDV_ATI = 0x8779
export DUDV_ATI
const X2X_BIT_ATI = 0x00000001
export X2X_BIT_ATI
const X4X_BIT_ATI = 0x00000002
export X4X_BIT_ATI
const X8X_BIT_ATI = 0x00000004
export X8X_BIT_ATI
const ADD_ATI = 0x8963
export ADD_ATI
const BIAS_BIT_ATI = 0x00000008
export BIAS_BIT_ATI
const BLUE_BIT_ATI = 0x00000004
export BLUE_BIT_ATI
const CND0_ATI = 0x896B
export CND0_ATI
const CND_ATI = 0x896A
export CND_ATI
const COLOR_ALPHA_PAIRING_ATI = 0x8975
export COLOR_ALPHA_PAIRING_ATI
const COMP_BIT_ATI = 0x00000002
export COMP_BIT_ATI
const CON_0_ATI = 0x8941
export CON_0_ATI
const CON_10_ATI = 0x894B
export CON_10_ATI
const CON_11_ATI = 0x894C
export CON_11_ATI
const CON_12_ATI = 0x894D
export CON_12_ATI
const CON_13_ATI = 0x894E
export CON_13_ATI
const CON_14_ATI = 0x894F
export CON_14_ATI
const CON_15_ATI = 0x8950
export CON_15_ATI
const CON_16_ATI = 0x8951
export CON_16_ATI
const CON_17_ATI = 0x8952
export CON_17_ATI
const CON_18_ATI = 0x8953
export CON_18_ATI
const CON_19_ATI = 0x8954
export CON_19_ATI
const CON_1_ATI = 0x8942
export CON_1_ATI
const CON_20_ATI = 0x8955
export CON_20_ATI
const CON_21_ATI = 0x8956
export CON_21_ATI
const CON_22_ATI = 0x8957
export CON_22_ATI
const CON_23_ATI = 0x8958
export CON_23_ATI
const CON_24_ATI = 0x8959
export CON_24_ATI
const CON_25_ATI = 0x895A
export CON_25_ATI
const CON_26_ATI = 0x895B
export CON_26_ATI
const CON_27_ATI = 0x895C
export CON_27_ATI
const CON_28_ATI = 0x895D
export CON_28_ATI
const CON_29_ATI = 0x895E
export CON_29_ATI
const CON_2_ATI = 0x8943
export CON_2_ATI
const CON_30_ATI = 0x895F
export CON_30_ATI
const CON_31_ATI = 0x8960
export CON_31_ATI
const CON_3_ATI = 0x8944
export CON_3_ATI
const CON_4_ATI = 0x8945
export CON_4_ATI
const CON_5_ATI = 0x8946
export CON_5_ATI
const CON_6_ATI = 0x8947
export CON_6_ATI
const CON_7_ATI = 0x8948
export CON_7_ATI
const CON_8_ATI = 0x8949
export CON_8_ATI
const CON_9_ATI = 0x894A
export CON_9_ATI
const DOT2_ADD_ATI = 0x896C
export DOT2_ADD_ATI
const DOT3_ATI = 0x8966
export DOT3_ATI
const DOT4_ATI = 0x8967
export DOT4_ATI
const EIGHTH_BIT_ATI = 0x00000020
export EIGHTH_BIT_ATI
const FRAGMENT_SHADER_ATI = 0x8920
export FRAGMENT_SHADER_ATI
const GREEN_BIT_ATI = 0x00000002
export GREEN_BIT_ATI
const HALF_BIT_ATI = 0x00000008
export HALF_BIT_ATI
const LERP_ATI = 0x8969
export LERP_ATI
const MAD_ATI = 0x8968
export MAD_ATI
const MOV_ATI = 0x8961
export MOV_ATI
const MUL_ATI = 0x8964
export MUL_ATI
const NEGATE_BIT_ATI = 0x00000004
export NEGATE_BIT_ATI
const NUM_FRAGMENT_CONSTANTS_ATI = 0x896F
export NUM_FRAGMENT_CONSTANTS_ATI
const NUM_FRAGMENT_REGISTERS_ATI = 0x896E
export NUM_FRAGMENT_REGISTERS_ATI
const NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI = 0x8973
export NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI
const NUM_INSTRUCTIONS_PER_PASS_ATI = 0x8971
export NUM_INSTRUCTIONS_PER_PASS_ATI
const NUM_INSTRUCTIONS_TOTAL_ATI = 0x8972
export NUM_INSTRUCTIONS_TOTAL_ATI
const NUM_LOOPBACK_COMPONENTS_ATI = 0x8974
export NUM_LOOPBACK_COMPONENTS_ATI
const NUM_PASSES_ATI = 0x8970
export NUM_PASSES_ATI
const QUARTER_BIT_ATI = 0x00000010
export QUARTER_BIT_ATI
const RED_BIT_ATI = 0x00000001
export RED_BIT_ATI
const REG_0_ATI = 0x8921
export REG_0_ATI
const REG_10_ATI = 0x892B
export REG_10_ATI
const REG_11_ATI = 0x892C
export REG_11_ATI
const REG_12_ATI = 0x892D
export REG_12_ATI
const REG_13_ATI = 0x892E
export REG_13_ATI
const REG_14_ATI = 0x892F
export REG_14_ATI
const REG_15_ATI = 0x8930
export REG_15_ATI
const REG_16_ATI = 0x8931
export REG_16_ATI
const REG_17_ATI = 0x8932
export REG_17_ATI
const REG_18_ATI = 0x8933
export REG_18_ATI
const REG_19_ATI = 0x8934
export REG_19_ATI
const REG_1_ATI = 0x8922
export REG_1_ATI
const REG_20_ATI = 0x8935
export REG_20_ATI
const REG_21_ATI = 0x8936
export REG_21_ATI
const REG_22_ATI = 0x8937
export REG_22_ATI
const REG_23_ATI = 0x8938
export REG_23_ATI
const REG_24_ATI = 0x8939
export REG_24_ATI
const REG_25_ATI = 0x893A
export REG_25_ATI
const REG_26_ATI = 0x893B
export REG_26_ATI
const REG_27_ATI = 0x893C
export REG_27_ATI
const REG_28_ATI = 0x893D
export REG_28_ATI
const REG_29_ATI = 0x893E
export REG_29_ATI
const REG_2_ATI = 0x8923
export REG_2_ATI
const REG_30_ATI = 0x893F
export REG_30_ATI
const REG_31_ATI = 0x8940
export REG_31_ATI
const REG_3_ATI = 0x8924
export REG_3_ATI
const REG_4_ATI = 0x8925
export REG_4_ATI
const REG_5_ATI = 0x8926
export REG_5_ATI
const REG_6_ATI = 0x8927
export REG_6_ATI
const REG_7_ATI = 0x8928
export REG_7_ATI
const REG_8_ATI = 0x8929
export REG_8_ATI
const REG_9_ATI = 0x892A
export REG_9_ATI
const SATURATE_BIT_ATI = 0x00000040
export SATURATE_BIT_ATI
const SECONDARY_INTERPOLATOR_ATI = 0x896D
export SECONDARY_INTERPOLATOR_ATI
const SUB_ATI = 0x8965
export SUB_ATI
const SWIZZLE_STQ_ATI = 0x8977
export SWIZZLE_STQ_ATI
const SWIZZLE_STQ_DQ_ATI = 0x8979
export SWIZZLE_STQ_DQ_ATI
const SWIZZLE_STRQ_ATI = 0x897A
export SWIZZLE_STRQ_ATI
const SWIZZLE_STRQ_DQ_ATI = 0x897B
export SWIZZLE_STRQ_DQ_ATI
const SWIZZLE_STR_ATI = 0x8976
export SWIZZLE_STR_ATI
const SWIZZLE_STR_DR_ATI = 0x8978
export SWIZZLE_STR_DR_ATI
const RENDERBUFFER_FREE_MEMORY_ATI = 0x87FD
export RENDERBUFFER_FREE_MEMORY_ATI
const TEXTURE_FREE_MEMORY_ATI = 0x87FC
export TEXTURE_FREE_MEMORY_ATI
const VBO_FREE_MEMORY_ATI = 0x87FB
export VBO_FREE_MEMORY_ATI
const COLOR_CLEAR_UNCLAMPED_VALUE_ATI = 0x8835
export COLOR_CLEAR_UNCLAMPED_VALUE_ATI
const RGBA_FLOAT_MODE_ATI = 0x8820
export RGBA_FLOAT_MODE_ATI
const MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI = 0x87F1
export MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI
const PN_TRIANGLES_ATI = 0x87F0
export PN_TRIANGLES_ATI
const PN_TRIANGLES_NORMAL_MODE_ATI = 0x87F3
export PN_TRIANGLES_NORMAL_MODE_ATI
const PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI = 0x87F7
export PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI
const PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI = 0x87F8
export PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI
const PN_TRIANGLES_POINT_MODE_ATI = 0x87F2
export PN_TRIANGLES_POINT_MODE_ATI
const PN_TRIANGLES_POINT_MODE_CUBIC_ATI = 0x87F6
export PN_TRIANGLES_POINT_MODE_CUBIC_ATI
const PN_TRIANGLES_POINT_MODE_LINEAR_ATI = 0x87F5
export PN_TRIANGLES_POINT_MODE_LINEAR_ATI
const PN_TRIANGLES_TESSELATION_LEVEL_ATI = 0x87F4
export PN_TRIANGLES_TESSELATION_LEVEL_ATI
const STENCIL_BACK_FAIL_ATI = 0x8801
export STENCIL_BACK_FAIL_ATI
const STENCIL_BACK_FUNC_ATI = 0x8800
export STENCIL_BACK_FUNC_ATI
const STENCIL_BACK_PASS_DEPTH_FAIL_ATI = 0x8802
export STENCIL_BACK_PASS_DEPTH_FAIL_ATI
const STENCIL_BACK_PASS_DEPTH_PASS_ATI = 0x8803
export STENCIL_BACK_PASS_DEPTH_PASS_ATI
const TEXT_FRAGMENT_SHADER_ATI = 0x8200
export TEXT_FRAGMENT_SHADER_ATI
const MODULATE_ADD_ATI = 0x8744
export MODULATE_ADD_ATI
const MODULATE_SIGNED_ADD_ATI = 0x8745
export MODULATE_SIGNED_ADD_ATI
const MODULATE_SUBTRACT_ATI = 0x8746
export MODULATE_SUBTRACT_ATI
const ALPHA_FLOAT16_ATI = 0x881C
export ALPHA_FLOAT16_ATI
const ALPHA_FLOAT32_ATI = 0x8816
export ALPHA_FLOAT32_ATI
const INTENSITY_FLOAT16_ATI = 0x881D
export INTENSITY_FLOAT16_ATI
const INTENSITY_FLOAT32_ATI = 0x8817
export INTENSITY_FLOAT32_ATI
const LUMINANCE_ALPHA_FLOAT16_ATI = 0x881F
export LUMINANCE_ALPHA_FLOAT16_ATI
const LUMINANCE_ALPHA_FLOAT32_ATI = 0x8819
export LUMINANCE_ALPHA_FLOAT32_ATI
const LUMINANCE_FLOAT16_ATI = 0x881E
export LUMINANCE_FLOAT16_ATI
const LUMINANCE_FLOAT32_ATI = 0x8818
export LUMINANCE_FLOAT32_ATI
const RGBA_FLOAT16_ATI = 0x881A
export RGBA_FLOAT16_ATI
const RGBA_FLOAT32_ATI = 0x8814
export RGBA_FLOAT32_ATI
const RGB_FLOAT16_ATI = 0x881B
export RGB_FLOAT16_ATI
const RGB_FLOAT32_ATI = 0x8815
export RGB_FLOAT32_ATI
const MIRROR_CLAMP_ATI = 0x8742
export MIRROR_CLAMP_ATI
const MIRROR_CLAMP_TO_EDGE_ATI = 0x8743
export MIRROR_CLAMP_TO_EDGE_ATI
const ARRAY_OBJECT_BUFFER_ATI = 0x8766
export ARRAY_OBJECT_BUFFER_ATI
const ARRAY_OBJECT_OFFSET_ATI = 0x8767
export ARRAY_OBJECT_OFFSET_ATI
const DISCARD_ATI = 0x8763
export DISCARD_ATI
const DYNAMIC_ATI = 0x8761
export DYNAMIC_ATI
const OBJECT_BUFFER_SIZE_ATI = 0x8764
export OBJECT_BUFFER_SIZE_ATI
const OBJECT_BUFFER_USAGE_ATI = 0x8765
export OBJECT_BUFFER_USAGE_ATI
const PRESERVE_ATI = 0x8762
export PRESERVE_ATI
const STATIC_ATI = 0x8760
export STATIC_ATI
const MAX_VERTEX_STREAMS_ATI = 0x876B
export MAX_VERTEX_STREAMS_ATI
const VERTEX_SOURCE_ATI = 0x8774
export VERTEX_SOURCE_ATI
const VERTEX_STREAM0_ATI = 0x876C
export VERTEX_STREAM0_ATI
const VERTEX_STREAM1_ATI = 0x876D
export VERTEX_STREAM1_ATI
const VERTEX_STREAM2_ATI = 0x876E
export VERTEX_STREAM2_ATI
const VERTEX_STREAM3_ATI = 0x876F
export VERTEX_STREAM3_ATI
const VERTEX_STREAM4_ATI = 0x8770
export VERTEX_STREAM4_ATI
const VERTEX_STREAM5_ATI = 0x8771
export VERTEX_STREAM5_ATI
const VERTEX_STREAM6_ATI = 0x8772
export VERTEX_STREAM6_ATI
const VERTEX_STREAM7_ATI = 0x8773
export VERTEX_STREAM7_ATI
@getCFun "libGL" glDrawBuffersATI glDrawBuffersATI(n::GLsizei, bufs::Ptr{GLenum})::Void
export glDrawBuffersATI
@getCFun "libGL" glElementPointerATI glElementPointerATI(type_::GLenum, pointer::Ptr{Void})::Void
export glElementPointerATI
@getCFun "libGL" glDrawElementArrayATI glDrawElementArrayATI(mode::GLenum, count::GLsizei)::Void
export glDrawElementArrayATI
@getCFun "libGL" glDrawRangeElementArrayATI glDrawRangeElementArrayATI(mode::GLenum, start::GLuint, END::GLuint, count::GLsizei)::Void
export glDrawRangeElementArrayATI
@getCFun "libGL" glTexBumpParameterivATI glTexBumpParameterivATI(pname::GLenum, param::Ptr{GLint})::Void
export glTexBumpParameterivATI
@getCFun "libGL" glTexBumpParameterfvATI glTexBumpParameterfvATI(pname::GLenum, param::Ptr{GLfloat})::Void
export glTexBumpParameterfvATI
@getCFun "libGL" glGetTexBumpParameterivATI glGetTexBumpParameterivATI(pname::GLenum, param::Ptr{GLint})::Void
export glGetTexBumpParameterivATI
@getCFun "libGL" glGetTexBumpParameterfvATI glGetTexBumpParameterfvATI(pname::GLenum, param::Ptr{GLfloat})::Void
export glGetTexBumpParameterfvATI
@getCFun "libGL" glGenFragmentShadersATI glGenFragmentShadersATI(range_::GLuint)::Cuint
export glGenFragmentShadersATI
@getCFun "libGL" glBindFragmentShaderATI glBindFragmentShaderATI(id::GLuint)::Void
export glBindFragmentShaderATI
@getCFun "libGL" glDeleteFragmentShaderATI glDeleteFragmentShaderATI(id::GLuint)::Void
export glDeleteFragmentShaderATI
@getCFun "libGL" glBeginFragmentShaderATI glBeginFragmentShaderATI()::Void
export glBeginFragmentShaderATI
@getCFun "libGL" glEndFragmentShaderATI glEndFragmentShaderATI()::Void
export glEndFragmentShaderATI
@getCFun "libGL" glPassTexCoordATI glPassTexCoordATI(dst::GLuint, coord::GLuint, swizzle::GLenum)::Void
export glPassTexCoordATI
@getCFun "libGL" glSampleMapATI glSampleMapATI(dst::GLuint, interp::GLuint, swizzle::GLenum)::Void
export glSampleMapATI
@getCFun "libGL" glColorFragmentOp1ATI glColorFragmentOp1ATI(op::GLenum, dst::GLuint, dstMask::GLuint, dstMod::GLuint, arg1::GLuint, arg1Rep::GLuint, arg1Mod::GLuint)::Void
export glColorFragmentOp1ATI
@getCFun "libGL" glColorFragmentOp2ATI glColorFragmentOp2ATI(op::GLenum, dst::GLuint, dstMask::GLuint, dstMod::GLuint, arg1::GLuint, arg1Rep::GLuint, arg1Mod::GLuint, arg2::GLuint, arg2Rep::GLuint, arg2Mod::GLuint)::Void
export glColorFragmentOp2ATI
@getCFun "libGL" glColorFragmentOp3ATI glColorFragmentOp3ATI(op::GLenum, dst::GLuint, dstMask::GLuint, dstMod::GLuint, arg1::GLuint, arg1Rep::GLuint, arg1Mod::GLuint, arg2::GLuint, arg2Rep::GLuint, arg2Mod::GLuint, arg3::GLuint, arg3Rep::GLuint, arg3Mod::GLuint)::Void
export glColorFragmentOp3ATI
@getCFun "libGL" glAlphaFragmentOp1ATI glAlphaFragmentOp1ATI(op::GLenum, dst::GLuint, dstMod::GLuint, arg1::GLuint, arg1Rep::GLuint, arg1Mod::GLuint)::Void
export glAlphaFragmentOp1ATI
@getCFun "libGL" glAlphaFragmentOp2ATI glAlphaFragmentOp2ATI(op::GLenum, dst::GLuint, dstMod::GLuint, arg1::GLuint, arg1Rep::GLuint, arg1Mod::GLuint, arg2::GLuint, arg2Rep::GLuint, arg2Mod::GLuint)::Void
export glAlphaFragmentOp2ATI
@getCFun "libGL" glAlphaFragmentOp3ATI glAlphaFragmentOp3ATI(op::GLenum, dst::GLuint, dstMod::GLuint, arg1::GLuint, arg1Rep::GLuint, arg1Mod::GLuint, arg2::GLuint, arg2Rep::GLuint, arg2Mod::GLuint, arg3::GLuint, arg3Rep::GLuint, arg3Mod::GLuint)::Void
export glAlphaFragmentOp3ATI
@getCFun "libGL" glSetFragmentShaderConstantATI glSetFragmentShaderConstantATI(dst::GLuint, value::Ptr{GLfloat})::Void
export glSetFragmentShaderConstantATI
@getCFun "libGL" glMapObjectBufferATI glMapObjectBufferATI(buffer::GLuint)::Ptr{Void}
export glMapObjectBufferATI
@getCFun "libGL" glUnmapObjectBufferATI glUnmapObjectBufferATI(buffer::GLuint)::Void
export glUnmapObjectBufferATI
@getCFun "libGL" glPNTrianglesiATI glPNTrianglesiATI(pname::GLenum, param::GLint)::Void
export glPNTrianglesiATI
@getCFun "libGL" glPNTrianglesfATI glPNTrianglesfATI(pname::GLenum, param::GLfloat)::Void
export glPNTrianglesfATI
@getCFun "libGL" glStencilOpSeparateATI glStencilOpSeparateATI(face::GLenum, sfail::GLenum, dpfail::GLenum, dppass::GLenum)::Void
export glStencilOpSeparateATI
@getCFun "libGL" glStencilFuncSeparateATI glStencilFuncSeparateATI(frontfunc::GLenum, backfunc::GLenum, ref::GLint, mask::GLuint)::Void
export glStencilFuncSeparateATI
@getCFun "libGL" glNewObjectBufferATI glNewObjectBufferATI(size::GLsizei, pointer::Ptr{Void}, usage::GLenum)::Cuint
export glNewObjectBufferATI
@getCFun "libGL" glIsObjectBufferATI glIsObjectBufferATI(buffer::GLuint)::Bool
export glIsObjectBufferATI
@getCFun "libGL" glUpdateObjectBufferATI glUpdateObjectBufferATI(buffer::GLuint, offset::GLuint, size::GLsizei, pointer::Ptr{Void}, preserve::GLenum)::Void
export glUpdateObjectBufferATI
@getCFun "libGL" glGetObjectBufferfvATI glGetObjectBufferfvATI(buffer::GLuint, pname::GLenum, params::Ptr{GLfloat})::Void
export glGetObjectBufferfvATI
@getCFun "libGL" glGetObjectBufferivATI glGetObjectBufferivATI(buffer::GLuint, pname::GLenum, params::Ptr{GLint})::Void
export glGetObjectBufferivATI
@getCFun "libGL" glFreeObjectBufferATI glFreeObjectBufferATI(buffer::GLuint)::Void
export glFreeObjectBufferATI
@getCFun "libGL" glArrayObjectATI glArrayObjectATI(array::GLenum, size::GLint, type_::GLenum, stride::GLsizei, buffer::GLuint, offset::GLuint)::Void
export glArrayObjectATI
@getCFun "libGL" glGetArrayObjectfvATI glGetArrayObjectfvATI(array::GLenum, pname::GLenum, params::Ptr{GLfloat})::Void
export glGetArrayObjectfvATI
@getCFun "libGL" glGetArrayObjectivATI glGetArrayObjectivATI(array::GLenum, pname::GLenum, params::Ptr{GLint})::Void
export glGetArrayObjectivATI
@getCFun "libGL" glVariantArrayObjectATI glVariantArrayObjectATI(id::GLuint, type_::GLenum, stride::GLsizei, buffer::GLuint, offset::GLuint)::Void
export glVariantArrayObjectATI
@getCFun "libGL" glGetVariantArrayObjectfvATI glGetVariantArrayObjectfvATI(id::GLuint, pname::GLenum, params::Ptr{GLfloat})::Void
export glGetVariantArrayObjectfvATI
@getCFun "libGL" glGetVariantArrayObjectivATI glGetVariantArrayObjectivATI(id::GLuint, pname::GLenum, params::Ptr{GLint})::Void
export glGetVariantArrayObjectivATI
@getCFun "libGL" glVertexAttribArrayObjectATI glVertexAttribArrayObjectATI(index::GLuint, size::GLint, type_::GLenum, normalized::GLboolean, stride::GLsizei, buffer::GLuint, offset::GLuint)::Void
export glVertexAttribArrayObjectATI
@getCFun "libGL" glGetVertexAttribArrayObjectfvATI glGetVertexAttribArrayObjectfvATI(index::GLuint, pname::GLenum, params::Ptr{GLfloat})::Void
export glGetVertexAttribArrayObjectfvATI
@getCFun "libGL" glGetVertexAttribArrayObjectivATI glGetVertexAttribArrayObjectivATI(index::GLuint, pname::GLenum, params::Ptr{GLint})::Void
export glGetVertexAttribArrayObjectivATI
@getCFun "libGL" glVertexStream1sATI glVertexStream1sATI(stream::GLenum, x::GLshort)::Void
export glVertexStream1sATI
@getCFun "libGL" glVertexStream1svATI glVertexStream1svATI(stream::GLenum, coords::Ptr{GLshort})::Void
export glVertexStream1svATI
@getCFun "libGL" glVertexStream1iATI glVertexStream1iATI(stream::GLenum, x::GLint)::Void
export glVertexStream1iATI
@getCFun "libGL" glVertexStream1ivATI glVertexStream1ivATI(stream::GLenum, coords::Ptr{GLint})::Void
export glVertexStream1ivATI
@getCFun "libGL" glVertexStream1fATI glVertexStream1fATI(stream::GLenum, x::GLfloat)::Void
export glVertexStream1fATI
@getCFun "libGL" glVertexStream1fvATI glVertexStream1fvATI(stream::GLenum, coords::Ptr{GLfloat})::Void
export glVertexStream1fvATI
@getCFun "libGL" glVertexStream1dATI glVertexStream1dATI(stream::GLenum, x::GLdouble)::Void
export glVertexStream1dATI
@getCFun "libGL" glVertexStream1dvATI glVertexStream1dvATI(stream::GLenum, coords::Ptr{GLdouble})::Void
export glVertexStream1dvATI
@getCFun "libGL" glVertexStream2sATI glVertexStream2sATI(stream::GLenum, x::GLshort, y::GLshort)::Void
export glVertexStream2sATI
@getCFun "libGL" glVertexStream2svATI glVertexStream2svATI(stream::GLenum, coords::Ptr{GLshort})::Void
export glVertexStream2svATI
@getCFun "libGL" glVertexStream2iATI glVertexStream2iATI(stream::GLenum, x::GLint, y::GLint)::Void
export glVertexStream2iATI
@getCFun "libGL" glVertexStream2ivATI glVertexStream2ivATI(stream::GLenum, coords::Ptr{GLint})::Void
export glVertexStream2ivATI
@getCFun "libGL" glVertexStream2fATI glVertexStream2fATI(stream::GLenum, x::GLfloat, y::GLfloat)::Void
export glVertexStream2fATI
@getCFun "libGL" glVertexStream2fvATI glVertexStream2fvATI(stream::GLenum, coords::Ptr{GLfloat})::Void
export glVertexStream2fvATI
@getCFun "libGL" glVertexStream2dATI glVertexStream2dATI(stream::GLenum, x::GLdouble, y::GLdouble)::Void
export glVertexStream2dATI
@getCFun "libGL" glVertexStream2dvATI glVertexStream2dvATI(stream::GLenum, coords::Ptr{GLdouble})::Void
export glVertexStream2dvATI
@getCFun "libGL" glVertexStream3sATI glVertexStream3sATI(stream::GLenum, x::GLshort, y::GLshort, z::GLshort)::Void
export glVertexStream3sATI
@getCFun "libGL" glVertexStream3svATI glVertexStream3svATI(stream::GLenum, coords::Ptr{GLshort})::Void
export glVertexStream3svATI
@getCFun "libGL" glVertexStream3iATI glVertexStream3iATI(stream::GLenum, x::GLint, y::GLint, z::GLint)::Void
export glVertexStream3iATI
@getCFun "libGL" glVertexStream3ivATI glVertexStream3ivATI(stream::GLenum, coords::Ptr{GLint})::Void
export glVertexStream3ivATI
@getCFun "libGL" glVertexStream3fATI glVertexStream3fATI(stream::GLenum, x::GLfloat, y::GLfloat, z::GLfloat)::Void
export glVertexStream3fATI
@getCFun "libGL" glVertexStream3fvATI glVertexStream3fvATI(stream::GLenum, coords::Ptr{GLfloat})::Void
export glVertexStream3fvATI
@getCFun "libGL" glVertexStream3dATI glVertexStream3dATI(stream::GLenum, x::GLdouble, y::GLdouble, z::GLdouble)::Void
export glVertexStream3dATI
@getCFun "libGL" glVertexStream3dvATI glVertexStream3dvATI(stream::GLenum, coords::Ptr{GLdouble})::Void
export glVertexStream3dvATI
@getCFun "libGL" glVertexStream4sATI glVertexStream4sATI(stream::GLenum, x::GLshort, y::GLshort, z::GLshort, w::GLshort)::Void
export glVertexStream4sATI
@getCFun "libGL" glVertexStream4svATI glVertexStream4svATI(stream::GLenum, coords::Ptr{GLshort})::Void
export glVertexStream4svATI
@getCFun "libGL" glVertexStream4iATI glVertexStream4iATI(stream::GLenum, x::GLint, y::GLint, z::GLint, w::GLint)::Void
export glVertexStream4iATI
@getCFun "libGL" glVertexStream4ivATI glVertexStream4ivATI(stream::GLenum, coords::Ptr{GLint})::Void
export glVertexStream4ivATI
@getCFun "libGL" glVertexStream4fATI glVertexStream4fATI(stream::GLenum, x::GLfloat, y::GLfloat, z::GLfloat, w::GLfloat)::Void
export glVertexStream4fATI
@getCFun "libGL" glVertexStream4fvATI glVertexStream4fvATI(stream::GLenum, coords::Ptr{GLfloat})::Void
export glVertexStream4fvATI
@getCFun "libGL" glVertexStream4dATI glVertexStream4dATI(stream::GLenum, x::GLdouble, y::GLdouble, z::GLdouble, w::GLdouble)::Void
export glVertexStream4dATI
@getCFun "libGL" glVertexStream4dvATI glVertexStream4dvATI(stream::GLenum, coords::Ptr{GLdouble})::Void
export glVertexStream4dvATI
@getCFun "libGL" glNormalStream3bATI glNormalStream3bATI(stream::GLenum, nx::GLbyte, ny::GLbyte, nz::GLbyte)::Void
export glNormalStream3bATI
@getCFun "libGL" glNormalStream3bvATI glNormalStream3bvATI(stream::GLenum, coords::Ptr{GLbyte})::Void
export glNormalStream3bvATI
@getCFun "libGL" glNormalStream3sATI glNormalStream3sATI(stream::GLenum, nx::GLshort, ny::GLshort, nz::GLshort)::Void
export glNormalStream3sATI
@getCFun "libGL" glNormalStream3svATI glNormalStream3svATI(stream::GLenum, coords::Ptr{GLshort})::Void
export glNormalStream3svATI
@getCFun "libGL" glNormalStream3iATI glNormalStream3iATI(stream::GLenum, nx::GLint, ny::GLint, nz::GLint)::Void
export glNormalStream3iATI
@getCFun "libGL" glNormalStream3ivATI glNormalStream3ivATI(stream::GLenum, coords::Ptr{GLint})::Void
export glNormalStream3ivATI
@getCFun "libGL" glNormalStream3fATI glNormalStream3fATI(stream::GLenum, nx::GLfloat, ny::GLfloat, nz::GLfloat)::Void
export glNormalStream3fATI
@getCFun "libGL" glNormalStream3fvATI glNormalStream3fvATI(stream::GLenum, coords::Ptr{GLfloat})::Void
export glNormalStream3fvATI
@getCFun "libGL" glNormalStream3dATI glNormalStream3dATI(stream::GLenum, nx::GLdouble, ny::GLdouble, nz::GLdouble)::Void
export glNormalStream3dATI
@getCFun "libGL" glNormalStream3dvATI glNormalStream3dvATI(stream::GLenum, coords::Ptr{GLdouble})::Void
export glNormalStream3dvATI
@getCFun "libGL" glClientActiveVertexStreamATI glClientActiveVertexStreamATI(stream::GLenum)::Void
export glClientActiveVertexStreamATI
@getCFun "libGL" glVertexBlendEnviATI glVertexBlendEnviATI(pname::GLenum, param::GLint)::Void
export glVertexBlendEnviATI
@getCFun "libGL" glVertexBlendEnvfATI glVertexBlendEnvfATI(pname::GLenum, param::GLfloat)::Void
export glVertexBlendEnvfATI
end
|
using AWSCore
using AWSS3
using AWSLambda
JL_VERSION_BASE="0.6"
JL_VERSION_PATCH="4"
JL_VERSION="$JL_VERSION_BASE.$JL_VERSION_PATCH"
image_name = "octech/$(replace(basename(pwd()), "_", "")):$JL_VERSION"
lambda_name = basename(pwd())
source_bucket = "octech.com.au.ap-southeast-2.awslambda.jl.deploy"
base_zip = "$(lambda_name)_$(VERSION)_$(AWSLambda.aws_lamabda_jl_version).zip"
if length(ARGS) == 0 || ARGS[1] == "build"
cp("../../src/AWSLambda.jl", "AWSLambda.jl"; remove_destination=true)
run(`docker build
--build-arg JL_VERSION_BASE=$JL_VERSION_BASE
--build-arg JL_VERSION_PATCH=$JL_VERSION_PATCH
-t $image_name .`)
end
if length(ARGS) > 0 && ARGS[1] == "shell"
run(`docker run --rm -it -v $(pwd()):/var/host $image_name bash`)
end
if length(ARGS) > 0 && ARGS[1] == "zip"
rm(base_zip; force=true)
cmd = `zip --symlinks -r -9 /var/host/$base_zip .`
run(`docker run --rm -it -v $(pwd()):/var/host $image_name $cmd`)
end
if length(ARGS) > 0 && ARGS[1] == "deploy"
AWSCore.Services.s3("PUT", "/$source_bucket/$base_zip",
headers=Dict("x-amz-acl" => "public-read"),
Body=read(base_zip))
end
if length(ARGS) > 0 && ARGS[1] == "deploy_regions"
lambda_regions = ["us-east-1",
"us-east-2",
"us-west-1",
"us-west-2",
"ap-northeast-2",
"ap-south-1",
"ap-southeast-1",
"ap-northeast-1",
"eu-central-1",
"eu-west-1",
"eu-west-2"]
@sync for r in lambda_regions
raws = merge(default_aws_config(), Dict(:region => r))
bucket = "octech.com.au.$r.awslambda.jl.deploy"
@async begin
s3_create_bucket(raws, bucket)
AWSS3.s3(default_aws_config(), "PUT", bucket;
path = base_zip,
headers = Dict(
"x-amz-copy-source" => "$source_bucket/$base_zip",
"x-amz-acl" => "public-read"))
end
end
end
|
using BetaVQE
using Yao, Yao.EasyBuild, Yao.BitBasis
using Test, Random, StatsBase
using Zygote
using BetaVQE.VAN
@testset "VAN" begin
include("VAN/VAN.jl")
end
@testset "sample" begin
Random.seed!(3)
nbits = 4
nhiddens = [10, 20]
nsamples = 1000
β = 1.0
h = heisenberg(nbits)
c = dispatch!(variational_circuit(nbits), :random)
model = AutoRegressiveModel(nbits, nhiddens)
configs = bitarray(collect(0:(1<<nbits-1)), nbits)
logp = get_logp(model, configs)
@test isapprox(sum(exp.(logp)), 1.0, rtol=1e-2)
f = sum(exp.(logp) .* free_energy_local(β, h, model, c, configs))
samples = gen_samples(model, nsamples)
f_sample = free_energy(β, h, model, c, samples)
@test isapprox(f, f_sample, rtol=1e-1)
end
@testset "circuit diff" begin
Random.seed!(3)
nbits = 4
nhiddens = [10]
nsamples = 2000
h = heisenberg(nbits)
c = dispatch!(variational_circuit(nbits), :random)
model = AutoRegressiveModel(nbits, nhiddens)
samples = gen_samples(model, nsamples)
# check the gradient of circuit parameters
params = parameters(c)
ϵ = 1e-5
for k in 1:length(params)
params[k] -= ϵ
dispatch!(c, params)
l1 = free_energy(2.0, h, model, c, samples)
params[k] += 2ϵ
dispatch!(c, params)
l2 = free_energy(2.0, h, model, c, samples)
params[k] -= ϵ
dispatch!(c, params)
g = (l2-l1)/2ϵ
g2 = gradient(c->free_energy(2.0, h, model, c, samples), c)[1]
@test isapprox(g, g2[k], rtol=1e-2)
end
end
@testset "network diff" begin
Random.seed!(7)
nbits = 2
nhiddens = [10]
nsamples = 1000
h = heisenberg(nbits)
c = dispatch!(variational_circuit(nbits), :random)
model = AutoRegressiveModel(nbits, nhiddens)
ϵ = 1e-5
# check the gradient of model
configs = bitarray(collect(0:(1<<nbits-1)), nbits)
function f(model)
logp = get_logp(model, configs)
sum(exp.(logp) .* free_energy_local(2.0, h, model, c, configs))
end
m, n = 1, 1
params = model_parameters(model)
params[m][n] -= ϵ
model_dispatch!(model, params)
l1 = f(model)
params[m][n] += 2ϵ
model_dispatch!(model, params)
l2 = f(model)
g = (l2-l1)/2ϵ
#tune it back
params[m][n] -= ϵ
model_dispatch!(model, params)
samples = gen_samples(model, nsamples)
g2 = gradient(model->free_energy(2.0, h, model, c, samples), model)[1]
@test isapprox(g, g2.W[1][n], rtol=1e-1)
@show g, g2.W[1][n]
end
@testset "tns circuit diff" begin
Random.seed!(3)
nx = 2
ny = 2
nbits = nx*ny
depth = 3
nhiddens = [10]
nsamples = 2000
h = heisenberg(nbits)
c = tns_circuit(nbits, depth, EasyBuild.pair_square(nx, ny; periodic=false); entangler=(n,i,j)->put(n,(i,j)=>general_U4(rand(15)*2π)))
model = AutoRegressiveModel(nbits, nhiddens)
samples = gen_samples(model, nsamples)
# check the gradient of circuit parameters
params = parameters(c)
ϵ = 1e-5
for k in 1:length(params)
params[k] -= ϵ
dispatch!(c, params)
l1 = free_energy(2.0, h, model, c, samples)
params[k] += 2ϵ
dispatch!(c, params)
l2 = free_energy(2.0, h, model, c, samples)
params[k] -= ϵ
dispatch!(c, params)
g = (l2-l1)/2ϵ
g2 = gradient(c->free_energy(2.0, h, model, c, samples), c)[1]
@test isapprox(g, g2[k], atol=1e-2)
end
end
@testset "train" begin
nbits = 4
h = hamiltonian(TFIM(nbits, 1; Γ=0.0, periodic=false))
network = PSAModel(nbits)
circuit = tns_circuit(nbits, 2, EasyBuild.pair_square(nbits, 1; periodic=false); entangler=(n,i,j)->put(n,(i,j)=>general_U4()))
network_params, circuit_params = train(1.0, h, network, circuit; nbatch=1000, niter=100)
samples = gen_samples(network, 1000)
@test free_energy(1.0, h, network, circuit, samples) <= -3.2
end |
# constants
const a = 6.378137e6 # the semi-major axis of the earth
const F = 298.257222101 # the inverse 1st flattening
const n = 1/(2F-1)
const m₀ = 0.9999 # central meridian scale factor
A₀ = 1 + n^2/4 + n^4/64
const A̅ = A₀/(1+n) *m₀*a
## longitude, latitude of origin for zones in Japan
const Origin_LatLon_Japan = [ 33.0 129.5 ; # 1
33.0 131.0 ; # 2
36.0 132.0+1/6; # 3
33.0 133.5 ; # 4
36.0 134.0+1/3; # 5
36.0 136.0 ; # 6
36.0 137.0+1/6; # 7
36.0 138.5 ; # 8
36.0 139.0+5/6; # 9
40.0 140.0+5/6; # 10
44.0 140.25 ; # 11
44.0 142.25 ; # 12
44.0 144.25 ; # 13
26.0 142.0 ; # 14
26.0 127.5 ; # 15
26.0 124.0 ; # 16
26.0 131.0 ; # 17
20.0 136.0 ; # 18
26.0 154.0 ; # 19
]
|
using JuMP, EAGO
m = Model()
EAGO.register_eago_operators!(m)
@variable(m, -1 <= x[i=1:4] <= 1)
@variable(m, -32.35079088597315 <= q <= 33.04707617725232)
add_NL_constraint(m, :(log(1 + exp(0.7516814527569986 + 0.07211062597860263*log(1 + exp(0.800956367833014 + 0.1575422515944389*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.30181017969165413*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.5024447348308962*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + -0.7463877606567912*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + -0.28099609060437203*log(1 + exp(-0.8241959750660866 + 0.48752067922981546*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + -0.8942226763869914*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + -0.1882956347370066*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.0613423792438379*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + 0.19401527858092393*log(1 + exp(-0.014178711859067938 + -0.6496362145686132*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.5744456236018198*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.06990002879133872*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.11738131892224501*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + -0.43991506890783594*log(1 + exp(-0.38559964579408224 + -0.6882459841770032*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.5869261088566509*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.7286086900917508*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.9385542676650069*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))))) + log(1 + exp(0.5442086655639207 + -0.859033717055464*log(1 + exp(0.800956367833014 + 0.1575422515944389*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.30181017969165413*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.5024447348308962*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + -0.7463877606567912*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + -0.6994107397450926*log(1 + exp(-0.8241959750660866 + 0.48752067922981546*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + -0.8942226763869914*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + -0.1882956347370066*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.0613423792438379*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + -0.21447765318835765*log(1 + exp(-0.014178711859067938 + -0.6496362145686132*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.5744456236018198*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.06990002879133872*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.11738131892224501*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + 0.9247182813449877*log(1 + exp(-0.38559964579408224 + -0.6882459841770032*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.5869261088566509*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.7286086900917508*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.9385542676650069*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))))) + log(1 + exp(-0.33457802196328057 + 0.8511359109817849*log(1 + exp(0.800956367833014 + 0.1575422515944389*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.30181017969165413*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.5024447348308962*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + -0.7463877606567912*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + 0.9056512987027685*log(1 + exp(-0.8241959750660866 + 0.48752067922981546*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + -0.8942226763869914*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + -0.1882956347370066*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.0613423792438379*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + -0.901983268277478*log(1 + exp(-0.014178711859067938 + -0.6496362145686132*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.5744456236018198*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.06990002879133872*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.11738131892224501*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + -0.02854306019224717*log(1 + exp(-0.38559964579408224 + -0.6882459841770032*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.5869261088566509*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.7286086900917508*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.9385542676650069*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))))) + log(1 + exp(0.85223750045835 + -0.7468516096711739*log(1 + exp(0.800956367833014 + 0.1575422515944389*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.30181017969165413*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.5024447348308962*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + -0.7463877606567912*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + -0.1269236474608202*log(1 + exp(-0.8241959750660866 + 0.48752067922981546*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + -0.8942226763869914*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + -0.1882956347370066*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.0613423792438379*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + -0.5407492362268407*log(1 + exp(-0.014178711859067938 + -0.6496362145686132*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.5744456236018198*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.06990002879133872*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.11738131892224501*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))) + -0.8670343803826994*log(1 + exp(-0.38559964579408224 + -0.6882459841770032*log(1 + exp(-0.7991039641167363 + 0.28486813994855353*$(x[1]) + 0.682420711072186*$(x[2]) + 0.05952972537514656*$(x[3]) + 0.998655851604032*$(x[4]))) + 0.5869261088566509*log(1 + exp(-0.9827986828893067 + 0.8570099551669048*$(x[1]) + -0.029287184975956393*$(x[2]) + 0.28818320654817864*$(x[3]) + -0.9376552616355038*$(x[4]))) + 0.7286086900917508*log(1 + exp(0.33306588949676286 + 0.667638331016386*$(x[1]) + 0.7691056200843742*$(x[2]) + 0.5908191290581821*$(x[3]) + 0.06769592108634237*$(x[4]))) + 0.9385542676650069*log(1 + exp(-0.7350489056562997 + 0.545921427040915*$(x[1]) + -0.3116746162014481*$(x[2]) + 0.844944868364411*$(x[3]) + -0.9086564944285445*$(x[4]))))))) - $q <= 0.0))
@objective(m, Min, q)
return m
|
# Networks found by Bose-Nelson algorithm, except for N=16
# http://pages.ripco.net/~jgamble/nw.html
# http://www.cs.brandeis.edu/~hugues/sorting_networks.html
# https://github.com/JeffreySarnoff/SortingNetworks.jl
sorting_network_parameters = Dict(
2 => (((1,2),),),
4 => (((1,2), (3,4)), ((1,3), (2,4)), ((2,3),)),
8 => (
((1, 2), (3, 4), (5, 6), (7, 8)), ((1, 3), (2, 4), (5, 7), (6, 8)),
((2, 3), (6, 7), (1, 5), (4, 8)), ((2, 6), (3, 7)),
((2, 5), (4, 7)), ((3, 5), (4, 6)), ((4, 5),)
),
16 => (
((4, 11), (12, 15), (5, 14), (3, 13), (1, 7), (9, 10), (2,8), (6, 16)),
((1, 2), (3, 5), (7, 8), (13, 14), (4, 6), (9, 12), (11, 16), (10, 15)),
((1, 4), (7, 11), (14, 15), (2, 6), (8, 16), (3, 9), (10, 13), (5, 12)),
((1, 3), (8, 14), (15, 16), (2, 5), (6, 12), (4, 9), (11, 13), (7, 10)),
((2, 3), (4, 7), (8, 9), (12, 14), (6, 10), (13, 15), (5, 11)),
((3, 7), (12, 13), (2, 4), (6, 8), (9, 10), (14, 15)),
((3, 4), (5, 7), (11, 12), (13, 14)),
((9, 11), (5, 6), (7, 8), (10, 12)),
((4, 5), (6, 7), (8, 9), (10, 11), (12, 13)),
((7, 8), (9, 10))
),
32 => (
((1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (15, 16), (17, 18), (19, 20), (21, 22), (23, 24),
(25, 26), (27, 28), (29, 30), (31, 32)),
((1, 3), (2, 4), (5, 7), (6, 8), (9, 11), (10, 12), (13, 15), (14, 16), (17, 19), (18, 20), (21, 23), (22, 24),
(25, 27), (26, 28), (29, 31), (30, 32)),
((2, 3), (6, 7), (1, 5), (4, 8), (10, 11), (14, 15), (9, 13), (12, 16), (18, 19), (22, 23), (17, 21), (20, 24),
(26, 27), (30, 31), (25, 29), (28, 32)),
((2, 6), (3, 7), (10, 14), (11, 15), (1, 9), (8, 16), (18, 22), (19, 23), (26, 30), (27, 31), (17, 25),
(24, 32)),
((2, 5), (4, 7), (10, 13), (12, 15), (18, 21), (20, 23), (26, 29), (28, 31), (1, 17), (16, 32)),
((3, 5), (4, 6), (11, 13), (12, 14), (2, 10), (7, 15), (19, 21), (20, 22), (27, 29), (28, 30), (18, 26), (23, 31)),
((4, 5), (12, 13), (2, 9), (3, 11), (6, 14), (8, 15), (20, 21), (28, 29), (18, 25), (19, 27), (22, 30), (24, 31)),
((4, 12), (3, 9), (5, 13), (8, 14), (20, 28), (19, 25), (21, 29), (24, 30), (2, 18), (15, 31)),
((4, 11), (6, 13), (20, 27), (22, 29), (2, 17), (3, 19), (14, 30), (16, 31)),
((4, 10), (7, 13), (20, 26), (23, 29), (3, 17), (16, 30)),
((4, 9), (8, 13), (6, 10), (7, 11), (20, 25), (24, 29), (22, 26), (23, 27)),
((5, 9), (8, 12), (21, 25), (24, 28), (4, 20), (13, 29)),
((6, 9), (8, 11), (22, 25), (24, 27), (4, 19), (5, 21), (12, 28), (14, 29)),
((7, 9), (8, 10), (23, 25), (24, 26), (4, 18), (6, 22), (11, 27), (15, 29)),
((8, 9), (24, 25), (4, 17), (6, 21), (7, 23), (10, 26), (12, 27), (16, 29)),
((8, 24), (7, 21), (5, 17), (6, 18), (9, 25), (12, 26), (15, 27), (16, 28)),
((8, 23), (6, 17), (7, 19), (10, 25), (14, 26), (16, 27)), ((8, 22), (7, 17), (11, 25), (16, 26)),
((8, 21), (12, 25)), ((8, 20), (13, 25)), ((8, 19), (14, 25), (12, 20), (13, 21)),
((8, 18), (15, 25), (11, 19), (14, 22)), ((8, 17), (16, 25), (10, 18), (12, 19), (14, 21), (15, 23)),
((9, 17), (12, 18), (16, 24), (15, 21)), ((10, 17), (16, 23), (14, 18), (15, 19)), ((11, 17), (16, 22)),
((12, 17), (16, 21)), ((13, 17), (16, 20)), ((14, 17), (16, 19)), ((15, 17), (16, 18)), ((16, 17),)
)
)
|
struct Framework
plugins
Framework(plugins, hooks=[]; opts...) = new(PluginStack(plugins, hooks; opts...))
end
struct EmptyPlugin{Id} <: Plugin
EmptyPlugin{Id}(;opts...) where Id = new{Id}()
end
Plugins.symbol(::EmptyPlugin) = :empty
for i = 1:1000
Plugins.register(EmptyPlugin{i})
end
mutable struct CounterPlugin{Id} <: Plugin
hook1count::Int
hook2count::Int
hook3count::Int
CounterPlugin{Id}() where Id = new{Id}(0, 0, 0)
end
Plugins.symbol(::CounterPlugin) = :counter
for i = 1:100
Plugins.register(CounterPlugin{i})
end
@inline hook1(plugin::CounterPlugin, framework) = begin
plugin.hook1count += 1
return false
end
hook2_handler(plugin::CounterPlugin, framework) = begin
plugin.hook2count += 1
return false
end
@inline hook3(plugin::CounterPlugin, framework, p1, p2) = begin
plugin.hook3count += p2
return false
end
chain_of_empties(length=20, startat=0) = [EmptyPlugin{i + startat} for i = 1:length]
callmanytimes(framework, hook, times=1e5) = for i=1:times hook(framework) end
mutable struct FrameworkTestPlugin <: Plugin
calledwithframework
FrameworkTestPlugin() = new("Never called")
end
Plugins.register(FrameworkTestPlugin)
hook1(plugin::FrameworkTestPlugin, framework) = plugin.calledwithframework = framework
mutable struct EventTestPlugin <: Plugin
calledwithframework
calledwithevent
EventTestPlugin() = new("Never called", "Never called")
end
Plugins.register(EventTestPlugin)
event_handler(plugin::EventTestPlugin, framework, event) = begin
plugin.calledwithframework = framework
plugin.calledwithevent = event
end
struct ConfigurablePlugin <: Plugin
config::String
ConfigurablePlugin(;config = "default") = new(config)
end
Plugins.register(ConfigurablePlugin)
checkconfig_handler(plugin::ConfigurablePlugin, framework, event) = begin
if event.config !== plugin.config
throw("Not the same!")
end
return plugin.config
end
struct PropagationStopperPlugin <: Plugin
end
Plugins.register(PropagationStopperPlugin)
propagationtest(plugin::PropagationStopperPlugin, framework, data) = data == 42
propagationtest_nodata(plugin::PropagationStopperPlugin, framework) = true
struct PropagationCheckerPlugin <: Plugin
end
Plugins.register(PropagationCheckerPlugin)
propagationtest(plugin::PropagationCheckerPlugin, framework, data) = data === 32 || throw("Not 32!")
propagationtest_nodata(plugin::PropagationCheckerPlugin, framework) = throw("Not stopped!")
mutable struct DynamicPlugin <: Plugin
lastdata
end
Plugins.register(DynamicPlugin)
dynamismtest(plugin::DynamicPlugin, framework, data) = plugin.lastdata = data
# Hook cache test:
mutable struct SharedState
plugins::PluginStack
shared_counter::Int
end
struct App{TCache}
state::SharedState
hooks::TCache
function App(plugins, hooklist)
state = SharedState(PluginStack(plugins, hooklist), 0)
cache = hook_cache(state.plugins)
return new{typeof(cache)}(state, cache)
end
end
const OP_CYCLES = 1e7
function op(app::App)
counters = [counter for counter in app.state.plugins if counter isa CounterPlugin]
@info "op: A sample operation on the app, involving hook1() calls in a semi-realistic setting."
@info "op: $(length(counters)) CounterPlugins found, $(length(app.state.plugins)) plugins in total, each CounterPlugin incrementing a private counter."
start_ts = time_ns()
for i in 1:OP_CYCLES
app.hooks.hook3(app, i, 1)
end
end_ts = time_ns()
for i = 1:length(counters)
@test counters[i].hook3count == OP_CYCLES
end
time_diff = end_ts - start_ts
avg_calltime = time_diff / OP_CYCLES
@info "op: $OP_CYCLES hook1() calls took $(time_diff / 1e9) secs. That is $avg_calltime nanosecs per call on average, or $(avg_calltime / length(counters)) ns per in-plugin counter increment."
end
mutable struct LifeCycleTestPlugin <: Plugin
setupcalledwith
shutdowncalledwith
deferredinitcalledwith
LifeCycleTestPlugin() = new()
end
Plugins.register(LifeCycleTestPlugin)
Plugins.setup!(plugin::LifeCycleTestPlugin, framework) = plugin.setupcalledwith = framework
Plugins.shutdown!(plugin::LifeCycleTestPlugin, framework) = begin
plugin.shutdowncalledwith = framework
if framework === 42
error("shutdown called with 42")
end
end
deferred_init(plugin::Plugin, ::Any) = true
deferred_init(plugin::LifeCycleTestPlugin, data) = plugin.deferredinitcalledwith = data
@testset "Plugins.jl basics" begin
@testset "Plugin chain" begin
a1 = Framework([CounterPlugin{1}, EmptyPlugin])
@show innerplugin = a1.plugins[:empty]
@show counter = a1.plugins[:counter]
a1_hook1s = hooklist(a1.plugins, hook1)
@test length(a1_hook1s) === 1
callmanytimes(a1, a1_hook1s)
@info "$(length(a1.plugins))-length chain, $(length(a1_hook1s)) counter (1e5 cycles):"
@time callmanytimes(a1, a1_hook1s)
hooklist(a1.plugins, hook2_handler)(a1)
@test counter.hook1count == 2e5
@test counter.hook2count == 1
end
@testset "Same plugin twice" begin
a2 = Framework([CounterPlugin{1}, CounterPlugin{2}])
innercounter = a2.plugins[2]
outercounter = a2.plugins[1]
a2_hook1s = hooklist(a2.plugins, hook1)
@test length(a2_hook1s) === 2
callmanytimes(a2, a2_hook1s)
@info "$(length(a2.plugins))-length chain, $(length(a2_hook1s)) counters (1e5 cycles):"
@time callmanytimes(a2, a2_hook1s)
hooklist(a2.plugins, hook2_handler)(a2)
@test innercounter.hook1count == 2e5
@test innercounter.hook2count == 1
@test outercounter.hook1count == 2e5
@test outercounter.hook2count == 1
end
@testset "Chain of empty Plugins to skip" begin
chainedapp = Framework(vcat([CounterPlugin{1}], chain_of_empties(20), [CounterPlugin{2}], chain_of_empties(20, 21)))
innerplugin = chainedapp.plugins[22]
outerplugin = chainedapp.plugins[1]
chainedapp_hook1s = hooklist(chainedapp.plugins, hook1)
callmanytimes(chainedapp, chainedapp_hook1s)
@info "$(length(chainedapp.plugins))-length chain, $(length(chainedapp_hook1s)) counters (1e5 cycles):"
@time callmanytimes(chainedapp, chainedapp_hook1s)
@test outerplugin.hook1count == 2e5
@test outerplugin.hook2count == 0
@test innerplugin.hook1count == 2e5
@test innerplugin.hook2count == 0
end
@testset "Unhandled hook returns false" begin
app = Framework([EmptyPlugin{1}])
@test hooklist(app.plugins, hook1)() == false
@test call_optional(hooklist(app.plugins, hook1)) == nothing
end
@testset "Framework goes through" begin
frameworktestapp = Framework([EmptyPlugin{1}, FrameworkTestPlugin])
hooklist(frameworktestapp.plugins, hook1)(frameworktestapp)
@test frameworktestapp.plugins[2].calledwithframework === frameworktestapp
end
@testset "Event object" begin
eventtestapp = Framework([EmptyPlugin{1}, EventTestPlugin])
event = (name="test event", data=42)
hooklist(eventtestapp.plugins, event_handler)(eventtestapp, event)
@test eventtestapp.plugins[2].calledwithframework === eventtestapp
@test eventtestapp.plugins[2].calledwithevent === event
end
@testset "Multiple apps with same chain, differently configured" begin
app2config = "app2config"
app1 = Framework([EmptyPlugin{1}, ConfigurablePlugin])
app2 = Framework([EmptyPlugin{2}, ConfigurablePlugin]; config=app2config)
event1 = (config ="default",)
event2 = (config = app2config,)
hooklist(app1.plugins, checkconfig_handler)(app1, event1)
@test_throws String hooklist(app1.plugins, checkconfig_handler)(app1, event2)
@test call_optional(hooklist(app1.plugins, checkconfig_handler), app1, event1) == event1.config
hooklist(app2.plugins, checkconfig_handler)(app2, event2)
@test_throws String hooklist(app2.plugins, checkconfig_handler)(app2, event1)
@test call_optional(hooklist(app2.plugins, checkconfig_handler), app2, event2) == event2.config
end
@testset "Stopping Propagation" begin
spapp = Framework([EmptyPlugin{1}, PropagationStopperPlugin, EmptyPlugin{2}, PropagationCheckerPlugin])
hooklist(spapp.plugins, propagationtest)(spapp, 42) === true # It is stopped so the checker does not throw
hooklist(spapp.plugins, propagationtest)(spapp, 32) === false # Not stopped but accepted by the checker
@test_throws String hooklist(spapp.plugins, propagationtest)(spapp, 41)
@test hooklist(spapp.plugins, propagationtest_nodata)(spapp) === true
end
@testset "HookList iteration" begin
iapp = Framework([EmptyPlugin{1}, CounterPlugin{2}, EmptyPlugin{2}, CounterPlugin{1}, EmptyPlugin{3}])
c1 = iapp.plugins[4]
c2 = iapp.plugins[2]
hookers = [c2, c1]
@test length(hooklist(iapp.plugins, hook1)) === 2
i = 1
for hook in hooklist(iapp.plugins, hook1)
@test hookers[i] === hook.plugin
i += 1
end
end
@testset "Accessing plugins directly" begin
app = Framework([EmptyPlugin{1}, CounterPlugin{1}])
empty = app.plugins[1]
counter = app.plugins[2]
@test get(app.plugins, :empty) === empty
@test get(app.plugins, :counter) === counter
@test app.plugins[:empty] === empty
@test length(app.plugins) == 2
end
@testset "Hook cache" begin
counters = [CounterPlugin{i} for i=2:40]
empties = [EmptyPlugin{i} for i=1:100]
pluginarr = [CounterPlugin{1}, empties..., counters...]
@info "Measuring time to first hook call with $(length(pluginarr)) uniquely typed plugins, $(length(counters) + 1) implementig the hook."
@time begin
simpleapp = SharedState(PluginStack(pluginarr, [hook1]), 0)
simpleapp_hooks = hooks(simpleapp)
simpleapp_hooks.hook1(simpleapp)
@test simpleapp.plugins[1].hook1count == 1
end
end
@testset "Hook cache as type parameter" begin
counters = [CounterPlugin{i} for i=2:2]
empties = [EmptyPlugin{i} for i=1:100]
app = App([CounterPlugin{1}, empties..., counters...], [hook3])
op(app)
end
@testset "Lifecycle Hooks" begin
app = Framework([EmptyPlugin{1}, LifeCycleTestPlugin])
plugin = app.plugins[2]
@test setup!(app.plugins, app).allok == true
@test plugin.setupcalledwith === app
# Create a non-standard lifecycle hook
lifecycle_hook = Plugins.create_lifecyclehook(deferred_init)
@test string(lifecycle_hook) == "deferred_init"
@test lifecycle_hook(app.plugins, "42").allok === true
@test plugin.deferredinitcalledwith === "42"
@test Plugins.shutdown!(app.plugins, app).allok === true
@test plugin.shutdowncalledwith === app
notallok = Plugins.shutdown!(app.plugins, 42)
@test notallok.allok === false
@test (notallok.results[2] isa Tuple) === true
@test (notallok.results[2][1] isa Exception) === true
@test (stacktrace(notallok.results[2][2]) isa AbstractVector{StackTraces.StackFrame}) === true
@test plugin.shutdowncalledwith === 42
end
@testset "Modifying plugins" begin
c2 = CounterPlugin{2}()
app = Framework([EmptyPlugin, CounterPlugin{1}], [hook1])
c1 = app.plugins[2]
cache = hooks(app)
cache.hook1(app)
push!(app.plugins, c2)
cache = hooks(app)
cache.hook1(app)
@test c2.hook1count == 1
@test c1.hook1count == 2
@test pop!(app.plugins) === c2
cache = hooks(app)
cache.hook1(app)
@test c2.hook1count == 1
@test c1.hook1count == 3
@test popfirst!(app.plugins) isa EmptyPlugin
cache = hooks(app)
cache.hook1(app)
@test c2.hook1count == 1
@test c1.hook1count == 4
pushfirst!(app.plugins, c2)
cache = hooks(app)
cache.hook1(app)
@test c2.hook1count == 2
@test c1.hook1count == 5
@test app.plugins[1] === c2
pop!(app.plugins)
@test length(app.plugins) == 1
@test isempty(app.plugins) == false
pop!(app.plugins)
@test length(app.plugins) == 0
@test isempty(app.plugins) == true
@test_throws ArgumentError pop!(app.plugins)
app = Framework([EmptyPlugin{1}, CounterPlugin{3}], [hook1])
c3 = app.plugins[:counter]
@test isempty(app.plugins) == false
cache = hooks(app)
cache.hook1(app)
@test c3.hook1count == 1
empty!(app.plugins)
@test isempty(app.plugins) == true
cache = hooks(app)
cache.hook1(app)
@test c3.hook1count == 1
c5 = CounterPlugin{5}()
app = Framework([EmptyPlugin{1}, CounterPlugin{4}], [hook1])
c4 = app.plugins[:counter]
@test isempty(app.plugins) == false
cache = hooks(app)
cache.hook1(app)
@test c4.hook1count == 1
@test c5.hook1count == 0
app.plugins[2] = c5
cache = hooks(app)
cache.hook1(app)
@test c4.hook1count == 1
@test c5.hook1count == 1
end
end
|
"""
function function_value(f::Function, fs::ScalarFunctionSpace{dim,T}, cell::Int,q_point::Int) where {dim,T}
Evaluate function f(x): x ∈ ℝⁿ ↦ ℝ with x given by cell number `cell` and quadrature point with index `qpoint`
using fs FunctionSpace data
"""
function function_value(f::Function, fs::ScalarFunctionSpace{dim,T}, cell::Int,q_point::Int) where {dim,T}
coords = get_cell_coordinates(cell, fs.mesh)
return f(spatial_coordinate(fs, q_point, coords))
end
"""
function spatial_coordinate(fs::ScalarFunctionSpace{dim}, q_point::Int, x::AbstractVector{Vec{dim,T}})
Map coordinates of quadrature point `q_point` of Scalar Function Space `fs`
into domain with vertices `x`
"""
function spatial_coordinate(fs::ScalarFunctionSpace{dim}, q_point::Int, x::AbstractVector{Vec{dim,T}}) where {dim,T}
n_base_funcs = getngeobasefunctions(fs)
@assert length(x) == n_base_funcs
vec = zero(Vec{dim,T})
@inbounds for i in 1:n_base_funcs
vec += geometric_value(fs, q_point, i) * x[i]
end
return vec
end
# Trial Functions
struct TrialFunction{dim,T,shape,N1}
fs::DiscreteFunctionSpace
m_values::Array{T,N1}
components::Int
end
@inline getnbasefunctions(u::TrialFunction) = getnbasefunctions(u.fs)
@inline getfunctionspace(u::TrialFunction) = u.fs
@inline getnlocaldofs(u::TrialFunction) = getnlocaldofs(getfunctionspace(u))
@inline getncomponents(u::TrialFunction) = u.components
function TrialFunction(fs::ScalarTraceFunctionSpace{dim,T}) where {dim,T}
mesh = getmesh(fs)
m_values = fill(zero(T) * T(NaN), getncells(mesh), getnbasefunctions(fs), n_faces_per_cell(mesh))
return TrialFunction{dim,T,getshape(getfiniteelement(fs)),3}(fs, m_values, 1)
end
function TrialFunction(fs::ScalarFunctionSpace{dim,T}) where {dim,T}
mesh = getmesh(fs)
m_values = fill(zero(T) * T(NaN), getncells(mesh), getnbasefunctions(fs))
return TrialFunction{dim,T,getshape(getfiniteelement(fs)),2}(fs, m_values, 1)
end
function TrialFunction(fs::VectorFunctionSpace{dim,T}) where {dim,T}
mesh = getmesh(fs)
m_values = fill(zero(T) * T(NaN), getncells(mesh), getnbasefunctions(fs))
return TrialFunction{dim,T,getshape(getfiniteelement(fs)),2}(fs, m_values, dim)
end
function TrialFunction(fs::DiscreteFunctionSpace{dim}, components::Int, m_values::Array{T,N}) where {dim,T,N}
mesh = getmesh(fs)
@assert size(m_values,1) == getncells(mesh)
@assert size(m_values,2) == getnbasefunctions(fs)
return TrialFunction{dim,T,getshape(getfiniteelement(fs)),N}(fs, m_values, components)
end
reference_coordinate(fs::ScalarFunctionSpace{dim,T},
x_ref::Vec{dim,T}, x::Vec{dim,T}) where {dim,T} = fs.Jinv[]⋅(x-x_ref)
"""
function value(u_h::TrialFunction{dim,T}, cell::Int, x::Vec{dim,T})
get trial function value on cell `cell` at point `x`
"""
function value(u_h::TrialFunction{dim,T}, node::Int, cell::Int) where {dim,T}
u = zero(T)
mesh = getmesh(u_h.fs)
x = mesh.nodes[node].x
ξ = reference_coordinate(u_h.fs, mesh.nodes[mesh.cells[cell].nodes[1]].x, x)
for i in 1:getnbasefunctions(u_h.fs)
u += u_h.m_values[cell, i]*value(getfiniteelement(u_h.fs), i, ξ)
end
return u
end
function nodal_avg(u_h::TrialFunction{dim,T}) where {dim,T}
mesh = getmesh(u_h.fs)
nodalu_h = Vector{Float64}(undef, length(mesh.nodes))
share_count = zeros(Int,length(mesh.nodes))
fill!(nodalu_h,0)
@inbounds for (cell_idx, cell) in enumerate(CellIterator(mesh))
reinit!(u_h, cell)
for node in getnodes(cell)
u = value(u_h, node, cell)
nodalu_h[node] += u
share_count[node] += 1
end
end
return nodalu_h./share_count
end
function errornorm(u_h::TrialFunction{dim,T}, u_ex::Function, norm_type::String="L2") where {dim,T}
mesh = getmesh(u_h.fs)
Etu_h = zero(T)
if norm_type == "L2"
n_basefuncs_s = getnbasefunctions(u_h)
@inbounds for (cell_idx, cell) in enumerate(CellIterator(mesh))
reinit!(u_h, cell)
Elu_h = zero(T)
for q_point in 1:getnquadpoints(u_h.fs)
dΩ = getdetJdV(u_h.fs, q_point)
u = zero(T)
for i in 1:getnbasefunctions(u_h.fs)
u += u_h.m_values[cell.current_cellid[], i]*shape_value(u_h.fs, q_point, i)
end
# Integral (u_h - u_ex) dΩ
Elu_h += (u-u_ex(spatial_coordinate(u_h.fs, q_point, cell.coords)))^2*dΩ
end
Etu_h += Elu_h
end
else
throw("Norm $norm_type not available")
end
return Etu_h
end
|
###############################################################################
#
# fmpz.jl : BigInts
#
###############################################################################
# Copyright (c) 2009-2014: Jeff Bezanson, Stefan Karpinski, Viral B. Shah,
# and other contributors:
#
# https://github.com/JuliaLang/julia/contributors
#
# Copyright (C) 2014, 2015 William Hart
# Copyright (C) 2015, Claus Fieker
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
export fmpz, FlintZZ, FlintIntegerRing, parent, show, convert, hash, fac, bell,
binom, isprime, fdiv, cdiv, tdiv, div, rem, mod, gcd, xgcd, lcm, invmod,
powmod, abs, divrem, isqrt, popcount, prevpow2, nextpow2, ndigits, dec,
bin, oct, hex, base, one, zero, divexact, fits, sign, nbits, deepcopy,
tdivpow2, fdivpow2, cdivpow2, flog, clog, cmpabs, clrbit!, setbit!,
combit!, crt, divisible, divisor_lenstra, fdivrem, tdivrem, fmodpow2,
gcdinv, isprobabprime, issquare, jacobi, remove, root, size, isqrtrem,
sqrtmod, trailing_zeros, sigma, eulerphi, fib, moebiusmu, primorial,
risingfac, numpart, canonical_unit, needs_parentheses, isnegative,
show_minus_one, parseint, addeq!, mul!, isunit, isequal, num, den,
iszero, rand
###############################################################################
#
# Data type and parent methods
#
###############################################################################
parent_type(::Type{fmpz}) = FlintIntegerRing
doc"""
parent(a::fmpz)
> Returns the unique Flint integer parent object `FlintZZ`.
"""
parent(a::fmpz) = FlintZZ
elem_type(::Type{FlintIntegerRing}) = fmpz
doc"""
base_ring(a::FlintIntegerRing)
> Returns `Union{}` as this ring is not dependent on another ring.
"""
base_ring(a::FlintIntegerRing) = Union{}
doc"""
base_ring(a::fmpz)
> Returns `Union{}` as the parent ring is not dependent on another ring.
"""
base_ring(a::fmpz) = Union{}
isdomain_type(::Type{fmpz}) = true
################################################################################
#
# Hashing
#
################################################################################
# Similar to hash for BigInt found in julia/base
function _fmpz_is_small(a::fmpz)
return __fmpz_is_small(a.d)
end
function _fmpz_limbs(a::fmpz)
return __fmpz_limbs(a.d)
end
function hash_integer(a::fmpz, h::UInt)
return _hash_integer(a.d, h)
end
function hash(a::fmpz, h::UInt)
return hash_integer(a, h)
end
function __fmpz_is_small(a::Int)
return (unsigned(a) >> (Sys.WORD_SIZE - 2) != 1)
end
function __fmpz_limbs(a::Int)
if __fmpz_is_small(a)
return 0
end
b = unsafe_load(convert(Ref{Cint}, unsigned(a)<<2), 2)
return b
end
function _hash_integer(a::Int, h::UInt)
s = __fmpz_limbs(a)
s == 0 && return Base.hash_integer(a, h)
# get the pointer after the first two Cint
d = convert(Ptr{Ref{UInt}}, unsigned(a) << 2) + 2*sizeof(Cint)
p = unsafe_load(d)
b = unsafe_load(p)
h = xor(Base.hash_uint(xor(ifelse(s < 0, -b, b), h)), h)
for k = 2:abs(s)
h = xor(Base.hash_uint(xor(unsafe_load(p, k), h)), h)
end
return h
end
###############################################################################
#
# Basic manipulation
#
###############################################################################
function deepcopy_internal(a::fmpz, dict::ObjectIdDict)
z = fmpz()
ccall((:fmpz_set, :libflint), Void, (Ref{fmpz}, Ref{fmpz}), z, a)
return z
end
doc"""
one(R::FlintIntegerRing)
> Return the integer $1$.
"""
one(R::FlintIntegerRing) = fmpz(1)
doc"""
zero(R::FlintIntegerRing)
> Return the integer $1$.
"""
zero(R::FlintIntegerRing) = fmpz(0)
doc"""
sign(a::fmpz)
> Returns the sign of $a$, i.e. $+1$, $0$ or $-1$.
"""
sign(a::fmpz) = Int(ccall((:fmpz_sgn, :libflint), Cint, (Ref{fmpz},), a))
doc"""
fits(::Type{Int}, a::fmpz)
> Returns `true` if the given integer fits into an `Int`, otherwise returns
> `false`.
"""
fits(::Type{Int}, a::fmpz) = ccall((:fmpz_fits_si, :libflint), Bool,
(Ref{fmpz},), a)
doc"""
fits(::Type{UInt}, a::fmpz)
> Returns `true` if the given integer fits into a `UInt`, otherwise returns
> `false`.
"""
fits(::Type{UInt}, a::fmpz) = sign(a) < 0 ? false :
ccall((:fmpz_abs_fits_ui, :libflint), Bool, (Ref{fmpz},), a)
doc"""
size(a::fmpz)
> Returns the number of limbs required to store the absolute value of $a$.
"""
size(a::fmpz) = Int(ccall((:fmpz_size, :libflint), Cint, (Ref{fmpz},), a))
doc"""
isunit(a::fmpz)
> Return `true` if the given integer is a unit, i.e. $\pm 1$, otherwise return
> `false`.
"""
isunit(a::fmpz) = ccall((:fmpz_is_pm1, :libflint), Bool, (Ref{fmpz},), a)
doc"""
iszero(a::fmpz)
> Return `true` if the given integer is zero, otherwise return `false`.
"""
iszero(a::fmpz) = ccall((:fmpz_is_zero, :libflint), Bool, (Ref{fmpz},), a)
doc"""
isone(a::fmpz)
> Return `true` if the given integer is one, otherwise return `false`.
"""
isone(a::fmpz) = ccall((:fmpz_is_one, :libflint), Bool, (Ref{fmpz},), a)
doc"""
denominator(a::fmpz)
> Returns the denominator of $a$ thought of as a rational. Always returns $1$.
"""
function denominator(a::fmpz)
return fmpz(1)
end
doc"""
numerator(a::fmpz)
> Returns the numerator of $a$ thought of as a rational. Always returns $a$.
"""
function numerator(a::fmpz)
return a
end
###############################################################################
#
# AbstractString I/O
#
###############################################################################
string(x::fmpz) = dec(x)
show(io::IO, x::fmpz) = print(io, string(x))
show(io::IO, a::FlintIntegerRing) = print(io, "Integer Ring")
needs_parentheses(x::fmpz) = false
isnegative(x::fmpz) = x < 0
show_minus_one(::Type{fmpz}) = false
###############################################################################
#
# Canonicalisation
#
###############################################################################
canonical_unit(x::fmpz) = x < 0 ? fmpz(-1) : fmpz(1)
###############################################################################
#
# Unary operators and functions, e.g. -fmpz(12), ~fmpz(12)
#
###############################################################################
function -(x::fmpz)
z = fmpz()
ccall((:__fmpz_neg, :libflint), Void, (Ref{fmpz}, Ref{fmpz}), z, x)
return z
end
function ~(x::fmpz)
z = fmpz()
ccall((:fmpz_complement, :libflint), Void, (Ref{fmpz}, Ref{fmpz}), z, x)
return z
end
function abs(x::fmpz)
z = fmpz()
ccall((:fmpz_abs, :libflint), Void, (Ref{fmpz}, Ref{fmpz}), z, x)
return z
end
###############################################################################
#
# Binary operators and functions
#
###############################################################################
# Metaprogram to define functions +, -, *, gcd, lcm,
# &, |, $
for (fJ, fC) in ((:+, :add), (:-,:sub), (:*, :mul),
(:&, :and), (:|, :or), (:$, :xor))
@eval begin
function ($fJ)(x::fmpz, y::fmpz)
z = fmpz()
ccall(($(string(:fmpz_, fC)), :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
return z
end
end
end
# Metaprogram to define functions fdiv, cdiv, tdiv, div, mod
for (fJ, fC) in ((:fdiv, :fdiv_q), (:cdiv, :cdiv_q), (:tdiv, :tdiv_q),
(:div, :tdiv_q))
@eval begin
function ($fJ)(x::fmpz, y::fmpz)
iszero(y) && throw(DivideError())
z = fmpz()
ccall(($(string(:fmpz_, fC)), :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
return z
end
end
end
function divexact(x::fmpz, y::fmpz)
iszero(y) && throw(DivideError())
z = fmpz()
ccall((:fmpz_divexact, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
z
end
function rem(x::fmpz, c::fmpz)
iszero(c) && throw(DivideError())
q = fmpz()
r = fmpz()
ccall((:fmpz_tdiv_qr, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), q, r, x, abs(c))
return r
end
###############################################################################
#
# Ad hoc binary operators
#
###############################################################################
function +(x::fmpz, c::Int)
z = fmpz()
if c >= 0
ccall((:fmpz_add_ui, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
else
ccall((:fmpz_sub_ui, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, -c)
end
return z
end
+(c::Int, x::fmpz) = x + c
function -(x::fmpz, c::Int)
z = fmpz()
if c >= 0
ccall((:fmpz_sub_ui, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
else
ccall((:fmpz_add_ui, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, -c)
end
return z
end
function -(c::Int, x::fmpz)
z = fmpz()
if c >= 0
ccall((:fmpz_sub_ui, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
else
ccall((:fmpz_add_ui, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, -c)
end
ccall((:__fmpz_neg, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}), z, z)
return z
end
function *(x::fmpz, c::Int)
z = fmpz()
ccall((:fmpz_mul_si, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
*(c::Int, x::fmpz) = x * c
+(a::fmpz, b::Integer) = a + fmpz(b)
+(a::Integer, b::fmpz) = fmpz(a) + b
-(a::fmpz, b::Integer) = a - fmpz(b)
-(a::Integer, b::fmpz) = fmpz(a) - b
*(a::fmpz, b::Integer) = a*fmpz(b)
*(a::Integer, b::fmpz) = fmpz(a)*b
###############################################################################
#
# Ad hoc exact division
#
###############################################################################
function divexact(x::fmpz, y::Int)
y == 0 && throw(DivideError())
z = fmpz()
ccall((:fmpz_divexact_si, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, y)
z
end
divexact(x::fmpz, y::Integer) = divexact(x, fmpz(y))
divexact(x::Integer, y::fmpz) = divexact(fmpz(x), y)
###############################################################################
#
# Ad hoc division
#
###############################################################################
function rem(x::fmpz, c::Int)
c == 0 && throw(DivideError())
r = ccall((:fmpz_tdiv_ui, :libflint), Int, (Ref{fmpz}, Int), x, abs(c))
return sign(x) > 0 ? r : -r
end
function tdivpow2(x::fmpz, c::Int)
c < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_tdiv_q_2exp, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
function fdivpow2(x::fmpz, c::Int)
c < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_fdiv_q_2exp, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
function fmodpow2(x::fmpz, c::Int)
c < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_fdiv_r_2exp, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
function cdivpow2(x::fmpz, c::Int)
c < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_cdiv_q_2exp, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
function div(x::fmpz, c::Int)
c == 0 && throw(DivideError())
z = fmpz()
ccall((:fmpz_tdiv_q_si, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
function tdiv(x::fmpz, c::Int)
c == 0 && throw(DivideError())
z = fmpz()
ccall((:fmpz_tdiv_q_si, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
function fdiv(x::fmpz, c::Int)
c == 0 && throw(DivideError())
z = fmpz()
ccall((:fmpz_fdiv_q_si, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
function cdiv(x::fmpz, c::Int)
c == 0 && throw(DivideError())
z = fmpz()
ccall((:fmpz_cdiv_q_si, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
###############################################################################
#
# Division with remainder
#
###############################################################################
function divrem(x::fmpz, y::fmpz)
iszero(y) && throw(DivideError())
z1 = fmpz()
z2 = fmpz()
ccall((:fmpz_tdiv_qr, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z1, z2, x, y)
z1, z2
end
function tdivrem(x::fmpz, y::fmpz)
iszero(y) && throw(DivideError())
z1 = fmpz()
z2 = fmpz()
ccall((:fmpz_tdiv_qr, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z1, z2, x, y)
z1, z2
end
function fdivrem(x::fmpz, y::fmpz)
iszero(y) && throw(DivideError())
z1 = fmpz()
z2 = fmpz()
ccall((:fmpz_fdiv_qr, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z1, z2, x, y)
z1, z2
end
###############################################################################
#
# Powering
#
###############################################################################
function ^(x::fmpz, y::Int)
if y < 0; throw(DomainError()); end
if isone(x); return x; end
if x == -1; return isodd(y) ? x : -x; end
if y > typemax(UInt); throw(DomainError()); end
if y == 0; return one(FlintZZ); end
if y == 1; return x; end
z = fmpz()
ccall((:fmpz_pow_ui, :libflint), Void, (Ref{fmpz}, Ref{fmpz}, UInt), z, x, UInt(y))
return z
end
###############################################################################
#
# Comparison
#
###############################################################################
function cmp(x::fmpz, y::fmpz)
Int(ccall((:fmpz_cmp, :libflint), Cint,
(Ref{fmpz}, Ref{fmpz}), x, y))
end
==(x::fmpz, y::fmpz) = cmp(x,y) == 0
<=(x::fmpz, y::fmpz) = cmp(x,y) <= 0
>=(x::fmpz, y::fmpz) = cmp(x,y) >= 0
<(x::fmpz, y::fmpz) = cmp(x,y) < 0
>(x::fmpz, y::fmpz) = cmp(x,y) > 0
function cmpabs(x::fmpz, y::fmpz)
Int(ccall((:fmpz_cmpabs, :libflint), Cint,
(Ref{fmpz}, Ref{fmpz}), x, y))
end
isless(x::fmpz, y::fmpz) = x < y
###############################################################################
#
# Ad hoc comparison
#
###############################################################################
function cmp(x::fmpz, y::Int)
Int(ccall((:fmpz_cmp_si, :libflint), Cint, (Ref{fmpz}, Int), x, y))
end
==(x::fmpz, y::Int) = cmp(x,y) == 0
<=(x::fmpz, y::Int) = cmp(x,y) <= 0
>=(x::fmpz, y::Int) = cmp(x,y) >= 0
<(x::fmpz, y::Int) = cmp(x,y) < 0
>(x::fmpz, y::Int) = cmp(x,y) > 0
==(x::Int, y::fmpz) = cmp(y,x) == 0
<=(x::Int, y::fmpz) = cmp(y,x) >= 0
>=(x::Int, y::fmpz) = cmp(y,x) <= 0
<(x::Int, y::fmpz) = cmp(y,x) > 0
>(x::Int, y::fmpz) = cmp(y,x) < 0
function cmp(x::fmpz, y::UInt)
Int(ccall((:fmpz_cmp_ui, :libflint), Cint, (Ref{fmpz}, UInt), x, y))
end
==(x::fmpz, y::UInt) = cmp(x,y) == 0
<=(x::fmpz, y::UInt) = cmp(x,y) <= 0
>=(x::fmpz, y::UInt) = cmp(x,y) >= 0
<(x::fmpz, y::UInt) = cmp(x,y) < 0
>(x::fmpz, y::UInt) = cmp(x,y) > 0
==(x::UInt, y::fmpz) = cmp(y,x) == 0
<=(x::UInt, y::fmpz) = cmp(y,x) >= 0
>=(x::UInt, y::fmpz) = cmp(y,x) <= 0
<(x::UInt, y::fmpz) = cmp(y,x) > 0
>(x::UInt, y::fmpz) = cmp(y,x) < 0
###############################################################################
#
# Shifting
#
###############################################################################
doc"""
<<(x::fmpz, c::Int)
> Return $2^cx$ where $c \geq 0$.
"""
function <<(x::fmpz, c::Int)
c < 0 && throw(DomainError())
c == 0 && return x
z = fmpz()
ccall((:fmpz_mul_2exp, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
doc"""
>>(x::fmpz, c::Int)
> Return $x/2^c$, discarding any remainder, where $c \geq 0$.
"""
function >>(x::fmpz, c::Int)
c < 0 && throw(DomainError())
c == 0 && return x
z = fmpz()
ccall((:fmpz_fdiv_q_2exp, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, c)
return z
end
###############################################################################
#
# Modular arithmetic
#
###############################################################################
doc"""
mod(x::fmpz, y::fmpz)
> Return the remainder after division of $x$ by $y$. The remainder will be the
> least nonnegative remainder.
"""
function mod(x::fmpz, y::fmpz)
z = fmpz()
ccall((:fmpz_mod, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
return z
end
doc"""
mod(x::fmpz, y::Int)
> Return the remainder after division of $x$ by $y$. The remainder will be the
> least nonnegative remainder.
"""
function mod(x::fmpz, c::Int)
c == 0 && throw(DivideError())
if c > 0
return ccall((:fmpz_fdiv_ui, :libflint), Int, (Ref{fmpz}, Int), x, c)
else
r = ccall((:fmpz_fdiv_ui, :libflint), Int, (Ref{fmpz}, Int), x, -c)
return r == 0 ? 0 : r + c
end
end
doc"""
powmod(x::fmpz, p::fmpz, m::fmpz)
> Return $x^p (\mod m)$. The remainder will be in the range $[0, m)$
"""
function powmod(x::fmpz, p::fmpz, m::fmpz)
m <= 0 && throw(DomainError())
if p < 0
x = invmod(x, m)
p = -p
end
r = fmpz()
ccall((:fmpz_powm, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}),
r, x, p, m)
return r
end
doc"""
powmod(x::fmpz, p::Int, m::fmpz)
> Return $x^p (\mod m)$. The remainder will be in the range $[0, m)$
"""
function powmod(x::fmpz, p::Int, m::fmpz)
m <= 0 && throw(DomainError())
if p < 0
x = invmod(x, m)
p = -p
end
r = fmpz()
ccall((:fmpz_powm_ui, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int, Ref{fmpz}),
r, x, p, m)
return r
end
doc"""
invmod(x::fmpz, m::fmpz)
> Return $x^{-1} (\mod m)$. The remainder will be in the range $[0, m)$
"""
function invmod(x::fmpz, m::fmpz)
m <= 0 && throw(DomainError())
z = fmpz()
if isone(m)
return fmpz(0)
end
if ccall((:fmpz_invmod, :libflint), Cint,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, m) == 0
error("Impossible inverse in invmod")
end
return z
end
doc"""
sqrtmod(x::fmpz, m::fmpz)
> Return a square root of $x (\mod m)$ if one exists. The remainder will be in
> the range $[0, m)$. We require that $m$ is prime, otherwise the algorithm may
> not terminate.
"""
function sqrtmod(x::fmpz, m::fmpz)
m <= 0 && throw(DomainError())
z = fmpz()
if (ccall((:fmpz_sqrtmod, :libflint), Cint,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, m) == 0)
error("no square root exists")
end
return z
end
doc"""
crt(r1::fmpz, m1::fmpz, r2::fmpz, m2::fmpz, signed=false)
> Find $r$ such that $r \equiv r_1 (\mod m_1)$ and $r \equiv r_2 (\mod m_2)$.
> If `signed = true`, $r$ will be in the range $-m_1m_2/2 < r \leq m_1m_2/2$.
> If `signed = false` the value will be in the range $0 \leq r < m_1m_2$.
"""
function crt(r1::fmpz, m1::fmpz, r2::fmpz, m2::fmpz, signed=false)
z = fmpz()
ccall((:fmpz_CRT, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Cint),
z, r1, m1, r2, m2, signed)
return z
end
doc"""
crt(r1::fmpz, m1::fmpz, r2::Int, m2::Int, signed=false)
> Find $r$ such that $r \equiv r_1 (\mod m_1)$ and $r \equiv r_2 (\mod m_2)$.
> If `signed = true`, $r$ will be in the range $-m_1m_2/2 < r \leq m_1m_2/2$.
> If `signed = false` the value will be in the range $0 \leq r < m_1m_2$.
"""
function crt(r1::fmpz, m1::fmpz, r2::Int, m2::Int, signed=false)
z = fmpz()
r2 < 0 && throw(DomainError())
m2 < 0 && throw(DomainError())
ccall((:fmpz_CRT_ui, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Int, Int, Cint),
z, r1, m1, r2, m2, signed)
return z
end
###############################################################################
#
# Integer logarithm
#
###############################################################################
doc"""
flog(x::fmpz, c::fmpz)
> Return the floor of the logarithm of $x$ to base $c$.
"""
function flog(x::fmpz, c::fmpz)
c <= 0 && throw(DomainError())
x <= 0 && throw(DomainError())
return ccall((:fmpz_flog, :libflint), Int,
(Ref{fmpz}, Ref{fmpz}), x, c)
end
doc"""
clog(x::fmpz, c::fmpz)
> Return the ceiling of the logarithm of $x$ to base $c$.
"""
function clog(x::fmpz, c::fmpz)
c <= 0 && throw(DomainError())
x <= 0 && throw(DomainError())
return ccall((:fmpz_clog, :libflint), Int,
(Ref{fmpz}, Ref{fmpz}), x, c)
end
doc"""
flog(x::fmpz, c::Int)
> Return the floor of the logarithm of $x$ to base $c$.
"""
function flog(x::fmpz, c::Int)
c <= 0 && throw(DomainError())
return ccall((:fmpz_flog_ui, :libflint), Int,
(Ref{fmpz}, Int), x, c)
end
doc"""
clog(x::fmpz, c::Int)
> Return the ceiling of the logarithm of $x$ to base $c$.
"""
function clog(x::fmpz, c::Int)
c <= 0 && throw(DomainError())
return ccall((:fmpz_clog_ui, :libflint), Int,
(Ref{fmpz}, Int), x, c)
end
###############################################################################
#
# GCD and LCM
#
###############################################################################
doc"""
gcd(x::fmpz, y::fmpz)
> Return the greatest common divisor of $x$ and $y$. The returned result will
> always be nonnegative and will be zero iff $x$ and $y$ are zero.
"""
function gcd(x::fmpz, y::fmpz)
z = fmpz()
ccall((:fmpz_gcd, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
return z
end
doc"""
gcd(x::Array{fmpz, 1})
> Return the greatest common divisor of the elements of $x$. The returned
> result will always be nonnegative and will be zero iff all elements of $x$
> are zero.
"""
function gcd(x::Array{fmpz, 1})
if length(x) == 0
error("Array must not be empty")
elseif length(x) == 1
return x[1]
end
z = fmpz()
ccall((:fmpz_gcd, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x[1], x[2])
for i in 3:length(x)
ccall((:fmpz_gcd, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, z, x[i])
if isone(z)
return z
end
end
return z
end
doc"""
lcm(x::fmpz, y::fmpz)
> Return the least common multiple of $x$ and $y$. The returned result will
> always be nonnegative and will be zero iff $x$ and $y$ are zero.
"""
function lcm(x::fmpz, y::fmpz)
z = fmpz()
ccall((:fmpz_lcm, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
return z
end
doc"""
lcm(x::Array{fmpz, 1})
> Return the least common multiple of the elements of $x$. The returned result
> will always be nonnegative and will be zero iff the elements of $x$ are zero.
"""
function lcm(x::Array{fmpz, 1})
if length(x) == 0
error("Array must not be empty")
elseif length(x) == 1
return x[1]
end
z = fmpz()
ccall((:fmpz_lcm, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x[1], x[2])
for i in 3:length(x)
ccall((:fmpz_lcm, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, z, x[i])
end
return z
end
###############################################################################
#
# Extended GCD
#
###############################################################################
doc"""
gcdx(a::fmpz, b::fmpz)
> Return a tuple $g, s, t$ such that $g$ is the greatest common divisor of $a$
> and $b$ and integers $s$ and $t$ such that $g = as + bt$.
"""
function gcdx(a::fmpz, b::fmpz)
if b == 0 # shortcut this to ensure consistent results with gcdx(a,b)
return a < 0 ? (-a, -one(FlintZZ), zero(FlintZZ)) : (a, one(FlintZZ), zero(FlintZZ))
end
g = fmpz()
s = fmpz()
t = fmpz()
ccall((:fmpz_xgcd, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}),
g, s, t, a, b)
g, s, t
end
doc"""
gcdinv(a::fmpz, b::fmpz)
> Return a tuple $g, s$ where $g$ is the greatest common divisor of $a$ and
> $b$ and where $s$ is the inverse of $a$ modulo $b$ if $g = 1$. This function
> can be used to detect impossible inverses, i.e. where $a$ and $b$ are not
> coprime, and to yield the common factor of $a$ and $b$ if they are not
> coprime. We require $b \geq a \geq 0$.
"""
function gcdinv(a::fmpz, b::fmpz)
a < 0 && throw(DomainError())
b < a && throw(DomainError())
g = fmpz()
s = fmpz()
ccall((:fmpz_gcdinv, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}),
g, s, a, b)
return g, s
end
###############################################################################
#
# Roots
#
###############################################################################
doc"""
isqrt(x::fmpz)
> Return the floor of the square root of $x$.
"""
function isqrt(x::fmpz)
x < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_sqrt, :libflint), Void, (Ref{fmpz}, Ref{fmpz}), z, x)
return z
end
doc"""
isqrtrem(x::fmpz)
> Return a tuple $s, r$ consisting of the floor $s$ of the square root of $x$
> and the remainder $r$, i.e. such that $x = s^2 + r$. We require $x \geq 0$.
"""
function isqrtrem(x::fmpz)
x < 0 && throw(DomainError())
s = fmpz()
r = fmpz()
ccall((:fmpz_sqrtrem, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), s, r, x)
return s, r
end
doc"""
root(x::fmpz, n::Int)
> Return the floor of the $n$-the root of $x$. We require $n > 0$ and that
> $x \geq 0$ if $n$ is even.
"""
function root(x::fmpz, n::Int)
x < 0 && iseven(n) && throw(DomainError())
n <= 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_root, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, n)
return z
end
###############################################################################
#
# Factorization
#
###############################################################################
function _factor(a::fmpz)
# This is a hack around https://github.com/JuliaLang/julia/issues/19963
# Remove this once julia 6.0 is required
if a == 1 || a == -1
return Dict{fmpz, Int}(), a
end
F = fmpz_factor()
ccall((:fmpz_factor, :libflint), Void, (Ref{fmpz_factor}, Ref{fmpz}), F, a)
res = Dict{fmpz, Int}()
for i in 1:F.num
z = fmpz()
ccall((:fmpz_factor_get_fmpz, :libflint), Void,
(Ref{fmpz}, Ref{fmpz_factor}, Int), z, F, i - 1)
res[z] = unsafe_load(F.exp, i)
end
return res, canonical_unit(a)
end
function factor(a::fmpz)
fac, z = _factor(a)
return Fac(z, fac)
end
###############################################################################
#
# Number theoretic/combinatorial
#
###############################################################################
doc"""
divisible(x::fmpz, y::fmpz)
> Return `true` if $x$ is divisible by $y$, otherwise return `false`. We
> require $x \neq 0$.
"""
function divisible(x::fmpz, y::fmpz)
iszero(y) && throw(DivideError())
Bool(ccall((:fmpz_divisible, :libflint), Cint,
(Ref{fmpz}, Ref{fmpz}), x, y))
end
doc"""
divisible(x::fmpz, y::Int)
> Return `true` if $x$ is divisible by $y$, otherwise return `false`. We
> require $x \neq 0$.
"""
function divisible(x::fmpz, y::Int)
y == 0 && throw(DivideError())
Bool(ccall((:fmpz_divisible_si, :libflint), Cint,
(Ref{fmpz}, Int), x, y))
end
doc"""
issquare(x::fmpz)
> Return `true` if $x$ is a square, otherwise return `false`.
"""
issquare(x::fmpz) = Bool(ccall((:fmpz_is_square, :libflint), Cint,
(Ref{fmpz},), x))
doc"""
is_prime(x::UInt)
> Return `true` if $x$ is a prime number, otherwise return `false`.
"""
is_prime(x::UInt) = Bool(ccall((:n_is_prime, :libflint), Cint, (UInt,), x))
doc"""
isprime(x::fmpz)
> Return `true` if $x$ is a prime number, otherwise return `false`.
"""
# flint's fmpz_is_prime doesn't work yet
isprime(x::fmpz) = Bool(ccall((:fmpz_is_probabprime, :libflint), Cint,
(Ref{fmpz},), x))
doc"""
isprobabprime(x::fmpz)
> Return `true` if $x$ is a very probably a prime number, otherwise return
> `false`. No counterexamples are known to this test, but it is conjectured
> that infinitely many exist.
"""
isprobabprime(x::fmpz) = Bool(ccall((:fmpz_is_probabprime, :libflint), Cint,
(Ref{fmpz},), x))
doc"""
remove(x::fmpz, y::fmpz)
> Return the tuple $n, z$ such that $x = y^nz$ where $y$ and $z$ are coprime.
"""
function remove(x::fmpz, y::fmpz)
iszero(y) && throw(DivideError())
z = fmpz()
num = ccall((:fmpz_remove, :libflint), Int,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
return num, z
end
remove(x::fmpz, y::Integer) = remove(x, fmpz(y))
remove(x::Integer, y::fmpz) = remove(fmpz(x), y)
remove(x::Integer, y::Integer) = remove(fmpz(x), fmpz(y))
doc"""
valuation(x::fmpz, y::fmpz)
> Return the largest $n$ such that $y^n$ divides $x$.
"""
function valuation(x::fmpz, y::fmpz)
n, _ = remove(x, y)
return n
end
valuation(x::fmpz, y::Integer) = valuation(x, fmpz(y))
valuation(x::Integer, y::fmpz) = valuation(fmpz(x), y)
valuation(x::Integer, y::Integer) = valuation(fmpz(x), fmpz(y))
doc"""
divisor_lenstra(n::fmpz, r::fmpz, m::fmpz)
> If $n$ has a factor which lies in the residue class $r (\mod m)$ for
> $0 < r < m < n$, this function returns such a factor. Otherwise it returns
> $0$. This is only efficient if $m$ is at least the cube root of $n$. We
> require gcd$(r, m) = 1$ and this condition is not checked.
"""
function divisor_lenstra(n::fmpz, r::fmpz, m::fmpz)
r <= 0 && throw(DomainError())
m <= r && throw(DomainError())
n <= m && throw(DomainError())
z = fmpz()
if !Bool(ccall((:fmpz_divisor_in_residue_class_lenstra, :libflint),
Cint, (Ref{fmpz}, Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, n, r, m))
z = 0
end
return z
end
doc"""
fac(x::Int)
> Return the factorial of $x$, i.e. $x! = 1.2.3\ldots x$. We require
> $x \geq 0$.
"""
function fac(x::Int)
x < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_fac_ui, :libflint), Void, (Ref{fmpz}, UInt), z, x)
return z
end
doc"""
risingfac(x::fmpz, y::Int)
> Return the rising factorial of $x$, i.e. $x(x + 1)(x + 2)\ldots (x + n - 1)$.
> If $n < 0$ we throw a `DomainError()`.
"""
function risingfac(x::fmpz, y::Int)
y < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_rfac_ui, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, UInt), z, x, y)
return z
end
doc"""
risingfac(x::Int, y::Int)
> Return the rising factorial of $x$, i.e. $x(x + 1)(x + 2)\ldots (x + n - 1)$.
> If $n < 0$ we throw a `DomainError()`.
"""
function risingfac(x::Int, y::Int)
y < 0 && throw(DomainError())
z = fmpz()
if x < 0
if y <= -x # we don't pass zero
z = isodd(y) ? -risingfac(-x - y + 1, y) :
risingfac(-x - y + 1, y)
end
else
ccall((:fmpz_rfac_uiui, :libflint), Void,
(Ref{fmpz}, UInt, UInt), z, x, y)
end
return z
end
doc"""
primorial(x::Int)
> Return the primorial of $n$, i.e. the product of all primes less than or
> equal to $n$. If $n < 0$ we throw a `DomainError()`.
"""
function primorial(x::Int)
x < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_primorial, :libflint), Void,
(Ref{fmpz}, UInt), z, x)
return z
end
doc"""
fib(x::Int)
> Return the $n$-th Fibonacci number $F_n$. We define $F_1 = 1$, $F_2 = 1$ and
> $F_{i + 1} = F_i + F_{i - 1}$ for all $i > 2$. We require $n \geq 0$. For
> convenience, we define $F_0 = 0$.
"""
function fib(x::Int)
x < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_fib_ui, :libflint), Void,
(Ref{fmpz}, UInt), z, x)
return z
end
doc"""
bell(x::Int)
> Return the Bell number $B_n$.
"""
function bell(x::Int)
x < 0 && throw(DomainError())
z = fmpz()
ccall((:arith_bell_number, :libflint), Void,
(Ref{fmpz}, UInt), z, x)
return z
end
doc"""
binom(n::Int, k::Int)
> Return the binomial coefficient $\frac{n!}{(n - k)!k!}$. If $n, k < 0$ or
> $k > n$ we return $0$.
"""
function binom(n::Int, k::Int)
n < 0 && return fmpz(0)
k < 0 && return fmpz(0)
z = fmpz()
ccall((:fmpz_bin_uiui, :libflint), Void,
(Ref{fmpz}, UInt, UInt), z, n, k)
return z
end
doc"""
moebiusmu(x::fmpz)
> Returns the Moebius mu function of $x$ as an \code{Int}. The value
> returned is either $-1$, $0$ or $1$. If $x < 0$ we throw a `DomainError()`.
"""
function moebiusmu(x::fmpz)
x < 0 && throw(DomainError())
return Int(ccall((:fmpz_moebius_mu, :libflint), Cint,
(Ref{fmpz},), x))
end
doc"""
jacobi(x::fmpz, y::fmpz)
> Return the value of the Jacobi symbol $\left(\frac{x}{y}\right)$. If
> $y \leq x$ or $x < 0$, we throw a `DomainError()`.
"""
function jacobi(x::fmpz, y::fmpz)
y <= x && throw(DomainError())
x < 0 && throw(DomainError())
return Int(ccall((:fmpz_jacobi, :libflint), Cint,
(Ref{fmpz}, Ref{fmpz}), x, y))
end
doc"""
sigma(x::fmpz, y::Int)
> Return the value of the sigma function, i.e. $\sum_{0 < d \;| x} d^y$. If
> $y < 0$ we throw a `DomainError()`.
"""
function sigma(x::fmpz, y::Int)
y < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_divisor_sigma, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, y)
return z
end
doc"""
eulerphi(x::fmpz)
> Return the value of the Euler phi function at $x$, i.e. the number of
> positive integers less than $x$ that are coprime with $x$.
"""
function eulerphi(x::fmpz)
x < 0 && throw(DomainError())
z = fmpz()
ccall((:fmpz_euler_phi, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}), z, x)
return z
end
doc"""
numpart(x::Int)
> Return the number of partitions of $x$. This function is not available on
> Windows 64.
"""
function numpart(x::Int)
if (is_windows() ? true : false) && Int == Int64
error("not yet supported on win64")
end
x < 0 && throw(DomainError())
z = fmpz()
ccall((:partitions_fmpz_ui, :libarb), Void,
(Ref{fmpz}, UInt), z, x)
return z
end
doc"""
numpart(x::fmpz)
> Return the number of partitions of $x$. This function is not available on
> Windows 64.
"""
function numpart(x::fmpz)
if (is_windows() ? true : false) && Int == Int64
error("not yet supported on win64")
end
x < 0 && throw(DomainError())
z = fmpz()
ccall((:partitions_fmpz_fmpz, :libarb), Void,
(Ref{fmpz}, Ref{fmpz}, Int), z, x, 0)
return z
end
###############################################################################
#
# Number bases/digits
#
###############################################################################
doc"""
bin(n::fmpz)
> Return $n$ as a binary string.
"""
bin(n::fmpz) = base(n, 2)
doc"""
oct(n::fmpz)
> Return $n$ as a octal string.
"""
oct(n::fmpz) = base(n, 8)
doc"""
dec(n::fmpz)
> Return $n$ as a decimal string.
"""
dec(n::fmpz) = base(n, 10)
doc"""
hex(n::fmpz) = base(n, 16)
> Return $n$ as a hexadecimal string.
"""
hex(n::fmpz) = base(n, 16)
doc"""
base(n::fmpz, b::Integer)
> Return $n$ as a string in base $b$. We require $2 \leq b \leq 62$.
"""
function base(n::fmpz, b::Integer)
2 <= b <= 62 || error("invalid base: $b")
p = ccall((:fmpz_get_str,:libflint), Ref{UInt8},
(Ref{UInt8}, Cint, Ref{fmpz}), C_NULL, b, n)
s = unsafe_string(p)
ccall((:flint_free, :libflint), Void, (Ref{UInt8},), p)
return s
end
function ndigits_internal(x::fmpz, b::Integer = 10)
# fmpz_sizeinbase might return an answer 1 too big
n = Int(ccall((:fmpz_sizeinbase, :libflint), UInt,
(Ref{fmpz}, Int32), x, b))
abs(x) < fmpz(b)^(n - 1) ? n - 1 : n
end
doc"""
ndigits(x::fmpz, b::Integer = 10)
> Return the number of digits of $x$ in the base $b$ (default is $b = 10$).
"""
ndigits(x::fmpz, b::Integer = 10) = iszero(x) ? 1 : ndigits_internal(x, b)
doc"""
nbits(x::fmpz)
> Return the number of binary bits of $x$. We return zero if $x = 0$.
"""
nbits(x::fmpz) = iszero(x) ? 0 : Int(ccall((:fmpz_sizeinbase, :libflint), UInt,
(Ref{fmpz}, Int32), x, 2)) # docu states: always correct
#if base is power of 2
###############################################################################
#
# Bit fiddling
#
###############################################################################
doc"""
popcount(x::fmpz)
> Return the number of ones in the binary representation of $x$.
"""
popcount(x::fmpz) = Int(ccall((:fmpz_popcnt, :libflint), UInt,
(Ref{fmpz},), x))
doc"""
prevpow2(x::fmpz)
> Return the previous power of $2$ up to including $x$.
"""
prevpow2(x::fmpz) = x < 0 ? -prevpow2(-x) :
(x <= 2 ? x : one(FlintZZ) << (ndigits(x, 2) - 1))
doc"""
nextpow2(x::fmpz)
> Return the next power of $2$ that is at least $x$.
"""
nextpow2(x::fmpz) = x < 0 ? -nextpow2(-x) :
(x <= 2 ? x : one(FlintZZ) << ndigits(x - 1, 2))
doc"""
trailing_zeros(x::fmpz)
> Count the trailing zeros in the binary representation of $x$.
"""
trailing_zeros(x::fmpz) = ccall((:fmpz_val2, :libflint), Int,
(Ref{fmpz},), x)
###############################################################################
#
# Bitwise operations (unsafe)
#
###############################################################################
doc"""
clrbit!(x::fmpz, c::Int)
> Clear bit $c$ of $x$, where the least significant bit is the $0$-th bit. Note
> that this function modifies its input in-place.
"""
function clrbit!(x::fmpz, c::Int)
c < 0 && throw(DomainError())
ccall((:fmpz_clrbit, :libflint), Void, (Ref{fmpz}, Int), x, c)
end
doc"""
setbit!(x::fmpz, c::Int)
> Set bit $c$ of $x$, where the least significant bit is the $0$-th bit. Note
> that this function modifies its input in-place.
"""
function setbit!(x::fmpz, c::Int)
c < 0 && throw(DomainError())
ccall((:fmpz_setbit, :libflint), Void, (Ref{fmpz}, Int), x, c)
end
doc"""
combit!(x::fmpz, c::Int)
> Complement bit $c$ of $x$, where the least significant bit is the $0$-th bit.
> Note that this function modifies its input in-place.
"""
function combit!(x::fmpz, c::Int)
c < 0 && throw(DomainError())
ccall((:fmpz_combit, :libflint), Void, (Ref{fmpz}, Int), x, c)
end
###############################################################################
#
# Unsafe operators
#
###############################################################################
function mul!(z::fmpz, x::fmpz, y::fmpz)
ccall((:fmpz_mul, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
return z
end
function addmul!(z::fmpz, x::fmpz, y::fmpz, c::fmpz)
ccall((:fmpz_addmul, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
return z
end
function addeq!(z::fmpz, x::fmpz)
ccall((:fmpz_add, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, z, x)
return z
end
function add!(z::fmpz, x::fmpz, y::fmpz)
ccall((:fmpz_add, :libflint), Void,
(Ref{fmpz}, Ref{fmpz}, Ref{fmpz}), z, x, y)
return z
end
function zero!(z::fmpz)
ccall((:fmpz_zero, :libflint), Void,
(Ref{fmpz},), z)
return z
end
###############################################################################
#
# Parent object overloads
#
###############################################################################
(::FlintIntegerRing)() = fmpz()
(::FlintIntegerRing)(a::Integer) = fmpz(a)
(::FlintIntegerRing)(a::AbstractString) = fmpz(a)
(::FlintIntegerRing)(a::fmpz) = a
(::FlintIntegerRing)(a::Float64) = fmpz(a)
(::FlintIntegerRing)(a::Float32) = fmpz(Float64(a))
(::FlintIntegerRing)(a::Float16) = fmpz(Float64(a))
(::FlintIntegerRing)(a::BigFloat) = fmpz(BigInt(a))
###############################################################################
#
# String parser
#
###############################################################################
function parse(::Type{fmpz}, s::String, base::Int = 10)
s = string(s)
sgn = s[1] == '-' ? -1 : 1
i = 1 + (sgn == -1)
z = fmpz()
err = ccall((:fmpz_set_str, :libflint),
Int32, (Ref{fmpz}, Ref{UInt8}, Int32),
z, string(SubString(s, i)), base)
err == 0 || error("Invalid big integer: $(repr(s))")
return sgn < 0 ? -z : z
end
###############################################################################
#
# Random generation
#
###############################################################################
function rand(R::FlintIntegerRing, n::UnitRange{Int})
return R(rand(n))
end
###############################################################################
#
# Constructors
#
###############################################################################
fmpz(s::AbstractString) = parse(fmpz, s)
fmpz(z::Integer) = fmpz(BigInt(z))
fmpz(z::Float16) = fmpz(Float64(z))
fmpz(z::Float32) = fmpz(Float64(z))
fmpz(z::BigFloat) = fmpz(BigInt(z))
###############################################################################
#
# Conversions and promotions
#
###############################################################################
convert(::Type{fmpz}, a::Integer) = fmpz(a)
function convert(::Type{BigInt}, a::fmpz)
r = BigInt()
ccall((:fmpz_get_mpz, :libflint), Void, (Ref{BigInt}, Ref{fmpz}), r, a)
return r
end
function convert(::Type{Int}, a::fmpz)
(a > typemax(Int) || a < typemin(Int)) && throw(InexactError())
return ccall((:fmpz_get_si, :libflint), Int, (Ref{fmpz},), a)
end
function convert(::Type{UInt}, a::fmpz)
(a > typemax(UInt) || a < 0) && throw(InexactError())
return ccall((:fmpz_get_ui, :libflint), UInt, (Ref{fmpz}, ), a)
end
function convert(::Type{Float64}, n::fmpz)
# rounds to zero
ccall((:fmpz_get_d, :libflint), Float64, (Ref{fmpz},), n)
end
convert(::Type{Float32}, n::fmpz) = Float32(Float64(n))
convert(::Type{Float16}, n::fmpz) = Float16(Float64(n))
convert(::Type{BigFloat}, n::fmpz) = BigFloat(BigInt(n))
Base.promote_rule(::Type{fmpz}, ::Type{T}) where {T <: Integer} = fmpz
promote_rule(::Type{fmpz}, ::Type{T}) where {T <: Integer} = fmpz
|
module PrecessionNutation
using AstronomicalTime
using ERFA
using StaticArrays
using MuladdMacro
import EarthOrientation: precession_nutation00
include("helper.jl")
include("tables.jl")
export precession_nutation_erfa, precession_nutation_06
function precession_nutation_erfa(ep::TTEpoch)
x, y = ERFA.xy06(julian1(ep), julian2(ep))
s = ERFA.s06(julian1(ep), julian2(ep), x, y)
x, y, s
end
### IAU 2006 precession and IAU 2000A_R06 nutation
function precession_nutation_IAU2006_IAU2000A_R06(ep_tt::TTEpoch; revision = 0)
tt_jc = jc(ep_tt)
if revision === 0
# P03
X = @evalpoly(tt_jc, -16_617.0, +2_004_191_898.00, -429_782.90, -198_618.34, +7.578, +5.928_5) # μas
Y = @evalpoly(tt_jc, -6_951.0, -25_896.00, -22_407_274.70, +1_900.59, +1_112.526, +0.135_8) # μas
s = @evalpoly(tt_jc, +94.0, +3_808.65, -122.68, -72_574.11, +27.980, +15.620_0) # μas
elseif revision === 1
# P03_rev1
X = @evalpoly(tt_jc, -16_617.0, +2_004_191_804.00, -429_755.80, -198_618.29, +7.575, +5.928_5) # μas
Y = @evalpoly(tt_jc, -6_951.0, -24_867.00, -22_407_272.70, +1_900.26, +1_112.525, +0.135_8) # μas
# TODO: confirm values for s
s = @evalpoly(tt_jc, +94.0, +3_808.65, -122.68, -72_574.11, +27.980, +15.620_0) # μas
elseif revision === 2
# P03_rev2
X = @evalpoly(tt_jc, -16_617.0, +2_004_192_130.00, -429_775.20, -198_618.39, +7.576, +5.928_5) # μas
Y = @evalpoly(tt_jc, -6_951.0, -25_817.00, -22_407_280.10, +1_900.46, +1_112.526, +0.135_8) # μas
# TODO: confirm values for s
s = @evalpoly(tt_jc, +94.0, +3_808.65, -122.68, -72_574.11, +27.980, +15.620_0) # μas
else
error("Revision $revision not implemented")
end
fund_args = fundamental_arguments(tt_jc)
X_harm_coeff = zeros(MVector{5, Float64})
Y_harm_coeff = zeros(MVector{5, Float64})
s_harm_coeff = zeros(MVector{5, Float64})
@inbounds for frequency in frequencies
arg = 0.0
@inbounds @simd for k in frequency.coefficients_idx
@muladd arg += frequency.coefficients[k] * fund_args[k]
end
si = sin(arg)
co = cos(arg)
@inbounds for component in frequency.components
@muladd ampl = component.s * si + component.c * co
if component.variable == 1
X_harm_coeff[component.poweridx] += ampl
elseif component.variable == 2
Y_harm_coeff[component.poweridx] += ampl
else
s_harm_coeff[component.poweridx] += ampl
end
end
end
X += @evalpoly(tt_jc, X_harm_coeff[1], X_harm_coeff[2], X_harm_coeff[3], X_harm_coeff[4], X_harm_coeff[5])
Y += @evalpoly(tt_jc, Y_harm_coeff[1], Y_harm_coeff[2], Y_harm_coeff[3], Y_harm_coeff[4], Y_harm_coeff[5])
s += @evalpoly(tt_jc, s_harm_coeff[1], s_harm_coeff[2], s_harm_coeff[3], s_harm_coeff[4], s_harm_coeff[5])
X = μas_to_rad(X)
Y = μas_to_rad(Y)
s = μas_to_rad(s)
X, Y, s - X * Y / 2
end
const precession_nutation_06 = precession_nutation_IAU2006_IAU2000A_R06
end # module
|
struct DeepTreeEnv
depth::Int64
adj_list::Dict{Int64, Vector{Int64}}
end
function DeepTreeEnv(depth::Int64, model::String, rng::MersenneTwister)
@assert depth > 3
num_nodes = compute_num_nodes(depth)
list_of_nodes = collect(1:num_nodes)
if model == "true"
elseif model == "optimistic"
else
end
end
function compute_num_nodes(depth::Int64)
sum([2^i for i in 0:depth])
end |
function PlotStairs(label_id, values::AbstractArray{T}, count::Integer, xscale::Real = 1.0, x0::Real = 0.0, offset::Integer = 0, stride::Integer = sizeof(T)) where {T<:ImPlotData}
LibCImPlot.PlotStairs(label_id, values, count, xscale, x0, offset, stride)
end
function PlotStairs(label_id, values::AbstractArray{T}, count::Integer, xscale::Real = 1.0, x0::Real = 0.0, offset::Integer = 0, stride::Integer = sizeof(Float64)) where {T<:Real}
LibCImPlot.PlotStairs(label_id, Float64.(values), count, xscale, x0, offset, stride)
end
function PlotStairs(label_id, x::AbstractArray{T}, y::AbstractArray{T}, count::Integer, offset::Integer = 0, stride::Integer = sizeof(T)) where {T<:ImPlotData}
LibCImPlot.PlotStairs(label_id, x, y, count, offset, stride)
end
function PlotStairs(label_id, x::AbstractArray{T}, y::AbstractArray{T}, count::Integer, offset::Integer = 0, stride::Integer = sizeof(Float64)) where {T<:Real}
LibCImPlot.PlotStairs(label_id, Float64.(x), Float64.(y), count, offset, stride)
end
function PlotStairs(y::AbstractArray{T};
label_id::String="",
count::Integer=length(y),
xscale::Real = 1.0, x0::Real = 0.0,
offset::Integer=0,
stride::Integer=1
) where {T <: ImPlotData}
LibCImPlot.PlotStairs(label_id, y, count, xscale, x0, offset, stride * sizeof(T))
end
function PlotStairs(x::AbstractArray{T}, y::AbstractArray{T};
count::Integer = min(length(x), length(y)),
offset::Integer = 0,
stride::Integer = 1,
label_id::String = ""
) where {T <: ImPlotData}
LibCImPlot.PlotStairs(label_id, x, y, count, offset, stride * sizeof(T))
end
|
using LinearAlgebra
using Distances
# unittest performance
# versus python hsic_varioustests_npy.py unittest:
# 20sec elapsed / 52sec user (i.e. multithreaded)
# using distmat1: 10.3sec
# using Distances.jl pairwise 13.2sec
# using distmatvec: 10.7sec
# performance discussion see https://discourse.julialang.org/t/sum-of-hadamard-products/3531/5
# for comparison, do the non-vectorized calculation
# points are in columns, dimensions(variables) across rows
# note transposed from previous convention!
function distmatslow(X,Y)
m = size(X,2)
@assert m==size(Y,2) #"size mismatch"
D = Array{Float32}(undef,m,m)
for ix = 1:m
@inbounds for iy = 1:m
x = X[:,ix]
y = Y[:,iy]
d = norm(x-y)
D[ix,iy] = d*d
end
end
return D
end
function distmat(X,Y)
m = size(X,2)
@assert m==size(Y,2) #"size mismatch"
D = Array{Float32}(undef,m,m)
for ix = 1:m
@inbounds for iy = ix:m
x = X[:,ix]
y = Y[:,iy]
d = x-y
d2 = d'*d
D[ix,iy] = d2
D[iy,ix] = d2
end
end
return D
end
#
function distmatvec(X,Y)
"""
points are in columns, dimensions(variables) down rows
"""
m = size(X,2)
@assert m==size(Y,2) #"size mismatch"
XY = sum(X .* Y,dims=1)
#XY = XY.reshape(m,1)
#R1 = n_.tile(XY,(1,Y.shape[0]))
R1 = repeat(XY',1,m) # outer=(1,m) not suported by autograd
R2 = repeat(XY,m,1)
#xy_ = X * Y'
D = R1 + R2 - 2.f0 * X' * Y
D
end
# python-ish version requires broadcasting different shapes - "outer sum"
function distmat1(X,Y)
A = sum(X .* X,dims=1)'
B = sum(Y .* Y,dims=1)
C = X' * Y
A .+ B .- 2.f0 * C
end
function eye(n)
Matrix{Float32}(I,n,n)
end
function hsic(X,Y,sigma)
#=
# 1/m^2 Tr Kx H Ky H
X,Y have data in COLUMNS, each row is a dimension
# NB is transposed from python
=#
#println("X=\n", X'[1:2,:])
#Yt = Y;; println("Y=\n", Yt[1:2:])
m = size(X,2)
println("hsic between ",m,"points")
H = eye(m) - (1.f0 / m) * ones(Float32,m,m)
#Dxx = distmatvec(X,X)
#Dyy = distmatvec(Y,Y)
Dxx = distmat1(X,X)
Dyy = distmat1(Y,Y)
#Dxx = pairwise(SqEuclidean(),X,X,dims=2)
#Dyy = pairwise(SqEuclidean(),Y,Y,dims=2)
sigma2 = 2.f0 * sigma*sigma
Kx = exp.( -Dxx / sigma2 )
Ky = exp.( -Dyy / sigma2 )
Kxc = Kx * H
Kyc = Ky * H
thehsic = (1.f0 / (m*m)) * sum(Kxc' .* Kyc)
return thehsic # type float32
end
# Pkg.add("NPZ")
using NPZ
# aug19: this matches the output of the unittest in hsic_varioustests_npy
function unittest()
X = Float32[0.1 0.2 0.3;
5 4 3]
Y = Float32[1 2 3;
2 2 2]
X = transpose(X)
Y = transpose(Y)
println(distmatslow(X,X))
println(distmat(X,X))
println(distmatslow(Y,Y))
println(distmat(Y,Y))
println("hsic(X,Y,0.5)=",hsic(X,Y,0.5f0))
# larger test
data = npzread("/tmp/_data.npz")
# todo convert arrays to float32
X = data["arr_0"]
Y = data["arr_1"]
X = convert(Array{Float32,2},X')
Y = convert(Array{Float32,2},Y')
println("X=\n", X'[1:2,:])
println("Y=\n", Y'[1:2,:])
println("\nindependent hsic(X,Y,1)=",hsic(X,Y,1.f0))
println("\nidentical hsic(X,X,1)=",hsic(X,copy(X),1.f0))
Y2 = X .* X
println("Y2=",Y2'[1:2,:])
println("\nnonlinear hsic(X,Y*Y,1)=",hsic(X,Y2,1.f0))
end
|
using KernelAbstractions.Extras.LoopInfo: @unroll
#####
##### Periodic boundary conditions
#####
@kernel function fill_periodic_west_and_east_halo!(c, H::Int, N)
j, k = @index(Global, NTuple)
@unroll for i = 1:H
@inbounds begin
c[i, j, k] = c[N+i, j, k] # west
c[N+H+i, j, k] = c[H+i, j, k] # east
end
end
end
@kernel function fill_periodic_south_and_north_halo!(c, H::Int, N)
i, k = @index(Global, NTuple)
@unroll for j = 1:H
@inbounds begin
c[i, j, k] = c[i, N+j, k] # south
c[i, N+H+j, k] = c[i, H+j, k] # north
end
end
end
@kernel function fill_periodic_bottom_and_top_halo!(c, H::Int, N)
i, j = @index(Global, NTuple)
@unroll for k = 1:H
@inbounds begin
c[i, j, k] = c[i, j, N+k] # top
c[i, j, N+H+k] = c[i, j, H+k] # bottom
end
end
end
function fill_west_and_east_halo!(c, ::PBC, ::PBC, arch, dep, grid, args...; kw...)
c_parent = parent(c)
yz_size = size(c_parent)[[2, 3]]
event = launch!(arch, grid, yz_size, fill_periodic_west_and_east_halo!, c_parent, grid.Hx, grid.Nx; dependencies=dep, kw...)
return event
end
function fill_south_and_north_halo!(c, ::PBC, ::PBC, arch, dep, grid, args...; kw...)
c_parent = parent(c)
xz_size = size(c_parent)[[1, 3]]
event = launch!(arch, grid, xz_size, fill_periodic_south_and_north_halo!, c_parent, grid.Hy, grid.Ny; dependencies=dep, kw...)
return event
end
function fill_bottom_and_top_halo!(c, ::PBC, ::PBC, arch, dep, grid, args...; kw...)
c_parent = parent(c)
xy_size = size(c_parent)[[1, 2]]
event = launch!(arch, grid, xy_size, fill_periodic_bottom_and_top_halo!, c_parent, grid.Hz, grid.Nz; dependencies=dep, kw...)
return event
end
####
#### Implement single periodic directions (for Distributed memory architectures)
####
@kernel function fill_periodic_west_halo!(c, H::Int, N)
j, k = @index(Global, NTuple)
@unroll for i = 1:H
@inbounds begin
c[i, j, k] = c[N+i, j, k] # west
end
end
end
@kernel function fill_periodic_east_halo!(c, H::Int, N)
j, k = @index(Global, NTuple)
@unroll for i = 1:H
@inbounds begin
c[N+H+i, j, k] = c[H+i, j, k] # east
end
end
end
@kernel function fill_periodic_south_halo!(c, H::Int, N)
i, k = @index(Global, NTuple)
@unroll for j = 1:H
@inbounds begin
c[i, j, k] = c[i, N+j, k] # south
end
end
end
@kernel function fill_periodic_north_halo!(c, H::Int, N)
i, k = @index(Global, NTuple)
@unroll for j = 1:H
@inbounds begin
c[i, N+H+j, k] = c[i, H+j, k] # north
end
end
end
@kernel function fill_periodic_bottom_halo!(c, H::Int, N)
i, j = @index(Global, NTuple)
@unroll for k = 1:H
@inbounds begin
c[i, j, k] = c[i, j, N+k] # bottom
end
end
end
@kernel function fill_periodic_top_halo!(c, H::Int, N)
i, j = @index(Global, NTuple)
@unroll for k = 1:H
@inbounds begin
c[i, j, N+H+k] = c[i, j, H+k] # top
end
end
end
function fill_west_halo!(c, ::PBC, arch, dep, grid, args...; kw...)
c_parent = parent(c)
yz_size = size(c_parent)[[2, 3]]
event = launch!(arch, grid, yz_size, fill_periodic_west_halo!, c_parent, grid.Hx, grid.Nx; dependencies=dep, kw...)
return event
end
function fill_east_halo!(c, ::PBC, arch, dep, grid, args...; kw...)
c_parent = parent(c)
yz_size = size(c_parent)[[2, 3]]
event = launch!(arch, grid, yz_size, fill_periodic_east_halo!, c_parent, grid.Hx, grid.Nx; dependencies=dep, kw...)
return event
end
function fill_south_halo!(c, ::PBC, arch, dep, grid, args...; kw...)
c_parent = parent(c)
xz_size = size(c_parent)[[1, 3]]
event = launch!(arch, grid, xz_size, fill_periodic_south_halo!, c_parent, grid.Hy, grid.Ny; dependencies=dep, kw...)
return event
end
function fill_north_halo!(c, ::PBC, arch, dep, grid, args...; kw...)
c_parent = parent(c)
xz_size = size(c_parent)[[1, 3]]
event = launch!(arch, grid, xz_size, fill_periodic_north_halo!, c_parent, grid.Hy, grid.Ny; dependencies=dep, kw...)
return event
end
function fill_bottom_halo!(c, ::PBC, arch, dep, grid, args...; kw...)
c_parent = parent(c)
xy_size = size(c_parent)[[1, 2]]
event = launch!(arch, grid, xy_size, fill_periodic_bottom_halo!, c_parent, grid.Hz, grid.Nz; dependencies=dep, kw...)
return event
end
function fill_top_halo!(c, ::PBC, arch, dep, grid, args...; kw...)
c_parent = parent(c)
xy_size = size(c_parent)[[1, 2]]
event = launch!(arch, grid, xy_size, fill_periodic_top_halo!, c_parent, grid.Hz, grid.Nz; dependencies=dep, kw...)
return event
end
|
using Printf
import Flux: σ
using ModelingToolkit
using GalacticOptim
using Optim
using DiffEqFlux
using NeuralPDE
using Quadrature, Cubature, Cuba
using Plots
@parameters t,x
@variables c(..)
@derivatives Dt'~t
@derivatives Dxx''~x
@derivatives Dx'~x
# Parameters
v = 1
R = 0
D = 0.1 # diffusion
t_max = 2.0
x_min = -1.0
x_max = 1.0
# Equations, initial and boundary conditions
eqs = [ Dt(c(t, x)) ~ D * Dxx(c(t,x)) - Dx(c(t,x)) ]
bcs = [
c(0, x) ~ cos(π*x) + 1.0,
c(t, x_min) ~ c(t, x_max)
]
# Space and time domains
domains = [t ∈ IntervalDomain(0.0,t_max),
x ∈ IntervalDomain(x_min,x_max)
]
# Discretization
nx = 32
dx = (x_max-x_min) / (nx - 1)
dt = 0.01
# Neural network
dim = length(domains)
output = length(eqs)
hidden = 8
chain = FastChain( FastDense(dim, hidden, σ),
FastDense(hidden, hidden, σ),
FastDense(hidden, 1))
strategy = GridTraining(dx=[dt,dx])
discretization = PhysicsInformedNN(chain, strategy=strategy)
pde_system = PDESystem(eqs, bcs, domains, [t,x], [c])
prob = discretize(pde_system,discretization)
cb = function (p,l)
println("Current loss is: $l")
return false
end
res = GalacticOptim.solve(prob,Optim.BFGS();cb=cb,maxiters=1200)
# Plots
phi = discretization.phi
initθ = discretization.initθ
acum = [0;accumulate(+, length.(initθ))]
sep = [acum[i]+1 : acum[i+1] for i in 1:length(acum)-1]
minimizers = [res.minimizer[s] for s in sep]
ts,xs = [domain.domain.lower:dx:domain.domain.upper for domain in domains]
anim = @animate for (i, t) in enumerate(0:dt:t_max)
@info "Animating frame $i..."
c_predict = reshape([phi([t, x], res.minimizer)[1] for x in xs], length(xs))
title = @sprintf("Advection-diffusion t = %.3f", t)
plot(xs, c_predict, label="", title=title , ylims=(0., 2))
end
gif(anim, "advection_diffusion_pinn.gif", fps=15)
c_predict = reshape([ phi([0, x], res.minimizer)[1] for x in xs], length(xs))
plot(xs,c_predict)
# Plot correct solution
using JLD2
file = jldopen("advection_diffusion/simulation/cosine_advection_diffusion.jld2")
iterations = parse.(Int, keys(file["timeseries/t"]))
anim = @animate for (i, iter) in enumerate(iterations)
@info "Animating frame $i..."
Hx = file["grid/Hx"]
x = file["grid/xC"][1+Hx:end-Hx]
t = file["timeseries/t/$iter"]
c = file["timeseries/c/$iter"][:]
title = @sprintf("Advection-diffusion t = %.3f", t)
p = plot(x, c .+ 1, linewidth=2, title=title, label="Oceananigans",
xlabel="x", ylabel="Tracer", xlims=(-1, 1), ylims=(0, 2))
c_predict = reshape([phi([t, x], res.minimizer)[1] for x in xs], length(xs))
plot!(p, x, c_predict, linewidth=2, label="Neural PDE")
end
gif(anim, "advection_diffusion_comparison.gif", fps=15)
|
module AutoARIMA
using LinearAlgebra
using Optim
using Polynomials
using RecipesBase
using StaticArrays
using Statistics
using HypothesisTests
export seriesA,seriesB,seriesB2,seriesC,seriesD,seriesE,seriesF,seriesG,dowj,wine,lake
export autocovariance,autocovariance_matrix,autocorrelation,autocorrelation_matrix,partial_autocorrelation
export isinversible, isstationary
export innovations, levinson_durbin, least_squares, yule_walker, hannan_rissanen
export boxcox, inv_boxcox, guerrero, difference, integrate
export simulate, forecast, fit, toarma, k, residuals
export aic, aicc, bic, mse, rmse, mae, mape
export correlogram,partial_correlogram
export AbstractModel, AbstractParams
export ARParams, MAParams, ARMAParams, ARIMAParams, MSARIMAParams
export ARModel, MAModel, ARMAModel
export MA∞, AR∞
export boxjenkins
include("datasets.jl")
include("stats.jl")
include("transforms.jl")
include("abstract.jl")
include("criteria.jl")
include("simulate.jl")
include("recipes.jl")
include("ls.jl")
include("arma.jl")
include("ar.jl")
include("ma.jl")
include("arima.jl")
include("sarima.jl")
include("auto.jl")
end |
module GLM_
import MLJBase
export OLSRegressor #, OLS, LinearRegression
import ..GLM # strange syntax for lazy-loading
const OLSFitResult = GLM.LinearModel
OLSFitResult(coefs::Vector, b=nothing) = OLSFitResult(coefs, b)
####
#### OLSRegressor
####
mutable struct OLSRegressor <: MLJBase.Deterministic{OLSFitResult}
fit_intercept::Bool
# allowrankdeficient::Bool
end
function OLSRegressor(;fit_intercept=true)
return OLSRegressor(fit_intercept)
end
# synonyms
# const OLS = OLSRegressor
# const LinearRegression = OLSRegressor
####
#### fit/predict OLSRegressor
####
function MLJBase.fit(model::OLSRegressor, verbosity::Int, X, y::Vector)
Xmatrix = MLJBase.matrix(X)
features = MLJBase.schema(X).names
if model.fit_intercept
fitresult = GLM.lm(hcat(Xmatrix, ones(eltype(Xmatrix), size(Xmatrix, 1), 1)), y)
else
fitresult = GLM.lm(Xmatrix, y)
end
coefs = GLM.coef(fitresult)
## TODO: add feature importance curve to report using `features`
report = Dict(:coef => coefs[1:end-Int(model.fit_intercept)]
, :intercept => ifelse(model.fit_intercept, coefs[end], nothing)
, :deviance => GLM.deviance(fitresult)
, :dof_residual => GLM.dof_residual(fitresult)
, :stderror => GLM.stderror(fitresult)
, :vcov => GLM.vcov(fitresult))
cache = nothing
return fitresult, cache, report
end
function MLJBase.predict(model::OLSRegressor, fitresult::OLSFitResult, Xnew)
Xmatrix = MLJBase.matrix(Xnew)
model.fit_intercept && (Xmatrix = hcat(Xmatrix, ones(eltype(Xmatrix), size(Xmatrix, 1), 1)))
return GLM.predict(fitresult, Xmatrix)
end
# metadata:
MLJBase.load_path(::Type{<:OLSRegressor}) = "MLJModels.GLM_.OLSRegressor"
MLJBase.package_name(::Type{<:OLSRegressor}) = "GLM"
MLJBase.package_uuid(::Type{<:OLSRegressor}) = "38e38edf-8417-5370-95a0-9cbb8c7f171a"
MLJBase.package_url(::Type{<:OLSRegressor}) = "https://github.com/JuliaStats/GLM.jl"
MLJBase.is_pure_julia(::Type{<:OLSRegressor}) = :yes
MLJBase.input_kinds(::Type{<:OLSRegressor}) = [:continuous, ]
MLJBase.output_kind(::Type{<:OLSRegressor}) = :continuous
MLJBase.output_quantity(::Type{<:OLSRegressor}) = :univariate
end # module
|
function run_simulation(set_sizes; fun = conjunctive_set, kwargs...)
results = DataFrame[]
for n in set_sizes
experiment = Experiment(set_size = n, populate_visicon = fun,
n_trials = 10^4)
run_condition!(experiment; kwargs...)
df = DataFrame(experiment.data)
hit_rate = mean(df.target_present .== df.response)
g = groupby(df, [:target_present,:response])
temp = combine(g, :rt => mean)
temp[!,:distractors] .= n
temp[!,:hit_rate] .= hit_rate
push!(results, temp)
end
return vcat(results...)
end |
export Apply
"""
Apply{J, O} <: SFunc{Tuple{SFunc{J, O}, J}, O}
Apply represents an sfunc that takes two groups of arguments. The first group is a single
argument, which is an sfunc to apply to the second group of arguments.
# Additional supported operators
- `support`
- `support_quality`
- `sample`
- `logcpdf`
- `compute_pi`
- `send_lambda`
# Type parameters
- `J`: the input type of the *sfunc* that may be applied; that *sfunc* is the input type of the `Apply`
- `O`: the output type of the *sfunc* that may be applied, which is also the output type of the `Apply`
"""
struct Apply{J <: Tuple, O} <: SFunc{Tuple{SFunc{J, O}, J}, O}
end
@impl begin
struct ApplySupport end
function support(::Apply{J,O},
parranges::NTuple{N,Vector},
size::Integer,
curr::Vector{<:O}) where {J<:Tuple,O,N}
result = Vector{O}()
for sf in parranges[1]
append!(result, support(sf, (parranges[2],), size, curr))
end
return unique(result)
end
end
@impl begin
struct ApplySupportQuality end
function support_quality(::Apply{J,O}, parranges) where {J,O}
q = support_quality_rank(:CompleteSupport)
for sf in parranges[1]
imp = get_imp(MultiInterface.get_policy(), Support, sf, parranges[2], 0, O[])
q = min(q, support_quality_rank(support_quality(imp, sf, parranges[2])))
end
return support_quality_from_rank(q)
end
end
@impl begin
struct ApplySample end
function sample(::Apply{J,O}, input::Tuple{SFunc{J,O}, J})::O where {J<:Tuple,O}
return sample(input[1], input[2])
end
end
@impl begin
struct ApplyLogcpdf end
function logcpdf(::Apply{J,O}, i::Tuple{SFunc{J,O}, J}, o::O)::AbstractFloat where {J<:Tuple,O}
return logcpdf(i[1], i[2], o)
end
end
# WARNING: THIS LOGIC DOES NOT WORK WITH MORE THAN ONE PARENT
@impl begin
struct ApplyComputePi end
function compute_pi(::Apply{J,O},
range::__OptVec{<:O},
parranges::NTuple{N,Vector},
incoming_pis::Tuple)::Dist{<:O} where {N,J<:Tuple,O}
sfrange = parranges[1]
argsrange = parranges[2]
sfpi = incoming_pis[1]
argspi = incoming_pis[2]
result = zeros(Float64, length(range))
for sf in sfrange
p1 = cpdf(sfpi, (), sf)
p2 = compute_pi(sf, range, (argsrange,), (argspi,))
p3 = [p1 * cpdf(p2, (), x) for x in range]
result .+= p3
end
return Cat(range, result)
end
end
# WARNING: THIS LOGIC DOES NOT WORK WITH MORE THAN ONE PARENT
@impl begin
struct ApplySendLambda end
function send_lambda(::Apply{J,O},
lambda::Score{<:O},
range::__OptVec{<:O},
parranges::NTuple{N,Vector},
incoming_pis::Tuple,
parent_idx::Integer)::Score where {N,J<:Tuple,O}
@assert parent_idx == 1 || parent_idx == 2
sfrange = parranges[1]
argsrange = parranges[2]
sfpi = incoming_pis[1]
argspi = incoming_pis[2]
if parent_idx == 2
# For each x, we must sum over the sfunc argument compute P(y|x) for each possible sfunc
result = Vector{Float64}()
for args in argsrange
resultpieces = Vector{Float64}()
for sf in sfrange
sp = logcpdf(sfpi, (), sf)
for y in range
a = isa(args, Tuple) ? args : tuple(args)
push!(resultpieces, sp + logcpdf(sf, a, y) + get_log_score(lambda, y))
end
end
push!(result, logsumexp(resultpieces))
end
return LogScore(argsrange, result)
else # parent_idx == 1
# This is simpler; we must sum over the arguments, which is achieved by the embedded compute_pi
result = Vector{Float64}()
for sf in sfrange
resultpieces = Vector{Float64}()
ypi = compute_pi(sf, range, (argsrange,), (argspi,))
for y in range
push!(resultpieces, logcpdf(ypi, (), y) + get_log_score(lambda, y))
end
push!(result, logsumexp(resultpieces))
end
return LogScore(sfrange, result)
end
end
end
|
End of preview. Expand
in Dataset Viewer.
Julia-Proof-Pile-2
This dataset is part of Proof-Pile-2 dataset. This dataset is consisting of mathematical code, including numerical computing, computer algebra, and formal mathematics. This entire dataset is in Julia language. It is slightly more than 0.5 Billion tokens. I have removed Meta data from this dataset hence you can directly use it for training purpose. This dataset is in Jsonl format.
- Downloads last month
- 37