licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.5.1 | 4a51ecb0d0bb2bb7ccf06891437c7bf928f7d356 | code | 1290 |
@testset "Weighted sampling single tests" begin
@testset "method=$method" for method in (AlgWRSWRSKIP(),)
wv(el) = 1.0
a, b = 1, 100
z = itsample(a:b, wv, method)
@test a <= z <= b
z = itsample(Iterators.filter(x -> x != b+1, a:b+1), wv, method)
@test a <= z <= b
iter = Iterators.filter(x -> x != b + 1, a:b+1)
rs = ReservoirSample(Int, method)
for x in iter
fit!(rs, x, wv(x))
end
@test a <= value(rs) <= b
@test nobs(rs) == 100
rng = StableRNG(43)
wv2(el) = el <= 50 ? 1.0 : 2.0
iters = (a:b, Iterators.filter(x -> x != b + 1, a:b+1))
for it in iters
reps = 10000
dict_res = Dict{Int, Int}()
for _ in 1:reps
s = itsample(rng, it, wv2, method)
if s in keys(dict_res)
dict_res[s] += 1
else
dict_res[s] = 1
end
end
cases = 100
ps_exact = [wv2(el)/150 for el in keys(dict_res)]
count_est = collect(values(dict_res))
chisq_test = ChisqTest(count_est, ps_exact)
@test pvalue(chisq_test) > 0.05
end
end
end
| StreamSampling | https://github.com/JuliaDynamics/StreamSampling.jl.git |
|
[
"MIT"
] | 0.5.1 | 4a51ecb0d0bb2bb7ccf06891437c7bf928f7d356 | docs | 3881 | # StreamSampling.jl
[](https://github.com/JuliaDynamics/StreamSampling.jl/actions?query=workflow%3ACI)
[](https://juliadynamics.github.io/StreamSampling.jl/stable/)
[](https://codecov.io/gh/JuliaDynamics/StreamSampling.jl)
[](https://github.com/JuliaTesting/Aqua.jl)
[](https://zenodo.org/doi/10.5281/zenodo.12826684)
The scope of this package is to provide general methods to sample from any stream in a single pass through the data, even when
the number of items contained in the stream is unknown.
This has some advantages over other sampling procedures:
- If the iterable is lazy, the memory required grows in relation to the size of the sample, instead of the all population.
- The sample collected is a random sample of the portion of the stream seen thus far at any point of the sampling process.
- In some cases, sampling with the techniques implemented in this library can bring considerable performance gains, since
the population of items doesn't need to be previously stored in memory.
## Overview of the functionalities
The `itsample` function allows to consume all the stream at once and return the sample collected:
```julia
julia> using StreamSampling
julia> st = 1:100;
julia> itsample(st, 5)
5-element Vector{Int64}:
9
15
52
96
91
```
In some cases, one needs to control the updates the `ReservoirSample` will be subject to. In this case
you can simply use the `fit!` function to update the reservoir:
```julia
julia> using StreamSampling
julia> rs = ReservoirSample(Int, 5);
julia> for x in 1:100
fit!(rs, x)
end
julia> value(rs)
5-element Vector{Int64}:
7
9
20
49
74
```
Consult the [API page](https://juliadynamics.github.io/StreamSampling.jl/stable/api) for more information on these and other functionalities.
## Benchmark
As stated in the first section, using these sampling techniques can bring down considerably the memory usage of the program,
but there are cases where they are also more time efficient, as demostrated below with a comparison with the
equivalent methods of `StatsBase.sample`:
```julia
julia> using StreamSampling
julia> using BenchmarkTools, Random, StatsBase
julia> rng = Xoshiro(42);
julia> iter = Iterators.filter(x -> x != 10, 1:10^7);
julia> wv(el) = Float64(el);
julia> @btime itsample($rng, $iter, 10^4, AlgRSWRSKIP());
12.301 ms (6 allocations: 156.38 KiB)
julia> @btime sample($rng, collect($iter), 10^4; replace=true);
92.936 ms (35 allocations: 290.93 MiB)
julia> @btime itsample($rng, $iter, 10^4, AlgL());
12.719 ms (3 allocations: 78.19 KiB)
julia> @btime sample($rng, collect($iter), 10^4; replace=false);
93.544 ms (41 allocations: 291.08 MiB)
julia> @btime itsample($rng, $iter, $wv, 10^4, AlgWRSWRSKIP());
18.672 ms (22 allocations: 547.34 KiB)
julia> @btime sample($rng, collect($iter), Weights($wv.($iter)), 10^4; replace=true);
377.567 ms (83 allocations: 963.26 MiB)
julia> @btime itsample($rng, $iter, $wv, 10^4, AlgAExpJ());
37.600 ms (8 allocations: 234.55 KiB)
julia> @btime sample($rng, collect($iter), Weights($wv.($iter)), 10^4; replace=false);
258.426 ms (74 allocations: 658.24 MiB)
```
Some more performance comparisons in respect to `StatsBase` methods are in the [benchmark](https://github.com/JuliaDynamics/StreamSampling.jl/blob/main/benchmark/) folder.
## Contributing
Contributions are welcome! If you encounter any issues, have suggestions for improvements, or would like to add new
features, feel free to open an issue or submit a pull request.
| StreamSampling | https://github.com/JuliaDynamics/StreamSampling.jl.git |
|
[
"MIT"
] | 0.5.1 | 4a51ecb0d0bb2bb7ccf06891437c7bf928f7d356 | docs | 457 | # API
This is the API page of the package. For a general overview of the functionalities
consult the [ReadMe](https://github.com/JuliaDynamics/StreamSampling.jl).
## General Functionalities
```@docs
ReservoirSample
fit!
merge!
merge
empty!
value
ordvalue
nobs
itsample
```
## Sampling Algorithms
```@docs
StreamSampling.AlgR
StreamSampling.AlgL
StreamSampling.AlgRSWRSKIP
StreamSampling.AlgARes
StreamSampling.AlgAExpJ
StreamSampling.AlgWRSWRSKIP
```
| StreamSampling | https://github.com/JuliaDynamics/StreamSampling.jl.git |
|
[
"MIT"
] | 0.5.1 | 4a51ecb0d0bb2bb7ccf06891437c7bf928f7d356 | docs | 1732 | # An Illustrative Example
Suppose to receive data about some process in the form of a stream and you want
to detect if anything is going wrong in the data being received. A reservoir
sampling approach could be useful to evaluate properties on the data stream.
This is a demonstration of such a use case using `StreamSampling.jl`. We will
assume that the monitored statistic in this case is the mean of the data, and
you want that to be lower than a certain threshold otherwise some malfunctioning
is expected.
```julia
julia> using StreamSampling, Statistics, Random
julia> function monitor(stream, thr)
rng = Xoshiro(42)
# we use a reservoir sample of 10^4 elements
rs = ReservoirSample(rng, Int, 10^4)
# we loop over the stream and fit the data in the reservoir
for (i, e) in enumerate(stream)
fit!(rs, e)
# we check the mean value every 1000 iterations
if iszero(mod(i, 1000)) && mean(value(rs)) >= thr
return rs
end
end
end
```
We use some toy data for illustration
```julia
julia> stream = 1:10^8; # the data stream
julia> thr = 2*10^7; # the threshold for the mean monitoring
```
Then, we run the monitoring
```julia
julia> rs = monitor(stream, thr);
```
The number of observations until the detection is triggered is
given by
```julia
julia> nobs(rs)
40009000
```
which is very close to the true value of `4*10^7 - 1` observations.
Note that in this case we could use an online mean methods,
instead of holding all the sample into memory. However,
the approach with the sample is more general because it
allows to estimate any statistic about the stream.
| StreamSampling | https://github.com/JuliaDynamics/StreamSampling.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 9674 |
struct AhoCorasickAutomaton{T <: Unsigned}
base::Vector{T}
from::Vector{T}
ikey::Vector{T}
deep::Vector{T}
back::Vector{T}
arcs::Vector{Vector{UInt8}}
end
function AhoCorasickAutomaton{T}() where T
base = T[1]
from = T[1]
ikey = T[0]
deep = T[0]
back = T[0]
arcs = [UInt8[]]
return AhoCorasickAutomaton{T}(base, from, ikey, deep, back, arcs)
end
function AhoCorasickAutomaton{T}(keys::Vector, sort::Bool) where T
obj = AhoCorasickAutomaton{T}()
if sort && !issorted(keys) Base.sort!(keys) end
for (key, i) in keys
addkey!(obj, codeunits(key), T(i))
end
shrink!(obj)
@inbounds fillback!(obj)
validate(obj)
resize!(obj.arcs, 0)
return obj
end
function AhoCorasickAutomaton{T}(keys::AbstractDict{String, Ti}; sort::Bool = true) where {T, Ti}
return AhoCorasickAutomaton{T}(collect(keys), sort)
end
function AhoCorasickAutomaton{T}(keys::Vector{String}; sort::Bool = true) where T
return AhoCorasickAutomaton{T}(collect(zip(keys, 1:length(keys))), sort)
end
function ==(x::AhoCorasickAutomaton, y::AhoCorasickAutomaton)
return x.base == y.base && x.from == y.from && x.ikey == y.ikey && x.deep == y.deep && x.back == y.back
end
function in(key::AbstractString, obj::AhoCorasickAutomaton{T})::Bool where T
return get(obj, key, T(0)) > 0
end
function in(key::DenseVector{UInt8}, obj::AhoCorasickAutomaton{T})::Bool where T
return get(obj, key, T(0)) > 0
end
function get(obj::AhoCorasickAutomaton{T}, key::DenseVector{UInt8}, default::T)::T where T
cur::T = 1
n::T = length(obj.from)
for c in key
nxt = obj.base[cur] + c
if (nxt <= n && obj.from[nxt] == cur)
cur = nxt
else
return default
end
end
return obj.ikey[cur]
end
function get(obj::AhoCorasickAutomaton{T}, key::AbstractString, default::T)::T where T
return get(obj, codeunits(key), default)
end
function length(obj::AhoCorasickAutomaton{T}) where T
return count(!iszero, obj.ikey)
end
function collect(obj::AhoCorasickAutomaton{T}) where T
base = obj.base
from = obj.from
ikey = obj.ikey
res = Pair{String, Int}[]
for i = 1:length(ikey)
if ikey[i] == 0 continue end
codes = UInt8[]
j = i
while j > 1
c = j - base[from[j]]
push!(codes, c)
j = from[j]
end
push!(res, String(reverse!(codes)) => ikey[i])
end
return res
end
function keys(obj::AhoCorasickAutomaton{T}) where T
return map(first, collect(obj))
end
function values(obj::AhoCorasickAutomaton{T}) where T
return filter(!iszero, obj.ikey)
end
function shrink!(obj::AhoCorasickAutomaton{T})::T where T
actlen = findlast(!iszero, obj.from)
if (actlen < length(obj.from))
resize!(obj.base, actlen)
resize!(obj.from, actlen)
resize!(obj.ikey, actlen)
resize!(obj.deep, actlen)
resize!(obj.back, actlen)
resize!(obj.arcs, actlen)
end
return actlen
end
function enlarge!(obj::AhoCorasickAutomaton{T}, newlen::T)::T where T
base = obj.base; from = obj.from; deep = obj.deep; back = obj.back; ikey = obj.ikey; arcs = obj.arcs;
oldlen::T = length(obj.base)
newlen2 = oldlen
while newlen2 < newlen newlen2 *= 2 end
if (oldlen < newlen2)
resize!(base, newlen2)
resize!(from, newlen2)
resize!(ikey, newlen2)
resize!(deep, newlen2)
resize!(back, newlen2)
resize!(arcs, newlen2)
# for i = oldlen + 1:newlen2 base[i] = i end
base[oldlen + 1:newlen2] .= 0
from[oldlen + 1:newlen2] .= 0
ikey[oldlen + 1:newlen2] .= 0
deep[oldlen + 1:newlen2] .= 0
back[oldlen + 1:newlen2] .= 0
for i in oldlen + 1:newlen2
arcs[i] = UInt8[]
end
end
return newlen2
end
function addkey!(obj::AhoCorasickAutomaton{T}, code::Base.CodeUnits{UInt8,String}, icode::T)::Nothing where T
base = obj.base; from = obj.from; deep = obj.deep; back = obj.back; ikey = obj.ikey; arcs = obj.arcs;
cur::T = 1
nxt::T = 0
for c in code
nxt = base[cur] + c
enlarge!(obj, nxt)
if (from[nxt] == 0)
from[nxt] = cur
push!(arcs[cur], c)
deep[nxt] = deep[cur] + 1
cur = nxt
elseif (from[nxt] == cur)
cur = nxt
else # from[nxt] != cur
push!(arcs[cur], c)
if length(arcs[cur]) <= length(arcs[from[nxt]]) || from[nxt] == from[cur]
rebase!(obj, cur)
nxt = base[cur] + c
else
rebase!(obj, from[nxt])
end
from[nxt] = cur
deep[nxt] = deep[cur] + 1
cur = nxt
end
end
ikey[cur] = icode
return nothing
end
function rebase!(obj::AhoCorasickAutomaton{T}, cur::T)::Nothing where T
base = obj.base; from = obj.from; deep = obj.deep; back = obj.back; ikey = obj.ikey; arcs = obj.arcs;
oldbase = base[cur]
@assert length(arcs[cur]) > 0 string(cur)
newbase = findbase(obj, cur)
enlarge!(obj, newbase + maximum(arcs[cur]))
for i = eachindex(arcs[cur])
# arc = arcs[cur][i]
newson = newbase + arcs[cur][i]
from[newson] = cur
oldson = oldbase + arcs[cur][i]
if (from[oldson] != cur) continue end
base[newson] = base[oldson]
ikey[newson] = ikey[oldson]
deep[newson] = deep[oldson]
z = arcs[newson]; arcs[newson] = arcs[oldson]; arcs[oldson] = z;
# grandsons
for arc in arcs[newson]
from[base[newson] + arc] = newson
end
# oldson
base[oldson] = from[oldson] = ikey[oldson] = deep[oldson] = 0
end
base[cur] = newbase
return nothing
end
function findbase(obj::AhoCorasickAutomaton{T}, cur::T)::T where T
base = obj.base; from = obj.from; deep = obj.deep; back = obj.back; ikey = obj.ikey; arcs = obj.arcs;
n::T = length(from)
for b = max(cur + 1, base[cur]):n
ok = true
for arc in arcs[cur]
@inbounds ok &= arc + b > n || from[arc + b] == 0
end
if (ok)
return b
end
end
return T(n + 1)
end
function fillback!(obj::AhoCorasickAutomaton{T})::Nothing where T
base = obj.base; from = obj.from; deep = obj.deep; back = obj.back; ikey = obj.ikey; arcs = obj.arcs;
#println(arcs)
n::T = length(arcs)
root::T = 1
que = similar(base); head::T = 1; tail::T = 2;
que[1] = root; back[root] = root;
while head < tail
cur = que[head]; head += 1;
for arc in arcs[cur]
chd = base[cur] + arc
chdback = root
if (cur != root)
chdback = back[cur]
while chdback != root && (base[chdback] + arc > n || from[base[chdback] + arc] != chdback)
chdback = back[chdback]
end
if base[chdback] + arc <= n && from[base[chdback] + arc] == chdback
chdback = base[chdback] + arc
end
end
back[chd] = chdback
que[tail] = chd; tail += 1;
end
end
return nothing
end
function validate(obj::AhoCorasickAutomaton{T})::Nothing where T
base = obj.base; from = obj.from; deep = obj.deep; back = obj.back; ikey = obj.ikey; arcs = obj.arcs;
root = 1
que = similar(base); head = 1; tail = 2;
que[1] = root;
while head < tail
cur = que[head]; head += 1;
for arc in arcs[cur]
chd = base[cur] + arc
# @assert from[chd] == cur && back[chd] != chd && back[chd] != 0 string(chd, " fa=", cur, " from=", from[chd], " back=", back[chd])
@assert from[chd] == cur string("cur=", cur, " chd=", chd, " from=", from[chd])
que[tail] = chd; tail += 1;
end
end
return nothing
end
"""
ACMatch has 3 fields:
1. s : start of match
2. t : stop of match, [s, t), using str[s:prevind(str, t)] to get matched patterns
3. i : index of the key in *obj*, which is the original insertion order of keys to *obj*
The field *i* may be use as index of external property arrays, i.e., the AhoCorasickAutomaton
can act as a `Map{String, Any}`.
"""
struct ACMatch
s::Int
t::Int
i::Int
end
import Base.length
length(x::ACMatch) = x.t - x.s
function isless(x::ACMatch, y::ACMatch)::Bool
return x.s < y.s || x.s == y.s && x.t < y.t || x.s == y.s && x.t == y.t && x.i < y.i
end
function eachmatch(obj::AhoCorasickAutomaton{T}, text::AbstractString)::Vector{ACMatch} where T
return eachmatch(obj, codeunits(text))
end
function eachmatch(obj::AhoCorasickAutomaton{T}, codes::DenseVector{UInt8})::Vector{ACMatch} where T
base = obj.base; from = obj.from; deep = obj.deep; back = obj.back; ikey = obj.ikey; arcs = obj.arcs;
n = length(base)
root = cur = T(1)
res = ACMatch[]
for i = 1:length(codes)
c = codes[i]
while cur != root && (base[cur] + c > n || from[base[cur] + c ] != cur)
cur = back[cur]
end
if (base[cur] + c <= n && from[base[cur] + c] == cur)
cur = base[cur] + c
end
# if (ikey[cur] > 0)
node = cur
while node != root
if (ikey[node] > 0) push!(res, ACMatch(i + 1 - deep[node], i + 1, ikey[node])) end
node = back[node]
end
# end
end
return res
end
import Base.getindex
getindex(xs::String, match::ACMatch) = xs[match.s:prevind(xs, match.t)]
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 6743 |
struct CtbSentence
tree::Vector{Char}
postags::Vector{Pair{String, String}}
end
struct CtbDocument
type::String
sents::Vector{CtbSentence}
end
struct CtbTag
name::String
description::String
example::Vector{String}
end
"Chinese Treebank 8.0 of 3,007 docs, 71,369 sentences, 1,620,561 words and 2,589,848 characters (hanzi or foreign)"
struct ChTreebank
docs::Vector{CtbDocument}
end
function ChTreebank(home::String; nf=0)
home_data = joinpath(home, "data", "bracketed")
if (nf <= 0) nf = length(readdir(home_data)) end
docs = Vector{CtbDocument}(undef, nf)
@showprogress 1 "Parsing ChTreebank..." for (i, file_name) in enumerate(readdir(home_data))
if i > nf break end
type = ""
id = parse(Int, file_name[6:9])
if 0001<=id<=0325 || 0400<=id<=0454 || 0500<=id<=0540 || 0600<=id<=0885 || 0900<=id<=0931 || 4000<=id<=4050 type = "Newwire"
elseif 0590<=id<=0596 || 1001<=id<=1151 type = "Magazine articles"
elseif 2000<=id<=3145 || 4051<=id<=4111 type = "Broadcast news"
elseif 4112<=id<=4197 type = "Broadcast conversations"
elseif 4198<=id<=4411 type = "Weblogs"
elseif 5000<=id<=5558 type = "Discussion forums"
else type = "N/A"
end
trees = parsectbfile(joinpath(home_data, file_name))
sents = [CtbSentence(tree, postags(CtbTree(tree))) for tree in trees]
docs[i] = CtbDocument(type, sents)
end
return ChTreebank(docs)
end
Base.length(sent::CtbSentence) = length(sent.postags)
Base.length(doc::CtbDocument) = length(doc.sents)
Base.length(ctb::ChTreebank) = length(ctb.docs)
Base.getindex(sent::CtbSentence, inds...) = getindex(sent.postags, inds...)
Base.getindex(doc::CtbDocument, inds...) = getindex(doc.sents, inds...)
Base.getindex(ctb::ChTreebank, inds...) = getindex(ctb.docs, inds...)
Base.iterate(sent::CtbSentence, state=1) = state > length(sent) ? nothing : (sent.postags[state], state + 1)
Base.iterate(doc::CtbDocument, state=1) = state > length(doc) ? nothing : (doc.sents[state], state + 1)
Base.iterate(ctb::ChTreebank, state=1) = state > length(ctb) ? nothing : (ctb.docs[state], state + 1)
function Base.summary(ctb::ChTreebank)
ndoc = length(ctb.docs)
nsent = sum(map(doc -> length(doc.trees), ctb.docs))
nword = sum(map(doc -> sum(map(length, doc.postags)), ctb.docs))
return "CTB($(ndoc) D. $(nsent) S. $(nword) W.)"
end
mutable struct Block
chrs::Vector{Char}
nlb::Int
end
function Block()
chrs = Char[]
sizehint!(chrs, 100)
#resize!(chrs, 100)
return Block(chrs, 0)
end
function push!(b::Block, chrs::Vector{Char})
for c in chrs
if c == '('
b.nlb += 1
elseif c == ')'
b.nlb -= 1
end
push!(b.chrs, c)
end
end
function text(b::Block)
resize!(b.chrs, length(b.chrs));
return b.chrs
end
function ok(block::Block)
return block.nlb == 0
end
function parsectbfile(file_path)
ret = Vector{Char}[]
b = Block()
open(file_path, "r") do io
for line in eachline(io)
if startswith(line, "(")
push!(b, collect(line))
if !ok(b)
for line in eachline(io)
push!(b, collect(line))
if ok(b) break end
end
end
push!(ret, text(b))
b = Block()
end
end
end
return ret
end
text(tree::CtbTree) = tree.label
ispostag(tree::CtbTree) = length(tree.adj) == 1 && isleaf(tree.adj[1])
function postags(sent::CtbTree)
ret = Pair{String, String}[]
visitor(tree::CtbTree) = if ispostag(tree) && text(tree) != "-NONE-" push!(ret, text(tree)=>text(tree.adj[1])) end
dfstraverse(sent, visitor)
return ret
end
postags(doc::CtbDocument) = Iterators.flatten(doc)
function tokens(sent::CtbTree)
ret = String[]
visitor(tree::CtbTree) = if ispostag(tree) && text(tree) != "-NONE-" push!(ret, text(tree.adj[1])) end
dfstraverse(sent, visitor)
return ret
end
tokens(sent::CtbSentence) = map(last, sent)
tokens(doc::CtbDocument) = mapreduce(tokens, append!, doc)
raw(sent::CtbSentence) = mapreduce(last, *, sent) #todo speed up
raw(doc::CtbDocument) = mapreduce(raw, *, doc)
function ==(a::ChTreebank, b::ChTreebank)
return all(fname -> getfield(a, fname) == getfield(b, fname), fieldnames(ChTreebank))
end
function ==(a::CtbDocument, b::CtbDocument)
return all(fname -> getfield(a, fname) == getfield(b, fname), fieldnames(CtbDocument))
end
function ==(a::CtbSentence, b::CtbSentence)
return all(fname -> getfield(a, fname) == getfield(b, fname), fieldnames(CtbSentence))
end
function split(ctb::ChTreebank; percents::Vector{Float64}=[0.7, 0.2, 0.1])
percents ./= sum(percents)
n = length(ctb)
caps = map(p -> floor(p * n), percents)
caps[3] += n - sum(caps)
idx = randperm(n)
train = ChTreebank(ctb.tags, ctb.docs[1:caps[1]])
dev = ChTreebank(ctb.tags, ctb.docs[caps[1]+1:caps[1]+caps[2]])
test = ChTreebank(ctb.tags, ctb.docs[end-caps[3]+1:end])
return (train, dev, test)
end
import Base.+
function kfolds(docs; k::Int=10)
groups = DefaultDict{String, Vector{CtbDocument}}(()->CtbDocument[])
for doc in docs push!(groups[doc.type], doc) end
k = min(k, mapreduce(length, max, values(groups)))
@assert 2 <= k
r = [CtbDocument[] for _ in 1:k]
for (ig, group) in enumerate(values(groups))
ng = length(group)
kg = min(ng, k)
idx = randperm(ng)
from = 1
for i in 1:k
sz = div(ng, kg) + (i <= ng % kg ? 1 : 0)
to = from + sz - 1
append!(r[i], group[idx[from:to]])
from = to + 1
end
@assert from == ng + 1
end
return r
end
function postable()
tsv = readdlm(joinpath(pathof(KongYiji), "..", "..", "data", "postable.tsv"), '\t', String)
return UselessTable(tsv[2:end,:]; cnames=tsv[1,:], heads=["CTB postable"])
end | KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 1295 |
struct LinearChainConditionalRandomField{Tv <: AbstractFloat}
featurenames::Vector{String}
scores::Vector{Tv}
matrix::Matrix{Any}
end
#=
function LinearChainConditionalRandomField(fs=[
["Y-1", "Y", "W"],
["Y-1", "Y", "P"],
["Y-1", "Y", "P-1"],
["Y", "W"],
["Y", "D"],
])
fnames = ["Y-1", "Y", "P-1", "P", "P-2", "W-1", "W", "W+1", "D"]
scores = fill(0., 0)
end
=#
function display(model::LinearChainConditionalRandomField)
nr = size(model.matrix, 1)
nc = size(model.matrix, 2)
rows = Vector{Any}(undef, nr)
for i = 1:nr
rows[i] = map(x -> ismissing(x) ? "" : string(x), model.matrix[i, :])
pushfirst!(rows[i], model.featurenames[i])
end
pushfirst!(rows, Any["FN\\Score", model.scores...])
return display(Markdown.MD(Markdown.Table(rows, [:r, fill(:c, nc)...])))
end
function LinearChainConditionalRandomField(
edgeobservations::Vector{Function},
nodeobservations::Vector{Function},
observationfuncs::Vector{Function}
)
body
end
function inference(model::LinearChainConditionalRandomField)
end
function estimation(model::LinearChainConditionalRandomField)
end
function edgeobs1(tag::Vector{Int}, poswords::Matrix{String}, i::Int)
return (tag[i - 1], tag[i], poswords[i])
end
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 6559 |
struct CtbTree
label::String
adj::Vector{CtbTree}
# prob::Float64
end
isleaf(tree::CtbTree) = length(tree.adj) == 0
function dfstraverse(tree::CtbTree, visitor::Function)
for chd in tree.adj
dfstraverse(chd, visitor)
end
visitor(tree)
return nothing
end
function label(s::String) #todo special cases
t = findfirst(!isletter, s)
return (t == nothing || t == 1) ? s : s[1:t - 1]
end
function CtbTree(chars::Vector{Char}; l = findfirst(isequal('('), chars), trim = label)
nchar = length(chars)
l += 1
r = l
while chars[r] != '(' && chars[r] != ')' r += 1 end
if (chars[r] == ')')
ss = split(join(chars[l:r - 1]))
@assert length(ss) == 2
leaf = CtbTree(String(ss[2]), CtbTree[])
posn = CtbTree(trim(String(ss[1])), CtbTree[leaf])
return posn
else
@assert chars[r] == '('
ss = split(join(chars[l:r - 1]))
# @assert length(ss) == 1 string(l, " ", chars)
if length(ss) == 0
return CtbTree(chars; l = r)
end
@assert length(ss) == 1
fa = CtbTree(trim(String(ss[1])), CtbTree[])
# setlabel!(obj, cur, ss[1])
nlb = 1
while nlb > 0
if (chars[r] == '(')
if nlb == 1 l = r end
nlb += 1
elseif chars[r] == ')'
nlb -= 1
if nlb == 1
push!(fa.adj, CtbTree(chars; l = l, trim = trim))
end
end
r += 1
end
return fa
end
end
CtbTree(ct::String; trim = label) = CtbTree(collect(ct); trim = trim)
function ==(ta::CtbTree, tb::CtbTree)
ta.label == tb.label && length(ta.adj) == length(tb.adj) && all(i -> ta.adj[i] == tb.adj[i], 1:length(ta.adj))
end
function size(tree::CtbTree)
if isleaf(tree) return (1, 1)
else
h = w = 0
for chd in tree.adj
ch, cw = size(chd)
h += ch; w = max(w, cw + 1)
end
return (h, w)
end
end
function display(obj::CtbTree)
xlim, ylim = size(obj)
mat = fill("", xlim, ylim)
ileaf = 1
colors = Dict{String, Int}()
edges = Vector{Tuple{Int, Int, Int, Int}}()
function dfs(cur::CtbTree)
if !haskey(colors, cur.label)
colors[cur.label] = (1 + (length(colors) + 1) * 10) % 256
end
if isleaf(cur)
mat[ileaf, ylim] = cur.label
ileaf += 1
return (ileaf - 1, ylim)
else
cxys = Vector{Tuple{Int, Int}}()
x = xlim; y = ylim;
for chd in cur.adj
cx, cy = dfs(chd)
x = min(x, cx)
y = min(y, cy - 1)
push!(cxys, (cx, cy))
end
for cxy in cxys push!(edges, (x, y, cxy[1], cxy[2])) end
mat[x, y] = cur.label
return (x, y)
end
end
dfs(obj);
for (lx, ly, rx, ry) in edges
for x = lx + 1:rx - 1
new = old = mat[x, ly]
if old == "" new = "│" end
if old == "└" new = "├" end
mat[x, ly] = new
end
if lx < rx mat[rx, ly] = "└" end
mat[rx, ly + 1:ry - 1] .= "─";
end
yw = mapreduce(length, max, mat; dims = 1) .+ 2
for x = 1:xlim, y = 1:ylim
s = mat[x, y]; ns = length(s)
# words
if y == ylim println(" ", s); continue end
padl = div(yw[y] - ns, 2)
if (y == ylim - 1)
padl = yw[y] - ns
end
padr = yw[y] - ns - padl
padlc = padrc = '─'
if s == "" || s == "│"
padlc = padrc = ' '
elseif s == "└" || s == "├" || x == 1 && y == 1
padlc = ' '
end
ns = padlc ^ padl * s * padrc ^ padr
for i = 1:padl print(padlc) end
if haskey(colors, s) printstyled(s; color = colors[s]) else print(s) end
for i = 1:padr print(padrc) end
end
return nothing
end
# ctb = parsectb("data/ctb8.0")
# using DataFrames
# import Base.stat
# function stat(ctb::CtbTreeBank)
# from = Vector{String}(); to = Vector{Vector{String}}()
# from2 = Vector{String}(); to2 = Vector{String}()
# function visitor(tree, cur)
# nchds = length(tree.adj[cur])
# if nchds > 0
# if nchds == 1
# chd = tree.adj[cur][1]
# if length(tree.adj[chd]) == 0
# if tree.label[cur] != "-NONE-"
# push!(from2, tree.label[cur])
# push!(to2, tree.label[chd])
# end
# elseif tree.label[chd] != "-NONE-"
# push!(from, tree.label[cur])
# push!(to, tree.label[tree.adj[cur]])
# end
# else
# push!(from, tree.label[cur])
# push!(to, tree.label[tree.adj[cur]])
# end
# end
# end
# for vec in ctb
# for tree in vec
# dfstraverse(tree, visitor)
# end
# end
# function f(df::DataFrame)
# return by(df, [:from, :to], tot = :from => length, sort = true)
# end
# inn = f(DataFrame(from = from, to = to))
# pos = f(DataFrame(from = from2, to = to2))
# inn, pos
# end
# CtbTreeNode = Union{InnerTreeNode, PosTreeNode, LeafTreeNode}
# CtbTreeNode(label::String, id::String) == InnerTreeNode(label, id, Int[], 0.0)
function cnf(root::CtbTree)::CtbTree
nchd = length(root.adj)
if nchd == 0
return root
elseif nchd <= 2
newroot = CtbTree(root.label, CtbTree[])
for i = 1:nchd push!(newroot.adj, cnf(root.adj[i])) end
return newroot
else
newroot = CtbTree(root.label, CtbTree[])
newright = CtbTree(join(map(x -> x.label, root.adj[2:end]), "+"), root.adj[2:end])
push!(newroot.adj, cnf(root.adj[1]))
push!(newroot.adj, cnf(newright))
return newroot
end
end
function decnf(root::CtbTree)
nodes = decnf2(root)
return length(nodes) == 1 ? nodes[1] : CtbTree(join(map(x -> x.label, nodes), "+"), nodes)
end
function decnf2(root::CtbTree)::Vector{CtbTree}
nchd = length(root.adj)
if nchd == 0 return CtbTree[root] end
if nchd == 1
newroot = CtbTree(root.label, decnf2(root.adj[1]))
return CtbTree[newroot]
end
newroot = CtbTree(root.label, append!(decnf2(root.adj[1]), decnf2(root.adj[2])))
istmp = in('+', root.label)
return istmp ? newroot.adj : CtbTree[newroot]
end
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 8664 | const Td = Dict
const Tf = Float64
struct CykModel
nrule::Int
base2::Int
labelid::Td{String, Int}
idlabel::Vector{String}
fa2lr::Vector{Vector{Tuple{Int, Int, Tf}}}
ss2fa::Vector{Vector{Tuple{Int, Tf}}}
lr2fa::Td{Int, Vector{Tuple{Int, Tf}}}
l2far::Vector{Vector{Tuple{Int, Int, Tf}}}
end
function CykModel(ctb::ChTreebank)
labelid = Td{String, Int}()
falr = Td{Tuple{Int, Int, Int}, Tf}()
fass = Td{Tuple{Int, Int}, Tf}()
function visitor(cur::ChTree)::Nothing
nchd = length(cur.adj)
if isleaf(cur) || isposn(cur)
;
elseif nchd == 1
key = (cur.label, cur.adj[1].label)
for pos in key if !haskey(labelid, pos) labelid[pos] = length(labelid) + 1 end end
key = map(x -> labelid[x], key)
fass[key] = Base.get(fass, key, 0) + 1
else
key = (cur.label, cur.adj[1].label, cur.adj[2].label)
for pos in key if !haskey(labelid, pos) labelid[pos] = length(labelid) + 1 end end
key = map(x -> labelid[x], key)
falr[key] = Base.get(falr, key, 0) + 1
end
return nothing
end
for vt in ctb
for tree in vt
tree = cnf(tree)
dfstraverse(tree, visitor)
end
end
npos = length(labelid)
base2 = 1; while (1 << base2) <= npos base2 += 1 end;
# smoothing?
fatot = Td{Int, Tf}()
for (key, cnt) in falr
fa = key[1]
fatot[fa] = Base.get(fatot, fa, 0) + 1
end
for (key, cnt) in fass
fa = key[1]
fatot[fa] = Base.get(fatot, fa, 0) + 1
end
for (key, cnt) in falr
fa = key[1]
prob = -log(cnt / fatot[fa])
falr[key] = prob
end
for (key, cnt) in fass
fa = key[1]
prob = -log(cnt / fatot[fa])
fass[key] = prob
end
return CykModel(base2, labelid, falr, fass)
end
import Base.length
length(model::CykModel) = model.nrule
function CykModel(base2::Int, labelid::Td{String, Int}, falr::Td{Tuple{Int, Int, Int}, Tf}, fass::Td{Tuple{Int, Int}, Tf})
idlabel = Vector{String}(undef, length(labelid))
for (pos, id) in labelid idlabel[id] = pos end
lr2fa = Td{Int, Vector{Tuple{Int, Tf}}}()
for ((fa, l, r), prob) in falr
lr = (l << base2) + r
if !haskey(lr2fa, lr) lr2fa[lr] = Vector{Tuple{Int, Tf}}() end
fas = lr2fa[lr]
push!(fas, (fa, prob))
end
for ((fa, ss), prob) in fass
if !haskey(lr2fa, ss) lr2fa[ss] = Vector{Tuple{Int, Tf}}() end
fas = lr2fa[ss]
push!(fas, (fa, prob))
end
nlabel = length(labelid)
l2far = Vector{Vector{Tuple{Int, Int, Tf}}}(undef, nlabel)
for i = 1:nlabel l2far[i] = Vector{Tuple{Int, Int, Tf}}() end
for ((fa, l, r), prob) in falr
push!(l2far[l], (fa, r, prob))
end
fa2lr = Vector{Vector{Tuple{Int, Int, Tf}}}(undef, nlabel)
for i = 1:nlabel fa2lr[i] = Vector{Tuple{Int, Int, Tf}}() end
for ((fa, l, r), prob) in falr
push!(fa2lr[fa], (l, r, prob))
end
ss2fa = Vector{Vector{Tuple{Int, Tf}}}(undef, nlabel)
for i = 1:nlabel ss2fa[i] = Vector{Tuple{Int, Tf}}() end
for ((fa, ss), prob) in fass
push!(ss2fa[ss], (fa, prob))
end
return CykModel(length(falr), base2, labelid, idlabel, fa2lr, ss2fa, lr2fa, l2far)
end
import Base: read, write, ==
==(x::CykModel, y::CykModel) = length(x) == length(y) && x.idlabel == y.idlabel && x.base2 == y.base2 && x.fa2lr == y.fa2lr && x.ss2fa == y.ss2fa
function read(io::IO, ::Type{CykModel})
base2 = 0; labelid = Td{String, Int}(); lr2fa = Td{Int, Td{Int, Tf}}()
fa2lr = Td{Tuple{Int, Int, Int}, Tf}()
fa2ss = Td{Tuple{Int, Int}, Tf}()
for line in eachline(io)
cells = split(line); ncell = length(cells)
if ncell == 1 base2 = parse(Int, cells[1]) end
if ncell == 2 labelid[cells[1]] = parse(Int, cells[2]) end
if ncell == 3
fa = parse(Int, cells[1])
ss = parse(Int, cells[2])
prob = parse(Tf, cells[2])
fa2ss[(fa, ss)] = prob
end
if ncell == 4
fa = parse(Int, cells[1])
l = parse(Int, cells[2])
r = parse(Int, cells[3])
prob = parse(Tf, cells[4])
fa2lr[(fa, l, r)] = prob
end
end
return CykModel(base2, labelid, fa2lr, fa2ss)
end
function write(io::IO, obj::CykModel)
println(io, obj.base2)
for (pos, id) in obj.labelid
println(io, pos, " ", id)
end
for (falr, prob) in obj.fa2lr
fa = falr[1]; l = falr[2]; r = falr[3];
println(io, fa, " ", l, " ", r, " ", prob)
end
for (fass, prob) in obj.fa2ss
fa = fass[1]; ss = fass[2];
println(io, fa, " ", ss, " ", prob)
end
end
import Base.get
const single = Td{String, Tf}()
get(model::CykModel, l::Int, r::Int) = get(model.lr2fa, (l << model.base2) + r, single)
get(model::CykModel, ss::Int) = get(model.lr2fa, ss, single)
function cyk(poswords::Vector{Tuple{String, String}}, model::CykModel)
nrule = model.nrule
labelid = model.labelid
fa2lr = model.fa2lr
ss2fa = model.ss2fa
l2far = model.l2far
nlabel = length(labelid)
nword = length(poswords)
Tf = Float64
Td = Dict{Int, Tf}
dp = Matrix{Td}(undef, nword, nword)
Td2 = Dict{Int, Union{Tuple{Int, Int, Int}, Tuple{Int, Int}, Tuple{String}}}
nx = Matrix{Td2}(undef, nword, nword)
@inbounds begin
for len = 1:nword
@show len
for i = 1:nword - len + 1
res = Td()
res2 = Td2()
if len == 1
pos = labelid[poswords[i][1]]
res[pos] = 0.0
res2[pos] = (poswords[i][2],)
else
for k = 1:len - 1
dpl = dp[i, k]; dpr = dp[i + k, len - k]
# @show length(dpl) * length(dpr), length(model.fa2lr)
if length(dpl) * length(dpr) << 1 >= nrule
# if false
for fa = 1:nlabel
for (l, r, prob) in fa2lr[fa]
if haskey(dpl, l) && haskey(dpr, r)
old = get(res, fa, Inf)
lp = dpl[l]
rp = dpr[r]
new = lp + rp + prob
if new < old
res[fa] = new
res2[fa] = (l, r, k)
end
end
end
end
else
for (l, pl) in dpl
for (fa, r, prob) in l2far[l]
if haskey(dpr, r)
old = get(res, fa, Inf)
new = pl + dpr[r] + prob
if new < old
res[fa] = new
res2[fa] = (l, r, k)
end
end
end
end
end
end
end
while true
upd = false
for (ss, pss) in res
for (fa, prule) in ss2fa[ss]
old = get(res, fa, Inf)
new = prule + pss
if new < old res[fa] = new; res2[fa] = (ss, len); upd = true end
end
end
if !upd break end
end
dp[i, len] = res
nx[i, len] = res2
end
end
end
start = findmin(dp[1, nword])
function dfs(s, o, ilabel)::ChTree
cur = ChTree(model.idlabel[ilabel], ChTree[])
nxt = nx[s, o][ilabel]; nnxt = length(nxt)
if nnxt == 1
push!(cur.adj, ChTree(nxt[1], ChTree[]))
elseif nnxt == 2
push!(cur.adj, dfs(s, o, nxt[1]))
else
no = nxt[3]
push!(cur.adj, dfs(s, no, nxt[1]))
push!(cur.adj, dfs(s + no, o - no, nxt[2]))
end
return cur
end
return (start[1], dfs(1, nword, start[2]))
end
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 6966 |
const Tv = Float64
const Ti = UInt32
mutable struct HMM
dict::AhoCorasickAutomaton{Ti}
words::Vector{String}
user_words::Int
tags::Vector{String}
hpr::Vector{Tv}
h2h::Matrix{Tv}
h2v::Vector{Dict{Int, Tv}}
INF::Vector{Tv}
end
function HMM(corpus)
wmp, words, pmp, tags = Dict{String, Int}(), String[], Dict{String, Int}(), String[]
for doc in corpus, sent in doc, (pos, word) in sent
if !haskey(wmp, word) wmp[word] = length(wmp) + 1; push!(words, word) end
if !haskey(pmp, pos) pmp[pos] = length(pmp) + 1; push!(tags, pos) end
end
np = length(pmp)
hpr, h2h, h2v, INF = fill(Tv(0), np), fill(Tv(0), (np, np)), [DefaultDict{Int, Tv}(Tv(0)) for _ in 1:np], fill(Tv(0), np)
for doc in corpus, sent in doc
pp = 0
for (pos, word) in sent
iw, ip = wmp[word], pmp[pos]
if pp == 0 hpr[ip] += 1 else h2h[pp,ip] += 1 end
pp = ip
h2v[ip][iw] += 1
end
end
dict = AhoCorasickAutomaton{Ti}(words)
return HMM(dict, words, 0, tags, hpr, h2h, h2v, INF)
end
function Kong(;user_dict_path="", user_dict_array=[], user_dict_weight=1, EPS::Tv=1e-9)
file = joinpath(pathof(KongYiji), "..", "..", "data", "hmm.jld2")
if !isfile(file) file = unzip7(joinpath(pathof(KongYiji), "..", "..", "data", "hmm.jld2.7z")) end
@assert isfile(file)
old = load(file)["hmm"]
if !isfile(user_dict_path) && length(user_dict_array) == 0
normalize!(old; EPS=EPS)
return old
end
wmp, pmp = str2int(old.words), str2int(old.tags)
max_cnt_h2v = [maximum(values(vs)) for vs in old.h2v]
if isfile(user_dict_path)
for line in eachline(user_dict_path)
cells = split(line)
word, pos = "", ""
if length(cells) > 0 word = cells[1] end
if length(cells) > 1 pos = cells[2] end
if pos != "" && !haskey(pmp, pos) error("Postag $(pos) not defined") end
if word == "" continue end
if pos == "" pos = "NR" end #NOTE default pos NR
if !haskey(wmp, word) wmp[word] = length(wmp) + 1; push!(old.words, word); old.user_words += 1 end
iw, ip = wmp[word], pmp[pos]
old.h2v[ip][iw] = user_dict_weight * max_cnt_h2v[ip]
end
end
if length(user_dict_array) > 0
pos, word = "", ""
for cell in user_dict_array
if cell isa String
word = cell
elseif cell isa Tuple || cell isa Pair
pos, word = cell
else
error("Not supported user_dict_array cell type (String || Pair{String, String} || Tuple{String, String})")
end
if pos == "" pos = "NR" end
if !haskey(pmp, pos) error("Postag $(pos) not defined") end
if !haskey(wmp, word) wmp[word] = length(wmp) + 1; push!(old.words, word); old.user_words += 1 end
iw, ip = wmp[word], pmp[pos]
old.h2v[ip][iw] = user_dict_weight * max_cnt_h2v[ip]
end
end
old.dict = AhoCorasickAutomaton{Ti}(old.words)
normalize!(old; EPS=EPS)
return old
end
function normalize!(hmm::HMM; EPS::Tv=1e-9)
xs = hmm.hpr
xs .+= EPS;
xs .= log.(xs ./ sum(xs))
xs = hmm.h2h
xs .+= EPS;
xs .= log.(xs ./ sum(xs; dims=2))
for (ih, vs) in enumerate(hmm.h2v)
tot = sum(values(vs)) + EPS * (length(vs) + 1)
for (k, v) in vs
vs[k] = log((v + EPS) / tot) #todo race condition?
end
hmm.INF[ih] = log(EPS / tot)
end
end
function str2int(xs::Vector{String})
r = Dict{String, Int}()
for (i, w) in enumerate(xs) r[w] = i end
return r
end
function (hmm::HMM)(xs::Vector{String})
nc_max = mapreduce(ncodeunits, max, xs)
np = length(hmm.hpr)
@assert np > 0
dp = fill(Tv(-Inf), (nc_max + 1, np))
pre = fill((1, 0), (nc_max + 1, np))
return [hmm(x, dp, pre) for x in xs]
end
function (hmm::HMM)(x::String)
return hmm([x])[1]
end
function (hmm::HMM)(x::String, dp::Matrix{Tv}, pre::Matrix{Tuple{Int, Int}})
chrs = codeunits(x) #todo slow?
vtxs = collect(eachmatch(hmm.dict, chrs))
sort!(vtxs)
nv, nc, np = length(vtxs), length(chrs), length(hmm.hpr)
for i = 1:nc + 1, j in 1:np dp[i,j] = -Inf end
pv = 1
dp[1, :] = hmm.hpr
pre_i = 1
for i in 1:nc + 1
if dp[i,1] != -Inf pre_i = i end
while pv <= nv && vtxs[pv].s < i pv = pv + 1 end
if !(pv <= nv && vtxs[pv].s == i || i == nc + 1) continue end
if dp[i, 1] == -Inf
#@show i, pre_i
for pi = 1:np, pj = 1:np
maybe = dp[pre_i, pj] + hmm.INF[pj] + hmm.h2h[pj,pi]
if maybe > dp[i, pi] dp[i, pi] = maybe; pre[i, pi] = (pre_i, pj) end
end
end
while pv <= nv && vtxs[pv].s == i
vtx = vtxs[pv]
j = i + length(vtx)
for pi = 1:np
for pj = 1:np
maybe = dp[i, pi] + hmm.h2h[pi,pj] + get(hmm.h2v[pi], vtx.i, hmm.INF[pi])
if maybe > dp[j,pj] dp[j,pj] = maybe; pre[j,pj] = (i, pi) end
end
end
pv = pv + 1
end
end
#===
@show hmm
@show maximum(dp[nc + 1, :])
@show dp
@show vtxs
=###
v = (nc + 1, argmax(dp[nc + 1,:]))
ret = fill("", 0)
while v[1] != 1
pv = pre[v[1],v[2]]
push!(ret, x[pv[1]:prevind(x, v[1])])
v = pv
end
reverse!(ret)
return ret
end
function ==(a::HMM, b::HMM)
return all(fname -> getfield(a, fname) == getfield(b, fname), fieldnames(HMM))
end
#### Interfaces to ChTreebank
function (hmm::HMM)(sent::CtbSentence)
return hmm(raw(sent))
end
function (hmm::HMM)(doc::CtbDocument)
return hmm(raw(doc)) #todo split sentences???
end
function (hmm::HMM)(docs::Vector{CtbDocument})
return hmm([raw(doc) for doc in docs])
end | KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 3655 | ###### legacy codes
function splits(text::AbstractString, obj::HiddenMarkovModel; ntrial = 2, pos = true)
codes = codeunits(text)
aca = obj.aca; pos = obj.pos;
hpr = obj.hpr; h2h = obj.h2h;
alpha = obj.alpha; h2v = obj.h2v;
positions = collect(eachmatch(aca, text))
if (length(positions) == 0) return [String(text)] end
ncode = length(codes); npos = length(pos);
dp = Array{Float64, 3}(undef, ntrial, npos, ncode + 1); dp .= 1.0 / 0.0; dp[1, 1, ncode + 1] = 0.0;
nx = Array{Tuple{Int, Int, Int}, 3}(undef, ntrial, npos, ncode + 1)
j = length(positions)
charindexes = collect(eachindex(text)); push!(charindexes, ncode + 1);
k = nchar = length(charindexes) - 1
for i = ncode:-1:1
while j > 0 && i < positions[j].t j -= 1 end
while j > 0 && i == positions[j].t
iword = positions[j].i
s = positions[j].s
t = positions[j].t
for ipos = 1:npos
res = view(dp, :, ipos, s)
H2V = get(h2v[ipos], iword, alpha[ipos])
nxt = view(nx, :, ipos, s)
for ipos2 = 1:npos
for itrial2 = 1:ntrial
cur = H2V + h2h[ipos2, ipos] + dp[itrial2, ipos2, t + 1]
for itrial = 1:ntrial
if cur < res[itrial]
res[itrial + 1:end] .= res[itrial:end - 1]
nxt[itrial + 1:end] .= nxt[itrial:end - 1]
res[itrial] = cur
nxt[itrial] = (itrial2, ipos2, t)
# @show itrial, ipos, s, itrial2, ipos2, t + 1
break
end
end
end
end
end
j -= 1
end
if i == charindexes[k]
iword = 0
s = i
t = charindexes[k + 1] - 1
for ipos = 1:npos
res = view(dp, :, ipos, s)
H2V = get(h2v[ipos], iword, alpha[ipos])
nxt = view(nx, :, ipos, s)
for ipos2 = 1:npos
for itrial2 = 1:ntrial
cur = H2V + h2h[ipos2, ipos] + dp[itrial2, ipos2, t + 1]
for itrial = 1:ntrial
if cur < res[itrial]
res[itrial + 1:end] .= res[itrial:end - 1]
nxt[itrial + 1:end] .= nxt[itrial:end - 1]
res[itrial] = cur
nxt[itrial] = (itrial2, ipos2, t)
break
end
end
end
end
end
k -= 1
end
end
# dp[:, :, 1] .+= hpr
for i = 1:ntrial dp[i, :, 1] .+= hpr end
res = Vector()
dp1 = dp[:, :, 1]
for i = 1:ntrial
minind = findmin(dp1)[2]
dp1[minind] = 1.0 / 0.0
itrial = minind[1]
ipos = minind[2]
pvis = 1
segs = Vector{Tuple{String, String}}()
while pvis <= ncode
# @show nx[ipos, pvis]
nxt = nx[itrial, ipos, pvis]
itrial2 = nxt[1]
ipos2 = nxt[2]
pvis2 = nxt[3]
push!(segs, (pos[ipos], String(codes[pvis:pvis2])))
itrial = itrial2
ipos = ipos2
pvis = pvis2 + 1
end
push!(res, segs)
end
push!(res, dp[:, :, 1])
push!(res, nx[:, :, 1])
return res
end
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 8776 | ###### legacy codes
struct HiddenMarkovModel{Tv <: AbstractFloat, Ti <: Integer}
aca::AhoCorasickAutomaton{Ti}
pos::Vector{String}
hpr::Vector{Tv}
h2h::Matrix{Tv}
h2v::Vector{Dict{Int, Tv}}
MAX::Tv
sumhpr::Tv
sumh2hdim1::Matrix{Tv}
sumh2vdimv::Vector{Tv}
end
function HiddenMarkovModel{Tv, Ti}(;
model::Union{String, Nothing} = joinpath(dirname(pathof(ChineseTokenizers)), "..", "chmm"),
poswords::Union{String, Nothing} = nothing,
userdict::Union{String, Nothing} = nothing) where {Tv, Ti}
if model == nothing
@assert poswords != nothing "poswords must not be nothing."
dict = Dict{String, Int}()
if userdict != nothing
open(userdict, "r") do io
for line in eachline(io)
cells = split(line, " ")
word = String(cells[1])
if !haskey(dict, word)
dict[word] = length(dict) + 1
end
end
end
end
poss = Dict{String, Int}()
hpr = Tv[]
h2h = Dict{Int, Tv}[]
h2v = Dict{Int, Tv}[]
open(poswords, "r") do io
for line in eachline(io)
nword = parse(Int, line)
if nword <= 0 continue end
poswords = Vector{Tuple{String, String}}()
tmp = nword
for line2 in eachline(io)
cells = split(line2)
pos = String(split(cells[1], "-")[1])
word = String(cells[2])
push!(poswords, (pos, word))
tmp -= 1
if tmp == 0 break end
end
# hpr, h2h, h2v
for i = 1:nword
pos = poswords[i][1]
word = poswords[i][2]
ih = get(poss, pos, length(poss) + 1)
if ih == length(poss) + 1
poss[pos] = ih
push!(hpr, 0)
push!(h2h, Dict{Int, Tv}())
push!(h2v, Dict{Int, Tv}())
end
iw = get(dict, word, length(dict) + 1)
if iw == length(dict) + 1
dict[word] = iw
end
if i == 1 hpr[ih] += 1 end
if i > 1
ph = poss[poswords[i - 1][1]]
if !haskey(h2h[ph], ih) h2h[ph][ih] = 0 end
h2h[ph][ih] += 1
end
if !haskey(h2v[ih], iw) h2v[ih][iw] = 0 end
h2v[ih][iw] += 1
end
end
end
nword = length(dict)
aca = AhoCorasickAutomaton{Ti}(dict; sort = true)
npos = length(poss);
pos = Vector{String}(undef, npos)
for (p, i) in poss pos[i] = p end
sumhpr = norm!(hpr)
h2h2 = zeros(Tv, npos, npos)
for (ih, hs) in enumerate(h2h)
for (ih2, cnt) in hs
h2h2[ih2, ih] += cnt
end
end
sumh2hdim1 = norm!(h2h2)
sumh2vdimv = norm!(h2v)
MAX = mapreduce(x -> maximum(values(x)), max, h2v)
return HiddenMarkovModel{Tv, Ti}(aca, pos, hpr, h2h2, h2v, MAX, sumhpr, sumh2hdim1, sumh2vdimv)
else
old = open(model, "r") do io read(io, HiddenMarkovModel) end
if poswords == nothing && userdict == nothing return old end
dict = Dict(collect(old.aca))
posid = Dict{String, Int}(); for (id, pos) in enumerate(old.pos) posid[pos] = id end
hpr = denorm!(old.hpr, old.sumhpr)
h2h = denorm!(old.h2h, old.sumh2hdim1)
h2v = denorm!(old.h2v, old.sumh2vdimv)
if userdict != nothing
open(userdict, "r") do io
for line in eachline(io)
cells = split(line)
word = cells[1]
pos = length(cells) > 1 ? cells[2] : "NN"
iw = get(dict, word, length(dict) + 1)
if iw == length(dict) + 1 dict[word] = iw end
ih = get(posid, pos, 0)
@assert ih != 0 "Userdict contains an unrecognizable POS - " * pos
if !haskey(h2v[ih], iw) h2v[ih][iw] = 0 end
h2v[ih][iw] += 1
end
end
end
if poswords != nothing
open(poswords, "r") do io
for line in eachline(io)
nword = parse(Int, line)
ph = 0
for i = 1:nword
cells = split(readline(io))
pos = cells[1]
word = cells[2]
iw = get(dict, word, length(dict) + 1)
if iw == length(dict) + 1 dict[word] = iw end
ih = get(posid, pos, 0)
@assert ih != 0 "Poswords contains an unrecognizable POS - " * pos
if !haskey(h2v[ih], iw) h2v[ih][iw] = 0 end
h2v[ih][iw] += 1
if i == 1 hpr[ih] += 1 end
if i > 1 h2h[ih, ph] += 1 end
ph = ih
end
end
end
end
nword = length(dict)
aca = AhoCorasickAutomaton{Ti}(dict; sort = true)
pos = Vector{String}(undef, length(posid)); for (p, id) in posid pos[id] = p end
sumhpr = norm!(hpr)
sumh2hdim1 = norm!(h2h)
sumh2vdimv = norm!(h2v)
MAX = mapreduce(x -> maximum(values(x)), max, h2v)
return HiddenMarkovModel{Tv, Ti}(aca, pos, hpr, h2h, h2v, MAX, sumhpr, sumh2hdim1, sumh2vdimv)
end
end
HiddenMarkovModel() = HiddenMarkovModel{Float32, Int32}(;)
function display(obj::HiddenMarkovModel{Tv, Ti}) where Tv where Ti
title = string(typeof(obj), " ", (nword = length(obj.aca), npos = length(obj.pos), nbyte = Base.format_bytes(Base.summarysize(obj))))
println(title)
rows = Any[["POS", "nhead", "tot", "unique", "examples"]]
description = stat(obj)
for i = 1:length(obj.pos)
r = description[i]
push!(rows, [r.pos, r.nhead, r.tot, length(r.vs), r.pos == "URL" ? "Omitted." : string(r.vs[1:min(5, end)])])
end
return display(Markdown.MD(Markdown.Table(rows, Symbol[:l, :r, :r, :r, :l])))
end
function split(text::AbstractString, obj::HiddenMarkovModel{Tv, Ti}) where {Tv, Ti}
codes = codeunits(text)
nc = length(codes)
aca = obj.aca; pos = obj.pos;
hpr = obj.hpr; h2h = obj.h2h;
INF = obj.MAX * nc; h2v = obj.h2v;
matches = collect(eachmatch(aca, text))
sort!(matches)
nm = length(matches)
nh = length(pos)
dp = fill(Tv(Inf), nh, nc)
bk = fill((0, 0), nh, nc)
cover = fill(false, nc)
for m in matches cover[m.s:m.t] .= true end
pm = 1
sc = 1
while sc <= nc
if !cover[sc]
tc = sc + 1
while tc <= nc && !cover[tc] tc += 1 end
tc -= 1
for sh in 1:nh
for th in 1:nh
cur = (sc == 1 ? hpr[sh] : dp[sh, sc - 1]) + h2h[th, sh] + get(h2v[th], 0, INF)
if cur < dp[th, tc]
dp[th, tc] = cur
bk[th, tc] = (-sh, sc - 1)
end
end
end
sc = tc + 1
else
while pm <= nm && matches[pm].s < sc pm += 1 end
while pm <= nm && matches[pm].s == sc
m = matches[pm]
tc = m.t
iw = m.i
for sh in 1:nh
for th in 1:nh
cur = (sc == 1 ? hpr[sh] : dp[sh, sc - 1]) + h2h[th, sh] + get(h2v[th], iw, INF)
if cur < dp[th, tc]
dp[th, tc] = cur
bk[th, tc] = (sh, sc - 1)
end
end
end
pm += 1
end
sc += 1
end
end
poss = String[]
word = String[]
th = findmin(dp[:, nc])[2]
tc = nc
while 1 <= tc
sh = bk[th, tc][1]
sc = bk[th, tc][2]
if sh < 1
sh = -sh
push!(poss, pos[th] * "?")
push!(word, String(codes[sc + 1:tc]))
else
push!(poss, pos[th])
push!(word, String(codes[sc + 1:tc]))
end
th = sh
tc = sc
end
reverse!(poss)
reverse!(word)
# return (res = segs, dp = dp, segs = map(x -> String(codes[x.s:x.t]), matches))
return hcat(poss, word)
end
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 4218 |
function (hmm::HMM)(input::String, dlm::String)
standard = split(input, dlm)
x = join(standard)
return hmm(x, standard)
end
function (hmm::HMM)(x::String, standard::Vector)
chrs = codeunits(x)
vtxs = collect(eachmatch(hmm.dict, chrs))
sort!(vtxs)
nv, nc, np = length(vtxs), length(chrs), length(hmm.hpr)
dp = fill(-Inf, (nc + 1, np))
pre = fill((1, 0), (nc + 1, np))
for i = 1:nc + 1, j in 1:np dp[i,j] = -Inf end
pv = 1
dp[1, :] = hmm.hpr
pre_i = 1
for i in 1:nc + 1
if dp[i,1] != -Inf pre_i = i end
while pv <= nv && vtxs[pv].s < i pv = pv + 1 end
if !(pv <= nv && vtxs[pv].s == i || i == nc + 1) continue end
if dp[i, 1] == -Inf
#@show i, pre_i
for pi = 1:np, pj = 1:np
maybe = dp[pre_i, pj] + hmm.INF[pj] + hmm.h2h[pj,pi]
if maybe > dp[i, pi] dp[i, pi] = maybe; pre[i, pi] = (pre_i, pj) end
end
end
while pv <= nv && vtxs[pv].s == i
vtx = vtxs[pv]
j = i + length(vtx)
for pi = 1:np
for pj = 1:np
maybe = dp[i, pi] + hmm.h2h[pi,pj] + get(hmm.h2v[pi], vtx.i, hmm.INF[pi])
if maybe > dp[j,pj] dp[j,pj] = maybe; pre[j,pj] = (i, pi) end
end
end
pv = pv + 1
end
end
v = (nc + 1, argmax(dp[nc + 1,:]))
output = fill("", 0)
while v[1] != 1
pv = pre[v[1],v[2]]
push!(output, x[pv[1]:prevind(x, v[1])])
v = pv
end
reverse!(output)
#print debug infos
println("Standard : " * join(standard, " "))
println("Output : " * join(output, " "))
v = (nc + 1, argmax(dp[nc + 1,:]))
info = Matrix{Any}(undef, (length(x), 5))
nr = 1
while v[1] != 1
pv = pre[v[1],v[2]]
word, postag, source, prob_h2v, prob_add = "", "", "", 0., 0.
s, t = pv[1], v[1]
word = x[s:prevind(x, t)]
postag_id = pv[2]
postag = hmm.tags[postag_id]
word_id = 0
begin
vtx_id = searchsortedfirst(vtxs, ACMatch(s, t, -1))
if vtx_id < nv + 1 && vtxs[vtx_id].s == s && vtxs[vtx_id].t == t
word_id = vtxs[vtx_id].i
end
if word_id == 0 source = "algorithm"
else source = ifelse(word_id > length(hmm.words) - hmm.user_words, "usr.dict", "CTB")
end
end
prob_h2v = word_id == 0 ? hmm.INF[postag_id] : hmm.h2v[postag_id][word_id]
prob_add = dp[v[1],v[2]] - dp[pv[1],pv[2]]
prob_h2v, prob_add = map(x->trunc(exp(x); digits=6), [prob_h2v, prob_add])
info[nr,:] = [word, postag, source, prob_h2v, prob_add]
nr += 1
v = pv
end
nr -= 1
println(UselessTable(reverse(info[1:nr,:]; dims=1); cnames=["word", "pos.tag", "source", "prob.h2v", "Prob.Add."],
heads=["KongYiji(1) Debug Table",],
foots=["neg.log.likelihood = $(-maximum(dp[nc + 1,:]))"]
)
)
match_mat = Matrix{Any}(undef, (nv, 3))
match_mat[:,1] = [(v.s,v.t) for v in vtxs]
match_mat[:,2] = [x[v] for v in vtxs]
match_mat[:,3] = [(v.i > length(hmm.words) - hmm.user_words ? "user.dict" : "CTB") for v in vtxs]
println(UselessTable(match_mat; cnames=["UInt8.range", "word", "source"], heads=["AhoCorasickAutomaton Matched Words"]))
end | KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 4668 |
struct HmmScoreTable
c_cmat::Matrix{Int} #char level confusion matrix
c_f1::Vector{Float64} #char level f1 score
c_p::Vector{Float64} #char level precision
c_r::Vector{Float64} #char level recall
w_f1::Float64 #word level f1 score
w_p::Float64 #word level precision
w_r::Float64 #word level recall
n::Int #how many tables combined
end
HmmScoreTable(xs::Vector{Vector{String}}, ys::Vector{Vector{String}}) = mapreduce(p->HmmScoreTable(p...), +, zip(xs, ys))
"""
x : Standard output
y : KongYiji output
"""
function HmmScoreTable(x::Vector{String}, y::Vector{String})
#### char level
# confusion matrix
c_cmat, c_f1, c_p, c_r = fill(0, (4, 4)), fill(0., 4), fill(0., 4), fill(0., 4)
idx = Dict(:B=>1, :M=>2, :E=>3, :S=>4)
nchr = mapreduce(length, +, x)
xa = fill(:M, nchr)
p = 1
for w in x
nw = length(w)
xa[p] = :B
xa[p + nw - 1] = :E
if nw == 1 xa[p] = :S end
p += nw
end
ya = fill(:M, nchr)
p = 1
for w in y
nw = length(w)
ya[p] = :B
ya[p + nw - 1] = :E
if nw == 1 ya[p] = :S end
p += nw
end
for i = 1:nchr c_cmat[idx[ya[i]],idx[xa[i]]] += 1 end
# precision, recall, f1-score
c_f1, c_p, c_r = fill(0., 4), fill(0., 4), fill(0., 4)
for i = 1:4
num, den = c_cmat[i,i], sum(c_cmat[i,:])
c_p[i] = num == den ? 1. : (0. + num) / den
num, den = c_cmat[i,i], sum(c_cmat[:,i])
c_r[i] = num == den ? 1. : (0. + num) / den
c_f1[i] = f1(c_p[i], c_r[i])
end
##### word level
ix, iy, px, py, nx, ny, r = 1, 1, 1, 1, length(x), length(y), 0.
while ix <= nx && iy <= ny
if px == py
if x[ix] == y[iy] r += 1 end
nxi, nyi = length(x[ix]), length(y[iy])
if nxi == nyi px += nxi; py += nyi; ix += 1; iy += 1
elseif nxi < nyi px += nxi; ix += 1
else py += nyi; iy += 1
end
elseif px < py
while px < py && ix <= nx px += length(x[ix]); ix += 1 end
else
while py < px && iy <= ny py += length(y[iy]); iy += 1 end
end
end
w_p = r / length(y)
w_r = r / length(x)
w_f1 = f1(w_p, w_r)
return HmmScoreTable(c_cmat, c_f1, c_p, c_r, w_f1, w_p, w_r, 1)
end
+(a::HmmScoreTable, b::HmmScoreTable) = HmmScoreTable(map(x->getfield(a, x) + getfield(b, x), fieldnames(HmmScoreTable))...)
function show(io::IO, tb::HmmScoreTable)
n = size(tb.c_cmat, 1)
fm(d) = string(trunc(d * 100, sigdigits=3), "%")
fm1(d) = trunc(d, sigdigits=5)
char_f1, char_p, char_r = map(x->x / tb.n, [tb.c_f1, tb.c_p, tb.c_r])
word_f1, word_p, word_r = map(x->x / tb.n, [tb.w_f1, tb.w_p, tb.w_r])
mat = Array{Any}(missing, (n + 4, n + 1))
mat[1:n,1:n] .= tb.c_cmat
mat[n + 1,1:n] .= sum(tb.c_cmat, dims=1)[1,:]
mat[1:n,n + 1] .= sum(tb.c_cmat, dims=2)[:,1]
mat[n + 1,n + 1] = sum(tb.c_cmat)
mat[n + 2,1:n] .= fm.(char_p); mat[n + 2,n + 1] = ""
mat[n + 3,1:n] .= fm.(char_r); mat[n + 3,n + 1] = ""
mat[n + 4,1:n] .= fm1.(char_f1); mat[n + 4,n + 1] = ""
char_avg_f1, char_avg_p, char_avg_r = map(x->sum(x)/length(x), [char_f1, char_p, char_r])
utb = UselessTable(mat; cnames=(:B, :M, :E, :S, ""),
rnames=(:B, :M, :E, :S, "", :Precision, :Recall, :F1),
topleft="O\\S",
foots=["Char level avg.F1: $(fm1(char_avg_f1)), avg.precison: $(fm(char_avg_p)), avg.recall: $(fm(char_avg_r))",
"Word level F1: $(fm1(word_f1)), precison: $(fm(word_p)), recall: $(fm(word_r))",
],
heads=["KongYiji(1) HMM Score Table $(tb.n) combined"],
)
show(io, utb)
end
f1(x, y) = 2 / (1. / x + 1. / y)
############ Interfaces to ChTreebank
HmmScoreTable(xs::Vector{CtbDocument}, ys::Vector{Vector{String}}) = HmmScoreTable(map(tokens, xs), ys)
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 490 | module KongYiji
import Base: size, split, display, read, write, first, stat, push!, length, iterate, ==, getindex, summary, collect, values, isless, get, eachmatch
using Pkg
using JLD2, FileIO
using Random, DataStructures, ProgressMeter, DelimitedFiles
export Kong, postable
include("UselessTable.jl")
include("zip7.jl")
include("AhoCorasickAutomaton.jl")
include("CtbTree.jl")
include("ChTreebank.jl")
include("HMM.jl")
include("HmmScoreTable.jl")
include("HmmDebug.jl")
end # module
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 1709 | abstract type AbstractChineseTokenizer end
struct OneGramTokenizer <: AbstractChineseTokenizer
aca::AhoCorasickAutomaton{UInt32}
nlf::Vector{Float64}
INF::Float64
end
function OneGramTokenizer(words::Vector{String}, freqs::Vector{Int})
aca = AhoCorasickAutomaton{UInt32}(words)
nlf = -log.(freqs ./ Float64(sum(freqs)))
INF = maximum(nlf)
return OneGramTokenizer(aca, nlf, INF)
end
function OneGramTokenizer(;filepath::String = joinpath(Pkg.dir("ChineseTokenizers"), "data", "dict"))
words = String[]
freqs = Int[]
open(filepath, "r") do io
for line in eachline(io)
cells = split(line, " ")
push!(words, String(cells[1]))
push!(freqs, parse(Int, cells[2]))
end
end
return OneGramTokenizer(words, freqs)
end
function split(text::AbstractString, tokenizer::OneGramTokenizer)::Vector{String}
codes = codeunits(text)
res = String[]
aca = tokenizer.aca; nlf = tokenizer.nlf; INF = tokenizer.INF
positions = reverse!(eachmatch(aca, text))
@show sort(positions)
if (length(positions) == 0) return [String(text)] end
n = length(codes)
dp = fill(INF, n + 1); dp = cumsum(dp); reverse!(dp)
to = collect(1:n)
for pos in positions
if dp[pos.t + 1] + nlf[pos.i] < dp[pos.s]
dp[pos.s] = dp[pos.t + 1] + nlf[pos.i]
to[pos.s] = pos.t
end
end
println("dp: ", dp)
println("to: ", to)
s = 1
while s <= n
t = to[s]
if t == s
t += 1
while t <= n && t == to[t] t += 1 end
t -= 1
end
push!(res, String(codes[s:t]))
s = t + 1
end
return res
end
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 3933 |
struct UselessTable
mat::Matrix{Any}
heads::Vector{Any}
foots::Vector{Any}
useful::Any
end
import Base.show
function show(io::IO, tb::UselessTable)
compact = get(io, :compact, false)
dsize = get(io, :displaysize, displaysize())
limit = get(io, :limit, true)
offset = " "
nrow, ncol = size(tb.mat, 1), size(tb.mat, 2)
mat = fill("", (nrow, ncol))
for i in 1:nrow, j in 1:ncol
if ismissing(tb.mat[i,j]) mat[i,j] = "N/A"
elseif isnothing(tb.mat[i,j]) mat[i,j] = ""
else mat[i,j] = string(tb.mat[i,j])
end
#todo compact
end
colwidth = [maximum(map(textwidth, mat[:,i])) for i in 1:ncol] .+ 1
for i in 1:nrow, j in 1:ncol
pad = ifelse(j == 1, rpad, lpad)
val = mat[i,j]
val = pad(val, colwidth[j] - textwidth(val) + length(val))
if j == 1 val = offset * val end
mat[i,j] = val
end
function middle(s::String, width::Int)
r = offset * s
n = textwidth(r)
if n < width r = " " ^ div((width - n), 2) * r end
return r
end
function right(s::String, width::Int)
r = offset * s
n = textwidth(r)
if n < width r = " " ^ (width - n) * r end
return r
end
totw = sum(colwidth)
for i in 1:nrow
#print headers
if i == 1 && length(tb.heads) > 0
for head in tb.heads
println(io, middle(string(head), totw))
end
println(io, middle("-" ^ totw, totw))
end
for j in 1:ncol
print(io, mat[i,j])
end
println(io)
#print foots
if i == nrow && length(tb.foots) > 0
println(io, middle("=" ^ totw, totw))
for foot in tb.foots
println(io, right(string(foot), totw))
end
end
end
end
function UselessTable(mat::Matrix{Tv}; rnames=nothing, cnames=nothing, topleft=nothing, heads=[], foots=[], useful=nothing) where {Tv}
ncol = size(mat, 2); nrow = size(mat, 1)
if isnothing(cnames) cnames = 1:ncol end
if isnothing(rnames) rnames = 1:nrow end
ncol += 1; nrow += 1
mat2 = Matrix{Any}(missing, (nrow, ncol))
mat2[1,1] = topleft
mat2[1,2:end] .= cnames
mat2[2:end,1] .= rnames
for i in 2:nrow, j in 2:ncol
mat2[i,j] = mat[i-1,j-1]
end
return UselessTable(mat2, heads, foots, useful)
end
==(a::UselessTable, b::UselessTable) = a.mat == b.mat
#=
function UselessTable(dict::Dict{Tcname,Dict{Trname, Tv}}; topleft="") where {Tcname, Trname, Tv}
cnames = Dict{Tcname, Int}(map(reverse, enumerate(keys(dict))))
rnames = Dict{Trname, Int}()
for col in values(dict), (rname, cell) in col
if !haskey(rnames, rname) rnames[rname] = length(rnames) + 1 end
end
rnames2 = sort(collect(keys(rnames)), by=x->rnames[x])
cnames2 = sort(collect(keys(cnames)), by=x->cnames[x])
ncol = length(cnames) + 1
nrow = length(rnames) + 1
mat = Matrix{Any}(missing, (nrow, ncol))
mat[1,1] = topleft
mat[1,2:end] .= cnames2
mat[2:end,1] .= rnames2
for (cname, col) in dict, (rname, cell) in col
mat[rnames[rname]+1,cnames[cname]+1] = cell
end
return UselessTable(mat, dict)
end
=#
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 4192 |
###### legacy codes
function simplify(c::Char)
return c
end
function ==(a::HiddenMarkovModel{Tv, Ti}, b::HiddenMarkovModel{Tv, Ti}) where {Tv, Ti}
res = true
for fname in fieldnames(HiddenMarkovModel{Tv, Ti})
res &= getfield(a, fname) == getfield(b, fname)
end
return res
end
function write(io::IO, obj::HiddenMarkovModel{Tv, Ti}) where {Tv, Ti}
nbit = 0
nbit += write(io, sizeof(Tv))
if Ti isa Unsigned
nbit += write(io, +1)
else
nbit += write(io, -1)
end
nbit += write(io, sizeof(Ti))
nbit += write(io, obj.aca)
for p in obj.pos
nbit += write(io, p, " ")
end
nbit += write(io, "\n")
nbit += write(io, obj.hpr)
nbit += write(io, obj.h2h)
for vp in obj.h2v
nbit += write(io, length(vp))
for (v, p) in vp
nbit += write(io, v)
nbit += write(io, p)
end
end
nbit += write(io, obj.MAX)
nbit += write(io, obj.sumhpr)
nbit += write(io, obj.sumh2hdim1)
nbit += write(io, obj.sumh2vdimv)
return nbit
end
function nbit2type(nbit, types)
filter(x -> sizeof(x) == nbit, types)[1]
end
function read(io::IO, obj::Type{HiddenMarkovModel})
Tv = nbit2type(read(io, Int), [Float32, Float64])
sign = read(io, Int)
Ti = Int
if sign > 0
Ti = nbit2type(read(io, Int), [UInt8, UInt16, UInt32, UInt64])
else
Ti = nbit2type(read(io, Int), [Int8, Int16, Int32, Int64])
end
aca = read(io, AhoCorasickAutomaton)
pos = split(readline(io))
npos = length(pos)
hpr = reinterpret(Tv, read(io, npos * sizeof(Tv)))
h2h = reshape(reinterpret(Tv, read(io, npos * npos * sizeof(Tv))), (npos, npos))
h2v = Vector{Dict{Int, Tv}}(undef, npos)
for i = 1:npos
vps = Dict{Int, Tv}()
nv = read(io, Int)
for j = 1:nv
v = read(io, Int)
p = read(io, Tv)
vps[v] = p
end
h2v[i] = vps
end
MAX = read(io, Tv)
sumhpr = read(io, Tv)
sumh2hdim1 = reshape(reinterpret(Tv, read(io, npos * sizeof(Tv))), 1, npos)
sumh2vdimv = reinterpret(Tv, read(io, npos * sizeof(Tv)))
return HiddenMarkovModel{Tv, Ti}(aca, pos, hpr, h2h, h2v, MAX, sumhpr, sumh2hdim1, sumh2vdimv)
end
function h2v(obj::HiddenMarkovModel{Tv, Ti}, h::String, v::String) where Tv where Ti
ih = findfirst(isequal(h), obj.pos)
iv = get(obj.aca, v, Ti(0))
return get(obj.h2v[ih], iv, obj.alpha[ih])
end
function h2h(obj::HiddenMarkovModel{Tv, Ti}, pos1::String, pos2::String) where Tv where Ti
i1 = findfirst(isequal(pos1), obj.pos)
i2 = findfirst(isequal(pos2), obj.pos)
return obj.h2h[i2, i1]
end
function norm!(hpr::Vector{Tv}) where Tv
tot = sum(hpr)
@assert !isinf(tot)
hpr .= -log.(hpr ./ tot)
return tot
end
function norm!(h2h::Matrix{Tv}) where Tv
sum1 = sum(h2h; dims = 1)
h2h .= -log.(h2h ./ sum1)
return sum1
end
function norm!(h2v::Vector{Dict{Int, Tv}}) where Tv
sumv = Vector{Tv}(undef, length(h2v))
for (ih, vs) in enumerate(h2v)
tot = sum(values(vs))
sumv[ih] = tot
for v in keys(vs)
vs[v] = -log(vs[v]) + log(tot)
end
end
return sumv
end
function denorm!(hpr::Vector{Tv}, sumhpr::Tv) where Tv
return hpr .= exp.(.-hpr) .* sumhpr
end
function denorm!(h2h::Matrix{Tv}, sumh2hdim1::Matrix{Tv}) where Tv
return h2h .= exp.(.-h2h) .* sumh2hdim1
end
function denorm!(h2v::Vector{Dict{Int, Tv}}, sumh2vdimv::Vector{Tv}) where Tv
for (h, vs) in enumerate(h2v)
for (v, p) in vs
vs[v] = exp(-p) * sumh2vdimv[h]
end
end
return h2v
end
function stat(obj::HiddenMarkovModel{Tv, Ti}) where {Tv, Ti}
res = Vector()
dict = map(first, sort!(collect(obj.aca); by = last))
hpr = copy(obj.hpr)
denorm!(hpr, obj.sumhpr)
for i = 1:length(obj.pos)
pos = obj.pos[i]
nhead = round(Int, hpr[i])
tot = round(Int, obj.sumh2vdimv[i])
vs = sort!(collect(obj.h2v[i]); by = last, rev = true)
vs = map(x -> dict[x[1]], vs)
push!(res, (pos = pos, nhead = nhead, tot = tot, vs = vs))
end
return res
end
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 860 |
function zip7(file)
to = dirname(file)
dest = joinpath(to, string(basename(file), ".7z"))
try
cmd = "7z a -y -t7z -- $(dest) $(file)"
run(pipeline(ifelse(Sys.iswindows(), `cmd /c $cmd`, `sh -c $cmd`); stdout=joinpath(to, "7zip.log")))
catch e
rm(dest; force=true)
throw(e)
end
return dest
end
function unzip7(file)
to = dirname(file)
source = joinpath(dirname(file), basename(file)[1:end-3])
try
cmd = "7z e -y -o$(to) $(file)"
run(pipeline(ifelse(Sys.iswindows(), `cmd /c $cmd`, `sh -c $cmd`); stdout=joinpath(to, "7zip.log")))
catch e
rm(source; force=true)
throw(e)
end
return source
end
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | code | 4053 | using Test, KongYiji, Pkg, JLD2, FileIO, ProgressMeter
#=
@testset "Generating REQUIRE file..." begin
println(Pkg.METADATA_compatible_uuid("KongYiji"))
PT = Pkg.Types
Pkg.activate("..") # current directory as the project
ctx = PT.Context()
pkg = ctx.env.pkg
if pkg ≡ nothing
@error "Not in a package, I won't generate REQUIRE."
exit(1)
else
@info "found package" pkg = pkg
end
deps = PT.get_deps(ctx)
non_std_deps = sort(collect(setdiff(keys(deps), values(ctx.stdlibs))))
open(joinpath("..", "REQUIRE"), "w") do io
println(io, "julia 0.7")
for d in non_std_deps
println(io, d)
@info "listing $d"
end
end
end
=#
#=
@testset "Generating CTB data file..." begin
home = joinpath("d:\\", "ctb8.0")
@time ctb = KongYiji.ChTreebank(home; nf=0)
ctb_path = joinpath(pathof(KongYiji), "..", "..", "data")
ctb_name = joinpath(ctb_path, "ctb.jld2")
mkpath(ctb_path)
@time @save ctb_name ctb
@time zipped_name = KongYiji.zip7(ctb_name)
rm(ctb_name)
@time unzipped_name = KongYiji.unzip7(zipped_name)
@time ctb2 = load(unzipped_name)["ctb"]
@time @test ctb == ctb2
end
=#
@testset "Test CTB postable..." begin
println(postable())
end
#=
@testset "Cross validating HMM on CTB..." begin
@time unzipped_file = KongYiji.unzip7(joinpath(pathof(KongYiji), "..", "..", "data", "ctb.jld2.7z"))
@time ctb = load(unzipped_file)["ctb"]
@show length(ctb)
folds = KongYiji.kfolds(ctb; k=10)
k = length(folds)
tbs = Vector{KongYiji.HmmScoreTable}(undef, k)
@showprogress 1 "Cross Validating HMM..." for i in 1:k
test = folds[i]
train = collect(Iterators.flatten([folds[j] for j in 1:k if j != i]))
hmm = KongYiji.HMM(train)
KongYiji.normalize!(hmm) # Don't forget
x = test
y = hmm(x)
tbs[i] = KongYiji.HmmScoreTable(x, y)
# println(tbs[i])
end
hmmscoretable = sum(tbs)
println(hmmscoretable)
end
=#
#=
@testset "Generating HMM model file of CTB..." begin
@time ctb_home = KongYiji.unzip7(joinpath(pathof(KongYiji), "..", "..", "data", "ctb.jld2.7z"))
@time ctb = load(ctb_home)["ctb"]
@time hmm = KongYiji.HMM(ctb)
home = joinpath(pathof(KongYiji), "..", "..", "data", "hmm.jld2")
mkpath(dirname(home))
@time @save home hmm
@time zhome = KongYiji.zip7(home)
rm(home)
@time home2 = KongYiji.unzip7(zhome)
@assert home == home2
@time hmm2 = load(home2)["hmm"]
@test hmm == hmm2
end
=#
@testset "Test KongYiji(1) with Hand written examples..." begin
tk = Kong()
input = "一个脱离了低级趣味的人"
output = tk(input)
@show output
input = "一/个/脱离/了/低级/趣味/的/人"
tk(input, "/")
inputs = [
"他/说/的/确实/在理",
"这/事/的确/定/不/下来",
"费孝通/向/人大/常委会/提交/书面/报告",
"邓颖超/生前/使用/过/的/物品",
"停电/范围/包括/沙坪坝区/的/犀牛屙屎/和/犀牛屙屎抽水",
]
println("Input :")
for input in inputs
println(input)
end
println("raw output :")
for input in inputs
println(tk(filter(c -> c != '/', input)))
end
tk2 = Kong(; user_dict_array=[("VV", "定"),
("VA", "在理"),
"邓颖超",
"沙坪坝区",
"犀牛屙屎",
"犀牛屙屎抽水",
]
)
println("output with user dict supplied :")
for input in inputs
println(tk2(filter(c -> c != '/', input)))
end
end
| KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.1.0 | 09d9c045d14d223a31b94e9c39a0564a9c41b47f | docs | 7339 | # KongYiji.jl
断文识字的“孔乙己” -- 一个简单的中文分词工具
Kong Yiji, a simple fine tuned Chinese tokenizer
## Features
### Version 0.1.0
1. Trained on Chinese Treebank 8.0. Of version 1 now, using a extended word-level Hidden Markov Model(HMM) contrast by eariler char-level HMM.
2. Fine tuned to deal with **new words**(未登录词, 网络新词). If the algorithm cannot find them, just add them to user dict(see **Constructor**), and twist **usr_dict_weight** if necessary.
3. Fully exported debug info. See Usage.
## Constructor
```julia
kong(; user_dict_path="", user_dict_array=[], user_dict_weight=1)
```
+ **user_dict_path** : a file path of user dict, eachline of which begin a **word**, optionally followed by a **part-of-speech tag(postag)**;
If the postag not supplied, **NR (Proper noun, 专有名词)** is automatically inserted.
+ **user_dict_array** : a Vector{Tuple{String, String}} repr. [(postag, word)]
+ **user_dict_weight** : if value is **m**, frequency of (postag, word) in user dictionary will be $ m * maximum(values(h2v[postag])) $
***Note all user suppiled postags MUST conform to specifications of Chinest Treebank.***
```
CTB postable
-------------------------------------------------------------------------------------
part.of.speech summary
1 NR 专属名词
2 NT 时间
3 NN 其他名词
4 PN 代词
5 VA 形容词动词化
6 VC be、not be 对应的中文
7 VE have、not have 对应的中文
8 VV 其他动词
9 P 介词
10 LC 方位词
11 AD 副词
12 DT 谁的,哪一个
13 CD (数)量词
14 OD (顺)序词
15 M (数)量词
16 CC 连(接)词
17 CS 连(接)词
18 DEC 的
19 DEG 的
20 DER 得
21 DEV 地
22 AS Aspect Particle 表达英语中的进行式、完成式的词,比如(着,了,过)
23 SP 句子结尾词(了,吧,呢,啊,呀,吗)
24 ETC 等(等)
25 MSP 其他
26 IJ 句首感叹词
27 ON 象声词
28 LB 被
29 SB 被
30 BA 把
31 JJ 名词修饰词
32 PU 标点符号
33 FW POS不清楚的词(不是外语词)
```
## Usage
``` Julia
println("Simple Usage")
tk = Kong()
input = "一个脱离了低级趣味的人"
output = tk(input)
@show output
println()
println("Debug Output")
input = "一/个/脱离/了/低级/趣味/的/人"
tk(input, "/")
println()
println("Test some difficult cases, from https://www.matrix67.com/blog/archives/4212")
inputs = [
"他/说/的/确实/在理",
"这/事/的确/定/不/下来",
"费孝通/向/人大/常委会/提交/书面/报告",
"邓颖超/生前/使用/过/的/物品",
"停电/范围/包括/沙坪坝区/的/犀牛屙屎/和/犀牛屙屎抽水",
]
println("Input :")
for input in inputs
println(input)
end
println("Raw output :")
for input in inputs
println(tk(filter(c -> c != '/', input)))
end
tk2 = Kong(; user_dict_array=[("VV", "定"),
("VA", "在理"),
"邓颖超",
"沙坪坝区",
"犀牛屙屎",
"犀牛屙屎抽水",
]
)
println("Output with user dict supplied :")
for input in inputs
println(tk2(filter(c -> c != '/', input)))
end
```
## Output
```
Simple Usage
output = ["一", "个", "脱离", "了", "低级", "趣味", "的", "人"]
Debug Output
Standard : 一 个 脱离 了 低级 趣味 的 人
Output : 一 个 脱离 了 低级 趣味 的 人
KongYiji(1) Debug Table
-----------------------------------------
word pos.tag source prob.h2v Prob.Add.
1 一 CD CTB 0.323977 0.203435
2 个 M CTB 0.260022 0.019667
3 脱离 VV CTB 0.000177 1.1e-5
4 了 AS CTB 0.808087 0.045661
5 低级 JJ CTB 0.000462 0.000352
6 趣味 NN CTB 4.2e-5 2.0e-6
7 的 DEG CTB 0.972857 0.744126
8 人 NN CTB 0.01615 0.004388
=========================================
neg.log.likelihood = 50.088239033558935
AhoCorasickAutomaton Matched Words
---------------------------
UInt8.range word source
1 (1, 4) 一 CTB
2 (4, 7) 个 CTB
3 (7, 10) 脱 CTB
4 (7, 13) 脱离 CTB
5 (10, 13) 离 CTB
6 (13, 16) 了 CTB
7 (16, 19) 低 CTB
8 (16, 22) 低级 CTB
9 (19, 22) 级 CTB
10 (22, 25) 趣 CTB
11 (22, 28) 趣味 CTB
12 (25, 28) 味 CTB
13 (28, 31) 的 CTB
14 (31, 34) 人 CTB
Test some difficult cases, from https://www.matrix67.com/blog/archives/4212
Input :
他/说/的/确实/在理
这/事/的确/定/不/下来
费孝通/向/人大/常委会/提交/书面/报告
邓颖超/生前/使用/过/的/物品
停电/范围/包括/沙坪坝区/的/犀牛屙屎/和/犀牛屙屎抽水
Raw output :
["他", "说", "的", "确实", "在", "理"]
["这", "事", "的", "确定", "不", "下来"]
["费孝通", "向", "人大", "常委会", "提交", "书面", "报告"]
["邓", "颖", "超生", "前", "使用", "过", "的", "物品"]
["停电", "范围", "包括", "沙", "坪", "坝", "区", "的", "犀牛", "屙", "屎", "和", "犀牛", "屙", "屎", "抽水"]
Output with user dict supplied :
["他", "说", "的", "确实", "在理"]
["这", "事", "的确", "定", "不", "下来"]
["费孝通", "向", "人大", "常委会", "提交", "书面", "报告"]
["邓颖超", "生前", "使用", "过", "的", "物品"]
["停电", "范围", "包括", "沙坪坝区", "的", "犀牛屙屎", "和", "犀牛屙屎抽水"]
```
## Todos
+ Filter low frequency words from CTB
+ Exploit summary of POS table, insert a example column, plus constract with other POS scheme(PKU etc.)
+ Explore MaxEntropy & CRF related algorithms
<!--stackedit_data:
eyJoaXN0b3J5IjpbLTEyNDI5Nzk3MTUsLTIwMDY4ODQ4NF19
--> | KongYiji | https://github.com/hack1nt0/KongYiji.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 917 | module MotionCaptureJointCalibration
export
PoseData,
CalibrationProblem,
CalibrationResult,
solve,
calibration_joints,
free_joints,
num_poses,
num_calibration_params,
num_markers
using Requires
using StaticArrays
using RigidBodyDynamics
using JuMP
using LinearAlgebra
using MathProgBase: SolverInterface.AbstractMathProgSolver
using RigidBodyDynamics.Graphs: TreePath
include("util.jl")
include("problem.jl")
include("result.jl")
include("deconstruct.jl")
include("residual.jl")
include("solve.jl")
include("synthetic.jl")
function __init__()
@require DrakeVisualizer="49c7015b-b8db-5bc5-841b-fcb31c578176" begin
@require RigidBodyTreeInspector="82daab19-8fc9-5c1e-9f69-37d6aaa0269b" begin
@require Interact="c601a237-2ae4-5e1e-952c-7a85b0c7eef1" begin
include("visualization.jl")
end
end
end
end
end # module
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 955 | function deconstruct(ordered_marker_bodies::AbstractVector{<:RigidBody}, q::AbstractVector,
marker_positions_body::AbstractDict{<:RigidBody, <:AbstractVector{<:Point3D}})
x = Vector(q)
for body in ordered_marker_bodies
positions = marker_positions_body[body]
for j = 1 : length(positions)
append!(x, positions[j].v)
end
end
x
end
function reconstruct!(ordered_marker_bodies::AbstractVector{<:RigidBody}, q::AbstractVector,
marker_positions_body::AbstractDict{<:RigidBody, <:AbstractVector{<:Point3D}}, x...)
index = 1
for i = 1 : length(q)
q[i] = x[index]
index += 1
end
for body in ordered_marker_bodies
positions = marker_positions_body[body]
frame = default_frame(body)
for j = 1 : length(positions)
positions[j] = Point3D(frame, x[index], x[index + 1], x[index + 2])
index += 3
end
end
end
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 2515 | struct PoseData{T}
configuration::TreeJointSegmentedVector{T}
marker_positions::Dict{RigidBody{T}, Vector{Point3DS{T}}}
end
mutable struct CalibrationProblem{T}
mechanism::Mechanism{T}
calibration_param_bounds::Dict{<:Joint{T}, Vector{Tuple{T, T}}}
free_joint_configuration_bounds::Dict{<:Joint{T}, Vector{Tuple{T, T}}}
marker_location_bounds::Dict{RigidBody{T}, Vector{Tuple{Point3DS{T}, Point3DS{T}}}}
pose_data::Vector{PoseData{T}}
body_weights::Dict{RigidBody{T}, T}
ordered_marker_bodies::Vector{RigidBody{T}}
function CalibrationProblem(
mechanism::Mechanism{T},
calibration_param_bounds::Dict{<:Joint{T}, Vector{Tuple{T, T}}},
free_joint_configuration_bounds::Dict{<:Joint{T}, Vector{Tuple{T, T}}},
marker_location_bounds::Dict{RigidBody{T}, Vector{Tuple{Point3DS{T}, Point3DS{T}}}},
pose_data::Vector{PoseData{T}},
body_weights::Dict{RigidBody{T}, T} = Dict(b => one(T) for b in keys(marker_location_bounds))) where {T}
@assert isempty(symdiff(keys(marker_location_bounds), keys(body_weights)))
canonicalize!(marker_location_bounds)
ordered_marker_bodies = intersect(bodies(mechanism), keys(body_weights))
new{T}(mechanism, calibration_param_bounds, free_joint_configuration_bounds,
marker_location_bounds, pose_data, body_weights, ordered_marker_bodies)
end
end
num_poses(problem::CalibrationProblem) = length(problem.pose_data)
num_calibration_params(problem::CalibrationProblem) = sum(length, values(problem.calibration_param_bounds))
num_calibration_params(problem::CalibrationProblem, joint::Joint) = length(problem.calibration_param_bounds[joint])
num_markers(problem::CalibrationProblem) = sum(length, values(problem.marker_location_bounds))
num_markers(problem::CalibrationProblem, body::RigidBody) = length(problem.marker_location_bounds[body])
RigidBodyDynamics.num_bodies(problem::CalibrationProblem) = length(problem.body_weights)
calibration_joints(problem::CalibrationProblem) = keys(problem.calibration_param_bounds)
free_joints(problem::CalibrationProblem) = keys(problem.free_joint_configuration_bounds)
function Base.show(io::IO, problem::CalibrationProblem{T}) where {T}
msg = """CalibrationProblem{$T} with:
* $(num_poses(problem)) poses
* $(num_calibration_params(problem)) calibration parameters
* $(num_markers(problem)) markers attached to $(num_bodies(problem)) bodies
"""
println(io, msg)
end
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 3503 | function _marker_residual(state::MechanismState{X, M, C},
ordered_marker_bodies::AbstractVector{<:RigidBody},
marker_positions_world::AbstractDict{RigidBody{M}, <:AbstractVector{<:Point3D}},
marker_positions_body::AbstractDict{RigidBody{M}, <:AbstractVector{<:Point3D}},
body_weights::AbstractDict{RigidBody{M}, Float64}) where {X, M, C}
normalize_configuration!(state)
residual = zero(C)
for body in ordered_marker_bodies
weight = body_weights[body]
tf = transform_to_root(state, body)
positions_body = marker_positions_body[body]
positions_world = marker_positions_world[body]
for i in eachindex(positions_body, positions_world)
p = tf * positions_body[i]
pmeas = positions_world[i]
residual += weight * mapreduce(x -> zero_nans(x)^2, +, (p - pmeas).v)
end
end
residual
end
# NOTE: ∇residual_v maps the joint velocity vector to the time derivative of the marker residual, rd:
#
# rd = <∇residual_v , v>
#
# The desired gradient g is the mapping from the time derivative of the joint configuration vector to
# the time derivative of the marker residual:
#
# rd = <g , qd>
#
# qd and v are related by an invertible linear map (see e.g. Port-based modeling and control for
# efficient bipedal walking robots, Definition 2.9):
#
# v = v_Q qd
#
# so we have
#
# rd = <∇residual_v , v> = <∇residual_v , v_Q qd> = <v_Qᵀ ∇residual_v , qd>
#
# which shows that g = v_Qᵀ ∇residual_v
function _∇marker_residual!(g::AbstractVector{T},
state::MechanismState{T},
ordered_marker_bodies::AbstractVector{RigidBody{T}},
marker_positions_world::AbstractDict{RigidBody{T}, <:AbstractVector{Point3DS{T}}},
marker_positions_body::AbstractDict{RigidBody{T}, <:AbstractVector{Point3DS{T}}},
body_weights::AbstractDict{RigidBody{T}, T},
jacobians::Dict{RigidBody{T}, Pair{TreePath{RigidBody{T}, Joint{T}}, GeometricJacobian{Matrix{T}}}}) where {T}
normalize_configuration!(state)
nq = num_positions(state)
∇residual_q = SegmentedVector(view(g, 1 : nq), tree_joints(state.mechanism), num_positions) # TODO: allocates
∇residual_ps = view(g, nq + 1 : length(g)) # TODO: allocates
∇residual_v = zero(velocity(state)) # TODO: allocates
mechanism = state.mechanism
nv = num_velocities(state)
p_index = 0
for body in ordered_marker_bodies
weight = body_weights[body]
tf = transform_to_root(state, body)
path_to_root, J = jacobians[body]
geometric_jacobian!(J, state, path_to_root)
positions_body = marker_positions_body[body]
positions_world = marker_positions_world[body]
for i in eachindex(positions_body, positions_world)
p = tf * positions_body[i]
pmeas = positions_world[i]
e = zero_nans.((p - pmeas).v)
for j = 1 : nv
ω = SVector(J.angular[1, j], J.angular[2, j], J.angular[3, j])
v = SVector(J.linear[1, j], J.linear[2, j], J.linear[3, j])
∇residual_v[j] += 2 * weight * dot(e, ω × p.v + v)
end
∇residual_p = 2 * weight * e' * rotation(tf)
∇residual_ps[p_index += 1] = ∇residual_p[1]
∇residual_ps[p_index += 1] = ∇residual_p[2]
∇residual_ps[p_index += 1] = ∇residual_p[3]
end
end
configuration_derivative_to_velocity_adjoint!(∇residual_q, state, ∇residual_v)
g
end
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 988 | struct CalibrationResult{T}
status::Symbol
residual::T
calibration_params::Dict{<:Joint{T}, Vector{T}}
configurations::Vector{TreeJointSegmentedVector{T}}
marker_positions::Dict{RigidBody{T}, Vector{Point3DS{T}}}
end
num_poses(result::CalibrationResult) = length(result.configurations)
num_calibration_params(result::CalibrationResult) = sum(length, values(result.calibration_params))
num_markers(result::CalibrationResult) = sum(length, values(result.marker_positions))
RigidBodyDynamics.num_bodies(result::CalibrationResult) = length(result.marker_positions)
function Base.show(io::IO, result::CalibrationResult{T}) where {T}
println(io, "CalibrationResult{$T}: $(string(result.status)), residual = $(result.residual). Calibration parameters:")
num_joints = length(result.calibration_params)
n = 0
for (joint, params) in result.calibration_params
print(io, "$(joint.name): $params")
(n += 1) < num_joints && println(io)
end
end
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 6032 | function solve(problem::CalibrationProblem{T}, solver::AbstractMathProgSolver) where {T}
# unpack
mechanism = problem.mechanism
calibration_param_bounds = problem.calibration_param_bounds
marker_bodies = problem.ordered_marker_bodies
marker_location_bounds = problem.marker_location_bounds
free_joint_configuration_bounds = problem.free_joint_configuration_bounds
pose_data = problem.pose_data
body_weights = problem.body_weights
num_poses = MotionCaptureJointCalibration.num_poses(problem)
state = MechanismState{T}(mechanism)
m = Model(solver = solver)
# variables
calibration_params = Dict(j => @variable(m, [1 : num_calibration_params(problem, j)], basename="c_$(j.name)")
for j in calibration_joints(problem))
configurations = [copyto!(similar(configuration(state), JuMP.Variable),
@variable(m, [1 : num_positions(mechanism)], basename="q$i")) for i = 1 : num_poses]
marker_positions = Dict(b => [Point3D(default_frame(b), @variable(m, [1 : 3], basename="m_$(b.name)_$i"))
for i = 1 : num_markers(problem, b)] for b in marker_bodies)
@variable(m, pose_residuals[1 : num_poses])
# calibration param constraints
for (joint, bounds) in calibration_param_bounds
params = calibration_params[joint]
setlowerbound.(params, first.(bounds))
setupperbound.(params, last.(bounds))
setvalue.(params, 0)
end
# joint configuration constraints and initial values
for i = 1 : num_poses
q = configurations[i]
qmeasured = pose_data[i].configuration
setvalue.(q, qmeasured)
for joint in tree_joints(mechanism) # to fix the order
qjoint = q[joint]
if joint ∈ free_joints(problem)
# free joint configuration bounds
bounds = free_joint_configuration_bounds[joint]
lower = first.(bounds)
upper = last.(bounds)
if joint_type(joint) isa QuaternionFloating
# TODO: method for getting rotation part
qrot = qjoint[1 : 4]
@NLconstraint(m, qrot[1]^2 + qrot[2]^2 + qrot[3]^2 + qrot[4]^2 == 1) # Unit norm constraint
lower[1 : 4] .= max.(lower[1 : 4], -1)
upper[1 : 4] .= min.(upper[1 : 4], +1)
end
setlowerbound.(qjoint, lower)
setupperbound.(qjoint, upper)
elseif joint ∈ calibration_joints(problem)
# calibration joint model
# TODO: generalize to handle not just offsets but also other models
# TODO: add redundant bounds on qjoint?
qjoint_measured = qmeasured[joint]
cjoint = calibration_params[joint]
@constraint(m, qjoint_measured .== qjoint .+ cjoint)
else
# other joints: fix at measured position
JuMP.fix.(qjoint, qmeasured[joint])
end
end
end
# marker position constraints and initial values
for body in keys(marker_location_bounds)
for (position, bounds) in zip(marker_positions[body], marker_location_bounds[body])
lower, upper = bounds
@framecheck position.frame lower.frame
@framecheck position.frame upper.frame
for (coord, lower_coord, upper_coord) in zip(position.v, lower.v, upper.v)
if lower_coord == upper_coord
JuMP.fix(coord, lower_coord)
else
setlowerbound(coord, lower_coord)
setupperbound(coord, upper_coord)
end
end
end
end
# objective: sum of marker residuals
marker_positions_body = Dict(
b => [Point3D(default_frame(b), 0., 0., 0.) for i = 1 : num_markers(problem, b)] for b in marker_bodies)
paths_to_root = Dict(b => RigidBodyDynamics.path(mechanism, root_body(mechanism), b) for b in marker_bodies)
jacobians = Dict(b => (p => geometric_jacobian(state, p)) for (b, p) in paths_to_root)
for i = 1 : num_poses
marker_residual = (args::Float64...) -> begin
reconstruct!(marker_bodies, configuration(state), marker_positions_body, args...)
normalize_configuration!(state)
setdirty!(state)
_marker_residual(state, marker_bodies, pose_data[i].marker_positions, marker_positions_body, body_weights)
end
∇marker_residual! = (g, args::Float64...) -> begin
reconstruct!(marker_bodies, configuration(state), marker_positions_body, args...)
normalize_configuration!(state)
setdirty!(state)
_∇marker_residual!(g, state, marker_bodies, pose_data[i].marker_positions, marker_positions_body, body_weights, jacobians)
end
marker_residual_args = deconstruct(marker_bodies, configurations[i], marker_positions)
num_marker_residual_args = length(marker_residual_args) # actually the same for all poses
fun = Symbol("marker_residual_", i)
JuMP.register(m, fun, num_marker_residual_args, marker_residual, ∇marker_residual!, autodiff = false)
arg_expressions = [:($(marker_residual_args[i])) for i = 1 : num_marker_residual_args]
JuMP.addNLconstraint(m, :($(pose_residuals[i]) == $(fun)($(arg_expressions...))))
end
@NLobjective(m, Min, sum(pose_residuals[i] for i = 1 : num_poses) / num_poses)
@objective m Min 0
status = JuMP.solve(m)
calibration_params_sol = Dict(j => getvalue.(c) for (j, c) in calibration_params)
configurations_sol = [copyto!(similar(configuration, T), getvalue.(configuration)) for configuration in configurations]
marker_positions_sol = Dict(b => (p -> Point3D(p.frame, SVector{3}(
getvalue.(p.v)))).(positions) for (b, positions) in marker_positions)
CalibrationResult(status, getobjectivevalue(m), calibration_params_sol, configurations_sol, marker_positions_sol)
end
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 6709 | module SyntheticDataGeneration
export
MarkerPositionGenerationOptions,
PoseDataGenerationOptions,
generate_marker_positions,
generate_joint_offset,
generate_pose_data,
generate_calibration_problem
using MotionCaptureJointCalibration
using RigidBodyDynamics
using StaticArrays
using Parameters
using Base.Iterators
using Random: randperm, rand!
using MotionCaptureJointCalibration: Point3DS
@with_kw struct MarkerPositionGenerationOptions
marker_measurement_stddev::Float64 = 1e-5
marker_offset_max::Float64 = 0.1
num_markers::Int = 4
num_measured_markers::Int = 3
end
@with_kw struct PoseDataGenerationOptions
num_poses::Int = 25
motion_capture_noise_stddev::Float64 = 1e-6
joint_configuration_noise_stddev::Float64 = 1e-4
occlusion_probability::Float64 = 0.025
end
function generate_marker_positions(bodies::AbstractVector{<:RigidBody},
options::MarkerPositionGenerationOptions = MarkerPositionGenerationOptions())
# Marker positions in body frame
B = eltype(bodies)
T = Float64
ground_truth_marker_positions = Dict(b => Vector{Point3DS{T}}() for b in bodies)
measured_marker_positions = Dict(b => Vector{Tuple{Point3DS{T}, Point3DS{T}}}() for b in bodies)
for body in bodies
frame = default_frame(body) # TODO: use some other frame to improve test coverage
measured_marker_inds = randperm(options.num_markers)[1 : options.num_measured_markers]
for i = 1 : options.num_markers
ground_truth = Point3D(frame, (rand(SVector{3}) - 0.5) * 2 * options.marker_offset_max)
push!(ground_truth_marker_positions[body], ground_truth)
bounds = if i ∈ measured_marker_inds
measurement_error = FreeVector3D(frame, options.marker_measurement_stddev * randn(SVector{3}))
measured = ground_truth + measurement_error
measured, measured
else
lower = Point3D(frame, fill(-0.2, SVector{3}))
upper = Point3D(frame, fill(0.2, SVector{3}))
lower, upper
end
push!(measured_marker_positions[body], bounds)
end
end
ground_truth_marker_positions, measured_marker_positions
end
function generate_joint_offset(joint::Joint, max_offset::Number)
(rand(num_positions(joint)) .- 0.5) .* max_offset .* 2
end
function generate_joint_offsets(joints::AbstractVector{<:Joint}, max_offset::Number)
Dict(j => generate_joint_offset(j, max_offset) for j in joints)
end
function generate_pose_data(
state::MechanismState{X, M, C},
ground_truth_marker_positions::AbstractDict{<:RigidBody{M}, <:AbstractVector{Point3DS{T}}},
ground_truth_offsets::AbstractDict{<:Joint{M}, <:AbstractVector{T}},
free_joints::AbstractVector{<:Joint{M}},
options::PoseDataGenerationOptions = PoseDataGenerationOptions()) where {X, M, C, T}
ground_truth_pose_data = Vector{PoseData{C}}()
measured_pose_data = Vector{PoseData{C}}()
mechanism = state.mechanism
for i = 1 : options.num_poses
rand!(state)
# Joint configurations
q_ground_truth = copy(configuration(state))
q_measured = copy(q_ground_truth)
for (joint, offset) in ground_truth_offsets
qjoint = q_measured[joint]
qjoint .+= offset
end
for joint in free_joints
qjoint = q_measured[joint]
zero_configuration!(qjoint, joint)
end
for joint in setdiff(tree_joints(mechanism), free_joints)
qjoint = q_measured[joint]
qjoint .+= options.joint_configuration_noise_stddev * randn(num_positions(joint))
end
# Markers
S = promote_type(C, T)
markerbodies = keys(ground_truth_marker_positions)
ground_truth_marker_data = Dict(b => Vector{Point3DS{S}}() for b in markerbodies)
measured_marker_data = Dict(b => Vector{Point3DS{S}}() for b in markerbodies)
for body in markerbodies
toworld = transform_to_root(state, body)
for (j, marker_body) in enumerate(ground_truth_marker_positions[body])
marker_world = transform(marker_body, toworld)
push!(ground_truth_marker_data[body], marker_world)
occluded = rand() < options.occlusion_probability
measured = if occluded
Point3D(marker_world.frame, fill(S(NaN), SVector{3}))
else
noise = FreeVector3D(marker_world.frame, options.motion_capture_noise_stddev * randn(SVector{3}))
marker_world + noise
end
push!(measured_marker_data[body], measured)
end
end
push!(ground_truth_pose_data, PoseData(q_ground_truth, ground_truth_marker_data))
push!(measured_pose_data, PoseData(q_measured, measured_marker_data))
end
ground_truth_pose_data, measured_pose_data
end
function generate_calibration_problem(state::MechanismState{T}, body_weights::Dict{RigidBody{T}, T};
marker_options::MarkerPositionGenerationOptions = MarkerPositionGenerationOptions(),
pose_options::PoseDataGenerationOptions = PoseDataGenerationOptions()) where {T}
bodies = collect(keys(body_weights))
mechanism = state.mechanism
correction_joints = unique(flatten([collect(RigidBodyDynamics.path(mechanism, body1, body2)) for (body1, body2) in product(bodies, bodies)]))
calibration_param_bounds = Dict{Joint{T}, Vector{Tuple{T, T}}}(j => fill((-0.05, 0.05), num_positions(j)) for j in correction_joints)
free_joint_configuration_bounds = Dict{Joint{T}, Vector{Tuple{T, T}}}(
j => fill((-1., 1.), num_positions(j)) for j in tree_joints(mechanism) if isfloating(j))
free_joints = collect(keys(free_joint_configuration_bounds))
ground_truth_marker_positions, measured_marker_positions = generate_marker_positions(bodies, marker_options)
ground_truth_offsets = Dict{Joint{T}, Vector{T}}(j => generate_joint_offset(j, 1e-2) for j in correction_joints)
ground_truth_pose_data, measured_pose_data =
generate_pose_data(state, ground_truth_marker_positions, ground_truth_offsets, free_joints, pose_options)
problem = CalibrationProblem(
mechanism,
calibration_param_bounds,
free_joint_configuration_bounds,
measured_marker_positions,
measured_pose_data, body_weights)
configurations = [data.configuration for data in ground_truth_pose_data]
ground_truth = CalibrationResult(:Optimal, 0., ground_truth_offsets, configurations, ground_truth_marker_positions)
problem, ground_truth
end
end # module
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 655 | const Point3DS{T} = Point3D{SVector{3, T}}
zero_nans(x) = ifelse(isnan(x), zero(x), x)
function canonicalize(body::RigidBody, point::Point3D)
if point.frame != default_frame(body)
point = frame_definition(body, point.frame) * point
end
point
end
function canonicalize!(d::Dict{RigidBody{T}, Vector{Tuple{Point3DS{T}, Point3DS{T}}}}) where {T}
for (body, bounds) in d
for i in eachindex(bounds)
bounds[i] = canonicalize.(Ref(body), bounds[i])
end
end
end
const TreeJointSegmentedVector{T} = SegmentedVector{
RigidBodyDynamics.JointID, T, Base.OneTo{RigidBodyDynamics.JointID}, Vector{T}}
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 1838 | using DrakeVisualizer
using RigidBodyTreeInspector
using RigidBodyTreeInspector: RGBA, HyperSphere, Point
using Interact
function RigidBodyTreeInspector.inspect!(state::MechanismState, vis::Visualizer, problem::CalibrationProblem, result::CalibrationResult)
radius = 0.01
semitransparent_green = RGBA(0., 1, 0, 0.5)
for points in values(result.marker_positions)
for point in points
sphere = HyperSphere(Point{3, Float64}(point.v), radius)
addgeometry!(vis, state.mechanism, point.frame, GeometryData(sphere, semitransparent_green))
end
end
markervis = vis[:marker_measurements]
cal_selector = radiobuttons(Dict("Before calibration" => false, "After calibration" => true))
pose_slider = slider(1 : num_poses(result), value = 1, label = "Pose number")
map(pose_slider, cal_selector) do i, cal
set_configuration!(state, result.configurations[i])
if !cal
q_before_cal = problem.pose_data[i].configuration
for joint in keys(problem.calibration_param_bounds)
set_configuration!(state, joint, q_before_cal[joint])
end
end
settransform!(vis, state)
delete!(markervis)
for points in values(problem.pose_data[i].marker_positions)
for point in points
num_measured_coordinates = 3 - count(isnan.(point.v))
if num_measured_coordinates > 0
blueness = num_measured_coordinates / 3
color = RGBA(0., 0., blueness, 0.5)
sphere = HyperSphere(Point{3, Float64}(point.v), radius)
addgeometry!(markervis, state.mechanism, point.frame, GeometryData(sphere, color))
end
end
end
end
vbox(cal_selector, pose_slider)
end
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | code | 5847 | using MotionCaptureJointCalibration
using DrakeVisualizer
using RigidBodyTreeInspector
using Interact
using MotionCaptureJointCalibration.SyntheticDataGeneration
using RigidBodyDynamics
using StaticArrays
using ValkyrieRobot
using ForwardDiff
using Ipopt
using NBInclude
using Test
using LinearAlgebra
using MotionCaptureJointCalibration: Point3DS, reconstruct!, deconstruct, _marker_residual, _∇marker_residual!
using Random: seed!, rand!
T = Float64
val = Valkyrie()
mechanism = val.mechanism
remove_fixed_tree_joints!(mechanism)
state = MechanismState{T}(mechanism)
markerbodies = findbody.(Ref(mechanism), ["leftFoot", "pelvis"])
seed!(1)
body_weights = Dict(b => rand() for b in markerbodies)
marker_options = MarkerPositionGenerationOptions()
pose_options = PoseDataGenerationOptions()
problem, groundtruth = generate_calibration_problem(state, body_weights, marker_options = marker_options, pose_options = pose_options)
@testset "deconstruct/reconstruct!" begin
q = zeros(num_positions(mechanism))
marker_positions_body = Dict(b => [Point3D(default_frame(b), 0., 0., 0.) for i = 1 : num_markers(problem, b)] for b in markerbodies)
reconstruct!(markerbodies, q, marker_positions_body, deconstruct(markerbodies, configuration(state), groundtruth.marker_positions)...)
@test all(q .== configuration(state))
for (body, positions) in groundtruth.marker_positions
@test all(marker_positions_body[body] .== positions)
end
end
@testset "marker_residual gradient" begin
data = problem.pose_data[1]
marker_positions_world = data.marker_positions
function marker_residual_inefficient(x::X...) where {X}
M = eltype(mechanism)
state = MechanismState{X}(mechanism)
marker_positions_body = Dict{RigidBody{M}, Vector{Point3DS{X}}}(
b => [Point3D(default_frame(b), zero(X), zero(X), zero(X)) for i = 1 : num_markers(problem, b)] for b in markerbodies
)
reconstruct!(markerbodies, configuration(state), marker_positions_body, x...)
normalize_configuration!(state)
setdirty!(state)
_marker_residual(state, markerbodies, marker_positions_world, marker_positions_body, body_weights)
end
f(args) = [marker_residual_inefficient(args...)]
for i = 1 : 100
rand!(state)
q = configuration(state)
Jcheck = ForwardDiff.jacobian(f, deconstruct(markerbodies, q, groundtruth.marker_positions))
set_configuration!(state, q)
g = zeros(length(Jcheck))
paths_to_root = Dict(b => RigidBodyDynamics.path(mechanism, root_body(mechanism), b) for b in markerbodies)
jacobians = Dict(b => (p => geometric_jacobian(state, p)) for (b, p) in paths_to_root)
_∇marker_residual!(g, state, markerbodies, marker_positions_world, groundtruth.marker_positions, body_weights, jacobians)
J = g'
@test isapprox(J, Jcheck, atol = 1e-14)
end
end
@testset "problem" begin
@test num_poses(problem) == pose_options.num_poses
@test num_calibration_params(problem) == 6
@test num_markers(problem) == marker_options.num_markers * length(markerbodies)
@test num_bodies(problem) == length(markerbodies)
show(devnull, problem)
end
@testset "solve" begin
# NLopt SLSQP works well with up to 10 poses, free floating joint configurations and two unmeasured markers
# solver = NLoptSolver(algorithm = :LD_SLSQP)
solver = IpoptSolver(print_level = 4, max_iter = 10000, derivative_test = "first-order", check_derivatives_for_naninf = "yes", tol = 1e-10)
# other useful options:
# hessian_approximation = "limited-memory"
result = solve(problem, solver)
@test result.status == :Optimal
@test num_poses(problem) == num_poses(result)
@test num_calibration_params(problem) == num_calibration_params(result)
@test num_markers(problem) == num_markers(result)
@test num_bodies(problem) == num_bodies(result)
# check calibration parameters
for joint in calibration_joints(problem)
@test isapprox(result.calibration_params[joint], groundtruth.calibration_params[joint]; atol = 1e-3)
end
# check configurations
solutionstate = MechanismState{T}(mechanism)
groundtruthstate = MechanismState{T}(mechanism)
for i = 1 : num_poses(problem)
set_configuration!(solutionstate, result.configurations[i])
set_configuration!(groundtruthstate, groundtruth.configurations[i])
for body in bodies(mechanism)
@test isapprox(transform_to_root(solutionstate, body), transform_to_root(groundtruthstate, body); atol = 2e-3)
end
end
# printing and visualization (just to make sure the code doesn't error)
show(devnull, result)
vis = Visualizer()[:valkyrie]
geometry = visual_elements(mechanism, URDFVisuals(ValkyrieRobot.urdfpath(); package_path = [ValkyrieRobot.packagepath()]))
setgeometry!(vis, mechanism, geometry)
inspect!(state, vis, problem, result)
end
using RigidBodyTreeInspector
@testset "example notebooks" begin
notebookdir = joinpath(@__DIR__, "..", "notebooks")
excludedirs = [".ipynb_checkpoints"]
excludefiles = String[]
for (root, dir, files) in walkdir(notebookdir)
basename(root) in excludedirs && continue
for file in files
file in excludefiles && continue
name, ext = splitext(file)
lowercase(ext) == ".ipynb" || continue
path = joinpath(root, file)
@eval module $(gensym()) # Each notebook is run in its own module.
using Test
using NBInclude
@testset "Notebook: $($name)" begin
# Note: use #NBSKIP in a cell to skip it during tests.
@nbinclude($path; regex = r"^((?!\#NBSKIP).)*$"s)
end
end # module
end
end
end
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.3.0 | a4bc0ad02c25a442357189b60168a0173c9bbf76 | docs | 2769 | # MotionCaptureJointCalibration
[](https://travis-ci.org/JuliaRobotics/MotionCaptureJointCalibration.jl) [](http://codecov.io/github/JuliaRobotics/MotionCaptureJointCalibration.jl?branch=master)
MotionCaptureJointCalibration provides functionality for kinematic calibration of robots, given measurements of the positions of motion capture markers attached to the robot's links and positions of the robot's joints in a number of poses. It does so by solving a nonlinear program (NLP) with (weighted) square error between measured and predicted marker locations as the objective to minimize.
MotionCaptureJointCalibration is a small Julia library built on top of [JuMP](https://github.com/JuliaOpt/JuMP.jl) and [RigidBodyDynamics.jl](https://github.com/JuliaRobotics/RigidBodyDynamics.jl). JuMP makes it possible to choose between various NLP solvers. [Ipopt](https://github.com/JuliaOpt/Ipopt.jl) appears to perform fairly well for the problems formulated by this package.
## News
* October 18, 2017: [tagged version 0.0.1](https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl/releases/tag/v0.0.1).
* August 4, 2017: the package is under initial construction.
## Features
Features include:
* handling of occlusions
* handling of measurements of the body-fixed locations of only a subset of the markers attached to the robot (the unknown marker positions will be solved for, given rough bounds)
* handling of measurements of only a subset of a robot's joint positions (the unknown joint positions will be solved for, given rough bounds)
* proper handling of quaternion-parameterized floating joints (unit norm constraints for quaternions)
* visualization of calibration results using [RigidBodyTreeInspector](https://github.com/rdeits/RigidBodyTreeInspector.jl)
Currently, MotionCaptureJointCalibration can only estimate constant offsets between measured and actual joint positions.
## Installation
To install, simply run
```julia
Pkg.add("MotionCaptureJointCalibration")
```
This will install MotionCaptureJointCalibration and its required dependencies. RigidBodyTreeInspector.jl is an optional dependency and can be used to visualize the calibration results (`Pkg.add("RigidBodyTreeInspector")`). You'll also need an NLP solver that interfaces with JuMP, e.g. Ipopt (`Pkg.add("Ipopt")`).
## Usage
See [the demo notebook](https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl/blob/master/notebook/Demo.ipynb) for usage.
## Acknowledgements
A variant of the NLP formulation used in this package is due to Michael Posa.
| MotionCaptureJointCalibration | https://github.com/JuliaRobotics/MotionCaptureJointCalibration.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 881 | using ExtendedKronigPennyMatrix
using Documenter
DocMeta.setdocmeta!(ExtendedKronigPennyMatrix, :DocTestSetup, :(using ExtendedKronigPennyMatrix); recursive=true)
makedocs(;
modules=[ExtendedKronigPennyMatrix],
authors="Hiroharu Sugawara <[email protected]>",
repo="https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl/blob/{commit}{path}#{line}",
sitename="ExtendedKronigPennyMatrix.jl",
format=Documenter.HTML(;
prettyurls=get(ENV, "CI", "false") == "true",
canonical="https://hsugawa8651.github.io/ExtendedKronigPennyMatrix.jl",
assets=String[],
),
pages=[
"Home" => "index.md",
"Manual" => [
"Usage" => "usage.md",
"使い方" => "usageja.md"
],
"Reference" => "reference.md",
],
)
deploydocs(;
repo="github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl",
)
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 1020 |
using ExtendedKronigPennyMatrix
using LinearAlgebra
using PyPlot
pygui(false)
function plot_KP(v0, rho)
clf()
cm=get_cmap("tab10")
pot=FiniteSquareWell(v0, rho)
pf = get_potential(pot)
a=1
xs=-2a:a/100:3a
plot(xs, pf.(xs), "k")
for Ka in (-18:18)/18*π
model=Model(pot, Ka)
ev = eigvals(model.hnm)
for i in 1:5
plot(Ka/ π, ev[i], ".", color=cm(i-1))
end
end
xlim(-1,1)
ylim(-2,32)
xlabel(L"$Ka / \pi$")
ylabel(L"Energy / $E_0$")
title( L"$v_{0} =$"*string(v0)*", "*L"$\rho =$"*string(rho))
end
function main()
#
plot_KP( 0, 0.5)
ylim(-0.5,25)
savefig("Pavelich_Fig4a.png")
#
plot_KP( 10, 0.5)
ylim(-0.5,30)
savefig("Pavelich_Fig4b.png")
savefig("KP_10_05.png")
#
plot_KP( 10, 0.8)
ylim(-0.5,30)
savefig("KP_10_08.png")
#
plot_KP(20.5607, 0.5)
ylim(-0.5,40)
savefig("Pavelich_Fig6.png")
#
plot_KP(10.8775, 0.8)
ylim(-0.5,30)
savefig("Pavelich_Fig7.png")
end
main()
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 627 |
using ExtendedKronigPennyMatrix
using LinearAlgebra
using PyPlot
pygui(false)
function plot_IHO(v0)
clf()
cm=get_cmap("tab10")
pot=InvertedHarmonicOscillator(v0)
pf = get_potential(pot)
a=1
xs=-2a:a/100:3a
plot(xs, pf.(xs), "k")
for Ka in (-18:18)/18*π
model=Model(pot, Ka)
ev = eigvals(model.hnm)
for i in 1:5
plot(Ka/ π, ev[i], ".", color=cm(i-1))
end
end
xlim(-1,1)
ylim(0,50)
xlabel(L"$Ka / \pi$")
ylabel(L"Energy / $E_0$")
title( L"$v0 =$"*string(v0))
end
function main()
#
plot_IHO( 7.30815)
savefig("Pavelich_Fig9.png")
end
main()
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 608 |
using ExtendedKronigPennyMatrix
using LinearAlgebra
using PyPlot
pygui(false)
function plot_IHO(A)
clf()
cm=get_cmap("tab10")
pot= LinearWell(A)
pf = get_potential(pot)
a=1
xs=-2a:a/100:3a
plot(xs, pf.(xs), "k")
for Ka in (-18:18)/18*π
model=Model(pot, Ka)
ev = eigvals(model.hnm)
for i in 1:5
plot(Ka/ π, ev[i], ".", color=cm(i-1))
end
end
xlim(-1,1)
ylim(0,40)
xlabel(L"$Ka / \pi$")
ylabel(L"Energy / $E_0$")
title( L"$A =$"*string(A))
end
function main()
#
plot_IHO(19.8705)
savefig("Pavelich_Fig10.png")
end
main()
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 972 |
using ExtendedKronigPennyMatrix
using LinearAlgebra
using PyPlot
pygui(false)
function plot_potential()
clf()
cm=get_cmap("tab10")
potentials = [
[ FiniteSquareWell(1.0, 0.5), "Kronig-Penny ρ=0.5" ],
[ FiniteSquareWell(1.0, 0.8), "Kronig-Penny ρ=0.8" ],
[ SimpleHarmonicOscillator(1.0), "Simple Harmonic Oscillator" ],
[ InvertedHarmonicOscillator(1.0), "Inverted Harmonic Oscillator" ],
[ LinearWell(1.0), "LinearWell" ]
]
npotentials=length(potentials)
fig, axs = subplots(npotentials,1, sharex=true, tight_layout=true)
@show axs
for (cnt, desc) in enumerate(potentials)
pot, ttl = desc
pf = get_potential(pot)
a=1
xs=-2a:a/100:2a
axs[cnt].plot(xs, pf.(xs))
axs[cnt].set_title(ttl, y=-0.5)
axs[cnt].set_xlabel("")
axs[cnt].set_xticks([])
axs[cnt].set_ylabel("")
# axs[cnt].axis("off")
end
fig.savefig("Pavelich_Fig5.png")
end
plot_potential()
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 626 |
using ExtendedKronigPennyMatrix
using LinearAlgebra
using PyPlot
pygui(false)
function plot_SHO(v0)
clf()
cm=get_cmap("tab10")
pot=SimpleHarmonicOscillator(v0)
pf = get_potential(pot)
a=1
xs=-2a:a/100:3a
plot(xs, pf.(xs), "k")
for Ka in (-18:18)/18*π
model=Model(pot, Ka)
ev = eigvals(model.hnm)
for i in 1:5
plot(Ka/ π, ev[i], ".", color=cm(i-1))
end
end
xlim(-1,1)
ylim(0,30)
xlabel(L"$Ka / \pi$")
ylabel(L"Energy / $E_0$")
title( L"$v0 =$"*string(v0))
end
function main()
#
plot_SHO( 4.84105)
savefig("Pavelich_Fig8.png")
end
main()
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 1162 |
using ExtendedKronigPennyMatrix
using LinearAlgebra
using PyPlot
pygui(false)
function plot_potential()
clf()
cm=get_cmap("tab10")
potentials = [
[ FiniteSquareWell(20.5607, 0.5), "Kronig-Penny ρ=0.5" ],
[ InvertedHarmonicOscillator(7.30845), "Inverted HO" ],
[ FiniteSquareWell(10.8775, 0.8), "Kronig-Penny ρ=0.8" ],
[ LinearWell(19.8705), "LinearWell" ],
[ SimpleHarmonicOscillator(4.84105), "Simple HO" ],
]
npotentials=length(potentials)
for (cnt, desc) in enumerate(potentials)
pot, ttl = desc
pf = get_potential(pot)
a=1
Ka= -pi
model=Model(pot, Ka)
ev = eigvals(model.hnm)
ev30=ev[3]
@show ev30
for (j,Ka) in enumerate((-36:36)/36*π)
model=Model(pot, Ka)
ev = eigvals(model.hnm)
if j==1
plot(Ka/ π, ev[3] - ev30, ".", color=cm(cnt-1), label=ttl)
else
plot(Ka/ π, ev[3] - ev30, ".", color=cm(cnt-1))
end
end
end
legend(loc=3)
xlim(-1,1)
ylim(-3,0.2)
xlabel(L"$Ka / \pi$")
ylabel(L"Energy / $E_0$")
savefig("Pavelich_Fig11.png")
end
plot_potential()
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 446 |
__precompile__(true)
using LinearAlgebra
module ExtendedKronigPennyMatrix
using Unitful
include("basic.jl")
export
Alternates,
get_E10,
get_potential
export
Model
include("FiniteSquareWell.jl")
include("SimpleHarmonicOscillator.jl")
include("InvertedHarmonicOscillator.jl")
include("LinearWell.jl")
export
FiniteSquareWell,
SimpleHarmonicOscillator,
InvertedHarmonicOscillator,
LinearWell,
constructMatrix
end
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 2299 | # KronigPenny
"""
struct FiniteSquareWell(v0, ρ)
holds parameters of finite square well potential.
Fields
* `v0` : potential height in units of ``E_{1}^{(0)}``
* `ρ` : barrier width in units of period ``a``, where ``0 < \\rho = \\dfrac{b}{a} < 1``
* Note that a position ``x`` is expressed in units of ``a`` throughout this package.
The constructor `FiniteSquareWell(v0, ρ)` confirms that `0 ≤ ρ ≤ 1`, otherwise throws an error.
"""
struct FiniteSquareWell <: Potential
v0:: Real
ρ:: Real # ρ = b/a
FiniteSquareWell(v0, ρ) = 0 ≤ ρ ≤ 1 ? new(v0,ρ) : error("ρ < 0 or 1 < ρ")
end
"""
get_potential(::FiniteSquareWell)
returns a function ``v`` to evaluate potential ``v(x)`` as a position ``x``,
such that:
```math
\\begin{aligned}
v(x) & = \\begin{cases}
v_{0} &
\\text{inside well, i.e.,}
\\dfrac{1-\\rho}{2} \\le \\dfrac{x}{a} \\le \\dfrac{1+\\rho}{2},
\\\\
0 & \\text{outside well}\\end{cases}
\\\\
v(x+a) &= v(x)
\\end{aligned}
```
* Note that a position ``x`` is expressed in units of ``a`` throughout this package.
"""
function get_potential(pot::FiniteSquareWell)
return x -> (1-pot.ρ)/2 <= mod(x,1)< (1+pot.ρ)/2 ? 0 : pot.v0
end
"""
constuctMatrix(model::Model{FiniteSquareWell})
computes and fills Hamiltonian matrix fields `hnm` in `model` with finite square well.
```math
h_{nm} = \\begin{cases}
\\left(2n + \\dfrac{Ka}{\\pi}\\right)^{2} + v_{0} (1-\\rho) &
\\text{for}\\; n = m\\;\\text{(diagonal elements)} \\\\
v_{0}
\\dfrac{(-1)^{m-n+1}}{\\pi} \\dfrac{\\sin \\pi(m-n)\\rho}{m-n}
&
\\text{for}\\; n \\neq m\\;\\text{(off-diagonal elements)}\\end{cases}
```
"""
function constuctMatrix(model::Model{FiniteSquareWell})
qnum=model.qnum
hnm=model.hnm
Ka=model.Ka
potential=model.potential
v0=potential.v0
ρ=potential.ρ
for (i,m) in enumerate(qnum)
for (j,n) in Iterators.take(enumerate(qnum), i-1)
hnm[i,j] = 0
end
end
for (i,m) in enumerate(qnum)
hnm[i,i] = (2m+Ka/π)^2 + v0*(1-ρ)
end
for (i,m) in enumerate(qnum)
for (j,n) in Iterators.take(enumerate(qnum), i-1)
hnm[i,j] = v0*(-1)^(m-n+1)/π * sinpi((m-n)ρ)/(m-n)
end
for (j,n) in Iterators.drop(enumerate(qnum), i)
hnm[i,j] = v0*(-1)^(m-n+1)/π * sinpi((m-n)ρ)/(m-n)
end
end
end | ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 2226 | # Inverted Harmonic Oscillator
"""
struct InvertedHarmonicOscillator(v0)
holds parameters of finite square well potential.
Fields
* `v0` ``= \\hbar\\omega`` in units of ``E_{1}^{(0)}``
"""
struct InvertedHarmonicOscillator <: Potential
v0:: Real
end
"""
get_potential(::InvertedHarmonicOscillator)
returns a function ``v`` to evaluate potential ``v(x)`` as a position ``x``,
such that:
```math
\\begin{aligned}
v(x) & = \\begin{cases}
-\\dfrac{1}{2}m {\\omega}^{2} a^{2}
\\left[ \\left(\\dfrac{x}{a}\\right)^2 - \\dfrac{1}{4} \\right] &
0 \\le \\dfrac{x}{a} \\le \\dfrac{1}{2} \\\\
-\\dfrac{1}{2}m {\\omega}^{2} a^{2}
\\left[ \\left(\\dfrac{x}{a}-1\\right)^2 - \\dfrac{1}{4} \\right] &
\\dfrac{1}{2} \\le \\dfrac{x}{a} \\le 1
\\end{cases}
\\\\
v(x+a) &= v(x)
\\end{aligned}
```
* Note that a position ``x`` is expressed in units of ``a`` throughout this package.
"""
function get_potential(pot::InvertedHarmonicOscillator)
return x -> (x1 = mod(x,1.0);
x1 < 1/2 ?
pot.v0^2 * pi^2 / 4.0 * (1/4 - x1^2) :
pot.v0^2 * pi^2 / 4.0 * (1/4 - (x1-1)^2) )
end
"""
constuctMatrix(model::Model{InvertedHarmonicOscillator})
computes and fills Hamiltonian matrix fields `hnm` in `model` with finite square well.
```math
h_{nm} = \\begin{cases}
\\left(2n + \\dfrac{Ka}{\\pi}\\right)^{2} + v_{0}^{2} \\dfrac{\\pi^2}{24} &
\\text{for}\\; n = m\\;\\text{(diagonal elements)} \\\\
- \\dfrac{v_{0}^2}{8} \\dfrac{(-1)^{m-n}}{(m-n)^{2}}
&
\\text{for}\\; n \\neq m\\;\\text{(off-diagonal elements)}\\end{cases}
```
"""
function constuctMatrix(model::Model{InvertedHarmonicOscillator})
qnum=model.qnum
hnm=model.hnm
Ka=model.Ka
potential=model.potential
v0=potential.v0
for (i,m) in enumerate(qnum)
for (j,n) in Iterators.take(enumerate(qnum), i-1)
hnm[i,j] = 0
end
end
for (i,m) in enumerate(qnum)
hnm[i,i] = (2m+Ka/π)^2 + v0^2 * pi^2 / 24
end
for (i,m) in enumerate(qnum)
for (j,n) in Iterators.take(enumerate(qnum), i-1)
hnm[i,j] = -v0^2/8 * (-1)^(m-n) / (m-n)^2
end
for (j,n) in Iterators.drop(enumerate(qnum), i)
hnm[i,j] = -v0^2/8 * (-1)^(m-n) / (m-n)^2
end
end
end
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 1963 | # LinearWell
"""
struct LinearWell(A)
holds parameters of finite square well potential.
Fields
* `A` ``= \\hbar\\omega`` in units of ``E_{1}^{(0)}``
"""
struct LinearWell <: Potential
A:: Real
end
"""
get_potential(::LinearWell)
returns a function ``v`` to evaluate potential ``v(x)`` as a position ``x``,
such that:
```math
\\begin{aligned}
v(x) & = \\begin{cases}
2A \\left( \\dfrac{1}{2} - \\dfrac{x}{a} \\right) &
0 \\le \\dfrac{x}{a} \\le \\dfrac{1}{2} \\\\
2A \\left( \\dfrac{x}{a} - \\dfrac{1}{2} \\right) &
\\dfrac{1}{2} \\le \\dfrac{x}{a} \\le 1
\\end{cases}
\\\\
v(x+a) &= v(x)
\\end{aligned}
```
* Note that a position ``x`` is expressed in units of ``a`` throughout this package.
"""
function get_potential(pot::LinearWell)
return x -> (x1 = mod(x,1.0);
x1 < 1/2 ?
2 * pot.A * (1/2 - x1) :
2 * pot.A * (x1 - 1/2) )
end
"""
constuctMatrix(model::Model{LinearWell})
computes and fills Hamiltonian matrix fields `hnm` in `model` with finite square well.
```math
h_{nm} = \\begin{cases}
\\left(2n + \\dfrac{Ka}{\\pi}\\right)^{2} + \\dfrac{A}{2} &
\\text{for}\\; n = m\\;\\text{(diagonal elements)} \\\\
\\dfrac{-A}{\\pi^2 (m-n)^{2}} \\left[ 1-(-1)^{m-n}\\right]
&
\\text{for}\\; n \\neq m\\;\\text{(off-diagonal elements)}\\end{cases}
```
"""
function constuctMatrix(model::Model{LinearWell})
qnum=model.qnum
hnm=model.hnm
Ka=model.Ka
potential=model.potential
A=potential.A
for (i,m) in enumerate(qnum)
for (j,n) in Iterators.take(enumerate(qnum), i-1)
hnm[i,j] = 0
end
end
for (i,m) in enumerate(qnum)
hnm[i,i] = (2m+Ka/π)^2 + A / 2
end
for (i,m) in enumerate(qnum)
for (j,n) in Iterators.take(enumerate(qnum), i-1)
hnm[i,j] = -A / pi^2 / (m-n)^2 * ( 1 - (-1)^(m-n))
end
for (j,n) in Iterators.drop(enumerate(qnum), i)
hnm[i,j] = -A / pi^2 / (m-n)^2 * ( 1 - (-1)^(m-n))
end
end
end
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 1988 | # Simple Harmonic Oscillator
"""
struct SimpleHarmonicOscillator(v0)
holds parameters of finite square well potential.
Fields
* `v0` ``= \\hbar\\omega`` in units of ``E_{1}^{(0)}``
"""
struct SimpleHarmonicOscillator <: Potential
v0:: Real
end
"""
get_potential(::SimpleHarmonicOscillator)
returns a function ``v`` to evaluate potential ``v(x)`` as a position ``x``,
such that:
```math
\\begin{aligned}
v(x) & = \\dfrac{1}{2}m {\\omega}^{2} a^{2} \\left(\\dfrac{x}{a}-\\dfrac{1}{2}\\right)^2
= \\dfrac{\\pi^2}{4} v_{0}^2 E_{1}^{(0)} \\left(\\dfrac{x}{a}-\\dfrac{1}{2}\\right)^2,
\\quad 0 \\le \\dfrac{x}{a} \\le 1
\\\\
v(x+a) &= v(x)
\\end{aligned}
```
* Note that a position ``x`` is expressed in units of ``a`` throughout this package.
"""
function get_potential(pot::SimpleHarmonicOscillator)
return x -> pot.v0^2 * pi^2 / 4.0 * (mod(x,1.0)-1/2)^2
end
"""
constuctMatrix(model::Model{SimpleHarmonicOscillator})
computes and fills Hamiltonian matrix fields `hnm` in `model` with finite square well.
```math
h_{nm} = \\begin{cases}
\\left(2n + \\dfrac{Ka}{\\pi}\\right)^{2} + v_{0}^{2} \\dfrac{\\pi^2}{48} &
\\text{for}\\; n = m\\;\\text{(diagonal elements)} \\\\
\\dfrac{v_{0}^2}{8}
\\dfrac{(-1)^{m-n}}{(m-n)^{2}}
&
\\text{for}\\; n \\neq m\\;\\text{(off-diagonal elements)}\\end{cases}
```
"""
function constuctMatrix(model::Model{SimpleHarmonicOscillator})
qnum=model.qnum
hnm=model.hnm
Ka=model.Ka
potential=model.potential
v0=potential.v0
for (i,m) in enumerate(qnum)
for (j,n) in Iterators.take(enumerate(qnum), i-1)
hnm[i,j] = 0
end
end
for (i,m) in enumerate(qnum)
hnm[i,i] = (2m+Ka/π)^2 + v0^2 * pi^2 / 48
end
for (i,m) in enumerate(qnum)
for (j,n) in Iterators.take(enumerate(qnum), i-1)
hnm[i,j] = v0^2/8 * (-1)^(m-n) / (m-n)^2
end
for (j,n) in Iterators.drop(enumerate(qnum), i)
hnm[i,j] = v0^2/8 * (-1)^(m-n) / (m-n)^2
end
end
end | ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 3077 |
"""
Alternates(nmax)
is an iterator to generate the series ``\\{0, 1, -1, 2, -2, \\ldots \\}``
up to `nmax` as an ordering of quantum numbers.
```
collect(Alternates(0)) => [0]
collect(Alternates(1)) => [0, 1, -1]
collect(Alternates(2)) => [0, 1, -1, 2, -2]
```
"""
struct Alternates
nmax::Int
end
Base.eltype(::Type{Alternates}) = Int
Base.length(alt::Alternates) = alt.nmax*2+1
"""
Base.iterate(alt::Alternates, state::Int = 1)
"""
function Base.iterate(alt::Alternates, state::Int = 1)
state > alt.nmax*2+1 && return nothing
nxt = state ÷ 2
if state % 2 == 1
nxt *= -1
end
(nxt, state+1)
end
"""
get_E10(a; me=1)
calculates the ground state energy ``E_{1}^{(0)}``.
```math
E_{1}^{(0)} = \\dfrac{\\pi^2\\hbar^2}{2ma^2}
```
* `a` : system length
* `me` : electron mass
This function handles physical quantities with Unitful package.
* If `a` is dimensionless, suppose that `a` is in `nm` unit.
* Otherwise, `a` must have a dimension of length `L`.
* If `me` is dimensionless, suppose that `me` is an effective mass with respect to electron rest mass.
* Otherwise, `me` must have a dimension of mass `M`.
* The resultant enegy value is repesented in `eV`.
"""
function get_E10(a; me=1)
a0 = if isa(a, Unitful.Length)
a
elseif isa(a, Real)
a * 1u"nm"
else
throw(Unitful.DimensionError)
end
m0 = if isa(me, Unitful.Mass)
me
elseif isa(me, Real)
me * 1u"me"
else
throw(Unitful.DimensionError)
end
e10 = pi^2*(1u"ħ")^2 / (2*m0*a0^2) |> u"eV"
return e10
end
"""
Potential
is an abstraction of potential including
* potential height, and/or
* other parameters depending on specific potential.
A subtype of `Potential` is expected to possess following methods:
* `get_potential(<:Potential)`
* returns a function to evaluate potential value as a position.
"""
abstract type Potential
end
"""
struct Model{P<:Potential}
is an abstraction of model including following fields:
* `potential` : concrete Potential
* `Ka` : wavenumber multiplied by `a`, period
* `nmax` : maximum of quantum numbers
* `mmax` : size of Hamiltonian matrix
* `qnum` : iterator of quantum numbers
* `hnm` : hamiltonian matrix
A concrete subtype of model is expected to possess following methods:
* `constuctMatrix(model::Model{P})`
"""
struct Model{P<:Potential}
potential::P
Ka::Float64
nmax::Int64 # maximum of quantum numbers
mmax::Int64 # size of Hamiltonian
qnum::Alternates
hnm::Matrix
end
"""
function Model(pot::Potential,Ka::Float64,nmax::Int64=60)
is a constructor of Kronig-Penny model, and defines other fields: `qnum`, `nmax`, and `hnm`
* Mandantory parameters:
* `pot` : potential
* `Ka` : wavenumber multiplied by `a`, period
* Optional parameters:
* `nmax` : maximum of quantum numbers
"""
function Model(pot::Potential,Ka::Float64,nmax::Int64=60)
qnum=Alternates(nmax)
mmax=length(qnum)
hnm=zeros(Float64,(mmax,mmax))
model=Model(pot,Ka,nmax,mmax,qnum,hnm)
constuctMatrix(model)
model
end | ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 237 | @testset "Alternates" begin
@test collect(Alternates(0)) == [0]
@test collect(Alternates(1)) == [0, 1, -1 ]
@test collect(Alternates(2)) == [0, 1, -1, 2, -2 ]
@test collect(Alternates(3)) == [0, 1, -1, 2, -2, 3, -3 ]
end
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 512 | @testset "KronigPenny" begin
@testset "KP_ex" begin
filenames = [
"KP_10_05.png", "KP_10_08.png",
"Pavelich_Fig4a.png", "Pavelich_Fig4b.png",
"Pavelich_Fig6.png", "Pavelich_Fig7.png" ]
ENV["MPLBACKEND"]="agg" # no GUI
using PyPlot
include("../example/ex1_FiniteSquareWell.jl")
using CRC32c
for filename in filenames
@test open(crc32c, filename) == open(crc32c, joinpath("example", filename))
rm(filename)
end
end
end
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 185 | @testset "basic" begin
@test get_E10(1.0) ≈ 0.3760301626167376u"eV"
@test get_E10(1u"nm") ≈ 0.3760301626167376u"eV"
@test get_E10(1u"nm", me=1.0) ≈ 0.3760301626167376u"eV"
end
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | code | 195 |
using ExtendedKronigPennyMatrix
using Test
using Unitful
@testset "ExtendedKronigPennyMatrix.jl" begin
include("Alternates.jl")
include("basic.jl")
# include("KronigPennyTest.jl")
end
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | docs | 1099 | # ExtendedKronigPennyMatrix
<p align="center">
<img src="example/Pavelich_Fig6.png" alt="Pavelich_Fig6" width="600px">
</p>
[](https://hsugawa8651.github.io/ExtendedKronigPennyMatrix.jl/stable)
[](https://hsugawa8651.github.io/ExtendedKronigPennyMatrix.jl/dev)
[](https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl/actions)
Construct a numerical Hamiltonian matrix of Kronig-Penny model
extended to arbitrary potentials
based on the paper written by Pavelich and Marsiglio.
> R. L. Pavelicha and F. Marsigliob,
> "The Kronig-Penney model extended to arbitrary potentials via numerical matrix mechanics," American Journal of Physics 83, 774 (2015).
> [DOI:10.1119/1.4923026](https://doi.org/10.1119/1.4923026),
> [ResearchGate](https://www.researchgate.net/publication/268227429_The_Kronig-Penney_model_extended_to_arbitrary_potentials_via_numerical_matrix_mechanics)
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | docs | 975 | ```@meta
CurrentModule = ExtendedKronigPennyMatrix
```
# ExtendedKronigPennyMatrix
Documentation for [ExtendedKronigPennyMatrix](https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl).
# Introduction
Construct a numerical Hamiltonian matrix $(h_{nm})$ of Kronig-Penny model
extended to arbitrary potentials
based on the paper written by Pavelich and Marsiglio.
```math
\sum_{m=1}^{\infty} h_{nm} c_{m} = ec_{n}
```
Energy is expressed in units of $E_{1}^{(0)}$.
```math
E_{1}^{(0)} = \dfrac{\pi^2\hbar^2}{2ma^2}
```
Refer the formulations to the following paper:
> R. L. Pavelicha and F. Marsigliob,
> "The Kronig-Penney model extended to arbitrary potentials via numerical matrix mechanics," American Journal of Physics 83, 774 (2015).
> [DOI:10.1119/1.4923026](https://doi.org/10.1119/1.4923026),
> [ResearchGate](https://www.researchgate.net/publication/268227429_The_Kronig-Penney_model_extended_to_arbitrary_potentials_via_numerical_matrix_mechanics)
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | docs | 1285 |
## Interface
### Alternates - iterator for quantum numbers
```@docs
Alternates
```
```@docs
Base.iterate(::Alternates, state::Int = 1)
```
### E10 - the ground state energy
```@docs
ExtendedKronigPennyMatrix.get_E10
```
### Potential
```@docs
ExtendedKronigPennyMatrix.Potential
```
### Model
```@docs
ExtendedKronigPennyMatrix.Model
```
```@docs
ExtendedKronigPennyMatrix.Model(pot::ExtendedKronigPennyMatrix.Potential,Ka::Float64,nmax::Int64=60)
```
## Finite Square Well
```@docs
FiniteSquareWell
```
```@docs
get_potential(::FiniteSquareWell)
```
```@docs
ExtendedKronigPennyMatrix.constuctMatrix(::Model{FiniteSquareWell})
```
## Simple Harmonic Oscillator
```@docs
SimpleHarmonicOscillator
```
```@docs
get_potential(::SimpleHarmonicOscillator)
```
```@docs
ExtendedKronigPennyMatrix.constuctMatrix(::Model{SimpleHarmonicOscillator})
```
## Inverted Harmonic Oscillator
```@docs
InvertedHarmonicOscillator
```
```@docs
get_potential(::InvertedHarmonicOscillator)
```
```@docs
ExtendedKronigPennyMatrix.constuctMatrix(::Model{InvertedHarmonicOscillator})
```
## LinearWell
```@docs
LinearWell
```
```@docs
get_potential(::LinearWell)
```
```@docs
ExtendedKronigPennyMatrix.constuctMatrix(::Model{LinearWell})
```
## Alphabetical Index
```@index
```
| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | docs | 1868 | # Usage
```@setup session1
using PyPlot
clf()
```
Here is a sample REPL session to draw a dispersion relationship by using this package.
First, construct `FiniteSquareWell` potential object.
```@repl session1
using ExtendedKronigPennyMatrix
v0=10;
rho=0.5 # b/a;
pot=FiniteSquareWell(v0, rho)
```
Use `get_function` method to acquire potential function.
```@repl session1
begin
pf = get_potential(pot)
a = 1
xs=-a:a/100:2a
plot(xs, pf.(xs), "k")
xlim(0,1)
xlabel(L"$x / a$")
ylabel(L"Energy / $E_0$")
title( L"$\rho =$"*string(rho))
savefig("plot1.png", dpi=150); nothing # hide
end
```

Define `Model` by calling its constructor.
```@repl session1
Ka=0.0 # wavenumber multiplied by a;
model=Model(pot, Ka)
```
The field `hnm` of model contains Hamiltonian matrix.
```@repl session1
typeof(model.hnm)
size(model.hnm)
model.hnm[1:5,1:5]
```
Use [`LinearAlgebra.eigvals`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.eigvals) method to compute its energy eigenvalues.
Refer to the [`LinearAlgebra`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/) standard library section in Julia documentation.
```@repl session1
using LinearAlgebra
evs=eigvals(model.hnm);
evs[1:3]
```
Draw dispersion curve by scanning `Ka` values between ``[-\pi, \pi]``.
```@repl session1
using PyPlot
clf()
begin
a = 1
xs=-a:a/100:2a
plot(xs .- 1/2, pf.(xs), "k") # Holizontally shift to centerize the potential well
cm=get_cmap("tab10")
for Ka in (-18:18)/18*π
model=Model(pot, Ka)
ev = eigvals(model.hnm)
for i in 1:5
plot(Ka/ π, ev[i], ".", color=cm(i-1))
end
end
xlim(-1,1)
ylim(-2,32)
xlabel(L"$Ka / \pi$")
ylabel(L"Energy / $E_0$")
title( L"$\rho =$"*string(rho))
savefig("plot2.png", dpi=150); nothing # hide
end
```

| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"MIT"
] | 0.6.1 | 685e90c65e72a1d27065be39fac48a2a587c86a4 | docs | 1720 | # 使い方
このパッケージを利用して、分散関係を描画する手順を紹介します。
JuliaのREPLを用いた例です。
最初に、`FiniteSquareWell` ポテンシャルを作成します。
```@repl session1
using ExtendedKronigPennyMatrix
v0=10;
rho=0.5 # b/a;
pot=FiniteSquareWell(v0, rho)
```
ポテンシャル形状は `get_function`関数で得られます。
ここでは `PyPlot` パッケージを用いて、プロットします。
```@repl session1
using PyPlot
clf()
begin
pf = get_potential(pot)
a = 1
xs=-a:a/100:2a
plot(xs, pf.(xs), "k")
xlim(0,1)
xlabel(L"$x / a$")
ylabel(L"Energy / $E_0$")
title( L"$\rho =$"*string(rho))
# savefig("plot1.png", dpi=150); nothing # hide
end
```

次に、`Model` オブジェクトを作成します。
```@repl session1
Ka=0.0 # wavenumber multiplied by a;
model=Model(pot, Ka)
```
このオブジェクトの `hnm` フィールドに、ハミルトニアン行列が計算されました。
```@repl session1
typeof(model.hnm)
size(model.hnm)
model.hnm[1:5,1:5]
```
Juliaの [`LinearAlgebra.eigvals`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/#LinearAlgebra.eigvals) メソッドを用いて、エネルギー固有値を計算します。
詳しくは、Juliaドキュメントの [`LinearAlgebra`](https://docs.julialang.org/en/v1/stdlib/LinearAlgebra/)
標準ライブラリを参照してください。
```@repl session1
using LinearAlgebra
evs=eigvals(model.hnm);
evs[1:3]
```
波数(と周期`a`の積)`Ka` を ``[-\pi, \pi]`` の範囲で走査して、分散関係を描きます。
```@repl session1
using PyPlot
clf()
begin
a = 1
xs=-a:a/100:2a
plot(xs .- 1/2, pf.(xs), "k") # Holizontally shift to centerize the potential well
cm=get_cmap("tab10")
for Ka in (-18:18)/18*π
model=Model(pot, Ka)
ev = eigvals(model.hnm)
for i in 1:5
plot(Ka/ π, ev[i], ".", color=cm(i-1))
end
end
xlim(-1,1)
ylim(-2,32)
xlabel(L"$Ka / \pi$")
ylabel(L"Energy / $E_0$")
title( L"$\rho =$"*string(rho))
savefig("plot2.png", dpi=150); nothing # hide
end
```

| ExtendedKronigPennyMatrix | https://github.com/hsugawa8651/ExtendedKronigPennyMatrix.jl.git |
|
[
"Apache-2.0"
] | 1.0.0 | b14d2173208683125949ec04e71004a3ddd7cadc | code | 11175 | # Copyright 2022 XXIV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module CocktailDB
using HTTP
using JSON
export search, searchbyLetter, searchingredient
export search_ingredient_byid, filter_byingredient
export categoriesfilter, glassesfilter, ingredientsfilter
export alcoholicfilter, random, search_byid, filter_byglass
export filter_byalcoholic, filter_bycategory
struct CocktailDBException <: Exception
msg
end
function _getrequest(endpoint::String)
try
request = HTTP.request("GET", "https://thecocktaildb.com/api/json/v1/1/$endpoint")
response = String(request.body)
return response
catch ex
if isa(ex, HTTP.ExceptionRequest.StatusError)
return String(ex.response.body)
else
rethrow(ex)
end
end
end
"""
Search cocktail by name
* `s` cocktail name
"""
function search(s::String)
try
response = _getrequest("search.php?s=$(HTTP.URIs.escapeuri(s))")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["drinks"]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
Search cocktails by first letter
* `c` cocktails letter
"""
function searchbyLetter(c::Char)
try
response = _getrequest("search.php?f=$c")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["drinks"]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
Search ingredient by name
* `s` ingredient name
"""
function searchingredient(s::String)
try
response = _getrequest("search.php?i=$(HTTP.URIs.escapeuri(s))")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["ingredients"] == nothing || length(json["ingredients"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["ingredients"][1]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
Search cocktail details by id
* `i` cocktail id
"""
function search_byid(i::Int)
try
response = _getrequest("lookup.php?i=$i")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["drinks"][1]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
Search ingredient by ID
* `i` ingredient id
"""
function search_ingredient_byid(i::Int)
try
response = _getrequest("lookup.php?iid=$i")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["ingredients"] == nothing || length(json["ingredients"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["ingredients"][1]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
Search a random cocktail
"""
function random()
try
response = _getrequest("random.php")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["drinks"][1]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
Filter by ingredient
* `s` ingredient name
"""
function filter_byingredient(s::String)
try
response = _getrequest("filter.php?i=$(HTTP.URIs.escapeuri(s))")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["drinks"]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
Filter by alcoholic
* `s` alcoholic or non alcoholic
"""
function filter_byalcoholic(s::String)
try
response = _getrequest("filter.php?a=$(HTTP.URIs.escapeuri(s))")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["drinks"]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
Filter by Category
* `s` category name
"""
function filter_bycategory(s::String)
try
response = _getrequest("filter.php?c=$(HTTP.URIs.escapeuri(s))")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["drinks"]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
Filter by Glass
* `s` glass name
"""
function filter_byglass(s::String)
try
response = _getrequest("filter.php?g=$(HTTP.URIs.escapeuri(s))")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
return json["drinks"]
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
List the categories filter
"""
function categoriesfilter()
try
response = _getrequest("list.php?c=list")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
array = String[]
for i in json["drinks"]
push!(array, i["strCategory"])
end
return array
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
List the glasses filter
"""
function glassesfilter()
try
response = _getrequest("list.php?g=list")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
array = String[]
for i in json["drinks"]
push!(array, i["strGlass"])
end
return array
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
List the ingredients filter
"""
function ingredientsfilter()
try
response = _getrequest("list.php?i=list")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
array = String[]
for i in json["drinks"]
push!(array, i["strIngredient1"])
end
return array
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
"""
List the alcoholic filter
"""
function alcoholicfilter()
try
response = _getrequest("list.php?a=list")
if length(response) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
json = JSON.parse(response)
if json["drinks"] == nothing || length(json["drinks"]) == 0
throw(CocktailDBException("Something went wrong: Empty response"))
end
array = String[]
for i in json["drinks"]
push!(array, i["strAlcoholic"])
end
return array
catch ex
if isa(ex, CocktailDBException)
rethrow(ex)
else
throw(CocktailDBException(sprint(showerror, ex)))
end
end
end
end # CocktailDB | CocktailDB | https://github.com/thechampagne/CocktailDB.jl.git |
|
[
"Apache-2.0"
] | 1.0.0 | b14d2173208683125949ec04e71004a3ddd7cadc | docs | 1296 | # CocktailDB.jl
[](https://github.com/thechampagne/CocktailDB.jl/releases/latest) [](https://github.com/thechampagne/CocktailDB.jl/blob/main/LICENSE)
CocktailDB API client for **Julia**.
### Download
**Julia pkg REPL**
write `]` to enter the pkg repl
```
add CocktailDB
```
**Julia REPL**
```
using Pkg; Pkg.add("CocktailDB")
```
### Example
```julia
using CocktailDB
for i in search("Vodka")
println(i["strDrink"])
end
```
### License
CocktailDB API client is released under the [Apache License 2.0](https://github.com/thechampagne/CocktailDB.jl/blob/main/LICENSE).
```
Copyright 2022 XXIV
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
``` | CocktailDB | https://github.com/thechampagne/CocktailDB.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 678 | using Documenter, SignalOperators, SignalBase
DocMeta.setdocmeta!(SignalBase, :DocTestSetup, :(using SignalBase; using SignalBase.Units); recursive=true)
makedocs(;
modules=[SignalOperators, SignalBase],
format=Documenter.HTML(),
pages=[
"Home" => "index.md",
"Manual" => "manual.md",
"Custom Signals" => "custom_signal.md",
"Custom Sinks" => "custom_sink.md",
"Reference" => "reference.md",
],
repo="https://github.com/haberdashPI/SignalOperators.jl/blob/{commit}{path}#L{line}",
sitename="SignalOperators.jl",
authors="David Little",
)
deploydocs(;
repo="github.com/haberdashPI/SignalOperators.jl",
)
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 1414 | using .AxisArrays
function SignalTrait(::Type{<:AxisArray{T,N}}) where {T,N}
if N ∈ [1,2]
IsSignal{T,Float64,Int}()
else
error("Array must have 1 or 2 dimensions to be treated as a signal.")
end
end
function framerate(x::AxisArray)
times = axisvalues(AxisArrays.axes(x,Axis{:time}))[1]
inHz(1/step(times))
end
const WithAxes{Tu} = AxisArray{<:Any,<:Any,<:Any,Tu}
const AxTimeD1 = Union{
WithAxes{<:Tuple{Axis{:time}}},
WithAxes{<:Tuple{Axis{:time},<:Any}}}
const AxTimeD2 = WithAxes{<:Tuple{<:Any,Axis{:time}}}
const AxTime = Union{AxTimeD1,AxTimeD2}
nframes(x::AxisArray) = length(AxisArrays.axes(x,Axis{:time}))
function nchannels(x::AxisArray)
chdim = axisdim(x,Axis{:time}) == 1 ? 2 : 1
size(x,chdim)
end
sampletype(x::AxisArray) = eltype(x)
function Signal(x::AxisArray,fs::Union{Missing,Number}=missing)
if !isconsistent(fs,framerate(x))
error("Signal expected to have frame rate of $(inHz(fs)) Hz.")
else
x
end
end
timeslice(x::AxTimeD1,indices) = view(x,indices,:)
timeslice(x::AxTimeD2,indices) = PermutedDimsArray(view(x,:,indices),(2,1))
function initsink(x,::Type{<:AxisArray})
times = Axis{:time}(range(0s,length=nframes(x),step=float(s/framerate(x))))
channels = Axis{:channel}(1:nchannels(x))
AxisArray(initsink(x,Array),times,channels)
end
AxisArrays.AxisArray(x::AbstractSignal) = sink(x,AxisArray) | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 1338 | using .DimensionalData
using .DimensionalData: Time, @dim
@dim SigChannel "Signal Channel"
export SigChannel, Time
function Signal(x::AbstractDimensionalArray,::IsSignal,
fs::Union{Missing,Number}=missing)
if !isconsistent(fs,framerate(x))
error("Signal expected to have frame rate of $fs Hz.")
else
x
end
end
hastime(::Type{T}) where T <: Tuple = any(@λ(_ <: Time),T.types)
function SignalTrait(::Type{<:AbstractDimensionalArray{T,N,Dim}}) where {T,N,Dim}
if hastime(Dim)
IsSignal{T,Float64,Int}()
else
error("Dimensional array must have a `Time` dimension.")
end
end
nframes(x::AbstractDimensionalArray) = length(dims(x,Time))
sampletype(x::AbstractDimensionalArray) = eltype(x)
AbstractVecOrMat
nchannels(x::AbstractDimensionalArray) =
prod(length,setdiff(dims(x),(dims(x,Time),)))
framerate(x::AbstractDimensionalArray) =
1/inseconds(Float64,step(dims(x,Time).val))
timeslice(x::AbstractDimensionalArray,indices) = view(x,Time(indices))
function initsink(x,::Type{<:DimensionalArray})
times = Time(range(0s,length=nframes(x),
step=1s/convert(Float64,framerate(x))))
channels = SigChannel(1:nchannels(x))
DimensionalArray(initsink(x,Array),(times,channels))
end
DimensionalData.DimensionalArray(x::AbstractSignal) = sink(x,DimensionalArray) | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 231 | using .FixedPointNumbers
function Pad(x,p::typeof(one))
if isknowninf(nframes(x))
x
elseif sampletype(x) <: Fixed
x |> ToEltype(float(sampletype(x))) |> Pad(p)
else
PaddedSignal(x,p)
end
end | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 419 | using .LibSndFile
@info "Loading LibSndFile backend for SignalOperators."
for fmt in LibSndFile.supported_formats
if fmt != DataFormat{:WAV}
@eval function load_signal(::$fmt,filename,fs=missing)
Signal(load(filename),fs)
end
@eval function save_signal(::$fmt,filename,x)
data,sr = sink(x,Tuple)
save(filename,data,samplerate=sr)
end
end
end | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 664 | using .SampledSignals: SampleBuf
function Signal(x::SampleBuf,fs::Union{Missing,Number}=missing)
if !isconsistent(fs,framerate(x))
error("Signal expected to have frame rate of $(inHz(fs)) Hz.")
else
x
end
end
SignalTrait(::Type{<:SampleBuf{T}}) where T = IsSignal{T,Float64,Int}()
nframes(x::SampleBuf) = size(x,1)
nchannels(x::SampleBuf) = size(x,2)
framerate(x::SampleBuf) = SampledSignals.samplerate(x)
sampletype(x::SampleBuf) = eltype(x)
timeslice(x::SampleBuf,indices) = view(x,indices,:)
initsink(x,::Type{<:SampleBuf}) = SampleBuf(initsink(x,Array),framerate(x))
SampledSignals.SampleBuf(x::AbstractSignal) = sink(x,SampleBuf) | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 1855 | module SignalOperators
using Requires, DSP, LambdaFn, Unitful, Compat, PrettyPrinting, FillArrays,
FileIO
using PrettyPrinting: best_fit, indent, list_layout, literal, pair_layout
using SignalBase
import SignalBase: nframes, nchannels, sampletype, framerate, duration
using SignalBase.Units: FrameQuant
export nframes, nchannels, sampletype, framerate, duration
module Units
using SignalBase.Units
export kframes, frames, Hz, s, kHz, ms, dB, °, rad
end
using .Units
@static if VERSION ≤ v"1.3"
# patch in fix for clamp from Julia 1.3
clamp(x,lo,hi) = max(min(x,hi),lo)
clamp(::Missing,l,h) = missing
end
include("inflen.jl")
include("util.jl")
# signal definition
include("signal.jl")
include("sink.jl")
include("wrapping.jl")
# types of signals
include("numbers.jl")
include("arrays.jl")
include("functions.jl")
# various operators (transforms one signal into another)
include("cutting.jl")
include("appending.jl")
include("padding.jl")
include("filters.jl")
include("mapsignal.jl")
include("reformatting.jl")
include("ramps.jl")
function __init__()
# TODO: use @require for AxisArrays
@require WAV = "8149f6b0-98f6-5db9-b78f-408fbbb8ef88" begin
include("WAV.jl")
end
@require FixedPointNumbers = "53c48c17-4a7d-5ca2-90c5-79b7896eea93" begin
include("FixedPointNumbers.jl")
end
@require AxisArrays = "39de3d68-74b9-583c-8d2d-e117c070f3a9" begin
include("AxisArrays.jl")
end
# extensions
@require SampledSignals = "bd7594eb-a658-542f-9e75-4c4d8908c167" begin
include("SampledSignals.jl")
end
@require LibSndFile = "b13ce0c6-77b0-50c6-a2db-140568b8d1a5" begin
include("LibSndFile.jl")
end
@require DimensionalData = "0703355e-b756-11e9-17c0-8b28908087d0" begin
include("DimensionalData.jl")
end
end
end # module
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 418 | using .WAV
function save_signal(::DataFormat{:WAV},filename,x)
data,fs = sink(x,Tuple)
wavwrite(data,filename,Fs=round(Int,fs))
end
function load_signal(::DataFormat{:WAV},x,fs=missing)
x,_fs = wavread(x)
if !isconsistent(fs,_fs)
error("Expected file $x to have framerate $fs. If you wish to convert",
" the frame rate, you can use `ToFramerate`.")
end
Signal(x,_fs)
end | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 3354 | export Append, Prepend, append, prepend
struct AppendSignals{Si,Sis,T,L} <: WrappedSignal{Si,T}
signals::Sis
len::L
end
SignalTrait(x::Type{T}) where {Si,T <: AppendSignals{Si}} =
SignalTrait(x,SignalTrait(Si))
function SignalTrait(x::Type{<:AppendSignals{Si,Rst,T,L}},
::IsSignal{T,Fs}) where {Si,Rst,T,L,Fs}
IsSignal{T,Fs,L}()
end
child(x::AppendSignals) = x.signals[1]
nframes_helper(x::AppendSignals) = x.len
duration(x::AppendSignals) = sum(duration.(x.signals))
root(x::AppendSignals) = reduce(mergeroot,root.(x.signals))
"""
Append(x,y,...)
Append a series of signals, one after the other.
"""
Append(y) = x -> Append(x,y)
"""
Prepend(x,y,...)
Prepend the series of signals: `Prepend(xs...)` is equivalent to
`Append(reverse(xs)...)`.
"""
Prepend(x) = y -> Append(x,y)
Prepend(x,y,rest...) = Append(reverse((x,y,rest...))...)
"""
append(x,y,...)
Equivalent to `sink(Append(x,y,...))`
## See also
[`Append`](@ref)
"""
append(xs...) = sink(Append(xs...))
"""
prepend(x,y,...)
Equivalent to `sink(Prepend(x,y,...))`
## See also
[`Prepend`](@ref)
"""
prepend(xs...) = sink(Prepend(xs...))
function Append(xs...)
xs = Uniform(xs,channels=true)
if any(isknowninf ∘ nframes,xs[1:end-1])
error("Cannot Append to the end of an infinite signal")
end
El = promote_type(sampletype.(xs)...)
xs = map(xs) do x
if sampletype(x) != El
ToEltype(x,El)
else
x
end
end
len = any(isknowninf ∘ nframes,xs) ? inflen : sum(nframes,xs)
AppendSignals{typeof(xs[1]),typeof(xs),El,typeof(len)}(xs, len)
end
ToFramerate(x::AppendSignals,s::IsSignal{<:Any,<:Number},c::ComputedSignal,fs;blocksize) =
Append(ToFramerate.(x.signals,fs;blocksize=blocksize)...)
ToFramerate(x::AppendSignals,s::IsSignal{<:Any,Missing},__ignore__,fs;
blocksize) = Append(ToFramerate.(x.signals,fs;blocksize=blocksize)...)
struct AppendBlock{S,C}
signal::S
child::C
k::Int
end
child(x::AppendBlock) = x.child
nframes(x::AppendBlock) = nframes(x.child)
@Base.propagate_inbounds frame(::AppendSignals,x::AppendBlock,i) =
frame(x.signal,x.child,i)
function nextblock(x::AppendSignals,maxlen,skip)
child = nextblock(x.signals[1],maxlen,skip)
advancechild(x,maxlen,skip,1,child)
end
function nextblock(x::AppendSignals,maxlen,skip,block::AppendBlock)
childblock = nextblock(x.signals[block.k],maxlen,skip,child(block))
advancechild(x,maxlen,skip,block.k,childblock)
end
function advancechild(x::AppendSignals,maxlen,skip,k,childblock)
K = length(x.signals)
while k < K && isnothing(childblock)
k += 1
childblock = nextblock(x.signals[k],maxlen,skip)
end
if !isnothing(childblock)
AppendBlock(x.signals[k],childblock,k)
end
end
Base.show(io::IO,::MIME"text/plain",x::AppendSignals) = pprint(io,x)
function PrettyPrinting.tile(x::AppendSignals)
if length(x.signals) == 2
child = signaltile(x.signals[1])
operate = literal("Append(") * signaltile(x.signals[2]) * literal(")") |
literal("Append(") / indent(4) * signaltile(x.signals[2]) / literal(")")
tilepipe(child,operate)
else
list_layout(map(signaltile,x.signals),prefix="Append",sep=",",sep_brk=",")
end
end
signaltile(x::AppendSignals) = PrettyPrinting.tile(x)
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 4982 | export sink
errordim() = error("To treat an array as a signal it must have 1 or 2 dimensions")
# signals can be arrays with some metadata
"""
## Arrays
Any array can be interpreted as a signal. By default the first dimension is
time, the second channels and their frame rate is a missing value. If you
pass a non-missin gframerate, and the array currently has a missing frame
rate a `Tuple` value will be returned (see "Array & Number" below).
If you specify a non-missing frame rate to an array type with a missing frame
rate the return value will be a Tuple (see Array & Number
section below). Some array types change this default behavior, as follows.
!!! warning
Arrays of more than two dimensions are not currently supported.
- [`AxisArrays`](https://github.com/JuliaArrays/AxisArrays.jl), if they have an
axis labeled `time` and one or zero additional axes, can be treated as a
signal. The time dimension must be represented using on object with the `step`
function defined (e.g. any `AbstractRange` object).
- [`SampleBuf`](https://github.com/JuliaAudio/SampledSignals.jl) objects are
also properly interpreted as signals, as per the conventions employed for its
package.
- [`DimensionalArrays`](https://github.com/rafaqz/DimensionalData.jl) can be
treated as signals if there is a `Time` dimension, which must be represented
using an object with the `step` function defined (e.g. `AbstractRange`) and
zero or one additional dimensions (treated as channels)
"""
function Signal(x::AbstractArray,fs::Union{Missing,Number}=missing)
if ismissing(fs)
if ndims(x) ∈ [1,2]
return x
else
errordim()
end
else
(x,Float64(inHz(fs)))
end
end
ToFramerate(x::AbstractArray,::IsSignal{<:Any,Missing},::DataSignal,fs::Number;blocksize) =
Signal(x,fs)
ToFramerate(x::AbstractArray,s::IsSignal{<:Any,<:Number},::DataSignal,fs::Number;blocksize) =
__ToFramerate__(x,s,fs,blocksize)
function SignalTrait(::Type{<:AbstractArray{T,N}}) where{T,N}
if N ∈ [1,2]
IsSignal{T,Missing,Int}()
else
error("Array must have 1 or 2 dimensions to be treated as a signal.")
end
end
nframes(x::AbstractVecOrMat) = size(x,1)
nchannels(x::AbstractVecOrMat) = size(x,2)
sampletype(x::AbstractVecOrMat) = eltype(x)
framerate(x::AbstractVecOrMat) = missing
timeslice(x::AbstractArray,indices) = view(x,indices,:)
"""
## Array & Number
A tuple of an array and a number can be interepted as a signal. The first
dimension is time, the second channels, and the number determines the frame
rate (in Hertz).
"""
function Signal(x::Tuple{<:AbstractArray,<:Number},
fs::Union{Missing,Number}=missing)
if !isconsistent(fs,x[2])
error("Signal expected to have frame rate of $(inHz(fs)) Hz.")
else
x
end
end
function SignalTrait(::Type{<:Tuple{<:AbstractArray{T,N},<:Number}}) where {T,N}
if N ∈ [1,2]
IsSignal{T,Float64,Int}()
else
error("Array must have 1 or 2 dimensions to be treated as a signal.")
end
end
nframes(x::Tuple{<:AbstractVecOrMat,<:Number}) = size(x[1],1)
nchannels(x::Tuple{<:AbstractVecOrMat,<:Number}) = size(x[1],2)
framerate(x::Tuple{<:AbstractVecOrMat,<:Number}) = x[2]
sampletype(x::Tuple{<:AbstractVecOrMat,<:Number}) = eltype(x[1])
timeslice(x::Tuple{<:AbstractVecOrMat,<:Number},indices) = view(x[1],indices,:)
function nextblock(x::Tuple{<:AbstractVecOrMat,<:Number},maxlen,skip,
block=ArrayBlock([],0))
nextblock(x[1],maxlen,skip,block)
end
"""
ArrayBlock{A,S}(data::A,state::S)
A straightforward implementation of blocks as an array and a custom state.
The array allows a generic implementation of [`nframes`](@ref) and
[`SignalOperators.frame`](@ref). The fields of this struct are `data` and
`state`.
[Custom signals](@ref custom_signals) can return an `ArrayBlock` from
[`SignalOperators.nextblock`](@ref) to allow for fallback implementations of
[`nframes`](@ref) and [`SignalOperators.frame`](@ref).
"""
struct ArrayBlock{A,S}
data::A
state::S
end
nframes(block::ArrayBlock) = size(block.data,1)
@Base.propagate_inbounds frame(x,block::ArrayBlock,i) = view(block.data,i,:)
function nextblock(x::AbstractArray,maxlen,skip,block = ArrayBlock([],0))
offset = block.state + nframes(block)
if offset < nframes(x)
len = min(maxlen,nframes(x)-offset)
ArrayBlock(timeslice(x,offset .+ (1:len)),offset)
end
end
function signaltile(x)
io = IOBuffer()
signalshow(io,x)
literal(String(take!(io)))
end
function signalshow(io,x::AbstractArray,shownfs=false)
p = parent(x)
if p === x
show(IOContext(io,:displaysize=>(1,30),:limit=>true),
MIME("text/plain"),x)
!shownfs && show_fs(io,x)
else
signalshow(io,p,true)
show_fs(io,x)
end
end
function signalshow(io,x::Tuple{<:AbstractArray,<:Number},shownfs=false)
signalshow(io,x[1],true)
show_fs(io,x)
end
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 6371 | export Until, After, until, after, Window, window
################################################################################
# cutting signals
struct CutApply{Si,Tm,K,T} <: WrappedSignal{Si,T}
signal::Si
time::Tm
end
CutApply(signal::T,time,fn) where T = CutApply(signal,SignalTrait(T),time,fn)
CutApply(signal::Si,::IsSignal{T},time::Tm,kind::K) where {Si,Tm,K,T} =
CutApply{Si,Tm,K,T}(signal,time)
CutMethod(x::CutApply) = CutMethod(x.signal)
SignalTrait(::Type{T}) where {Si,T <: CutApply{Si}} =
SignalTrait(T,SignalTrait(Si))
function SignalTrait(::Type{<:CutApply{Si,Tm,K}},::IsSignal{T,Fs,L}) where
{Si,Tm,K,T,Fs,L}
if Fs <: Missing
IsSignal{T,Missing,Missing}()
elseif K <: Val{:Until}
IsSignal{T,Float64,Int}()
elseif K <: Val{:After}
IsSignal{T,Float64,L}()
else
error("Unexpected cut apply type $K")
end
end
child(x::CutApply) = x.signal
resolvelen(x::CutApply) = inframes(Int,maybeseconds(x.time),framerate(x))
const UntilApply{S,T} = CutApply{S,T,Val{:Until}}
const AfterApply{S,T} = CutApply{S,T,Val{:After}}
"""
Window(x;from,to)
Window(x;at,width)
Extract a window of time from a signal by specifying either the start and stop
point of the window (`from` and `to`) or the center and width (`at` and `wdith`)
of the window.
"""
Window(;kwds...) = x -> Window(x;kwds...)
function Window(x;at=nothing,width=nothing,from=nothing,to=nothing)
if isnothing(at) != isnothing(width) ||
isnothing(from) != isnothing(to) ||
isnothing(at) == isnothing(from)
error("`Window` must either use the two keywords `at` and `width` OR",
"the two keywords `from` and `to`.")
end
after,until = isnothing(from) ? (at-width/2,width) : from,to-from
x |> After(after) |> Until(until)
end
"""
window(x;from,to)
window(x;at,width)
Equivalent to `sink(Window(...))`.
## See also
[`Window`](@ref)
"""
window(x;kwds...) = sink(Window(x;kwds...))
"""
Until(x,time)
Create a signal of all frames of `x` up until and including `time`.
"""
Until(time) = x -> Until(x,time)
Until(x,time) = CutApply(Signal(x),time,Val{:Until}())
"""
until(x,time)
Equivalent to `sink(Until(x,time))`
## See also
[`Until`](@ref)
"""
until(x,time) = sink(Until(x,time))
"""
After(x,time)
Create a signal of all frames of `x` after `time`.
!!! note
If you use `frames` as the unit here, keep in mind that
because this returns all frames *after* the given index,
the result is effectively zero indexed:
i.e. `all(sink(After(1:10,1frames)) .== 2:10)`
"""
After(time) = x -> After(x,time)
After(x,time) = CutApply(Signal(x),time,Val{:After}())
"""
after(x,time)
Equivalent to `sink(After(x,time))`
## See also
[`After`](@ref)
"""
after(x,time) = sink(After(x,time))
Base.show(io::IO,::MIME"text/plain",x::CutApply) = pprint(io,x)
function PrettyPrinting.tile(x::CutApply)
operate = literal(string(cutname(x),"(",(x.time),")"))
tilepipe(signaltile(x.signal),operate)
end
signaltile(x::CutApply) = PrettyPrinting.tile(x)
cutname(x::UntilApply) = "Until"
cutname(x::AfterApply) = "After"
nframes_helper(x::UntilApply) = min(nframes_helper(x.signal),max(0,resolvelen(x)))
duration(x::UntilApply) =
min(duration(x.signal),max(0,inseconds(Float64,maybeseconds(x.time),framerate(x))))
nframes_helper(x::AfterApply) = clamp(nframes_helper(x.signal) - resolvelen(x),0,nframes_helper(x.signal))
duration(x::AfterApply) =
clamp(duration(x.signal) - inseconds(Float64,maybeseconds(x.time),framerate(x)),0,duration(x.signal))
EvalTrait(x::AfterApply) = DataSignal()
stretchtime(t,scale) = t
stretchtime(t::FrameQuant,scale::Number) = inframes(Int,t*scale)*frames
function ToFramerate(x::UntilApply,s::IsSignal{<:Any,<:Number},c::ComputedSignal,fs;blocksize)
t = stretchtime(x.time,fs/framerate(x))
CutApply(ToFramerate(child(x),fs;blocksize=blocksize),t,
Val{:Until}())
end
function ToFramerate(x::CutApply{<:Any,<:Any,K},s::IsSignal{<:Any,Missing},
__ignore__,fs; blocksize) where K
t = stretchtime(x.time,fs/framerate(x))
CutApply(ToFramerate(child(x),fs;blocksize=blocksize),t,K())
end
struct CutBlock{C}
n::Int
child::C
end
child(x::CutBlock) = x.child
function nextblock(x::AfterApply,maxlen,skip)
if resolvelen(x) == 0
childblock = nextblock(child(x),maxlen,false)
CutBlock(0,childblock)
else
len = max(0,resolvelen(x))
childblock = nextblock(child(x),len,true)
skipped = nframes(childblock)
while !isnothing(childblock) && skipped < len
childblock = nextblock(child(x),min(maxlen,len - skipped),true,
childblock)
isnothing(childblock) && break
skipped += nframes(childblock)
end
if skipped < len
io = IOBuffer()
signalshow(io,child(x))
sig_string = String(take!(io))
error("Signal is too short to skip $(maybeseconds(x.time)): ",
sig_string)
end
@assert skipped == len
nextblock(x,maxlen,skip,CutBlock(0,childblock))
end
end
function nextblock(x::AfterApply,maxlen,skip,block::CutBlock)
childblock = nextblock(child(x),maxlen,skip,child(block))
if !isnothing(childblock)
CutBlock(0,childblock)
end
end
nextblock(x::AfterApply,maxlen,skip,block::CutBlock{Nothing}) = nothing
function timeslice(x::AfterApply,indices)
from = clamp(resolvelen(x),0,nframes(x.signal))+1
to = nframes(x.signal)
timeslice(x.signal,(from:to)[indices])
end
initblock(x::UntilApply) = CutBlock(resolvelen(x),nothing)
function nextblock(x::UntilApply,len,skip,block::CutBlock=initblock(x))
nextlen = block.n - nframes(block)
if nextlen > 0
childblock = !isnothing(child(block)) ?
nextblock(child(x),min(nextlen,len),skip,child(block)) :
nextblock(child(x),min(nextlen,len),skip)
if !isnothing(childblock)
CutBlock(nextlen,childblock)
end
end
end
function timeslice(x::UntilApply,indices)
to = clamp(resolvelen(x),0,nframes(x.signal))
timeslice(x.signal,(1:to)[indices])
end
nframes(x::CutBlock) = nframes(child(x))
nframes(x::CutBlock{Nothing}) = 0
@Base.propagate_inbounds frame(x::CutApply,block::CutBlock,i) =
frame(child(x),child(block),i) | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 27 |
# signals can be filenames | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 11031 | export Normpower, Filt, normpower, filt, Lowpass, Bandpass, Bandstop, Highpass
const default_blocksize = 2^12
struct FilterFn{D,M,A}
design::D
method::M
args::A
end
(fn::FilterFn)(fs) =
digitalfilter(fn.design(inHz.(fn.args)...,fs=inHz(fs)),fn.method)
filterfn(design,method,args...) = FilterFn(design,method,args)
function nyquist_check(x,hz)
if !ismissing(framerate(x)) && inHz(hz) ≥ 0.5framerate(x)
error("The frequency $(hz) cannot be represented at a sampling rate ",
"of $(framerate(x)) Hz. Increase the frame rate or lower ",
"the frequency.")
end
end
"""
Filt(x,::Type{<:FilterType},bounds...;method=Butterworth(order),order=5,
blocksize=4096)
Apply the given filter type (e.g. `Lowpass`) using the given method to design
the filter coefficients. The type is specified as per the types from
[`DSP`](https://github.com/JuliaDSP/DSP.jl)
Filt(x,h;[blocksize=4096])
Apply the given digital filter `h` (from
[`DSP`](https://github.com/JuliaDSP/DSP.jl)) to signal `x`.
## Blocksize
Blocksize determines the size of the buffer used when computing intermediate
values of the filter. It need not normally be adjusted, though changing it
can alter how efficient filter application is.
!!! note
The non-lazy version of `Filt` is `filt` from the
[`DSP`](https://github.com/JuliaDSP/DSP.jl) package. Proper methods have
been defined such that it should be possible to call `filt` on a signal
and get a signal back.
The argument order for `filt` follows a different convention, with `x`
coming after the filter specification. In contrast, `Filt` uses the
convention of keeping `x` as the first argument to make piping possible.
"""
Filt(::Type{T},bounds...;kwds...) where T <: DSP.Filters.FilterType =
x -> Filt(x,T,bounds...;kwds...)
function Filt(x,::Type{F},bounds...;blocksize=default_blocksize,order=5,
method=Butterworth(order)) where F <: DSP.Filters.FilterType
nyquist_check.(Ref(x),bounds)
Filt(x, filterfn(F,method,bounds...),blocksize=blocksize)
end
Filt(h;kwds...) = x -> Filt(x,h;kwds...)
Filt(x,fn::Union{FilterFn,Function};kwds...) = Filt(x,SignalTrait(x),fn;kwds...)
Filt(x,h;kwds...) = Filt(x,SignalTrait(x),RawFilterFn(h);kwds...)
Filt(x,::Nothing,args...;kwds...) = Filt(Signal(x),args...;kwds...)
function DSP.filt(
b::Union{AbstractVector, Number}, a::Union{AbstractVector, Number},
x::AbstractSignal,
si::AbstractArray{S} = DSP._zerosi(b,a,T)) where {T,S}
R = promote_type(eltype(b), eltype(a), T, S)
data = initsink(ToEltype(x,R),refineroot(root(x)))
filt!(data,b,a,sink(x,Array),si)
data
end
function DSP.filt!(
data::AbstractArray,
b::Union{AbstractVector, Number}, a::Union{AbstractVector, Number},
x::AbstractSignal,
si::AbstractArray{S} = DSP._zerosi(b,a,T)) where {T,S}
filt!(data,b,a,sink(x,Array),si)
end
struct RawFilterFn{H}
h::H
end
(fn::RawFilterFn)(fs) = deepcopy(fn.h)
resolve_filter(x) = DSP.Filters.DF2TFilter(x)
resolve_filter(x::FIRFilter) = x
Filt(x,s::IsSignal,fn;blocksize=default_blocksize,newfs=framerate(x)) =
FilteredSignal(x,fn,blocksize,newfs)
struct FilteredSignal{T,Si,Fn,Fs} <: WrappedSignal{Si,T}
signal::Si
fn::Fn
blocksize::Int
framerate::Fs
end
function FilteredSignal(signal::Si,fn::Fn,blocksize::Number,newfs::Fs) where {Si,Fn,Fs}
T = float(sampletype(signal))
FilteredSignal{T,Si,Fn,Fs}(signal,fn,Int(blocksize),newfs)
end
SignalTrait(x::Type{T}) where {S,T <: FilteredSignal{<:Any,S}} =
SignalTrait(x,SignalTrait(S))
SignalTrait(x::Type{<:FilteredSignal{T}},::IsSignal{<:Any,Fs,L}) where {T,Fs,L} =
IsSignal{T,Fs,L}()
child(x::FilteredSignal) = x.signal
framerate(x::FilteredSignal) = x.framerate
EvalTrait(x::FilteredSignal) = ComputedSignal()
Base.show(io::IO,::MIME"text/plain",x::FilteredSignal) = pprint(io,x)
function PrettyPrinting.tile(x::FilteredSignal)
child = signaltile(x.signal)
operate = literal(filterstring(x.fn))
tilepipe(child,operate)
end
signaltile(x::FilteredSignal) = PrettyPrinting.tile(x)
function filterstring(fn::FilterFn)
if isempty(fn.args)
string("Filt(",designstring(fn.design),")")
else
string("Filt(",designstring(fn.design),",",
join(string.(fn.args),","),")")
end
end
filterstring(x) = string("Filt(",string(x),")")
function filtertring(fn::RawFilterFn)
io = IOBuffer()
show(IOContext(io,:displaysize=>(1,30),:limit=>true),
MIME("text/plain"),x)
string("Filt(",String(take!(io)),")")
end
designstring(::Type{<:Lowpass}) = "Lowpass"
designstring(::Type{<:Highpass}) = "Highpass"
designstring(::Type{<:Bandpass}) = "Bandpass"
designstring(::Type{<:Bandstop}) = "Bandstop"
function ToFramerate(x::FilteredSignal,s::IsSignal{<:Any,<:Number},::ComputedSignal,fs;
blocksize)
# is this a non-resampling filter?
if framerate(x) == framerate(x.signal)
FilteredSignal(ToFramerate(x.signal,fs,blocksize=blocksize),
x.fn,x.blocksize,fs)
else
ToFramerate(x.signal,s,DataSignal(),fs,blocksize=blocksize)
end
end
function ToFramerate(x::FilteredSignal,::IsSignal{<:Any,Missing},__ignore__,fs;
blocksize)
FilteredSignal(ToFramerate(x.signal,fs,blocksize=blocksize),
x.fn,x.blocksize,fs)
end
function nframes_helper(x::FilteredSignal)
if ismissing(framerate(x.signal))
missing
elseif framerate(x) == framerate(x.signal)
nframes_helper(x.signal)
else
ceil(Int,nframes_helper(x.signal)*framerate(x)/framerate(x.signal))
end
end
struct FilterBlock{H,S,T,C}
len::Int
last_output_index::Int
available_output::Int
last_input_offset::Int
last_output_offset::Int
hs::Vector{H}
input::Matrix{S}
output::Matrix{T}
child::C
end
child(x::FilterBlock) = x.child
init_length(x::FilteredSignal,h) = min(nframes(x),x.blocksize)
function init_length(x::FilteredSignal{<:Any,<:Any,<:ResamplerFn},h)
n = trunc(Int,max(1,min(nframes(x),x.blocksize) / x.fn.ratio))
out = DSP.outputlength(h,n)
if out > 0
n
else
n = trunc(Int,max(1,x.blocksize / x.fn.ratio))
out = DSP.outputlength(h,n)
if out > 0
n
else
error("Blocksize is too small for this resampling filter.")
end
end
end
struct UndefChild
end
const undef_child = UndefChild()
function FilterBlock(x::FilteredSignal)
hs = [resolve_filter(x.fn(framerate(x))) for _ in 1:nchannels(x.signal)]
len = init_length(x,hs[1])
input = Array{sampletype(x.signal)}(undef,len,nchannels(x))
output = Array{sampletype(x)}(undef,x.blocksize,nchannels(x))
FilterBlock(0,0,0, 0,0, hs,input,output,undef_child)
end
nframes(x::FilterBlock) = x.len
@Base.propagate_inbounds frame(::FilteredSignal,x::FilterBlock,i) =
view(x.output,i+x.last_output_index,:)
inputlength(x,n) = n
outputlength(x,n) = n
inputlength(x::DSP.Filters.Filter,n) = DSP.inputlength(x,n)
outputlength(x::DSP.Filters.Filter,n) = DSP.outputlength(x,n)
function nextblock(x::FilteredSignal,maxlen,skip,
block::FilterBlock=FilterBlock(x))
last_output_index = block.last_output_index + block.len
if nframes_helper(x) == last_output_index
return nothing
end
# check for leftover frames in the output buffer
if last_output_index < block.available_output
len = min(maxlen, block.available_output - last_output_index)
FilterBlock(len, last_output_index, block.available_output,
block.last_input_offset, block.last_output_offset, block.hs,
block.input, block.output, block.child)
# otherwise, generate more filtered output
else
@assert !isnothing(child(block))
psig = Pad(x.signal,zero)
childblock = !isa(child(block), UndefChild) ?
nextblock(psig,size(block.input,1),false,child(block)) :
nextblock(psig,size(block.input,1),false)
childblock = sink!(block.input,psig,SignalTrait(psig),childblock)
last_input_offset = block.last_input_offset + size(block.input,1)
# filter the input into the output buffer
out_len = outputlength(block.hs[1],size(block.input,1))
if out_len ≤ 0
error("Unexpected non-positive output length!")
end
for ch in 1:size(block.output,2)
filt!(view(block.output,1:out_len,ch),block.hs[ch],
view(block.input,:,ch))
end
last_output_offset = block.last_output_offset + out_len
FilterBlock(min(maxlen,out_len), 0,
out_len, last_input_offset, last_output_offset, block.hs,
block.input, block.output, childblock)
end
end
# TODO: create an online version of Normpower?
# TODO: this should be excuted lazzily to allow for unkonwn framerates
struct NormedSignal{Si,T} <: WrappedSignal{Si,T}
signal::Si
end
child(x::NormedSignal) = x.signal
nframes_helper(x::NormedSignal) = nframes_helper(x.signal)
NormedSignal(x::Si) where Si = NormedSignal{Si,float(sampletype(x))}(x)
SignalTrait(x::Type{T}) where {S,T <: NormedSignal{S}} =
SignalTrait(x,SignalTrait(S))
SignalTrait(x::Type{<:NormedSignal{<:Any,T}},::IsSignal{<:Any,Fs,L}) where {T,Fs,L} =
IsSignal{T,Fs,L}()
function ToFramerate(x::NormedSignal,s::IsSignal{<:Any,<:Number},
::ComputedSignal,fs;blocksize)
NormedSignal(ToFramerate(x.signal,fs,blocksize=blocksize))
end
function ToFramerate(x::NormedSignal,::IsSignal{<:Any,Missing},
__ignore__,fs;blocksize)
NormedSignal(ToFramerate(x.signal,fs,blocksize=blocksize))
end
struct NormedBlock{A}
offset::Int
len::Int
vals::A
end
nframes(x::NormedBlock) = x.len
@Base.propagate_inbounds frame(::NormedSignal,x::NormedBlock,i) =
view(x.vals,i,:)
function initblock(x::NormedSignal)
if isknowninf(nframes(x))
error("Cannot normalize an infinite-length signal. Please ",
"use `Until` to take a prefix of the signal")
end
vals = Array{sampletype(x)}(undef,nframes(x),nchannels(x))
sink!(vals, x.signal)
rms = sqrt(mean(x -> float(x)^2,vals))
vals ./= rms
S,V = typeof(x), typeof(vals)
NormedBlock(0,0,vals)
end
function nextblock(x::NormedSignal,maxlen,skip,block::NormedBlock=initblock(x))
len = min(maxlen,nframes(x) - block.offset)
NormedBlock(block.offset + block.len, len, block.vals)
end
"""
Normpower(x)
Return a signal with normalized power. That is, divide all frames by the
root-mean-squared value of the entire signal.
"""
function Normpower(x)
x = Signal(x)
NormedSignal{typeof(x),float(sampletype(x))}(Signal(x))
end
"""
normpower(x)
Equivalent to `sink(Normpower(x))`
## See also
[`Normpower`](@ref)
"""
normpower(x) = sink(Normpower(x))
Base.show(io::IO,::MIME"text/plain",x::NormedSignal) = pprint(io,x)
function PrettyPrinting.tile(x::NormedSignal)
tilepipe(signaltile(x.signal),literal("Normpower"))
end
signaltile(x::NormedSignal) = PrettyPrinting.tile(x) | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 3889 | using Random
# helpers
astuple(x::Number) = (x,)
astuple(x::Tuple) = x
astuple(x) = error("Function must return number or tuple of numbers.")
ntuple_T(::Type{<:NTuple{<:Any,T}}) where T = T
ntuple_N(::Type{<:NTuple{N}}) where N = N
# signals can be generated by functions of time
struct SignalFunction{Fn,Fr,El,T,Fs} <: AbstractSignal{El}
fn::Fn
first::El
ω::Fr
ϕ::Float64
framerate::Fs
function SignalFunction(fn::Fn,first::El,ω::Fr,ϕ,
sr::Fs=missing) where {Fn,El,Fr,Fs}
new{Fn,Fr,El,ntuple_T(El),Fs}(fn,first,ω,ϕ,sr)
end
end
SignalTrait(::Type{<:SignalFunction{<:Any,<:Any,<:Any,T,Fs}}) where {T,Fs} =
IsSignal{T,Fs,InfiniteLength}()
nchannels(x::SignalFunction) = ntuple_N(typeof(x.first))
nframes_helper(x::SignalFunction) = inflen
framerate(x::SignalFunction) = x.framerate
EvalTrait(x::SignalFunction) = ComputedSignal()
function Base.show(io::IO, ::MIME"text/plain",x::SignalFunction)
if ismissing(x.ω) && iszero(x.ϕ)
write(io,string(x.fn))
show_fs(io,x)
else
write(io,"Signal(")
write(io,string(x.fn))
!ismissing(x.ω) && write(io,",ω=",string(x.ω))
!iszero(x.ϕ) && write(io,",ϕ=",string(x.ϕ),"π")
write(io,")")
show_fs(io,x)
end
end
struct FunctionBlock
offset::Int
len::Int
end
nextblock(x::SignalFunction,maxlen,skip) = FunctionBlock(0,maxlen)
nextblock(x::SignalFunction,maxlen,skip,block::FunctionBlock) =
FunctionBlock(block.offset + block.len,maxlen)
nframes(block::FunctionBlock) = block.len
frame(x,block::FunctionBlock,i) =
x.fn(2π*(((i+block.offset)/x.framerate*x.ω + x.ϕ) % 1.0))
frame(x::SignalFunction{<:Any,Missing},block::FunctionBlock,i) =
x.fn((i+block.offset)/x.framerate + x.ϕ)
frame(x::SignalFunction{typeof(sin)},block::FunctionBlock,i) =
sinpi(2*((i+block.offset)/x.framerate*x.ω + x.ϕ))
frame(x::SignalFunction{typeof(sin),Missing},block::FunctionBlock,i) =
sinpi(2*((i+block.offset)/x.framerate + x.ϕ))
ToFramerate(x::SignalFunction,::IsSignal,::ComputedSignal,fs;blocksize) =
SignalFunction(x.fn,x.first,x.ω,x.ϕ,coalesce(inHz(Float64,fs),x.framerate))
abstract type Functor
end
"""
## Functions
Signal(fn,[framerate];[ω/frequency],[ϕ/phase])
Functions can define infinite length signals of known or unknown frame rate.
The function `fn` can either return a number or, for multi-channel signals,
a tuple of values.
The input to `fn` is either a phase value or a time value. If a frequency is
specified (using either the ω or frequency keyword), the input to `fn` will
be a phase value in radians, ranging from 0 to 2π. If no frequency is
specified the value passed to `fn` is the time in seconds. Specifying phase
(by the ϕ or phase keyword) will first add that value to the input before
passing it to `fn`. When frequency is specified, the phase is assumed to be
in units of radians (but you can also pass degrees by using `°` or a unit of
time (e.g. `s` for seconds)). When frequency is not specified the phase
is assumed to be in units of seconds.
"""
function Signal(fn::Union{Function,Functor},
framerate::Union{Missing,Number}=missing;
ω=missing,frequency=ω,ϕ=0,phase=ϕ)
SignalFunction(fn,astuple(fn(0.0)),inHz(ω),
ismissing(ω) ? inseconds(Float64,ϕ) :
inradians(Float64,ϕ,ω)/2π,
inHz(Float64,framerate))
end
struct RandFn{R}
rng::R
end
Base.string(x::RandFn) = "randn"
"""
If `fn == randn` no frequency or phase can be specified. Instead there is a
single keyword argument, `rng`, which allows you to specify the random number
generator; `rng` defaults to `Random.GLOBAL_RNG`.
"""
Signal(x::typeof(randn),fs::Union{Missing,Number}=missing;rng=Random.GLOBAL_RNG) =
SignalFunction(RandFn(rng),(randn(rng),),missing,0.0,inHz(Float64,fs))
frame(x::SignalFunction{<:RandFn,Missing},block::FunctionBlock,i) =
randn(x.fn.rng) | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 1468 | export inflen
abstract type Infinite
end
struct InfiniteLength <: Infinite
end
@doc """
inflen
Represents an infinite length. Proper overloads are defined to handle
arithmetic and ordering for the infinite value.
"""
const inflen = InfiniteLength()
Base.show(io::IO,::MIME"text/plain",::InfiniteLength) =
write(io,"inflen")
Base.isinf(::Infinite) = true
isknowninf(x) = isinf(x)
isknowninf(::Missing) = false
Base.ismissing(::Infinite) = false
Base.:(+)(x::Infinite,::Number) = x
Base.:(+)(::Number,x::Infinite) = x
Base.:(-)(x::Infinite,::Number) = x
Base.:(+)(x::Infinite,::Missing) = x
Base.:(+)(::Missing,x::Infinite) = x
Base.:(-)(x::Infinite,::Missing) = x
Base.isless(::Number,::Infinite) = true
Base.isless(::Infinite,::Number) = false
Base.isless(::Infinite,::Missing) = false
Base.isless(::Missing,::Infinite) = true
Base.isless(::Infinite,::Infinite) = false
Base.:(*)(x::Infinite,::Number) = x
Base.:(*)(::Number,x::Infinite) = x
Base.:(*)(x::Infinite,::Missing) = x
Base.:(*)(::Missing,x::Infinite) = x
Base.:(*)(x::Infinite,::Unitful.FreeUnits) = x
Base.:(/)(x::Infinite,::Number) = x
Base.:(/)(x::Infinite,::Missing) = x
Base.:(/)(::Number,::Infinite) = 0
Base.:(/)(::Missing,::Infinite) = 0
Base.ceil(::T,x::Infinite) where T = x
Base.ceil(x::Infinite) = x
Base.floor(::T,x::Infinite) where T = x
Base.floor(x::Infinite) = x
Base.length(::Infinite) = 1
Base.iterate(x::Infinite) = x, nothing
Base.iterate(::Infinite,::Nothing) = nothing | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 10864 | using Unitful
export OperateOn, Operate, Mix, Amplify, AddChannel, SelectChannel,
operate, mix, amplify, addchannel, selectchannel, Extend
################################################################################
# binary operators
struct MapSignal{Fn,N,C,T,Fs,El,Si,Pd,PSi} <: AbstractSignal{T}
fn::Fn
val::El
signals::Si
framerate::Fs
padding::Pd
padded_signals::PSi
blocksize::Int
bychannel::Bool
end
function MapSignal(fn::Fn,val::El,signals::Si,
framerate::Fs,padding::Pd,blocksize::Int,bychannel::Bool) where
{Fn,El,L,Si,Fs,Pd}
T = El == NoValues ? Nothing : ntuple_T(El)
N = El == NoValues ? 0 : length(signals)
C = El == NoValues ? 1 : nchannels(signals[1])
padded_signals = Extend.(signals,Ref(padding))
PSi = typeof(padded_signals)
MapSignal{Fn,N,C,T,Fs,El,Si,Pd,PSi}(fn,val,signals,framerate,padding,
padded_signals,blocksize,bychannel)
end
struct NoValues
end
novalues = NoValues()
SignalTrait(x::Type{<:MapSignal{<:Any,<:Any,<:Any,T,Fs,L}}) where {Fs,T,L} =
IsSignal{T,Fs,L}()
nchannels(x::MapSignal) = length(x.val)
framerate(x::MapSignal) = x.framerate
function duration(x::MapSignal)
durs = duration.(x.padded_signals)
Ns = nframes_helper.(x.padded_signals)
durlen = ifelse.(isknowninf.(durs),Ns ./ framerate(x),durs)
reduce(maxlen,durlen)
end
function ToFramerate(x::MapSignal,s::IsSignal{<:Any,<:Number},
c::ComputedSignal,fs;blocksize)
if inHz(fs) < x.framerate
# reframe input if we are downsampling
OperateOn(cleanfn(x.fn),ToFramerate.(x.signals,fs,blocksize=blocksize)...,
padding=x.padding,bychannel=x.bychannel,
blocksize=x.blocksize)
else
# reframe output if we are upsampling
ToFramerate(x,s,DataSignal(),fs,blocksize=blocksize)
end
end
root(x::MapSignal) = reduce(mergeroot,root.(x.signals))
ToFramerate(x::MapSignal,::IsSignal{<:Any,Missing},__ignore__,fs;blocksize) =
OperateOn(cleanfn(x.fn),ToFramerate.(x.signals,fs,blocksize=blocksize)...,
padding=x.padding,bychannel=x.bychannel,blocksize=x.blocksize)
"""
OperateOn(fn,arguments...;padding=default_pad(fn),bychannel=false)
Apply `fn` across the samples of the passed signals. The output length is the
maximum length of the arguments. Shorter signals are extended using
`Extend(x,padding)`.
!!! note
There is no piped version of `OperateOn`, use [`Operate`](@ref) to pipe.
The shorter name is used to pipe because it is expected to be the more
common use case.
## Channel-by-channel functions (default)
When `bychannel == false` the function `fn` should treat each of its
arguments as a single number and return a single number. This operation is
broadcast across all channels of the input. It is expected to be a type
stable function.
The signals are first promoted to have the same sample rate and the same
number of channels using [`Uniform`](@ref).
## Cross-channel functions
When `bychannel=false`, rather than being applied to each channel seperately
the function `fn` is applied to each frame, containing all channels. For
example, for a two channel signal, the following would swap these two
channels.
```julia
x = rand(10,2)
swapped = OperateOn(x,bychannel=false) do val
val[2],val[1]
end
```
The signals are first promoted to have the same sample rate, but the number of
channels of each input signal remains unchanged.
## Padding
Padding determines how frames past the end of shorter signals are reported.
If you wish to change the padding for all signals you can set the value of
the keyword argument `padding`. If you wish to specify distinct padding
values for some of the inputs, you can first call [`Extend`](@ref) on those
arguments.
The default value for `padding` is determined by the `fn` passed. A fallback
implementation of `default_pad` returns `zero`. The default value for the
four basic arithmetic operators is their identity (`one` for `*` and `zero`
for `+`).
To define a new default for a specific function, just create a new method of
`default_pad(fn)`
```julia
myfun(x,y) = x + 2y
SignalOperators.default_pad(::typeof(myfun)) = one
sink(OperateOn(myfun,Until(5,2frames),Until(2,4frames))) == [9,9,5,5]
```
"""
function OperateOn(fn,xs...;
padding = default_pad(fn),
bychannel = true,
blocksize = default_blocksize)
xs = Uniform(xs,channels=bychannel)
fs = framerate(xs[1])
vals = testvalue.(xs)
if bychannel
fn = FnBr(fn)
end
MapSignal(fn,astuple(fn(vals...)),xs,fs,padding,blocksize,
bychannel)
end
tolen(x::Extended) = x.len
tolen(x::Number) = x
tolen(x::NumberExtended) = 0
tolen(x::InfiniteLength) = inflen
tolen(x::Missing) = missing
maxlen(x,y) = max(tolen(x),tolen(y))
maxlen(x::NumberExtended,y::NumberExtended) = x
nframes_helper(x::MapSignal) = reduce(maxlen,nframes_helper.(x.signals))
"""
Operate(fn,rest...;padding,bychannel)
Equivalent to
```julia
(x) -> OperateOn(fn,x,rest...;padding=padding,bychannel=bychannel)
````
## See also
[`OperateOn`](@ref)
"""
Operate(fn,xs...;kwds...) = x -> OperateOn(fn,x,xs...;kwds...)
"""
operate(fn,args...;padding,bychannel)
Equivalent to `sink(OperateOn(fn,args...;padding,bychannel))`
## See also
[`OperateOn`](@ref)
"""
operate(fn,args...;kwds...) = sink(OperateOn(fn,args...;kwds...))
struct FnBr{Fn}
fn::Fn
end
(fn::FnBr)(xs...) = fn.fn.(xs...)
cleanfn(x) = x
cleanfn(x::FnBr) = x.fn
testvalue(x) = Tuple(zero(sampletype(x)) for _ in 1:nchannels(x))
const MAX_CHANNEL_STACK = 64
struct MapSignalBlock{Ch,C,O}
len::Int
offset::Int
channels::Ch
blocks::C
offsets::O
end
nframes(x::MapSignalBlock) = x.len
function prepare_channels(x::MapSignal)
nch = ntuple_N(typeof(x.val))
(nch > MAX_CHANNEL_STACK && (x.fn isa FnBr)) ?
Array{sampletype(x)}(undef,nch) :
nothing
end
struct EmptyChildBlock
end
const emptychild = EmptyChildBlock()
nframes(::EmptyChildBlock) = 0
nextblock(x,maxlen,skip,::EmptyChildBlock) = nextblock(x,maxlen,skip)
initblock(x::MapSignal{<:Any,N}) where N =
MapSignalBlock(0,0,prepare_channels(x),Tuple(emptychild for _ in 1:N),
Tuple(zeros(N)))
function nextblock(x::MapSignal{Fn,N,CN},maxlen,skip,
block::MapSignalBlock=initblock(x)) where {Fn,N,CN}
maxlen = min(maxlen,nframes(x) - (block.offset + block.len))
(maxlen == 0) && return nothing
offsets = map(block.offsets, block.blocks) do offset, childblock
offset += nframes(block)
offset == nframes(childblock) ? 0 : offset
end
blocks = map(x.padded_signals,block.blocks,offsets) do sig, childblock, offset
if offset == 0
nextblock(sig,maxlen,skip,childblock)
else
childblock
end
end
# find the smallest child block length, and use that as the length for the
# parent block length
len = min(maxlen,minimum(nframes.(blocks) .- offsets))
Ch, C, O = typeof(block.channels), typeof(blocks), typeof(offsets)
MapSignalBlock{Ch,C,O}(len,block.offset + block.len,block.channels,blocks,
offsets)
end
trange(::Val{N}) where N = (trange(Val(N-1))...,N)
trange(::Val{1}) = (1,)
@Base.propagate_inbounds function frame(x::MapSignal{<:FnBr,N,CN},
block::MapSignalBlock{<:Nothing},
i::Int) where {N,CN}
inputs = frame.(x.padded_signals,block.blocks,i .+ block.offsets)
map(ch -> x.fn(map(@λ(_[ch]),inputs)...),trange(Val{CN}()))
end
@Base.propagate_inbounds function frame(
x::MapSignal{<:FnBr,N,CN},
block::MapSignalBlock{<:Array},
i::Int) where {N,CN}
inputs = frame.(x.padded_signals,block.blocks,i .+ block.offsets)
map!(ch -> x.fn(map(@λ(_[ch]),inputs)...),block.channels,1:CN)
end
@Base.propagate_inbounds function frame(
x::MapSignal{<:Any,N,CN},
block::MapSignalBlock{<:Nothing},
i::Int) where {N,CN}
x.fn(frame.(x.padded_signals,block.blocks,i .+ block.offsets)...)
end
default_pad(x) = zero
default_pad(::typeof(*)) = one
default_pad(::typeof(/)) = one
Base.show(io::IO,::MIME"text/plain",x::MapSignal) = pprint(io,x)
function PrettyPrinting.tile(x::MapSignal)
if length(x.signals) == 1
tilepipe(signaltile(x.signals[1]),literal(string(mapstring(x.fn),")")))
elseif length(x.signals) == 2
operate =
literal(mapstring(x.fn)) * signaltile(x.signals[2]) * literal(")") |
literal(mapstring(x.fn)) / indent(4) * signaltile(x.signals[2]) /
literal(")")
tilepipe(signaltile(x.signals[1]),operate)
else
list_layout(signaltile.(collect(x.signals)),par=(mapstring(x.fn),")"))
end
# TODO: report the padding and bychannel values if a they are non-default
# values
end
signaltile(x::MapSignal) = PrettyPrinting.tile(x)
mapstring(fn) = string("Operate(",fn,",")
mapstring(x::FnBr) = string("Operate(",x.fn,",")
"""
Mix(xs...)
Sum all signals together, using [`OperateOn`](@ref). Unlike `OperateOn`,
`Mix` includes a piped version.
"""
Mix(y) = x -> Mix(x,y)
Mix(xs...) = OperateOn(+,xs...)
mapstring(::FnBr{<:typeof(+)}) = "Mix("
"""
mix(xs...)
Equivalent to `sink(Mix(xs...))`
## See also
[`Mix`](@ref)
"""
mix(xs...) = sink(Mix(xs...))
"""
Amplify(xs...)
Find the product, on a per-frame basis, for all signals `xs` using
[`OperateOn`](@ref). Unlike `OperateOn`, `Amplify` includes a piped
version.
"""
Amplify(y) = x -> Amplify(x,y)
Amplify(xs...) = OperateOn(*,xs...)
mapstring(::FnBr{<:typeof(*)}) = "Amplify("
"""
amplify(xs...)
Equivalent to `sink(Amplify(xs...))`
## See also
[`Amplify`](@ref)
"""
amplify(xs...) = sink(Amplify(xs...))
"""
AddChannel(xs...)
Concatenate the channels of all signals into one signal, using
[`OperateOn`](@ref). This will result in a signal with `sum(nchannels,xs)`
channels. Unlike `OperateOn`, `AddChannels` includes a piped
version.
"""
AddChannel(y) = x -> AddChannel(x,y)
AddChannel(xs...) = OperateOn(tuplecat,xs...;bychannel=false)
tuplecat(a,b) = (a...,b...)
tuplecat(a,b,c,rest...) = reduce(tuplecat,(a,b,c,rest...))
mapstring(::typeof(tuplecat)) = "AddChannel("
"""
addchannel(xs...)
Equivalent to `sink(AddChannel(xs...))`.
## See also
[`AddChannel`](@ref)
"""
addchannel(xs...) = sink(AddChannel(xs...))
"""
SelectChannel(x,n)
Select channel `n` of signal `x`, as a single-channel signal, using
[`OperateOn`](@ref). Unlike `OperateOn`, `SelectChannel` includes a piped
version.
"""
SelectChannel(n) = x -> SelectChannel(x,n)
SelectChannel(x,n) = OperateOn(GetChanFn(n),x,bychannel=false)
struct GetChanFn; n::Int; end
(fn::GetChanFn)(x) = x[fn.n]
mapstring(fn::GetChanFn) = string("SelectChannel(",fn.n)
"""
selectchannel(xs...)
Equivalent to `sink(SelectChannel(xs...))`
## See also
[`SelectChannel`](@ref)
"""
selectchannel(xs...) = sink(SelectChannel(xs...))
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 1837 | struct NumberSignal{T,S,DB} <: AbstractSignal{T}
val::T
framerate::S
end
struct NumberExtended <: Infinite
end
const numextend = NumberExtended()
nframes_helper(x::NumberSignal) = numextend
cleanextend(x::NumberExtended) = inflen
NumberSignal(x::T,sr::Fs;dB=false) where {T,Fs} = NumberSignal{T,Fs,dB}(x,sr)
function Base.show(io::IO, ::MIME"text/plain", x::NumberSignal{<:Any,<:Any,true})
show(io,MIME("text/plain"), uconvertrp(Units.dB, x.val))
show_fs(io,x)
end
function Base.show(io::IO, ::MIME"text/plain", x::NumberSignal{<:Any,<:Any,false})
show(io, MIME("text/plain"), x.val)
show_fs(io,x)
end
"""
## Numbers
Numbers can be treated as infinite length, constant signals of unknown
frame rate.
### Example
```julia
rand(10,2) |> Amplify(20dB) |> nframes == 10
```
!!! note
The length of numbers are treated specially when passed to
[`OperateOn`](@ref): if there are other types of signal passed as input,
the number signals are considered to be as long as the longest signal.
```julia
nframes(Mix(1,2)) == inflen
nframes(Mix(1,rand(10,2))) == 10
```
"""
Signal(val::Number,::Nothing,fs) = NumberSignal(val,inHz(Float64,fs))
Signal(val::Unitful.Gain{<:Any,<:Any,T},::Nothing,fs) where T =
NumberSignal(float(T)(uconvertrp(NoUnits,val)),inHz(Float64,fs),dB=true)
SignalTrait(::Type{<:NumberSignal{T,S}}) where {T,S} = IsSignal{T,S,InfiniteLength}()
nchannels(x::NumberSignal) = 1
framerate(x::NumberSignal) = x.framerate
ToFramerate(x::NumberSignal{<:Any,<:Any,DB},::IsSignal,::ComputedSignal,
fs=missing;blocksize) where DB = NumberSignal(x.val,fs,dB=DB)
struct NumberBlock
len::Int
end
nextblock(x::NumberSignal,len,skip,block::NumberBlock=NumberBlock(0)) = NumberBlock(len)
nframes(block::NumberBlock) = block.len
frame(x,block::NumberBlock,i) = x.val | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 8148 | export Pad, cycle, mirror, lastframe
struct PaddedSignal{S,T,E} <: WrappedSignal{S,T}
signal::S
Pad::T
end
PaddedSignal(x::S,pad::T,extending=false) where {S,T} =
PaddedSignal{S,T,extending}(x,pad)
SignalTrait(x::Type{T}) where {S,T <: PaddedSignal{S}} =
SignalTrait(x,SignalTrait(S))
SignalTrait(x::Type{<:PaddedSignal},::IsSignal{T,Fs}) where {T,Fs} =
IsSignal{T,Fs,InfiniteLength}()
nframes_helper(x::PaddedSignal) = inflen
nframes_helper(x::PaddedSignal{<:Any,<:Any,true}) = Extended(nframes(x.signal))
duration(x::PaddedSignal) = inflen
ToFramerate(x::PaddedSignal,s::IsSignal{<:Any,<:Number},c::ComputedSignal,fs;blocksize) =
PaddedSignal(ToFramerate(x.signal,fs,blocksize=blocksize),x.Pad)
ToFramerate(x::PaddedSignal,s::IsSignal{<:Any,Missing},__ignore__,fs;
blocksize) = PaddedSignal(ToFramerate(x.signal,fs;blocksize=blocksize),x.Pad)
"""
Pad(x,padding)
Create a signal that appends an infinite number of values, `padding`, to `x`.
The value `padding` can be:
- a number
- a tuple or vector
- a type function: a one argument function of the `sampletype` of `x`
- a value function: a one argument function of the signal `x` for which
`SignalOperators.valuefunction(padding) == true`.
- an indexing function: a three argument function following the same type
signature as `getindex` for two dimensional arrays.
If the signal is already infinitely long (e.g. a previoulsy padded signal),
`Pad` has no effect.
If `padding` is a number it is used as the value for all samples past the end
of `x`.
If `padding` is a tuple or vector it is the value for all frames past the end
of `x`.
If `padding` is a type function it is passed the [`sampletype`](@ref) of
the signal and the resulting value is used as the value for all frames past
the end of `x`. Examples include `zero` and `one`
If `padding` is a value function it is passed the signal `x` just before
padding occurs during a call to `sink`; it should return a tuple of
`sampletype(x)` values. The return value is repeated for all remaining
frames of the signal. For example, [`lastframe`](@ref) is a value function.
If `padding` is an indexing function (it accepts 3 arguments) it will be used
to retrieve frames from the signal `x` assuming it conforms to the
`AbstractArray` interface, with the first index being frames and the second
channels. If the frame index goes past the bounds of the array, it should be
transformed to an index within the range of that array. Note that such
padding functions only work on signals that are also AbstractArray objects.
You can always generate an array from a given signal by first passing it
through `sink` or `sink!`.
!!! info
A indexing function will also work on a signal represented as a tuple of
an array and number; it simply passed the array (leaving off the number).
## See also
[`Extend`](@ref)
[`cycle`](@ref)
[`mirror`](@ref)
[`lastframe`](@ref)
[`valuefunction`](@ref)
"""
Pad(p) = x -> Pad(x,p)
function Pad(x,p)
x = Signal(x)
isknowninf(nframes(x)) ? x : PaddedSignal(x,p)
end
"""
Extend(x,padding)
Behaves like [`Pad`](@ref), except when passed directly to
[`OperateOn`](@ref); in that case, the signal `x` will only be padded up to
the length of the longest signal input to `OperateOn`
## See Also
[`OperateOn`](@ref)
[`Pad`](@ref)
"""
Extend(p) = x -> Extend(x,p)
function Extend(x,p)
x = Signal(x)
isknowninf(nframes(x)) ? x : PaddedSignal(x,p,true)
end
"""
lastframe
When passed as an argument to `Pad`, allows padding using the last frame of a
signal. You cannot use this function in other contexts, and it will normally
throw an error. See [`Pad`](@ref).
"""
lastframe(x) = error("Must be passed as argument to `Pad`.")
"""
SignalOperators.valuefunction(fn)
Returns true if `fn` should be treated as a value function. See
[`Pad`](@ref). If you wish your own function to be a value function, you can
do this as follows.
SignalOperators.valuefunction(::typeof(myfun)) = true
"""
valuefunction(x) = false
valuefunction(::typeof(lastframe)) = true
"""
cycle(x,i,j)
An indexing function which wraps index i using mod, thus
repeating the signal when i > size(x,1). It can be passed as the second
argument to [`Pad`](@ref).
"""
@Base.propagate_inbounds cycle(x,i,j) = x[(i-1)%end+1,j]
"""
mirror(x,i,j)
An indexing function which mirrors the indices when i > size(x,1). This means
that past the end of the signal x, the signal first repeats with frames in
reverse order, then repeats in the original order, so on and so forth. It
can be passed as the second argument to [`Pad`](@ref).
"""
@Base.propagate_inbounds function mirror(x,i,j)
function helper(i,N)
count,remainder = divrem(i-1,N)
iseven(count) ? remainder+1 : N-remainder
end
x[helper(i,end),j]
end
usepad(x::PaddedSignal,block) = usepad(x,SignalTrait(x),block)
usepad(x::PaddedSignal,s::IsSignal,block) = usepad(x,s,x.Pad,block)
usepad(x::PaddedSignal,s::IsSignal{T},p::Number,block) where T =
Fill(convert(T,p),nchannels(x.signal))
function usepad(x::PaddedSignal,s::IsSignal{T},
p::Union{Array,Tuple},block) where T
map(x -> convert(T,x),p)
end
usepad(x::PaddedSignal,s::IsSignal,::typeof(lastframe),block) =
frame(x,block,nframes(block))
usepad(x::PaddedSignal,s::IsSignal,::typeof(lastframe),::Nothing) =
error("Signal is length zero; there is no last frame to pad with.")
indexable(x::AbstractArray) = true
indexable(x::Tuple{<:AbstractArray,<:Number}) = true
indexable(x) = false
indexing(x::AbstractArray) = x
indexing(x::Tuple{<:AbstractArray,<:Number}) = x[1]
function usepad(x::PaddedSignal,s::IsSignal{T},fn::Function,block) where T
nargs = map(x -> x.nargs - 1, methods(fn).ms)
if 3 ∈ nargs
if indexable(x.signal)
i -> fn(indexing(x.signal),i,:)
else
io = IOBuffer()
show(io,MIME("text/plain"),child(x))
sig_string = String(take!(io))
error("Attemped to specify an indexing pad function for the ",
"following signal, which is not known to support ",
"`getindex`.\n",sig_string)
end
elseif 1 ∈ nargs
if valuefunction(fn)
fn(x.signal)
else
Fill(fn(T),nchannels(x.signal))
end
else
error("Pad function ($fn) must take 1 or 3 arguments. ",
"Refer to `Pad` documentation.")
end
end
child(x::PaddedSignal) = x.signal
struct UsePad
end
const use_pad = UsePad()
struct PadBlock{P,C}
Pad::P
child_or_len::C
offset::Int
end
child(x::PadBlock{<:Nothing}) = x.child_or_len
child(x::PadBlock) = nothing
nframes(x::PadBlock{<:Nothing}) = nframes(child(x))
nframes(x::PadBlock) = x.child_or_len
@Base.propagate_inbounds frame(x,block::PadBlock{<:Nothing},i) =
frame(child(x),child(block),i)
@Base.propagate_inbounds frame(x,block::PadBlock{<:Function},i) =
block.Pad(i + block.offset)
@Base.propagate_inbounds frame(x,block::PadBlock,i) = block.Pad
function nextblock(x::PaddedSignal,maxlen,skip)
block = nextblock(child(x),maxlen,skip)
if isnothing(block)
PadBlock(usepad(x,block),maxlen,0)
else
PadBlock(nothing,block,0)
end
end
function nextblock(x::PaddedSignal,maxlen,skip,block::PadBlock{<:Nothing})
childblock = nextblock(child(x),maxlen,skip,child(block))
if isnothing(childblock)
PadBlock(usepad(x,block),maxlen,nframes(block) + block.offset)
else
PadBlock(nothing,childblock,nframes(block) + block.offset)
end
end
function nextblock(x::PaddedSignal,len,skip,block::PadBlock)
PadBlock(block.Pad,len,nframes(block) + block.offset)
end
Base.show(io::IO,::MIME"text/plain",x::PaddedSignal) = pprint(io,x)
function PrettyPrinting.tile(x::PaddedSignal)
child = signaltile(x.signal)
operate = literal(string("Pad(",x.Pad,")"))
tilepipe(child,operate)
end
function PrettyPrinting.tile(x::PaddedSignal{<:Any,<:Any,true})
child = signaltile(x.signal)
operate = literal(string("Extend(",x.Pad,")"))
tilepipe(child,operate)
end
signaltile(x::PaddedSignal) = PrettyPrinting.tile(x) | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 8284 |
export RampOn, RampOff, Ramp, FadeTo, sinramp, rampon, rampoff, ramp, fadeto
sinramp(x) = sinpi(0.5x)
struct RampSignal{D,S,Tm,Fn,T} <: WrappedSignal{S,T}
signal::S
time::Tm
fn::Fn
end
function RampSignal(D,signal::S,time::Tm,fn::Fn) where {S,Tm,Fn}
T = sampletype(signal)
RampSignal{D,S,Tm,Fn,float(T)}(signal,time,fn)
end
SignalTrait(::Type{T}) where {S,T <: RampSignal{<:Any,S}} =
SignalTrait(T,SignalTrait(S))
function SignalTrait(::Type{<:RampSignal{D,S,Tm,Fn,T}},::IsSignal{<:Any,Fs,L}) where
{D,S,Tm,Fn,T,Fs,L}
IsSignal{T,Fs,L}()
end
child(x::RampSignal) = x.signal
resolvelen(x::RampSignal) = max(1,inframes(Int,maybeseconds(x.time),framerate(x)))
function ToFramerate(
x::RampSignal{D},
s::IsSignal{<:Any,<:Number},
c::ComputedSignal,fs;blocksize) where D
t = stretchtime(x.time,fs/framerate(x))
RampSignal(D,ToFramerate(child(x),fs;blocksize=blocksize),x.time,x.fn)
end
function ToFramerate(
x::RampSignal{D},
s::IsSignal{<:Any,Missing},
__ignore__,fs; blocksize) where D
RampSignal(D,ToFramerate(child(x),fs;blocksize=blocksize),x.time,x.fn)
end
struct RampBlock{Fn,T}
Ramp::Fn
marker::Int
stop::Int
offset::Int
len::Int
end
RampBlock(x,fn,marker,stop,offset,len) =
RampBlock{typeof(fn),float(sampletype(x))}(fn,marker,stop,offset,len)
nframes(x::RampBlock) = x.len
frame(x::RampSignal{:on},block::RampBlock{Nothing,T},i) where T =
Fill(one(T),nchannels(x))
frame(x::RampSignal{:off},block::RampBlock{Nothing,T},i) where T =
Fill(one(T),nchannels(x))
function frame(x::RampSignal{:on},block::RampBlock,i)
ramplen = block.marker
rampval = block.Ramp((i+block.offset-1) / ramplen)
Fill(rampval,nchannels(x))
end
function frame(x::RampSignal{:off},block::RampBlock,i)
startramp = block.marker - block.offset
stop = block.stop - block.offset
rampval = block.stop > startramp ?
rampval = block.Ramp(1-(i - startramp)/(stop - startramp)) :
rampval = block.Ramp(1)
Fill(rampval,nchannels(x))
end
function nextblock(x::RampSignal{:on},maxlen,skip)
ramplen = resolvelen(x)
RampBlock(x,x.fn,ramplen,nframes(x),0,min(ramplen,maxlen))
end
function nextblock(x::RampSignal{:off},maxlen,skip)
rampstart = nframes(x) - resolvelen(x)
RampBlock(x,nothing,rampstart,nframes(x),0,min(rampstart,maxlen))
end
function nextblock(x::RampSignal{:on},maxlen,skip,block::RampBlock)
offset = block.offset + block.len
len = min(nframes(x) - offset,maxlen,block.marker - offset)
if len == 0
len = min(nframes(x) - offset,maxlen)
RampBlock(x,nothing,block.marker,block.stop,offset,len)
else
RampBlock(x,x.fn,block.marker,block.stop,offset,len)
end
end
function nextblock(x::RampSignal{:on},maxlen,skip,block::RampBlock{Nothing})
offset = block.offset + block.len
len = min(nframes(x) - offset,maxlen,block.stop - offset)
if len > 0
RampBlock(x,nothing,block.marker,block.stop,offset,len)
end
end
function nextblock(x::RampSignal{:off},maxlen,skip,block::RampBlock{Nothing})
offset = block.offset + block.len
len = min(nframes(x) - offset,maxlen,block.marker - offset)
if len == 0
len = min(nframes(x) - offset,maxlen)
RampBlock(x,x.fn,block.marker,block.stop,offset,len)
else
RampBlock(x,nothing,block.marker,block.stop,offset,len)
end
end
function nextblock(x::RampSignal{:off},maxlen,skip,block::RampBlock)
offset = block.offset + block.len
len = min(nframes(x) - offset,maxlen,block.stop - offset)
if len > 0
RampBlock(x,x.fn,block.marker,block.stop,offset,len)
end
end
function Base.show(io::IO, ::MIME"text/plain",x::RampSignal{D}) where D
if x.fn isa typeof(sinramp)
if D == :on
write(io,"RampOnFn(",string(x.time),")")
elseif D == :off
write(io,"RampOffFn(",string(x.time),")")
else
error("Reached unexpected code")
end
else
if D == :on
write(io,"RampOnFn(",string(x.time),",",string(x.fn),")")
elseif D == :off
write(io,"RampOffFn(",string(x.time),",",string(x.fn),")")
else
error("Reached unexpected code")
end
end
end
"""
RampOn(x,[len=10ms],[fn=x -> sinpi(0.5x)])
Ramp the onset of a signal, smoothly transitioning from 0 to full amplitude
over the course of `len` seconds.
The function determines the shape of the ramp and should be non-decreasing
with a range of [0,1] over the domain [0,1]. It should map over the entire
range: that is `fn(0) == 0` and `fn(1) == 1`.
Both `len` and `fn` are optional arguments: either one or both can be
specified, though `len` must occur before `fn` if present.
"""
RampOn(fun::Function) = RampOn(10ms,fun)
RampOn(len::Number=10ms,fun::Function=sinramp) = x -> RampOn(x,len,fun)
function RampOn(x,len::Number=10ms,fun::Function=sinramp)
x = Signal(x)
x |> Amplify(RampSignal(:on,x,len,fun))
end
"""
rampon(x,[len],[fn])
Equivalent to `sink(RampOn(x,[len],[fn]))`
## See also
[`RampOn`](@ref)
"""
rampon(args...) = sink(RampOn(args...))
"""
RampOff(x,[len=10ms],[fn=x -> sinpi(0.5x)])
Ramp the offset of a signal, smoothly transitioning from full amplitude to 0
amplitude over the course of `len` seconds.
The function determines the shape of the ramp and should be non-decreasing
with a range of [0,1] over the domain [0,1]. It should map over the entire
range: that is `fn(0) == 0` and `fn(1) == 1`.
Both `len` and `fn` are optional arguments: either one or both can be
specified, though `len` must occur before `fn` if present.
"""
RampOff(fun::Function) = RampOff(10ms,fun)
RampOff(len::Number=10ms,fun::Function=sinramp) = x -> RampOff(x,len,fun)
function RampOff(x,len::Number=10ms,fun::Function=sinramp)
x = Signal(x)
x |> Amplify(RampSignal(:off,x,len,fun))
end
"""
rampoff(x,[len],[fn])
Equivalent to `sink(RampOff(x,[len],[fn]))`
## See also
[`RampOff`](@ref)
"""
rampoff(args...) = sink(RampOff(args...))
"""
Ramp(x,[len=10ms],[fn=x -> sinpi(0.5x)])
Ramp the onset and offset of a signal, smoothly transitioning from 0 to full
amplitude over the course of `len` seconds at the start and from full to 0
amplitude over the course of `len` seconds.
The function determines the shape of the ramp and should be non-decreasing
with a range of [0,1] over the domain [0,1]. It should map over the entire
range: that is `fn(0) == 0` and `fn(1) == 1`.
Both `len` and `fn` are optional arguments: either one or both can be
specified, though `len` must occur before `fn` if present.
"""
Ramp(fun::Function) = Ramp(10ms,fun)
Ramp(len::Number=10ms,fun::Function=sinramp) = x -> Ramp(x,len,fun)
function Ramp(x,len::Number=10ms,fun::Function=sinramp)
x = Signal(x)
x |> RampOn(len,fun) |> RampOff(len,fun)
end
"""
ramp(x,[len],[fn])
Equivalent to `sink(Ramp(x,[len],[fn]))`
## See also
[`Ramp`](@ref)
"""
ramp(args...) = sink(Ramp(args...))
"""
FadeTo(x,y,[len=10ms],[fn=x->sinpi(0.5x)])
Append x to y, with a smooth transition lasting `len` seconds fading from
`x` to `y` (so the total length is `duration(x) + duration(y) - len`).
This fade is accomplished with a [`RampOff`](@ref) of `x` and a
[`RampOn`](@ref) for `y`. `fn` should be non-decreasing with a range of [0,1]
over the domain [0,1]. It should map over the entire range: that is
`fn(0) == 0` and `fn(1) == 1`.
Both `len` and `fn` are optional arguments: either one or both can be
specified, though `len` must occur before `fn` if present.
"""
FadeTo(y,fun::Function) = FadeTo(y,10ms,fun)
FadeTo(y,len::Number=10ms,fun::Function=sinramp) = x -> FadeTo(x,y,len,fun)
function FadeTo(x,y,len::Number=10ms,fun::Function=sinramp)
x,y = Uniform((x,y))
x = Signal(x)
if ismissing(framerate(x))
error("Unknown frame rate is not supported by `FadeTo`.")
end
n = inframes(Int,maybeseconds(len),framerate(x))
silence = Signal(zero(sampletype(y))) |> Until((nframes(x) - n)*frames)
x |> RampOff(len,fun) |> Mix(
y |> RampOn(len,fun) |> Prepend(silence))
end
"""
fadeto(x,y,[len],[fn])
Equivalent to `sink(FadeTo(x,[len],[fn]))`
## See also
[`FadeTo`](@ref)
"""
fadeto(args...) = sink(FadeTo(args...))
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 6406 | using DSP: FIRFilter, resample_filter
export ToFramerate, ToChannels, Format, Uniform, ToEltype,
toframerate, tochannels, format, toeltype
"""
ToFramerate(x,fs;blocksize)
Change the frame rate of `x` to the given frame rate `fs`. The underlying
implementation depends on whether the input is a computed or data signal,
as determined by [`EvalTrait`](@ref).
Computed signals (e.g. `Signal(sin)`) are resampled exactly: the result is
simply computed for more time points or fewer time points, so as to generate
the appropriate number of frames.
Data-based signals (`Signal(rand(50,2))`) are resampled using filtering (akin
to `DSP.resample`). In this case you can use the keyword arugment `blocksize`
to change the analysis window used. See [`Filt`](@ref) for more
details. Setting `blocksize` for a computed signal will succeed,
but different `blocksize` values have no effect on the underlying
implementation.
# Implementation
You need only implement this function for [custom signals](@ref
custom_signals) for particular scenarios, described below.
## Custom Computed Signals
If you implement a new sigal type that is a computed signal, you must
implement `ToFramerate` with the following type signature.
```julia
function ToFramerate(x::MyCustomSignal,s::IsSignal{<:Any,<:Number},
c::ComputedSignal,framerate;blocksize)
## ...
end
```
The result should be a new version of the computed signal with the given
frame rate.
## Handling missing frame rates
If you implement a new signal type that can handle missing frame rate values,
you will need to implement the following version of `ToFramerate` so that
a known frame rate can be applied to a signal with a missing frame rate.
```julia
function ToFramerate(x::MyCustomSignal,s::IsSignal{<:Any,Missing},
evaltrait,framerate;blocksize)
## ...
end
```
The result should be a new version of the signal with the specified frame rate.
"""
ToFramerate(fs;blocksize=default_blocksize) =
x -> ToFramerate(x,fs;blocksize=blocksize)
ToFramerate(x,fs;blocksize=default_blocksize) =
ismissing(fs) && ismissing(framerate(x)) ? x :
coalesce(inHz(fs) == framerate(x),false) ? x :
ToFramerate(x,SignalTrait(x),EvalTrait(x),inHz(fs);blocksize=blocksize)
ToFramerate(x,::Nothing,ev,fs;kwds...) = nosignal(x)
"""
toframerate(x,fs;blocksize)
Equivalent to `sink(ToFramerate(x,fs;blocksize=blocksize))`
## See also
[`ToFramerate`](@ref)
"""
toframerate(x,fs;blocksize=default_blocksize) =
sink(ToFramerate(x,fs;blocksize=blocksize))
ToFramerate(x,::IsSignal,::DataSignal,::Missing;kwds...) = x
ToFramerate(x,::IsSignal,::ComputedSignal,::Missing;kwds...) = x
function ToFramerate(x,s::IsSignal{<:Any,<:Number},::DataSignal,fs::Number;blocksize)
__ToFramerate__(x,s,fs,blocksize)
end
function (fn::ResamplerFn)(fs)
h = resample_filter(fn.ratio)
self = FIRFilter(h, fn.ratio)
τ = timedelay(self)
setphase!(self, τ)
self
end
filterstring(fn::ResamplerFn) =
string("ToFramerate(",inHz(fn.fs)*Hz,")")
function maybe_rationalize(r)
x = rationalize(r)
# only use rational number if it is a small integer ratio
if max(numerator(x),denominator(x)) ≤ 3
x
else
r
end
end
function __ToFramerate__(x,s::IsSignal{T},fs,blocksize) where T
# copied and modified from DSP's `resample`
ratio = maybe_rationalize(fs/framerate(x))
init_fs = framerate(x)
if ratio == 1
x
else
Filt(x,s,ResamplerFn(ratio,fs);blocksize=blocksize,newfs=fs)
end
end
"""
ToChannels(x,ch)
Force a signal to have `ch` number of channels, by mixing channels together
or broadcasting a single channel over multiple channels.
"""
ToChannels(ch) = x -> ToChannels(x,ch)
ToChannels(x,ch) = ToChannels(x,SignalTrait(x),ch)
ToChannels(x,::Nothing,ch) = ToChannels(Signal(x),ch)
"""
tochannels(x,ch)
Equivalent to `sink(ToChannels(x,ch))`
## See also
[`ToFramerate`](@ref)
"""
tochannels(x,ch) = sink(ToChannels(x,ch))
struct AsNChannels
ch::Int
end
(fn::AsNChannels)(x) = tuple((x[1] for _ in 1:fn.ch)...)
mapstring(fn::AsNChannels) = string("ToChannels(",fn.ch)
struct As1Channel
end
(fn::As1Channel)(x) = sum(x)
mapstring(fn::As1Channel) = string("ToChannels(1")
function ToChannels(x,::IsSignal,ch)
if ch == nchannels(x)
x
elseif ch == 1
OperateOn(As1Channel(),x,bychannel=false)
elseif nchannels(x) == 1
OperateOn(AsNChannels(ch),x,bychannel=false)
else
error("No rule to convert signal with $(nchannels(x)) channels to",
" a signal with $ch channels.")
end
end
struct ToEltypeFn{El}
end
(fn::ToEltypeFn{El})(x) where El = convert(El,x)
mapstring(fn::ToEltypeFn{El}) where El = string("ToEltype(",El,")")
"""
ToEltype(x,T)
Converts individual samples in signal `x` to type `T`.
"""
ToEltype(::Type{T}) where T = x -> ToEltype(x,T)
ToEltype(x,::Type{T}) where T = OperateOn(ToEltypeFn{T}(),x)
"""
toeltype(x,T)
Equivalent to `sink(ToEltype(x,T))`
## See also
[`ToEltype`](@ref)
"""
toeltype(x,::Type{T}) where T = sink(ToEltype(x,T))
"""
Format(x,fs,ch)
Efficiently convert both the framerate (`fs`) and channels `ch` of signal
`x`. This selects an optimal ordering for `ToFramerate` and `ToChannels` to
avoid redundant computations.
"""
function Format(x,fs,ch=nchannels(x))
if ch > 1 && nchannels(x) == 1
ToFramerate(x,fs) |> ToChannels(ch)
else
ToChannels(x,ch) |> ToFramerate(fs)
end
end
"""
format(x,fs,ch)
Equivalent to `sink(Format(x,fs,ch))`
## See also
[`Format`](@ref)
"""
format(x,fs,ch) = sink(Format(x,fs,ch))
"""
Uniform(xs;channels=false)
Promote the frame rate (and optionally the number of channels) to be the
highest frame rate (and optionally highest channel count) of the iterable of signals `xs`.
!!! note
`Uniform` rarely needs to be called directly. It is called implicitly on
all passed signals, within the body of operators such as
[`OperateOn`](@ref).
"""
function Uniform(xs;channels=false)
xs = Signal.(xs)
if any(!ismissing,SignalOperators.framerate.(xs))
framerate = maximum(skipmissing(SignalOperators.framerate.(xs)))
else
framerate = missing
end
if !channels
Format.(xs,framerate)
else
ch = maximum(skipmissing(nchannels.(xs)))
Format.(xs,framerate,ch)
end
end
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 5642 | export duration, nframes, framerate, nchannels, Signal, sink, sink!, sampletype
using FileIO
# Signals have a frame rate and some iterator element type
# T, which is an NTuple{N,<:Number}.
"""
SignalOperators.IsSignal{T,Fs,L}
Represents the format of a signal type with three type parameters:
* `T` - The [`sampletype`](@ref) of the signal.
* `Fs` - The type of the framerate. It should be either `Float64` or
`Missing`.
* `L` - The type of the length of the signal. It should be either
`Infinity`, `Missing` or `Int`.
"""
struct IsSignal{T,Fs,L}
end
# not everything that's a signal belongs to this package, (hence the use of
# trait-based dispatch), but everything that is in this package is a child of
# `AbstractSignal`. This allows for easy dispatch to convert such signals to
# another object type (e.g. Array or AxisArray). The value T refers to the
# sampletype
abstract type AbstractSignal{T}
end
nframes_helper(x) = nframes(x)
nframes_helper(x::AbstractSignal) =
error("Undefined `nframes_helper` for $(typeof(x))")
nframes(x::AbstractSignal) = cleanextend(nframes_helper(x))
cleanextend(x) = x
struct Extended{T} <:Infinite
len::T
end
cleanextend(x::Extended) = inflen
Base.:(/)(x::Extended,y::Number) = Extended(x.len / y)
"""
SiganlOperators.SignalTrait(::Type{T}) where T
Returns either `nothing` if the type T should not be considered a signal (the
default) or [`IsSignal`](@ref) to indicate the signal format for this signal.
"""
SignalTrait(x::T) where T = SignalTrait(T)
SignalTrait(::Type{T}) where T = nothing
sampletype(x::AbstractSignal) = sampletype(x,SignalTrait(x))
sampletype(x,::IsSignal{T}) where T = T
IsSignal{T}(fs::Fs,len::L) where {T,Fs,L} = IsSignal{T,Fs,L}()
function show_fs(io,x)
if !get(io,:compact,false) && !ismissing(framerate(x))
write(io," (")
show(io, MIME("text/plain"), framerate(x))
write(io," Hz)")
end
end
signalshow(io,x) = show(io,MIME("text/plain"),x)
function tilepipe(child,operate)
single = child * literal(" |> ") * operate
breaking = child * literal(" |>") / indent(4) * operate
single | breaking
end
nosignal(::Nothing) = error("Value is not a signal: nothing")
nosignal(x) = error("Value is not a signal: $x")
isconsistent(fs,_fs) = ismissing(fs) || inHz(_fs) == inHz(fs)
"""
Signal(x,[framerate])
Coerce `x` to be a signal, optionally specifying its frame rate (usually in
Hz). All signal operators first call `Signal(x)` for each argument. This
means you only need to call `Signal` when you want to pass additional
arguments to it.
!!! note
If you pipe `Signal` and pass a frame rate, you must specify the units of
the frame rate (e.g. `x |> Signal(20Hz)`). A unitless number is always
interpreted as a constant, infinite-length signal (see below).
!!! note
If you are implementing `Signal` for a [custom signal](@ref
custom_signals), you will need to support the second argument of `Signal`
by specifying `fs::Union{Number,Missing}=missing`, or equivalent.
The type of objects that can be coerced to signals are as follows.
"""
Signal(;kwds...) = x -> Signal(x;kwds...)
Signal(fs::Quantity;kwds...) = x -> Signal(x,fs;kwds...)
Signal(x,fs::Union{Number,Missing}=missing) = Signal(x,SignalTrait(x),fs)
Signal(x,::Nothing,fs) = error("Don't know how create a signal from $x.")
function filetype(x)
m = match(r".+\.([^\.]+$)",x)
if isnothing(m)
error("The file \"$x\" has no filetype.")
else
DataFormat{Symbol(uppercase(m[1]))}()
end
end
"""
## Filenames
A string with a filename ending with an appropriate filetype can be read in
as a signal. You will need to call `import` or `using` on the backend for
reading the file.
Available backends include the following pacakges
- [WAV](https://github.com/dancasimiro/WAV.jl)
- [LibSndFile](https://github.com/JuliaAudio/LibSndFile.jl)
"""
Signal(x::String,fs::Union{Missing,Number}=missing) =
load_signal(filetype(x),x,fs)
function load_signal(::DataFormat{T},x,fs) where T
error("No backend loaded for file of type $T. Refer to the ",
"documentation of `Signal` to find a list of available backends.")
end
"""
## Existing signals
Any existing signal just returns itself from `Signal`. If a frame rate is
specified it will be set if `x` has an unknown frame rate. If it has a known
frame rate and doesn't match `framerate(x)` an error will be thrown. If
you want to change the frame rate of a signal use [`ToFramerate`](@ref).
"""
function Signal(x,::IsSignal,fs)
if ismissing(framerate(x))
ToFramerate(x,fs)
elseif !isconsistent(fs,framerate(x))
error("Signal expected to have frame rate of $(inHz(fs)) Hz.")
else
x
end
end
# computed signals have to implement there own version of ToFramerate
# (e.g. resample) to avoid inefficient computations
struct DataSignal
end
struct ComputedSignal
end
"""
SiganlOperators.EvalTrait(x)
Indicates whether the signal is a `DataSignal` or
`ComputedSignal`. Data signals represent frames concretely
as a set of frames. Examples include arrays and numbers. Data signals
generally return themselves, or some wrapper type when `sink` is called on
them. Computed signals are any signal that invovles some intermediate
computation, in which frames must be computued on the fly. Calls to `sink`
on a computed signal results in some new, data signal. Most signals returned
by a signal operator are computed signals.
Computed signals have the extra responsibility of implementing
[`ToFramerate`](@ref)
"""
EvalTrait(x) = DataSignal()
EvalTrait(x::AbstractSignal) = ComputedSignal() | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 8040 |
"""
sink(signal,[to])
Creates a given type of object (`to`) from a signal. By default the type of
the resulting sink is determined by the type of the underlying data of the
signal: e.g. if `x` is a `SampleBuf` object then `sink(Mix(x,2))` is also a
`SampleBuf` object. If there is no underlying data (`Signal(sin) |> sink`)
then a Tuple of an array and the framerate is returned.
!!! warning
Though `sink` often makes a copy of an input array, it is not guaranteed
to do so. For instance `sink(Until(rand(10),5frames))` will simply take a view
of the first 5 frames of the input.
# Values for `to`
## Type
If `to` is an array type (e.g. `Array`, `DimensionalArray`) the signal is
written to a value of that type.
If `to` is a `Tuple` the result is an `Array` of samples and a number
indicating the sample rate in Hertz.
"""
sink() = x -> sink(x,refineroot(root(x)))
sink(to::Type) = x -> sink(x,to)
sink(x) = sink(x,refineroot(root(x)))
root(x) = x
refineroot(x::AbstractArray) = refineroot(x,SignalTrait(x))
refineroot(x,::Nothing) = Tuple{<:AbstractArray,<:Number}
refineroot(x,::IsSignal{<:Any,Missing}) = Array
refineroot(x,::IsSignal) = typeof(x)
refineroot(x) = Tuple{<:AbstractArray,<:Number}
refineroot(x::T) where T <: Tuple{<:AbstractArray,<:Number} = T
mergepriority(x) = 0
mergepriority(x::Array) = 1
mergepriority(x::AbstractArray) = mergepriority(x,SignalTrait(x))
mergepriority(x::AbstractArray,::IsSignal) = 2
mergepriority(x::AbstractArray,::Nothing) = 0
function mergeroot(x,y)
if mergepriority(x) ≥ mergepriority(y)
return x
else
return y
end
end
abstract type CutMethod
end
struct DataCut <: CutMethod
end
struct SinkCut <: CutMethod
end
CutMethod(x) = CutMethod(x,EvalTrait(x))
CutMethod(x,::DataSignal) = SinkCut()
CutMethod(x::AbstractArray,::DataSignal) = DataCut()
CutMethod(x::Tuple{<:AbstractArray,<:Number},::DataSignal) = DataCut()
CutMethod(x,::ComputedSignal) = SinkCut()
sink(x,::Type{T}) where T = sink(x,T,CutMethod(x))
function sink(x,::Type{T},::DataCut) where T
x = process_sink_params(x)
data = timeslice(x,:)
if Base.typename(typeof(parent(data))) == Base.typename(T)
data
else # if the sink type is new, we have to copy the data
# because it could be in a different memory layout
result = initsink(x,T)
sink!(result,x)
result
end
end
rawdata(x::SubArray) = x
function rawdata(x::AbstractArray)
p = parent(x)
if p === x
return p
else
return rawdata(p)
end
end
function sink(x,::Type{T},::SinkCut) where T
x = process_sink_params(x)
result = initsink(x,T)
sink!(result,x)
result
end
function process_sink_params(x)
x = Signal(x)
ismissing(nframes(x)) && error("Unknown number of frames in signal.")
isinf(nframes(x)) && error("Cannot store infinite signal.")
x
end
"""
SignalOperators.initsink(x,::Type{T})
Initialize an object of type T so that it can store all frames of signal `x`.
If you wish an object to serve as a [custom sink](@ref custom_sinks) you can
implement this method. You can use [`nchannels`](@ref) and
[`sampletype`](@ref) of `x` to determine how to initialize the object for the
first method, or you can just use `initsink(x,Array)` and wrap the return
value with your custom type.
"""
function initsink(x,::Type{<:Array})
Array{sampletype(x),2}(undef,nframes(x),nchannels(x))
end
initsink(x,::Type{<:Tuple}) =
(Array{sampletype(x)}(undef,nframes(x),nchannels(x)),framerate(x))
initsink(x,::Type{<:Array},data) = data
initsink(x,::Type{<:Tuple},data) = (data,framerate(x))
Base.Array(x::AbstractSignal) = sink(x,Array)
Base.Tuple(x::AbstractSignal) = sink(x,Tuple)
"""
## Filename
If `to` is a string, it is assumed to describe the name of a file to which
the signal will be written. You will need to call `import` or `using` on an
appropriate backend for writing to the given file type.
Available backends include the following pacakges
- [WAV](https://codecov.io/gh/haberdashPI/SignalOperators.jl/src/master/src/WAV.jl)
- [LibSndFile](https://github.com/JuliaAudio/LibSndFile.jl)
"""
sink(to::String) = x -> sink(x,to)
function sink(x,to::String)
x = process_sink_params(x)
save_signal(filetype(to),to,x)
end
function save_signal(::Val{T},filename,x) where T
error("No backend loaded for file of type $T. Refer to the documentation ",
"of `Signal` to find a list of available backends.")
end
"""
sink!(array,x)
Write `size(array,1)` frames of signal `x` to `array`.
"""
sink!(result::Union{AbstractVector,AbstractMatrix}) =
x -> sink!(result,x)
sink!(result::Tuple{<:AbstractArray,<:Number},x) =
(sink!(result[1],x), result[2])
function sink!(result::Union{AbstractVector,AbstractMatrix},x;
framerate=SignalOperators.framerate(x))
if nframes(x) < size(result,1)
error("Signal is too short to fill buffer of length $(size(result,1)).")
end
x = ToChannels(x,size(result,2))
sink!(result,x,SignalTrait(x))
result
end
"""
SignalOperators.nextblock(x,maxlength,skip,[last_block])
Retrieve the next block of frames for signal `x`, or nothing, if no more
blocks exist. Analogous to `Base.iterate`. The returned block must satisfy
the interface for signal blocks as described in [custom signals](@ref
custom_signals).
## Arugments
- `x`: the signal to retriev blocks from
- `maxlength`: The resulting block must have no more than `maxlength` frames,
but may have fewer frames than that; it should not have zero frames unless
`maxlength == 0`.
- `skip`: If `skip == true`, it is guaranted that [`frame`](@ref)
will never be called on the returned block. The value of `skip` is `true`
when skipping blocks during a call to [`After`](@ref)).
- `last_block` The fourth argument is optional. If included, the block that
occurs after this block is returned. If it is left out, nextblock returns the
very first block of the signal.
"""
function nextblock
end
"""
SignalOperators.timeslice(x::AbstractArray,indices)
Extract the slice of x with the given time indices.
[Custom signals](@ref custom_signals) can implement this method if the signal
is an `AbstractArray` allowing the use of a fallback implementation of
[`SignalOperators.nextblock`](@ref).
"""
function timeslice
end
"""
SignalOperators.frame(x,block,i)
Retrieves the frame at index `i` of the given block of signal `x`. A frame
is one or more channels of `sampletype(x)` values. The return value
should be an indexable object (e.g. a number, tuple or array) of these
channel values. This method should be implemented by blocks of [custom
signals](@ref custom_signals).
"""
function frame
end
fold(x) = zip(x,Iterators.drop(x,1))
sink!(result,x,sig::IsSignal) =
sink!(result,x,sig,nextblock(x,size(result,1),false))
function sink!(result,x,::IsSignal,block)
written = 0
while !isnothing(block) && written < size(result,1)
@assert nframes(block) > 0
sink_helper!(result,written,x,block)
written += nframes(block)
maxlen = size(result,1)-written
if maxlen > 0
block = nextblock(x,maxlen,false,block)
end
end
@assert written == nframes(result)
block
end
"""
SignalOperators.sink_helper!(result,written,x,block)
Write the given `block` of frames from signal `x` to `result` given that
a total of `written` frames have already been written to the result.
This method should be fast: i.e. a for loop using @simd and @inbounds. It
should call [`nframes`](@ref) and [`SignalOperators.frame`](@ref) on the
block to write the frames. **Do not call `frame` more than once for each
index of the block**.
"""
@noinline function sink_helper!(result,written,x,block)
@inbounds @simd for i in 1:nframes(block)
writesink!(result,i+written,frame(x,block,i))
end
end
@Base.propagate_inbounds function writesink!(result::AbstractArray,i,v)
for ch in 1:length(v)
result[i,ch] = v[ch]
end
v
end
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 570 |
function dictgroup(by,col)
x = by(first(col))
dict = Dict{typeof(x),Vector}()
for c in col
k = by(c)
dict[k] = push!(get(dict,k,[]),c)
end
dict
end
struct ResamplerFn{T,Fs}
ratio::T
fs::Fs
end
SignalBase.inframes(::InfiniteLength,fs=missing) = inflen
SignalBase.inframes(::Type{T}, ::InfiniteLength,fs=missing) where T = inflen
SignalBase.inseconds(::InfiniteLength,r=missing) = inflen
SignalBase.inseconds(::Type{T},::InfiniteLength,r=missing) where T = inflen
maybeseconds(x::Number) = x*s
maybeseconds(x::Quantity) = x | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 537 | using Statistics
abstract type WrappedSignal{C,T} <: AbstractSignal{T}
end
"""
child(x)
Retrieve the signal wrapped by x of type `WrappedSignal`
"""
function child
end
SignalTrait(::Type{<:WrappedSignal{C}}) where C = SignalTrait(C)
EvalTrait(x::WrappedSignal) = EvalTrait(child(x))
nchannels(x::WrappedSignal) = nchannels(child(x))
framerate(x::WrappedSignal) = framerate(child(x))
nframes_helper(x::WrappedSignal) = nframes_helper(child(x))
duration(x::WrappedSignal) = duration(child(x))
root(x::WrappedSignal) = root(child(x)) | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 3824 | using BenchmarkTools
using SignalOperators
using SignalOperators.Units
using Random
using Traceur
using Statistics
using DSP
# TODO: slow performance for my german_track project
# TODO: test randn on its own
# TODO: test randn combined with filter
dB = SignalOperators.Units.dB
suite = BenchmarkGroup()
suite["signal"] = BenchmarkGroup()
suite["baseline"] = BenchmarkGroup()
rng = MersenneTwister(1983)
# x = rand(rng,10^1,2)
# y = rand(rng,10^1,2)
x = rand(rng,10^4,2)
y = rand(rng,10^4,2)
Signal(x,1000Hz) |> ToFramerate(500Hz) |> sink
suite["signal"]["sinking"] = @benchmarkable Signal(x,1000Hz) |> sink
suite["baseline"]["sinking"] = @benchmarkable copy(x)
suite["signal"]["functions"] = @benchmarkable begin
Signal(sin,ω=10Hz) |> Until(10kframes) |> ToFramerate(1000Hz) |> sink
end
suite["baseline"]["functions"] = @benchmarkable begin
sinpi.(range(0,step=1/1000,length=10^4) .* (2*10))
end
suite["signal"]["numbers"] = @benchmarkable begin
1 |> Until(10_000frames) |> ToFramerate(1000Hz) |> sink
end
suite["baseline"]["numbers"] = @benchmarkable begin
ones(10_000)
end
suite["signal"]["cutting"] = @benchmarkable begin
x |> Until(5*10^3*frames) |> ToFramerate(1000Hz) |> sink
end
suite["baseline"]["cutting"] = @benchmarkable x[1:(5*10^3)]
suite["signal"]["padding"] = @benchmarkable begin
Pad($x,zero) |> Until(20_000frames) |> ToFramerate(1000Hz) |> sink
end
suite["baseline"]["padding"] = @benchmarkable vcat($x,zero($x))
suite["signal"]["appending"] = @benchmarkable sink(ToFramerate(Append($x,$y),1000Hz))
suite["baseline"]["appending"] = @benchmarkable vcat($x,$y)
suite["signal"]["mapping"] = @benchmarkable sink(ToFramerate(Mix($x,$y),1000Hz))
suite["baseline"]["mapping"] = @benchmarkable $x .+ $y
suite["signal"]["filtering"] = @benchmarkable begin
Filt($x,Lowpass,20Hz) |> ToFramerate(1000Hz) |> sink
end
suite["baseline"]["filtering"] = @benchmarkable begin
Filt($x,digitalfilter(Lowpass(20,fs=1000),Butterworth(5))) |>
ToFramerate(1000Hz) |> sink
end
suite["signal"]["resampling"] = @benchmarkable begin
Signal($x,1000Hz) |> ToFramerate(500Hz) |> sink
end
suite["baseline"]["resampling"] = @benchmarkable begin
Filters.resample($(x[:,1]),1//2)
Filters.resample($(x[:,2]),1//2)
end
suite["signal"]["resampling-irrational"] = @benchmarkable begin
Signal($x,1000Hz) |> ToFramerate(π*1000Hz) |> sink
end
suite["baseline"]["resampling-irrational"] = @benchmarkable begin
Filters.resample($(x[:,1]),Float64(π))
Filters.resample($(x[:,2]),Float64(π))
end
# TODO: there still seems to be some per O(N) growth
# in the # of allocs... is that just the call to `filter`?
suite["signal"]["overall"] = @benchmarkable begin
N = 10000
x_ = rand(2N,2)
Mix(Signal(sin,ω=10Hz),x_) |>
ToFramerate(2000Hz) |>
Until(0.5*N*frames) |> After(0.25*N*frames) |>
Append(sin) |> Until(N*frames) |>
Filt(Lowpass,20Hz) |>
Normpower |> Amplify(-10dB) |>
sink
end
suite["baseline"]["overall"] = @benchmarkable begin
N = 10000
x_ = rand(2N,2)
y = sin.(2π.*10.0.*range(0,0.5,length=N))
y = hcat(y,y)
z = sin.(range(0,0.5,length=N))
app = vcat(x_[1:N,:] .+ y,hcat(z,z))
f = filt(digitalfilter(Lowpass(20,fs=2000),Butterworth(5)),app)
f ./= 2sqrt(mean(f.^2))
f
end
paramspath = joinpath(@__DIR__,"params.json")
if isfile(paramspath)
loadparams!(suite, BenchmarkTools.load(paramspath)[1], :evals)
else
tune!(suite)
BenchmarkTools.save(paramspath, params(suite))
end
result = run(suite)
for case in keys(result["signal"])
m1 = minimum(result["signal"][case])
m2 = minimum(result["baseline"][case])
println("")
println("$case: ratio to bare julia")
println("----------------------------------------")
display(ratio(m1,m2))
end | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | code | 39578 | using SignalOperators, SignalOperators.Units
using SignalOperators: SignalTrait, IsSignal
using LambdaFn
using Test
using Statistics
using WAV
using FixedPointNumbers
using Unitful
using ProgressMeter
using BenchmarkTools
using Pkg
using DimensionalData
using DimensionalData: X, Time
using AxisArrays
using DSP
dB = SignalOperators.Units.dB
test_wav = "test.wav"
example_wav = "example.wav"
example_ogg = "example.ogg"
examples_wav = "examples.wav"
test_files = [test_wav,example_wav,example_ogg,examples_wav]
const total_test_groups = 33
progress = Progress(total_test_groups,desc="Running tests...")
@testset "SignalOperators.jl" begin
@testset "Function Currying" begin
x = Signal(1,10Hz)
@test isa(Mix(x),Function)
@test isa(Amplify(x),Function)
@test isa(Filt(Lowpass,200Hz,400Hz),Function)
@test isa(Ramp(10ms),Function)
@test isa(RampOn(10ms),Function)
@test isa(RampOff(10ms),Function)
@test isa(FadeTo(x),Function)
@test isa(Amplify(20dB),Function)
@test isa(AddChannel(x),Function)
@test isa(SelectChannel(1),Function)
@test isa(Filt(x -> x),Function)
end
next!(progress)
@testset "Basic signals" begin
@test SignalTrait(Signal([1,2,3,4],10Hz)) isa IsSignal
@test SignalTrait(Signal(1:100,10Hz)) isa IsSignal
@test SignalTrait(Signal(1,10Hz)) isa IsSignal
@test SignalTrait(Signal(sin,10Hz)) isa IsSignal
@test SignalTrait(Signal(randn,10Hz)) isa IsSignal
@test_throws ErrorException Signal(x -> [1,2],5Hz)
noise = Signal(randn,50Hz) |> Until(5s)
@test isapprox(noise |> Array |> mean,0,atol=0.3)
z = Signal(0,10Hz) |> Until(5s)
@test all(z |> Array .== 0)
o = Signal(1,10Hz) |> Until(5s)
@test all(o |> Array .== 1)
@test_throws ErrorException Signal(rand(5),10Hz) |> Signal(5Hz)
@test_throws ErrorException Signal(randn,10Hz) |> Signal(5Hz)
@test_throws ErrorException sink!(ones(10,2),ones(5,2))
end
next!(progress)
@testset "Array tuple output" begin
x = rand(10,2)
@test Signal(x,10Hz) == (x,10)
@test sink(Mix(Signal(x,10Hz),1)) == (x.+1,10)
end
next!(progress)
@testset "Function signals" begin
@test sink(Signal(sin,ω=5Hz,ϕ=π) |> Until(1s) |> ToFramerate(20Hz)) ==
sink(Signal(sin,ω=5Hz,ϕ=π*rad) |> Until(1s) |> ToFramerate(20Hz))
@test sink(Signal(sin,ω=5Hz,ϕ=π) |> Until(1s) |> ToFramerate(20Hz)) ==
sink(Signal(sin,ω=5Hz,ϕ=100ms) |> Until(1s) |> ToFramerate(20Hz))
@test sink(Signal(sin,ω=5Hz,ϕ=π) |> Until(1s) |> ToFramerate(20Hz)) ==
sink(Signal(sin,ω=5Hz,ϕ=180°) |> Until(1s) |> ToFramerate(20Hz))
@test sink(Signal(sin,ϕ=1s) |> Until(1s) |> ToFramerate(20Hz),Array) ≈
sink(Signal(sin,ω=1Hz,ϕ=0) |> Until(1s) |> ToFramerate(20Hz),Array)
@test_throws ErrorException Signal(sin,ϕ=2π*rad) |> Until(1s) |>
ToFramerate(20Hz) |> sink()
@test Signal(identity,ω=2Hz,10Hz) |> Until(10frames) |> sink |>
duration == 1.0
end
next!(progress)
@testset "Sink to arrays" begin
tone = Signal(sin,44.1kHz,ω=100Hz) |> Until(5s) |> Array
@test tone[1] .< tone[110] # verify bump of sine wave
end
next!(progress)
@testset "Files as signals" begin
tone = Signal(range(0,1,length=4),10Hz) |> sink(test_wav)
@test SignalTrait(Signal(test_wav)) isa IsSignal
@test isapprox(sink(Signal(test_wav),Array), range(0,1,length=4),rtol=1e-6)
end
next!(progress)
@testset "Change channel Count" begin
tone = Signal(sin,22Hz,ω=10Hz) |> Until(5s)
@test (tone |> ToChannels(2) |> nchannels) == 2
@test (tone |> ToChannels(1) |> nchannels) == 1
data = tone |> ToChannels(2) |> Array
@test size(data,2) == 2
data2 = Signal(data,22Hz) |> ToChannels(1) |> Array
@test all(data2 .== sum(data,dims=2))
@test size(data2,2) == 1
@test_throws ErrorException tone |> ToChannels(2) |> ToChannels(3)
end
next!(progress)
@testset "Cutting Operators" begin
for nch in 1:2
tone = Signal(sin,44.1kHz,ω=100Hz) |> ToChannels(nch) |> Until(5s)
@test !isinf(nframes(tone))
@test nframes(tone) == 44100*5
@test after(rand(10,nch),0frames) |> nframes == 10
@test after(rand(10,nch) |> Amplify(2),0frames) |> nframes == 10
@test all(until(1:10,5frames) .== 1:5)
@test length(until(1:10,-5frames)) == 0
x = rand(12,nch)
cutarray = Signal(x,6Hz) |> After(0.5s) |> Until(1s)
@test nframes(cutarray) == 6
cutarray = Signal(x,6Hz) |> Until(1s) |> After(0.5s)
@test nframes(cutarray) == 3
cutarray = Signal(x,6Hz) |> Until(1s) |> Until(0.5s)
cutarray2 = Signal(x,6Hz) |> Until(0.5s)
@test sink(cutarray) == sink(cutarray2)
@test_throws ErrorException Signal(1:10,5Hz) |> After(3s) |> sink
x = rand(20,nch)
@test window(x,from=0frames, to=5frames) == x[1:5,:]
@test window(x,from=15frames, to=25frames) == x[16:20,:]
x = rand(12,nch) |> Signal(6Hz)
@test Append(Until(x,1s),After(x,1s)) |> nframes == 12
aftered = tone |> After(2s)
@test nframes(aftered) == 44100*3
x = rand(12,nch)
xv = until(x,5frames)
xv .= 0
@test all(x[1:5] .== 0)
x = rand(12,nch)
xv = after(x,5frames)
xv .= 0
@test all(x[6:12] .== 0)
x = rand(12,nch)
xv = window(x,from=2frames,to=5frames)
xv .= 0
@test all(x[3:5] .== 0)
x = rand(12,nch)
y = copy(x)
xv = x |> Amplify(2) |> Until(5frames) |> sink
xv .= 0
@test x == y
end
end
next!(progress)
@testset "Padding" begin
for nch in 1:3
tone = Signal(sin,22Hz,ω=10Hz) |> ToChannels(nch) |> Until(5s) |>
Pad(zero) |> Until(7s) |> Array
@test mean(abs.(tone[1:22*5,:])) > 0
@test mean(abs.(tone[22*5:22*7,:])) == 0
tone = Signal(sin,22Hz,ω=10Hz) |> Until(5s) |> Pad(0) |>
Until(7s) |> Array
@test mean(abs.(tone[1:22*5,:])) > 0
@test mean(abs.(tone[22*5:22*7,:])) == 0
@test rand(10,nch) |> Signal(10Hz) |> Pad(zero) |> After(15frames) |>
Until(10frames) |> Array == zeros(10,nch)
x = 5ones(5,nch)
result = Pad(x,zero) |> Until(10frames) |> ToFramerate(10Hz) |>
Array
@test all(iszero,result[6:10,:])
x = rand(10,nch)
result = Pad(Signal(x,10Hz),cycle) |> Until(30frames) |> Array
@test result == vcat(x,x,x)
result = Pad(Signal(x,10Hz),mirror) |> Until(30frames) |> Array
@test result == vcat(x,reverse(x,dims=1),x)
result = Pad(Signal(x,10Hz),lastframe) |> Until(15frames) |> Array
@test all(result[11:end,:] .== result[10:10,:])
x = Signal(sin,10Hz) |> ToChannels(nch) |> Until(1s)
@test_throws ErrorException Pad(x,cycle) |> Array
@test_throws ErrorException Pad(x,mirror) |> Array
result = Pad(x,lastframe) |> Until(15frames) |> Array
@test all(result[11:end,:] .== result[10:10,:])
padv = rand(nch)
result = Pad(x,padv) |> Until(15frames) |> Array
@test all(result[11:end,:] .== padv')
@test_throws ErrorException sin |> Until(1s) |> Pad(mirror) |>
Until(2s) |> ToFramerate(10Hz) |> sink
@test_throws ErrorException sin |> Until(1s) |> Pad((a,b) -> a+b) |>
Until(2s) |> ToFramerate(10Hz) |> sink
x = rand(10,nch)
y = rand(15,nch)
@test Extend(x,one) |> nframes == inflen
@test Mix(Extend(x,one),y) |> nframes == 15
@test Mix(y,Extend(x,one)) |> nframes == 15
@test Mix(Pad(x,one),y) |> nframes |> isinf
@test Mix(1,rand(10,2)) |> nframes == 10
@test Mix(1,Extend(rand(10,2),zero)) |> nframes == 10
@test Mix(rand(10,2),1) |> nframes == 10
@test Mix(Extend(rand(10,2),zero),1) |> nframes == 10
@test Mix(sin,1,rand(10,2)) |> nframes |> isinf
@test Mix(1,sin,rand(10,2)) |> nframes |> isinf
@test Mix(1,rand(10,2),sin) |> nframes |> isinf
end
end
next!(progress)
@testset "Appending" begin
for nch in 1:2
a = Signal(sin,22Hz,ω=10Hz) |> ToChannels(nch) |> Until(5s)
b = Signal(sin,22Hz,ω=5Hz) |> ToChannels(nch) |> Until(5s)
tones = a |> Append(b)
@test duration(tones) == 10
@test nframes(Array(tones)) == 220
@test all(Array(tones) .== vcat(Array(a),Array(b)))
fs = 3
a = Signal(2,fs) |> ToChannels(nch) |> Until(2s) |>
Append(Signal(3,fs)) |> Until(4s)
@test nframes(Array(a)) == 4*fs
x = Append(
rand(10,nch) |> After(0.5s),
Signal(sin) |> ToChannels(nch) |> Until(0.5s)) |>
ToFramerate(20Hz) |> sink
@test duration(x) ≈ 0.5
@test_throws ErrorException Append(sin,1:10)
@test SignalTrait(Append(1:10,sin)) isa IsSignal
end
end
next!(progress)
@testset "Mixing" begin
for nch in 1:2
a = Signal(sin,30Hz,ω=10Hz) |> ToChannels(2) |> Until(2s)
b = Signal(sin,30Hz,ω=5Hz) |> ToChannels(2) |> Until(2s)
complex = Mix(a,b)
@test duration(complex) == 2
@test nframes(Array(complex)) == 60
end
x = rand(20,SignalOperators.MAX_CHANNEL_STACK+1)
y = rand(20,SignalOperators.MAX_CHANNEL_STACK+1)
@test (Mix(x,y) |> ToFramerate(20Hz) |> Array) == (x .+ y)
x = rand(20,2)
result = OperateOn(reverse,x,bychannel=false) |> ToFramerate(20Hz) |>
Array
@test result == [x[:,2] x[:,1]]
end
next!(progress)
@testset "Handling of padded Mix and Amplify" begin
for nch in 1:2
fs = 3Hz
a = Signal(2,fs) |> ToChannels(nch) |> Until(2s) |>
Append(Signal(3,fs)) |> Until(4s)
b = Signal(3,fs) |> ToChannels(nch) |> Until(3s)
result = Mix(a,b) |> Array
for ch in 1:nch
@test all(result[:,ch] .== [
fill(2,3*2) .+ fill(3,3*2);
fill(3,3*1) .+ fill(3,3*1);
fill(3,3*1)
])
end
result = Amplify(a,b) |> Array
for ch in 1:nch
@test all(result[:,ch] .== [
fill(2,3*2) .* fill(3,3*2);
fill(3,3*1) .* fill(3,3*1);
fill(3,3*1)
])
end
end
x = rand(10,2)
y = rand(5,2)
z = ones(10,4)
Signal(x,10Hz) |> AddChannel(y) |> sink!(z)
@test all(iszero,z[6:10,3:4])
end
next!(progress)
@testset "Filtering" begin
for nch in 1:2
a = Signal(sin,100Hz,ω=10Hz) |> ToChannels(nch) |> Until(5s)
b = Signal(sin,100Hz,ω=5Hz) |> ToChannels(nch) |> Until(5s)
cmplx = Mix(a,b)
high = cmplx |> Filt(Highpass,8Hz,method=Chebyshev1(5,1)) |>
DimensionalArray
low = cmplx |> Filt(Lowpass,6Hz,method=Butterworth(5)) |>
DimensionalArray
highlow = low |> Filt(Highpass,8Hz,method=Chebyshev1(5,1)) |>
DimensionalArray
bandp1 = cmplx |> Filt(Bandpass,20Hz,30Hz,method=Chebyshev1(5,1)) |>
DimensionalArray
bandp2 = cmplx |> Filt(Bandpass,2Hz,12Hz,method=Chebyshev1(5,1)) |>
DimensionalArray
bands1 = cmplx |> Filt(Bandstop,20Hz,30Hz,method=Chebyshev1(5,1)) |>
DimensionalArray
bands2 = cmplx |> Filt(Bandstop,2Hz,12Hz,method=Chebyshev1(5,1)) |>
DimensionalArray
@test_throws ErrorException Filt(a,Highpass,75Hz)
@test_throws ErrorException Filt(a,Lowpass,75Hz)
@test_throws ErrorException Filt(a,Bandpass,75Hz,80Hz)
@test_throws ErrorException Filt(a,Bandstop,75Hz,80Hz)
@test nframes(high) == 500
@test nframes(low) == 500
@test nframes(highlow) == 500
@test mean(high) < 0.01
@test mean(low) < 0.02
@test 10mean(abs,highlow) < mean(abs,low)
@test 10mean(abs,highlow) < mean(abs,high)
@test 10mean(abs,bandp1) < mean(abs,bandp2)
@test 10mean(abs,bands2) < mean(abs,bands1)
@test mean(abs,cmplx |> Amplify(10) |> Normpower |> Array) <
mean(abs,cmplx |> Amplify(10) |> Array)
# proper filtering of blocks
high2_ = cmplx |> Filt(Highpass,8Hz,method=Chebyshev1(5,1),blocksize=100)
@test high2_.blocksize == 100
high2 = high2_ |> Array
@test high2 ≈ high
# proper state of cut filtered signal (with blocks)
high3 = cmplx |>
Filt(Highpass,8Hz,method=Chebyshev1(5,1),blocksize=64) |>
After(1s)
@test Array(high3) ≈ Array(high)[101:500,:]
# custom filter interface
high4 = cmplx |>
Filt(digitalfilter(Highpass(8,fs=framerate(cmplx)),
Chebyshev1(5,1)))
@test Array(high) == Array(high4)
end
end
next!(progress)
@testset "Ramps" begin
for nch in 1:2
tone = Signal(sin,50Hz,ω=10Hz) |> ToChannels(nch) |> Until(5s)
ramped = Signal(sin,50Hz,ω=10Hz) |> ToChannels(nch) |> Until(5s) |>
Ramp(500ms) |> DimensionalArray
@test mean(@λ(_^2),ramped[Time(Between(0s,500ms))]) <
mean(@λ(_^2),ramped[Time(Between(500ms, 1s))])
@test mean(@λ(_^2),ramped[Time(Between(4.5s, 5s))]) <
mean(@λ(_^2),ramped[Time(Between(4s, 4.5s))])
@test mean(abs,vec(ramped)) < mean(abs,vec(sink(tone,Array)))
@test mean(ramped) < 1e-4
x = Signal(sin,22Hz,ω=10Hz) |> ToChannels(nch) |> Until(2s)
y = Signal(sin,22Hz,ω=5Hz) |> ToChannels(nch) |> Until(2s)
fading = FadeTo(x,y,500ms)
result = Array(fading)
@test nframes(fading) == ceil(Int,(2+2-0.5)*22)
@test nframes(result) == nframes(fading)
@test result[1:33,:] == Array(x)[1:33,:]
@test result[44:end,:] == Array(y)[11:end,:]
ramped2 = Signal(sin,500Hz,ω=20Hz,ϕ=π/2) |> ToChannels(nch) |>
Until(100ms) |> Ramp(identity) |> Array
@test mean(abs,ramped2[1:5,:]) < mean(abs,ramped2[6:10,:])
ramped2 = Signal(sin,500Hz,ω=20Hz,ϕ=π/2) |> ToChannels(nch) |>
Until(100ms) |> RampOn(identity) |> Array
@test mean(abs,ramped2[1:5,:]) < mean(abs,ramped2[6:10,:])
ramped2 = Signal(sin,500Hz,ω=20Hz,ϕ=π/2) |> ToChannels(nch) |>
Until(100ms) |> RampOff(identity) |> Array
@test mean(abs,ramped2[7:10,:]) < mean(abs,ramped2[1:6,:])
end
end
next!(progress)
@testset "Resampling" begin
for nch in 1:2
tone = Signal(sin,20Hz,ω=5Hz) |> ToChannels(nch) |> Until(5s)
resamp = ToFramerate(tone,40Hz)
@test framerate(resamp) == 40
@test nframes(resamp) == 2nframes(tone)
downsamp = ToFramerate(tone,15Hz)
@test framerate(downsamp) == 15
@test nframes(downsamp) == 0.75nframes(tone)
@test Array(downsamp) |> nframes == nframes(downsamp)
x = rand(10,nch) |> ToFramerate(2kHz) |> sink
@test framerate(x) == 2000
toned = tone |> sink
resamp = ToFramerate(toned,40Hz)
@test framerate(resamp) == 40
resampled = resamp |> sink
@test nframes(resampled) == 2nframes(tone)
# test multi-block resampling
resamp = ToFramerate(toned,40Hz,blocksize=64)
resampled2 = sink(resamp)
@test nframes(resampled) == 2nframes(tone)
@test resampled[1] ≈ resampled2[1]
# verify that the state of the filter is proplery reset
# (so it should produce same output a second time)
resampled3 = resamp |> sink
@test resampled2[1] ≈ resampled3[1]
padded = tone |> Pad(one) |> Until(7s)
resamp = ToFramerate(padded,40Hz)
@test nframes(resamp) == 7*40
@test resamp |> Array |> size == (7*40,nch)
@test ToFramerate(tone,20Hz) === tone
a = Signal(sin,48Hz,ω=10Hz) |> ToChannels(nch) |> Until(3s)
b = Signal(sin,48Hz,ω=5Hz) |> ToChannels(nch) |> Until(3s)
cmplx = Mix(a,b)
high = cmplx |> Filt(Highpass,8Hz,method=Chebyshev1(5,1))
resamp_high = ToFramerate(high,24Hz)
@test resamp_high |> Array |> size == (72,nch)
resamp_twice = ToFramerate(toned,15Hz) |> ToFramerate(50Hz)
@test resamp_twice isa SignalOperators.FilteredSignal
@test SignalOperators.child(resamp_twice) === toned
end
end
next!(progress)
@testset "Automatic reformatting" begin
a = Signal(sin,200Hz,ω=10Hz) |> ToChannels(2) |> Until(5s)
b = Signal(sin,100Hz,ω=5Hz) |> Until(3s)
complex = Mix(a,b)
@test nchannels(complex) == 2
@test framerate(complex) == 200
@test nframes(complex |> sink) == 1000
more = Mix(a,b,1)
@test nframes(more |> sink) == 1000
end
next!(progress)
@testset "Axis Arrays" begin
x = AxisArray(ones(20),Axis{:time}(range(0s,2s,length=20)))
proc = Signal(x) |> Ramp |> AxisArray
@test size(proc,1) == size(x,1)
@test proc isa AxisArray
end
next!(progress)
@testset "Operating over empty signals" begin
for nch in 1:2
tone = Signal(sin,200Hz,ω=10Hz) |> ToChannels(nch) |>
Until(10frames) |> Until(0frames)
@test nframes(tone) == 0
@test tone |> Operate(-) |> nframes == 0
end
end
next!(progress)
@testset "Normpower" begin
for nch in 1:2
tone = Signal(sin,10Hz,ω=2Hz) |> ToChannels(nch) |> Until(2s) |>
Ramp |> Normpower
@test all(sqrt.(mean(Array(tone).^2,dims=1)) .≈ 1)
resamp = tone |> ToFramerate(20Hz) |> Array
@test all(sqrt.(mean(Array(resamp).^2,dims=1)) .≈ 1)
end
end
next!(progress)
@testset "Handling of arrays/numbers" begin
stereo = Signal([10.0.*(1:10) 5.0.*(1:10)],5Hz)
@test stereo |> nchannels == 2
@test stereo |> sink(Array) |> size == (10,2)
@test stereo |> Until(5frames) |> Array |> size == (5,2)
@test stereo |> After(5frames) |> Array |> size == (5,2)
for nch in 1:2
# Numbers
tone = Signal(sin,200Hz,ω=10Hz) |> ToChannels(nch) |> Mix(1.5) |>
Until(5s) |> Array
@test all(tone .>= 0.5)
x = Signal(1,5Hz) |> ToChannels(nch) |> Until(5s) |> Array
@test x isa AbstractArray{Int}
@test all(10 |> ToChannels(nch) |> Until(1s) |>
ToFramerate(10Hz) |> Array .== 10)
dc_off = Signal(1,10Hz) |> ToChannels(nch) |> Until(1s) |>
Amplify(20dB) |> Array
@test all(dc_off .== 10)
dc_off = Signal(1,10Hz) |> ToChannels(nch) |> Until(1s) |>
Amplify(40dB) |> Array
@test all(dc_off .== 100)
# AbstractArrays
tone = Signal(sin,200Hz,ω=10Hz) |> ToChannels(nch) |> Until(10frames) |>
Mix(10.0.*(1:10)) |> Array
@test all(tone[1:10,:] .>= 10.0*(1:10))
x = Signal(10.0.*(1:10),5Hz) |> ToChannels(nch) |> Until(1s) |>
Array
@test x isa AbstractArray{Float64}
@test Signal(10.0.*(1:10),5Hz) |> ToChannels(nch) |>
SignalOperators.sampletype == Float64
end
# AxisArray
x = AxisArray(rand(2,10),Axis{:channel}(1:2),
Axis{:time}(range(0,1,length=10)))
@test x |> Until(500ms) |> Array |> size == (4,2)
@test x |> Until(500ms) |> sink |> size == (4,2)
# poorly shaped arrays
@test_throws ErrorException Signal(rand(2,2,2))
end
next!(progress)
@testset "Handling of infinite signals" begin
for nch in 1:2
tone = Signal(sin,200Hz,ω=10Hz) |> ToChannels(nch) |>
Until(10frames) |> After(5frames) |> After(2frames)
@test nframes(tone) == 3
@test size(Array(tone)) == (3,nch)
tone = Signal(sin,200Hz,ω=10Hz) |> ToChannels(nch) |>
After(5frames) |> Until(5frames)
@test nframes(tone) == 5
@test size(Array(tone)) == (5,nch)
@test Array(tone)[1] > 0.9
tone = Signal(sin,200Hz,ω=10Hz) |> ToChannels(nch) |>
Until(10frames) |> After(5frames)
@test nframes(tone) == 5
@test size(Array(tone)) == (5,nch)
@test Array(tone)[1] > 0.9
@test_throws ErrorException Signal(sin,200Hz) |> Normpower |>
Until(1s) |> Array
@test_throws ErrorException Signal(sin,200Hz) |> ToChannels(nch) |>
Array
end
end
next!(progress)
@testset "Test that non-signals correctly error" begin
x = r"nonsignal"
@test_throws MethodError x |> framerate
@test_throws MethodError x |> ToFramerate(10Hz) |> sink
@test_throws MethodError x |> duration
@test_throws ErrorException x |> Until(5s)
@test_throws ErrorException x |> After(2s)
@test_throws MethodError x |> nframes
@test_throws MethodError x |> nchannels
@test_throws ErrorException x |> Pad(zero)
@test_throws MethodError x |> Filt(Lowpass,3Hz)
@test_throws ErrorException x |> Normpower
@test_throws ErrorException x |> SelectChannel(1)
@test_throws ErrorException x |> Ramp
x = rand(5,2)
y = r"nonsignal"
@test_throws ErrorException x |> Append(y)
@test_throws ErrorException x |> Mix(y)
@test_throws ErrorException x |> AddChannel(y)
@test_throws ErrorException x |> FadeTo(y)
end
next!(progress)
@testset "Handle of frame units" begin
x = Signal(rand(100,2),10Hz)
y = Signal(rand(50,2),10Hz)
@test x |> Until(30frames) |> sink |> nframes == 30
@test x |> After(30frames) |> sink |> nframes == 70
@test x |> Append(y) |> After(20frames) |> sink |> nframes == 130
@test x |> Append(y) |> Until(130frames) |> sink |> nframes == 130
@test x |> Pad(zero) |> Until(150frames) |> sink |> nframes == 150
@test x |> Ramp(10frames) |> sink |> nframes == 100
@test x |> FadeTo(y,10frames) |> sink |> nframes > 100
end
next!(progress)
function showstring(x)
io = IOBuffer()
show(io,MIME("text/plain"),x)
String(take!(io))
end
@testset "Handle printing" begin
x = Signal(rand(100,2),10Hz)
y = Signal(rand(50,2),10Hz)
@test Signal(sin,22Hz,ω=10Hz,ϕ=π/4) |> showstring ==
"Signal(sin,ω=10,ϕ=0.125π) (22.0 Hz)"
@test Signal(2dB,10Hz) |> showstring ==
"2.0000000000000004 dB (10.0 Hz)"
@test x |> Until(5s) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> Until(5 s)"
@test x |> After(2s) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> After(2 s)"
# the below is a bit of a hack, but it works for now...
# this might break on future 1.x julia versions
if VERSION <= v"1.5.99"
@test x |> Append(y) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |>\n Append(50×2 $(Array{Float64,2}): … (10.0 Hz))"
else
@test x |> Append(y) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> Append(50×2 $(Array{Float64,2}): … (10.0 Hz))"
end
@test x |> Pad(zero) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> Pad(zero)"
@test x |> Extend(zero) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> Extend(zero)"
@test x |> Filt(Lowpass,3Hz) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> Filt(Lowpass,3 Hz)"
@test x |> Normpower |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> Normpower"
@test x |> Mix(y) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> Mix(50×2 $(Array{Float64,2}): … (10.0 Hz))"
@test x |> Amplify(y) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |>\n Amplify(50×2 $(Array{Float64,2}): … (10.0 Hz))"
@test x |> AddChannel(y) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |>\n AddChannel(50×2 $(Array{Float64,2}): … (10.0 Hz))"
@test x |> SelectChannel(1) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> SelectChannel(1)"
@test x |> Operate(identity) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> Operate(identity,)"
@test x |> ToFramerate(20Hz) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> ToFramerate(20 Hz)"
@test x |> ToChannels(1) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> ToChannels(1)"
@test ( x[1][:,1],x[2] ) |> ToChannels(2) |> showstring ==
"100-element $(Array{Float64,1}): … (10.0 Hz) |> ToChannels(2)"
@test startswith(rand(5,2) |> Filt(fs -> Highpass(10,20,fs=fs)) |> showstring,
"5×2 $(Array{Float64,2}): … |> Filt(")
@test x |> Ramp |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |>\n Amplify(RampOnFn(10 ms)) |> Amplify(RampOffFn(10 ms))"
@test x |> Ramp(identity) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |>\n Amplify(RampOnFn(10 ms,identity)) |> Amplify(RampOffFn(10 ms,identity))"
@test x |> FadeTo(y) |> showstring ==
"100×2 $(Array{Float64,2}): … (10.0 Hz) |> Amplify(RampOffFn(10 ms)) |>\n Mix(0.0 (10.0 Hz) |> Until(100 frames) |>\n ToChannels(2) |> Append(50×2 $(Array{Float64,2}): … (10.0 Hz) |>\n Amplify(RampOnFn(10 ms))))"
end
next!(progress)
@testset "Non-lazy operators" begin
x = Signal(rand(10,2),10Hz) |> sink(DimensionalArray)
y = Signal(rand(10,2),10Hz) |> sink(DimensionalArray)
@test until(x,5frames) |> size == (5,2)
@test after(x,5frames) |> size == (5,2)
@test append(x,y) |> size == (20,2)
@test prepend(x,y) |> size == (20,2)
@test operate(+,x,y) == x.+y
@test mix(x,y) == x.+y
@test amplify(x,y) == x.*y
@test addchannel(x,y) |> size == (10,4)
@test all(selectchannel(x,1) .== x[:,1])
@test rampon(x) |> size == (10,2)
@test rampoff(x) |> size == (10,2)
@test ramp(x) |> size == (10,2)
@test fadeto(x,y,4frames) |> size == (10+10-4,2)
# @test toframerate(x,5Hz) |> size == (5,2)
x_ = Signal(rand(40,2),20Hz) |> sink(DimensionalArray)
@test toframerate(x_,40Hz) |> size == (80,2)
@test tochannels(x,1) |> size == (10,1)
@test toeltype(x,Float32) |> eltype <: Float32
# @test format(x,5Hz,1) |> size == (5,1)
@test format(x_,40Hz,1) |> size == (80,1)
end
next!(progress)
@testset "Handle lower bitrate" begin
x = Signal(rand(Float32,100,2),10Hz)
y = Signal(rand(Float32,50,2),10Hz)
@test x |> framerate == 10
@test x |> sink(Array) |> eltype == Float32
@test x |> duration == 10
@test x |> Until(5s) |> Array |> eltype == Float32
@test x |> After(2s) |> Array |> eltype == Float32
@test x |> nframes == 100
@test x |> nchannels == 2
@test x |> Append(y) |> Array |> eltype == Float32
@test x |> Append(y) |> After(2s) |> Array |> eltype == Float32
@test x |> Append(y) |> Until(13s) |> Array |> eltype == Float32
@test x |> Pad(zero) |> Until(15s) |> Array |> eltype == Float32
@test x |> Filt(Lowpass,3Hz) |> Array |> eltype == Float32
@test x |> Normpower |> Amplify(-10f0*dB) |> Array |> eltype == Float32
@test x |> Mix(y) |> ToFramerate(10Hz) |> Array |> eltype == Float32
@test x |> AddChannel(y) |> ToFramerate(10Hz) |> Array |> eltype == Float32
@test x |> SelectChannel(1) |> ToFramerate(10Hz) |> Array |> eltype == Float32
@test x |> Ramp |> Array |> eltype == Float32
@test x |> FadeTo(y) |> Array |> eltype == Float32
end
next!(progress)
@testset "Handle fixed point numbers" begin
x = Signal(rand(Fixed{Int16,15},100,2),10Hz)
y = Signal(rand(Fixed{Int16,15},50,2),10Hz)
@test x |> framerate == 10
@test x |> sink |> framerate == 10
@test x |> duration == 10
@test x |> Until(5s) |> duration == 5
@test x |> After(2s) |> duration == 8
@test x |> nframes == 100
@test x |> nchannels == 2
@test x |> Until(3s) |> sink |> nframes == 30
@test x |> After(3s) |> sink |> nframes == 70
@test x |> Append(y) |> sink |> nframes == 150
@test x |> Append(y) |> After(2s) |> sink |> nframes == 130
@test x |> Append(y) |> Until(13s) |> sink |> nframes == 130
@test x |> Pad(zero) |> Until(15s) |> sink |> nframes == 150
@test x |> Filt(Lowpass,3Hz) |> sink |> nframes == 100
@test x |> Normpower |> Amplify(-10dB) |> sink |> nframes == 100
@test x |> Mix(y) |> sink() |> ToFramerate(10Hz) |> nframes == 100
@test x |> AddChannel(y) |> sink() |> ToFramerate(10Hz) |> nframes == 100
@test x |> SelectChannel(1) |> sink() |> ToFramerate(10Hz) |> nframes == 100
@test x |> Ramp |> sink |> nframes == 100
@test x |> FadeTo(y) |> sink |> nframes == 150
end
next!(progress)
@testset "Handle unknown frame rates" begin
x = rand(100,2)
y = rand(50,2)
@test x |> framerate |> ismissing
@test x |> ToFramerate(10Hz) |> sink |> framerate == 10
@test x |> ToFramerate(10Hz) |> framerate == 10
@test x |> duration |> ismissing
@test x |> Until(5s) |> duration |> ismissing
@test x |> After(2s) |> duration |> ismissing
@test x |> nframes == 100
@test x |> nchannels == 2
@test x |> ToFramerate(10Hz) |> sink |> framerate == 10
@test x |> Until(3s) |> ToFramerate(10Hz) |> sink |> nframes == 30
@test x |> After(3s) |> ToFramerate(10Hz) |> sink |> nframes == 70
@test x |> Append(y) |> ToFramerate(10Hz) |> sink |> nframes == 150
@test x |> Append(y) |> After(2s) |> ToFramerate(10Hz) |> sink |>
nframes == 130
@test x |> Append(y) |> Until(13s) |> ToFramerate(10Hz) |> sink |>
nframes == 130
@test x |> Pad(zero) |> Until(15s) |> ToFramerate(10Hz) |> sink |>
nframes == 150
@test x |> Filt(Lowpass,3Hz) |> ToFramerate(10Hz) |> sink |>
nframes == 100
@test x |> Normpower |> Amplify(-10dB) |> ToFramerate(10Hz) |> sink |>
nframes == 100
@test x |> Mix(y) |> ToFramerate(10Hz) |> sink |> nframes == 100
@test x |> AddChannel(y) |> ToFramerate(10Hz) |> sink |> nframes == 100
@test x |> SelectChannel(1) |> ToFramerate(10Hz) |> sink |>
nframes == 100
@test x |> Ramp |> ToFramerate(10Hz) |> sink |> nframes == 100
@test_throws ErrorException x |> FadeTo(y) |> ToFramerate(10Hz) |> sink
end
next!(progress)
@testset "Short-block Operators" begin
x = Signal(ones(25,2),10Hz)
y = Signal(ones(10,2),10Hz)
z = Signal(ones(15,2),10Hz)
@test sink(x |> Append(y) |> Append(z) |> Filt(Lowpass,3Hz,blocksize=5)) ==
sink(x |> Append(y) |> Append(z) |> Filt(Lowpass,3Hz))
@test sink(x |> Pad(zero) |> Until(15s) |> Append(y) |> Filt(Lowpass,3Hz,blocksize=5)) ==
sink(x |> Pad(zero) |> Until(15s) |> Append(y) |> Filt(Lowpass,3Hz,blocksize=5))
@test sink(x |> RampOn(7frames) |> Filt(Lowpass,3Hz,blocksize=5)) ==
sink(x |> RampOn(7frames) |> Filt(Lowpass,3Hz))
@test sink(x |> Ramp(3frames) |> Filt(Lowpass,3Hz,blocksize=5)) ==
sink(x |> Ramp(3frames) |> Filt(Lowpass,3Hz))
@test toframerate(y,40Hz) |> first |> size == (40,2)
@test toframerate(y,5Hz) |> first |> size == (5,2)
@test_throws ErrorException toframerate(y,40Hz,blocksize=5)
@test_throws ErrorException toframerate(y,5Hz,blocksize=5)
end
# try out more complicated combinations of various features
@testset "Stress tests" begin
# Append, dropping the first signal entirely
a = Until(sin,2s)
b = Until(cos,2s)
x = Append(a,b) |> After(3s)
@test (x |> ToFramerate(20Hz) |> sink) ==
(b |> After(1s) |> ToFramerate(20Hz) |> sink())
noise = Signal(randn,20Hz) |> Until(6s) |> sink
# filtering in combination with `After`
x = noise |> Filt(Lowpass,7Hz) |> Until(4s)
afterx = noise |> Filt(Lowpass,7Hz) |> Until(4s) |> After(2s)
@test sink(x,DimensionalArray)[Time(Between(2s, 4s))] ≈
sink(afterx,DimensionalArray)
# multiple frame rates
x = Signal(sin,ω=10Hz,20Hz) |> Until(4s) |> sink |>
ToFramerate(30Hz) |> Filt(Lowpass,10Hz) |>
FadeTo(Signal(sin,ω=5Hz) |> Until(4s),500ms) |>
ToFramerate(22Hz)
@test framerate(x) == 22
@test duration(x) == 7.5
x = Signal(sin,ω=10Hz,20Hz) |> Until(4s) |>
ToFramerate(30Hz) |> Filt(Lowpass,10Hz) |>
FadeTo(Signal(sin,ω=5Hz) |> Until(4s),500ms) |>
ToFramerate(22Hz) |> sink
@test framerate(x) == 22
@test duration(x) == 7.5
# multiple filters
x = noise |>
Filt(Lowpass,9Hz) |>
Mix(Signal(sin,ω=12Hz) |> Until(6s)) |>
Filt(Highpass,4Hz,method=Chebyshev1(5,1)) |>
Array
y = noise |>
Filt(Lowpass,9Hz) |>
Mix(Signal(sin,ω=12Hz) |> Until(6s)) |>
sink |>
Filt(Highpass,4Hz,method=Chebyshev1(5,1)) |>
Array
@test x ≈ y
y = noise |>
Filt(Lowpass,9Hz,blocksize=11) |>
Mix(Signal(sin,ω=12Hz) |> Until(6s)) |>
Filt(Highpass,4Hz,method=Chebyshev1(5,1),blocksize=9) |>
Array
@test x ≈ y
# multiple After and Until commands
x = Signal(sin,ω=5Hz) |> After(2s) |> Until(20s) |> After(2s) |>
Until(15s) |> After(2s) |> After(2s) |> Until(5s) |> Until(2s) |>
ToFramerate(12Hz) |> sink
@test duration(x) == 2
# different offset appending summation
x = Append(1 |> Until(1s),2 |> Until(2s))
y = Append(3 |> Until(2s),4 |> Until(1s))
result = Mix(x,y) |> ToFramerate(10Hz) |> Array
@test all(result .== [fill(4,10);fill(5,10);fill(6,10)])
# multiple operators with a Mix in the middle
x = randn |> Until(4s) |> After(50ms) |> Filt(Lowpass,5Hz) |>
Mix(Signal(sin,ω=7Hz)) |>
Until(3.5s) |>
Filt(Highpass,2Hz) |>
Append(rand(10,2)) |>
Append(rand(5,2)) |>
ToFramerate(20Hz) |> sink
@test duration(x) == 4.25
end
next!(progress)
@testset "README Examples" begin
randn |> Until(2s) |> Normpower |> ToFramerate(44.1kHz) |>
sink(example_wav)
sound1 = Signal(sin,ω=1kHz) |> Until(5s) |> Ramp |> Normpower |>
Amplify(-20dB)
result = sound1 |> ToFramerate(4kHz) |> sink
@test result |> nframes == 4000*5
@test mean(abs,result[1]) > 0
sound2 = example_wav |> Normpower |> Amplify(-20dB)
# a 1kHz sawtooth wave
sound3 = Signal(ϕ -> ϕ/π - 1,ω=1kHz) |> Until(2s) |> Ramp |>
Normpower |> Amplify(-20dB)
# a 5 Hz amplitude modulated noise
sound4 = randn |>
Amplify(Signal(ϕ -> 0.5sin(ϕ) + 0.5,ω=5Hz)) |>
Until(5s) |> Normpower |> Amplify(-20dB)
# a 1kHz tone surrounded by a notch noise
SNR = 5dB
x = Signal(sin,ω=1kHz) |> Until(1s) |> Ramp |> Normpower |> Amplify(-20dB + SNR)
y = Signal(randn) |> Until(1s) |> Filt(Bandstop,0.5kHz,2kHz) |> Normpower |>
Amplify(-20dB)
scene = Mix(x,y)
# write all of the signal to a single file, at 44.1 kHz
Append(sound1,sound2,sound3,sound4,scene) |> sink(examples_wav)
@test isfile(examples_wav)
end
next!(progress)
@testset "Testing DimensionalData" begin
x = rand(10,2)
data = DimensionalArray(x,(Time(range(0s,0.9s,step=0.1s)),SigChannel(1:2)))
@test all(Array(Mix(data,1)) .== data .+ 1)
data2 = x |> Signal(10Hz) |> sink(DimensionalArray)
# failed test!!
@test data2 == data
@test sink(Mix(data,1)) isa DimensionalArray
end
next!(progress)
# test LibSndFile and SampleBuf
# (only supported for Julia versions 1.3 or higher)
@static if VERSION ≥ v"1.3"
mydir = mktempdir(@__DIR__)
Pkg.activate(mydir)
Pkg.add("LibSndFile")
Pkg.add("SampledSignals")
@testset "Testing LibSndFile" begin
using LibSndFile
using SampledSignals: SampleBuf
randn |> Until(2s) |> Normpower |> ToFramerate(4kHz) |>
sink(example_ogg)
x = example_ogg |> sink(SampleBuf)
example_ogg |> sink(AxisArray)
@test SignalOperators.framerate(x) == 4000
@test sink(Mix(x,1)) isa SampleBuf
end
next!(progress)
@testset "Test adaptive return type" begin
x = rand(10,2)
data = DimensionalArray(x,(Time(range(0s,1s,length=10)),X(1:2)))
@test sink(Mix(1,data)) isa DimensionalArray
data = SampleBuf(x,10)
@test sink(Mix(1,data)) isa SampleBuf
data = Signal(rand(10,2),10Hz) |> sink(AxisArray)
data2 = SampleBuf(x,10)
@test sink(Mix(rand(10,2),data2)) isa SampleBuf
@test sink(Mix(data,data2)) isa AxisArray
@test sink(Mix(data2,data)) isa SampleBuf
end
rm(mydir,recursive=true,force=true)
next!(progress)
end
for file in test_files
isfile(file) && rm(file)
end
end
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | docs | 4314 | # SignalOperators
[](https://www.repostatus.org/#active)
[](https://haberdashPI.github.io/SignalOperators.jl/stable)
[](https://haberdashPI.github.io/SignalOperators.jl/dev)
[](https://github.com/haberdashPI/SignalOperators.jl/actions?query=workflow%3ACI)
[](https://juliaci.github.io/NanosoldierReports/pkgeval_badges/report.html)
[](https://codecov.io/gh/haberdashPI/SignalOperators.jl)
SignalOperators is a [Julia](https://julialang.org/) package that aims to provide a clean interface for generating and manipulating signals: typically sounds, but any signal regularly sampled in time can be manipulated.
```julia
using WAV
using SignalOperators
using SignalOperators.Units # allows the use of dB, Hz, s etc... as unitful values
# a pure tone 20 dB below a power 1 signal, with on and off ramps (for
# a smooth onset/offset)
sound1 = Signal(sin,ω=1kHz) |> Until(5s) |> Ramp |> Normpower |> Amplify(-20dB)
# a sound defined by a file, matching the overall power to that of sound1
sound2 = "example.wav" |> Normpower |> Amplify(-20dB)
# a 1kHz sawtooth wave
sound3 = Signal(ϕ -> ϕ-π,ω=1kHz) |> Ramp |> Normpower |> Amplify(-20dB)
# a 5 Hz amplitude modulated noise
sound4 = randn |>
Amplify(Signal(ϕ -> 0.5sin(ϕ) + 0.5,ω=5Hz)) |>
Until(5s) |> Normpower |> Amplify(-20dB)
# a 1kHz tone surrounded by a notch noise
SNR = 5dB
x = Signal(sin,ω=1kHz) |> Until(1s) |> Ramp |> Normpower |> Amplify(-20dB + SNR)
y = Signal(randn) |> Until(1s) |> Filt(Bandstop,0.5kHz,2kHz) |> Normpower |>
Amplify(-20dB)
scene = Mix(x,y)
# write all of the signals to a single file, at 44.1 kHz
Append(sound1,sound2,sound3,sound4,scene) |> ToFramerate(44.1kHz) |> sink("examples.wav")
```
The interface is relatively generic and can be used to operate on or produce
a number of different signal representations, including
[`AxisArrays`](https://github.com/JuliaArrays/AxisArrays.jl),
[`DimensionalData`](https://github.com/rafaqz/DimensionalData.jl) and
`SampleBuf` objects from
[`SampledSignals`](https://github.com/JuliaAudio/SampledSignals.jl). It
should also be straightforward to extend the operators to [new signal
representations](https://haberdashpi.github.io/SignalOperators.jl/stable/custom_signal/).
Operators generally produce signals that match the type input values, when these are uniform.
In many cases, operators are designed to create efficient, lazy
representations of signals, and will only generate data on a call to [`sink`](https://haberdashpi.github.io/SignalOperators.jl/stable/reference/#SignalOperators.sink);
however, there are non-lazy versions of the operators as well, for quick,
one-off usage.
```julia
using SampledSignals: SampleBuf
a = SampleBuf(rand(100,2),100)
b = SampleBuf(ones(100,2),100)
using SignalOperators
c = mix(a,b)
c == sink(Mix(a,b))
```
Because of the smarts in the operators, the resulting value `c` will also be a `SampleBuf` object.
Read more about how to use the operators in the [documentation](https://haberdashPI.github.io/SignalOperators.jl/stable).
## Status
The functions are relatively bug-free and thoroughly documented.
Everything here will run pretty fast. All calls should fall within the same
order of magnitude of equivalent "raw" julia code (e.g. loops and
broadcasting over arrays).
I'm the only person I know who has made thorough use of this package: it's obviously possible there are still some bugs or performance issues lurking about. (I welcome new issues or PRs!!!)
## Acknowledgements
Many thanks to @ssfrr for some great discussions during this [PR](https://github.com/JuliaAudio/SampledSignals.jl/pull/44), and related issues on the [SampledSignals](https://github.com/JuliaAudio/SampledSignals.jl) package. Those interactions definitely influenced my final design here.
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | docs | 910 | This documents my git workflow.
*Before version 0.2*: all commits are to master, and tags denote new, stable
releases of the 0.1 branch.
*Starting with the development of version 0.2 features*
1. master includes the latest and greatest, working features
2. release-x.y: stable branch for older release x.y, making it
easy to backport any bug fixes
3. feat-X branches contain new, WIP features, that may not yet compile
and may be quite buggy
4. fix-X branches contain new, WIP bug fixes, that may not yet compile
5. refactor-X branches contain new, WIP refactoring of code that may not
yet compile
New releases of the most recent version # are tagged on master.
When a `feat`, `fix` or `refactor` branch is merged, it should first be rebased into commits that conform to the [Conventiional Commit](https://www.conventionalcommits.org/en/v1.0.0-beta.2/#summary) standard.
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | docs | 2467 | # [Custom Signals](@id custom_signals)
To treat new custom objects as signals, you must support the signal
interface. Such an object must return an appropriate
[`SignalOperators.IsSignal`](@ref) object when calling
[`SignalOperators.SignalTrait`](@ref).
`IsSignal` is an emptry struct that has three type parameters, indicating the
[`sampletype`](@ref) the type of [`framerate`](@ref) and the type used to
represent the length returned by [`nframes`](@ref). For example, for an array
`SignalTrait` is implemented as follows.
```julia
SignalTrait(x::Type{<:Array{T}}) where T = IsSignal{T,Missing,Int}
```
All signals should implement the appropriate methods from [`SignalBase`](https://github.com/haberdashPI/SignalBase.jl).
What additional methods you should implement depends on what kind of signal
you have.
## AbstractArray objects
If your signal is an array of some kind you should implement
[`SignalOperators.timeslice`](@ref), which should return a requested range of
frames from the signal.
You should also consider defining your array type to be a [custom sink](@ref custom_sinks).
## Other objects
Any other type of signal should implement
[`SignalOperators.nextblock`](@ref), which is used to sequentially retrieve
blocks from a signal.
Analogous to `Base.iterate`, [`SignalOperators.nextblock`](@ref) will return
`nothing` when there are no more blocks to produce.
If the returned blocks will be represetend by an array of numbers, then
[`SignalOperators.ArrayBlock`](@ref) should be used.
In other cases, such as when you want to compute individual frames of the block on-the-fly, you should return an object that implements the following two methods.
* [`nframes`](@ref) Like a signal, each block has some number of frames. Unlike signals, this cannot be an infinite or missing value. The implementation should be a fast, type-stable function.
* [`SignalOperators.frame`](@ref) Individual frames of the block can be accessed by their index within the block (falling in the range of `1:nframes(block)`). This should be a fast, type-stable function. The method is guaranteed to only be called at most once for each index in the block.
## Optional Methods
There are several **optional** methods you can define for signals as
well.
* [`Signal`](@ref) - to enable one more other types to be interpreted as your custom signal type
* [`SignalOperators.EvalTrait`](@ref) and [`ToFramerate`](@ref) - to enable custom handling of signal resmapling | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | docs | 946 | # [Custom Sinks] (@id custom_sinks)
You can create custom sinks, which can be passed to [`sink`](@ref) or
[`sink!`](@ref) by defining two methods: [`SignalOperators.initsink`](@ref)
and [`SignalOperators.sink_helper!`](@ref). The first method is called when a
call to `sink` is made (e.g. `sink(MyCustomSink)`). The second method is
called inside `sink!` and provides the core operation to write blocks of
frames to the sink. There is already a method of `sink_helper!` defined for
`AbstractArray` objects, so you likely do not need to implement it if your
custom sink is an `AbtractArray`.
You may also want to implement a constructor of the sink type that takes a
single argument `x` of type `SignalOperators.AbstractSignal`. This should
generally just call `sink(x,CustomSink)`.
!!! note
Implementing `initsink` is not strictly necessary. If you do not implement
`initsink` you will only be able to write to the sink using `sink!`. | SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | docs | 1907 | # SignalOperators.jl
SignalOperators is a [Julia](https://julialang.org/) package that aims to provide a clean interface for generating and manipulating signals: typically sounds, but any signal regularly sampled in time can be manipulated.
You can install it in Julia by starting the Pkg prompt (hit `]`), and using the `add` command.
```julia
(1.2) pkg> add SignalOperators
```
As a preview of functionality, here are some example sound generation routines. You can find more detailed information in the manual and reference.
```julia
using SignalOperators
using SignalOperators.Units # allows the use of dB, Hz, s etc... as unitful values
# a pure tone 20 dB below a power 1 signal, with on and off ramps (for
# a smooth onset/offset)
sound1 = Signal(sin,ω=1kHz) |> Until(5s) |> Ramp |> Normpower |> Amplify(-20dB)
# a sound defined by a file, matching the overall power to that of sound1
sound2 = "example.wav" |> Normpower |> Amplify(-20dB)
# a 1kHz sawtooth wave
sound3 = Signal(ϕ -> ϕ-π,ω=1kHz) |> Ramp |> Normpower |> Amplify(-20dB)
# a 5 Hz amplitude modulated noise
sound4 = randn |>
Amplify(Signal(ϕ -> 0.5sin(ϕ) + 0.5,ω=5Hz)) |>
Until(5s) |> Normpower |> Amplify(-20dB)
# a 1kHz tone surrounded by a notch noise
SNR = 5dB
x = Signal(sin,ω=1kHz) |> Until(1s) |> Ramp |> Normpower |> Amplify(-20dB + SNR)
y = Signal(randn) |> Until(1s) |> Filt(Bandstop,0.5kHz,2kHz) |> Normpower |>
Amplify(-20dB)
scene = Mix(x,y)
# write all of the signals to a single file, at 44.1 kHz
Append(sound1,sound2,sound3,sound4,scene) |> ToFramerate(44.1kHz) |> sink("examples.wav")
```
## Acknowledgements
Many thanks to @ssfrr for some great discussions during this [PR](https://github.com/JuliaAudio/SampledSignals.jl/pull/44), and related issues on the [SampledSignals](https://github.com/JuliaAudio/SampledSignals.jl) package. Those interactions definitely influenced my final design here.
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | docs | 11969 | # Manual
SignalOperators is composed of a set of functions for generating, inspecting and operating over signals. Here, a "signal" is represented as a number of frames: each frame contains some number of channels (e.g. left and right speaker) with a sampled value (e.g. `Float64`) for each channel. The values are sampled regularly in time (e.g. every 100th of a second, or 100 Hz); this is referred to as the frame rate.
## Key concepts
There are several important concepts employed across the public interface. Let's step through one of the examples from the homepage (and README.md), which demonstrates most of these concepts.
```julia
sound1 = Signal(sin,ω=1kHz) |> Until(5s) |> Ramp |> Normpower |> Amplify(-20dB)
```
This example creates a 1 kHz pure-tone (sine wave) that lasts 5 seconds. Its amplitude is 20 dB lower than a signal with unit 1 power.
There are a few things going on here: piping, the use of units, lazy evaluation, infinite length signals and unspecified frame rates.
### Piping
Almost all of the operators in SignalOperators can be piped. This means that instead of passing the first argument you can pipe it using `|>`. For example, the two statements below have the same meaning.
```julia
sound1 = Signal(sin,ω=1kHz) |> Until(5s)
sound1 = Until(Signal(sin,ω=1kHz),5s)
```
The use of piping makes it easier to read the sequence of operations that are performed on the signal.
### Units
In any place where a function needs a time or a frequency, it can be specified in appropriate units. There are many places where units can be passed. They all have a default assumed unit if a plain number without units is passed. The default units are seconds, Hertz, and radians as appropriate for the given argument.
```julia
sound1 = Signal(sin,ω=1kHz)
sound1 = Signal(sin,ω=1000)
```
Each unit is represented by a constant you can multiply by a number (in Julia, 10ms == 10*ms). To make use of the unit constants, you must call `using SignalOperators.Units`. This exports the following units: `frames`, `kframes`, `Hz`, `kHz` `s`, `ms`, `rad`, `°`, and `dB`. You can just include the ones you want using e.g. `using SignalOperators.Units: Hz`, or you can include more by adding the [`Unitful`](https://github.com/PainterQubits/Unitful.jl) package to your project and adding the desired units from there. For example, `using Unitful: MHz` would include mega-Hertz frequencies (not normally useful for sound signals). Most of the default units have been re-exported from `Unitful`. However, the `frames` unit and its derivatives (e.g. `kframes`) are unique to the SignalOperators package. They allow you to specify the time in terms of the number of frames: e.g. at a frame rate of 100 Hz, `2s == 200frames`. Other powers of ten are represented for `frames`, (e.g. `Mframes` for mega-frames) but they are not exported (e.g. you would have to call `SignalOperators.Units: Mframes` before using `20Mframes`).
!!! note
You can find the available powers-of-ten for units in `Unitful.prefixdict`
Note that the output of functions to inspect a signal (e.g. `duration`, `framerate`) are bare values in the default unit (e.g. seconds or Hertz). No unit is explicitly provided by the return value.
#### Decibels
You can pass an amplification value as a unitless or a unitful value in `dB`; a unitless value is not assumed to be in decibels. Instead, it's assumed to be the actual ratio by which you wish to multiply the signal. For example, `Amplify(x,2)` will make `x` twice as loud while `Amplify(x,2dB)` will increase the amplitude by two decibells.
### Lazy Evaluation
To ensure efficient signal generation, signal operators are lazy: no computations are performed until the actual signal data is requested. This lazy quality is reflected in the captilization of the operators: conceptually the operators define some new signal object which can be used to generate frames of data based on the input signal or signals.
To request evaluation of a lazy signal you can use an array constructor: `Array`, `AxisArray`, `DimensinoalArray` or `SampleBuf`, or you can call the more general methods [`sink`](@ref) or [`sink!`](@ref). The result of `sink` is itself a (non-lazy) signal. You can always specify the return type of `sink`, but by default it tries to maintain the same representation of the signal or signals used as input, favoring the earlier arguments over later arguments. For example `sink(SampleBuf(rand(10,2),10) |> Mix(1)) isa SampleBuf`.
The function [`sink`](@ref) can also write data to a file. To store the five second signal in the above example to "example.wav" we could write the following.
```julia
sound1 |> ToFramerate(44.1kHz) |> sink("example.wav")
```
In this case `sound1` had no defined frame rate, so we must specify one using
[`ToFramerate`](@ref).
#### Non-lazy operators
If you prefer the result of an operator to be non-lazy, so you don't have to call `sink` first, you can make use the lower case versions of the operators. These operators do not allow for piping, as this would typically be quite
inefficient. If you want to combine multiple operators, they should normally be evaluated lazily.
### Infinite lengths
Some of the ways you can define a signal lead to an infinite length signal.
To allow for calls to `sink`, you have to specify the length, using
[`Until`](@ref). For example, when using `Signal(sin)`, the signal is an
infinite length sine wave. That's why, in the example above, we use
[`Until`](@ref) to specify the length, as follows.
```julia
Signal(sin,ω=1kHz) |> Until(5s)
```
Infinite lengths are represented as the value [`inflen`](@ref) (e.g. when calling [`nframes`](@ref)). This has overloaded definitions of various operators to play nicely with ordering, arithmetic etc...
### Unspecified frame rates
You may notice that the above signal has no defined frame rate. Such a signal is defined by a function, and can be sampled at whatever rate you desire. If you add a signal to the chain of operations that does have a defined frame rate, the unspecified frame rate will be resolved to that same rate (see signal promotion, below).
### Signal promotion
A final concept, which is not as obvious from the examples, is the use of
automatic signal promotion. When multiple signals are passed to the same
operator, and they have a different number of channels or different frame
rate, the signals are first converted to the highest fidelity format and then
operated on. This allows for a relatively seamless chain of operations where
you don't have to worry about the specific format of the signal, and you
won't loose information about your signals unless you explicitly request a
lower fidelity signal format (e.g. using [`ToChannels`](@ref) or
[`ToFramerate`](@ref)).
## Signal generation
There are four basic types that can be interpreted as signals: numbers,
arrays, functions and files. Internally the function [`Signal`](@ref) is
called on any object passed to a function that operates on a
signal; you can call [`Signal`](@ref) yourself if you want to specify more
information. For example, you may want to provide the exact frame rate the
signal should be interpreted to have.
### Numbers
A number is treated as an infinite length signal, with unknown frame rate.
```julia
1 |> Until(1s) |> ToFramerate(10Hz) |> sink == ones(10)
```
### Arrays
A standard array is treated as a finite signal with unknown frame rate.
```julia
rand(10,2) |> ToFramerate(10Hz) |> sink |> duration == 1
```
An `AxisArray`, `DimesnionalArray` or `SampleBuf` (from [`SampledSignals`](https://github.com/JuliaAudio/SampledSignals.jl)) is treated as a finite signal with a known frame rate (and is the default output of [`sink`](@ref))
```julia
using AxisArrays
x = AxisArray(rand(10,1),Axis{:time}(range(0,1,length=10)))
framerate(x) == 10
```
### Functions
A single argument function of time (in seconds) can be treated as an infinite
signal. It can be also be a function of radians if you specify a frequency
using `ω` (or `frequency`). See [`Signal`](@ref)'s documentation for more
details.
```julia
Signal(sin,ω=1kHz) |> duration |> isinf == true
```
A small exception to this is `randn`. It can be used directly as a signal with unknown frame rate.
```julia
randn |> duration == isinf
```
### Files
A file is interpreted as an audio file to be loaded into memory. You must
include the `WAV` or `LibSndFile` package for this to work.
```julia
using WAV
x = Signal("example.wav")
```
## Signal inspection
You can examine the properties of a signal using [`nframes`](@ref), [`nchannels`](@ref), [`framerate`](@ref), and [`duration`](@ref).
## Signal operators
There are several categories of signal operators: extending, cutting, filtering, ramping, and mapping.
### Extending
You can extend a signal using [`Pad`](@ref) or [`Append`](@ref). A padded signal becomes infinite by appending the signal by a repeated value, usually `one` or `zero`. You can append two or more signals (or [`Prepend`](@ref)) so they occur one after another.
```julia
Pad(x,zero) |> duration |> isinf == true
Append(x,y,z) |> duration == duration(x) + duration(y) + duration(z)
```
!!! note
You cannot append more than one new signal within a pipe. That is,
the following will throw an error.
```julia
# Don't do this!
x |> Append(y,z)
```
This is because `Append(y,z)` does not return a function to be piped (as
`Append(y)` does). It returns a signal with `y` followed by `z`. You can instead call this as follows.
```julia
# This will do what you want!
x |> Append(y) |> Append(z)
```
### Cutting
You can cut signals apart, removing either the end of the signal ([`Until`](@ref)) or the beginning ([`After`](@ref)). The operations are exact compliments of one another.
```julia
Append(Until(x,2s),After(x,2s)) |> nframes == nframes(x)
```
### Filtering
You can filter signals, removing undesired frequencies using [`Filt`](@ref).
```julia
Signal(randn) |> Filt(Lowpass,20Hz)
```
!!! warning
If you write `using DSP` you will have to also write `dB = SignalOperators.Units.dB` if you want to make use of the proper meaning of `dB` for `SignalOperators`: `DSP` also defines `dB`.
An unusual filter is [`Normpower`](@ref): it computes the root mean squared power of the signal and then normalizes each frame by that value.
### Ramping
A Ramp allows for smooth transitions between 0 amplitude and the full amplitude of the signal. It is useful to avoid clicks in the onset or offset of a sound. For example, pure-tones are typically ramped when presented.
```julia
Signal(sin,ω=2kHz) |> Until(5s) |> Ramp
```
You can ramp only the start of a signal ([`RampOn`](@ref)), or the end of it ([`RampOff`](@ref)) and you can use ramps to create a smooth transition between two signals ([`FadeTo`](@ref)).
### General operators
The most general operator is [`OperateOn`](@ref). It works a lot like `map` but automatically promotes the signals, as with all operators, *and* it pads the end of the signal appropriately, so different length signals can be combined. The output is always the length of the longest *finite*-length signal.
```julia
a = Signal(sin,ω=2kHz) |> Until(2s)
b = Signal(sin,ω=1kHz) |> Until(3s)
a_minus_b = OperateOn(-,a,b)
```
The function [`OperateOn`](@ref) cannot itself be piped, due to ambiguity in the arguments, but you can use the shorter [`Operate`](@ref) for these purposes.
```julia
a_minus_b = a |> Operate(-,b)
```
A number of shortcuts for `OperateOn` exist, and these can be piped normally. There are shortcuts for addition ([`Mix`](@ref)) and multiplication ([`Amplify`](@ref)).
```julia
a_plus_b = a |> Mix(b)
a_times_b = a |> Amplify(b)
```
There are shortcuts to add or isolate channels, [`AddChannel`](@ref) and
[`SelectChannel`](@ref). These set the keyword argument `bychannel` of
[`OperateOn`](@ref) to `false` (see [`OperateOn`](@ref)'s documentation for
details).
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.5.1 | d8dcac8d4c1876d6e23226145ac6e3ac8d4d0b85 | docs | 1022 | # Reference
## Signal Generation
```@docs
Signal
sink
sink!
```
## Signal Inspection
```@docs
inflen
duration
nframes
nchannels
framerate
sampletype
```
## Signal Operators
### Basic Operators
```@docs
Until
until
After
after
Window
window
Append
append
Prepend
prepend
Pad
Extend
mirror
cycle
lastframe
SignalOperators.valuefunction
```
### Mapping Operators
```@docs
Filt
Normpower
normpower
OperateOn
Operate
operate
Mix
mix
Amplify
amplify
AddChannel
addchannel
SelectChannel
selectchannel
```
### Ramping Operators
```@docs
RampOn
rampon
RampOff
rampoff
Ramp
ramp
FadeTo
fadeto
```
### Reformatting Operators
```@docs
ToFramerate
toframerate
ToChannels
tochannels
ToEltype
toeltype
Format
format
Uniform
```
## Custom Signals
```@docs
SignalOperators.SignalTrait
SignalOperators.IsSignal
SignalOperators.EvalTrait
SignalOperators.nextblock
SignalOperators.frame
SignalOperators.timeslice
SignalOperators.ArrayBlock
```
## Custom Sinks
```@docs
SignalOperators.initsink
SignalOperators.sink_helper!
```
| SignalOperators | https://github.com/haberdashPI/SignalOperators.jl.git |
|
[
"MIT"
] | 0.1.0 | 655dc935ae8cfe92c07c1b414e629b774e0b42dc | code | 3939 | # version = v"1.14.1119"
version = v"1.14.1227"
deps_dir = dirname(@__FILE__)
par_dir = abspath(joinpath(deps_dir, ".."))
sdk_dir = joinpath(deps_dir, "sdk_v$version")
lib_target_dir = joinpath(par_dir, "lib")
lib_dir = joinpath(sdk_dir, "lib")
lib_x64_dir = joinpath(lib_dir, "x64")
lib_x86_dir = joinpath(lib_dir, "x86")
lib_mac_dir = joinpath(lib_dir, "mac")
if Sys.islinux() || Sys.isapple()
sdk_file = joinpath(deps_dir, "ASI_linux_mac_SDK_V$version.tar.bz2")
if !isfile(sdk_file)
println("Downloading ASI_linux_mac_SDK_V$version.tar.bz2 from astronomy-imaging-camera.com (ZWO)")
download("https://astronomy-imaging-camera.com/software/ASI_linux_mac_SDK_V$version.tar.bz2", sdk_file)
end
elseif Sys.iswindows()
sdk_file = joinpath(deps_dir, "ASI_Windows_SDK_V$version.zip")
if !isfile(sdk_file)
println("Downloading ASI_Windows_SDK_V$version.zip from astronomy-imaging-camera.com (ZWO)")
download("https://astronomy-imaging-camera.com/software/ASI_Windows_SDK_V$version.zip", sdk_file)
end
end
if !isdir(sdk_dir) mkdir(sdk_dir) end
if !isdir(lib_target_dir) mkdir(lib_target_dir) end
#extract
if isfile(sdk_file)
if Sys.isunix()
unpack_cmd = `tar xjf $sdk_file --directory=$sdk_dir` end
if Sys.iswindows()
if isdefined(Base, :LIBEXECDIR)
const exe7z = joinpath(Sys.BINDIR, Base.LIBEXECDIR, "7z.exe")
else
const exe7z = joinpath(Sys.BINDIR, "7z.exe")
end
unpack_cmd = `$exe7z x -o$sdk_dir -y $sdk_file`
end
run(unpack_cmd)
end
# copy extracted library file to lib subfolder
if Sys.islinux()
mv(joinpath(lib_dir, "asi.rules"), joinpath(deps_dir, "..", "asi.rules"), force=true)
if Sys.ARCH==:x86_64
if Sys.WORD_SIZE==64
source_file = joinpath(lib_x64_dir, "libASICamera2.so.$version")
target_file = joinpath(lib_target_dir, "libASICamera2.so")
mv(source_file, target_file, force=true)
else
source_file = joinpath(lib_x86_dir, "libASICamera2.so.$version")
target_file = joinpath(lib_target_dir, "libASICamera2.so")
mv(source_file, target_file, force=true)
end
# RaspberryPi support
elseif Sys.ARCH==:aarch64
source_file = joinpath(lib_dir, "armv8", "libASICamera2.so.$version")
target_file = joinpath(lib_target_dir, "libASICamera2.so")
mv(source_file, target_file, force=true)
elseif Sys.ARCH==:arm || (Sys.ARCH==:aarch && Sys.WORD_SIZE==32)
source_file = joinpath(lib_dir, "armv7", "libASICamera2.so.$version")
target_file = joinpath(lib_target_dir, "libASICamera2.so")
mv(source_file, target_file, force=true)
end
elseif Sys.isapple()
source_file = joinpath(lib_mac_dir, "libASICamera2.dylib.$version")
target_file = joinpath(lib_target_dir, "libASICamera2.dylib")
mv(source_file, target_file, force=true)
elseif Sys.iswindows()
if isa(1, Int64)
source_file = joinpath(sdk_dir, "ASI SDK", "lib", "x64", "ASICamera2.dll")
target_file = joinpath(lib_target_dir, "ASICamera2.dll")
mv(source_file, target_file, force=true)
else
source_file = joinpath(sdk_dir, "ASI SDK", "lib", "x86", "ASICamera2.dll")
target_file = joinpath(lib_target_dir, "ASICamera2.dll")
mv(source_file, target_file, force=true)
end
end
# cleanup
rm(sdk_file)
rm(sdk_dir, recursive=true)
if Sys.isunix()
rules_file = joinpath(par_dir, "asi.rules")
println("\nPlease install the udev rules for the camera device, so that you can
access it without root privileges. To install the rules, run
'sudo install $rules_file /lib/udev/rules.d'\n
or\n
'sudo install $rules_file /etc/udev/rules.d'\n
and reboot or relog and reconnect the camera. Then run\n
'cat /sys/module/usbcore/parameters/usbfs_memory_mb'\n
and make sure the result is 200.\n")
end
| LibASICamera | https://github.com/AlfTetzlaff/LibASICamera.jl.git |
|
[
"MIT"
] | 0.1.0 | 655dc935ae8cfe92c07c1b414e629b774e0b42dc | code | 135 | using Documenter, LibASICamera
makedocs(sitename="LibASICamera API")
deploydocs(repo = "github.com/AlfTetzlaff/LibASICamera.jl.git")
| LibASICamera | https://github.com/AlfTetzlaff/LibASICamera.jl.git |
|
[
"MIT"
] | 0.1.0 | 655dc935ae8cfe92c07c1b414e629b774e0b42dc | code | 925 | module LibASICamera
import Libdl
using CEnum
if Sys.isunix()
const libASICamera2 = joinpath(@__DIR__, "../lib/libASICamera2")
elseif Sys.isapple() # don't know if apple counts as unix
const libASICamera2 = joinpath(@__DIR__, "../lib/libASICamera2")
elseif Sys.iswindows()
const libASICamera2 = joinpath(@__DIR__, "../lib/ASICamera2")
end
include(joinpath(@__DIR__, "LibASICamera_highlevel.jl"))
export
ASICamera,
open_camera,
close_camera,
init_camera,
start_exposure,
stop_exposure,
start_video,
stop_video,
allocate_buffer,
enable_dark_subtract,
disable_dark_subtract,
pulse_guide_on,
pulse_guide_off,
send_soft_trigger,
capture_still
#capture_video
# export the rest
foreach(names(@__MODULE__, all=true)) do s
if startswith(string(s), "ASI") || startswith(string(s), "set") ||startswith(string(s), "get")
@eval export $s
end
end
end # module
| LibASICamera | https://github.com/AlfTetzlaff/LibASICamera.jl.git |
|
[
"MIT"
] | 0.1.0 | 655dc935ae8cfe92c07c1b414e629b774e0b42dc | code | 7246 | function ASIGetNumOfConnectedCameras()
ccall((:ASIGetNumOfConnectedCameras, libASICamera2), Cint, ())
end
function ASIGetProductIDs(pPIDs)
ccall((:ASIGetProductIDs, libASICamera2), Cint, (Ref{Cint},), pPIDs)
end
function ASIGetCameraProperty(pASICameraInfo, iCameraIndex)
ccall((:ASIGetCameraProperty, libASICamera2), ASI_ERROR_CODE, (Ref{_ASI_CAMERA_INFO}, Cint), pASICameraInfo, iCameraIndex)
end
function ASIGetCameraPropertyByID(iCameraID, pASICameraInfo)
ccall((:ASIGetCameraPropertyByID, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{ASI_CAMERA_INFO}), iCameraID, pASICameraInfo)
end
function ASIOpenCamera(iCameraID)
ccall((:ASIOpenCamera, libASICamera2), ASI_ERROR_CODE, (Cint,), iCameraID)
end
function ASIInitCamera(iCameraID)
ccall((:ASIInitCamera, libASICamera2), ASI_ERROR_CODE, (Cint,), iCameraID)
end
function ASICloseCamera(iCameraID)
ccall((:ASICloseCamera, libASICamera2), ASI_ERROR_CODE, (Cint,), iCameraID)
end
# ASI_ERROR_CODE ASIGetNumOfControls(int iCameraID, int * piNumberOfControls);
function ASIGetNumOfControls(iCameraID, piNumberOfControls::Ref{Cint})
ccall((:ASIGetNumOfControls, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{Cint}), iCameraID, piNumberOfControls)
end
function ASIGetControlCaps(iCameraID, iControlIndex, pControlCaps)
ccall((:ASIGetControlCaps, libASICamera2), ASI_ERROR_CODE, (Cint, Cint, Ref{_ASI_CONTROL_CAPS}), iCameraID, iControlIndex, pControlCaps)
end
function ASIGetControlValue(iCameraID, ControlType, plValue::Ref{Clong}, pbAuto::Ref{ASI_BOOL})
ccall((:ASIGetControlValue, libASICamera2), ASI_ERROR_CODE, (Cint, Cint, Ref{Clong}, Ref{ASI_BOOL}), iCameraID, ControlType, plValue, pbAuto)
end
function ASISetControlValue(iCameraID, ControlType, lValue, bAuto)
ccall((:ASISetControlValue, libASICamera2), ASI_ERROR_CODE, (Cint, Cint, Clong, Cint), iCameraID, ControlType, lValue, bAuto)
end
function ASISetROIFormat(iCameraID, iWidth, iHeight, iBin, Img_type::ASI_IMG_TYPE)
ccall((:ASISetROIFormat, libASICamera2), ASI_ERROR_CODE, (Cint, Cint, Cint, Cint, ASI_IMG_TYPE), iCameraID, iWidth, iHeight, iBin, Img_type)
end
function ASIGetROIFormat(iCameraID, piWidth::Ref{Cint}, piHeight::Ref{Cint}, piBin::Ref{Cint}, pImg_type::Ref{ASI_IMG_TYPE})
ccall((:ASIGetROIFormat, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{ASI_IMG_TYPE}), iCameraID, piWidth, piHeight, piBin, pImg_type)
end
function ASISetStartPos(iCameraID, iStartX, iStartY)
ccall((:ASISetStartPos, libASICamera2), ASI_ERROR_CODE, (Cint, Cint, Cint), iCameraID, iStartX, iStartY)
end
function ASIGetStartPos(iCameraID, piStartX::Ref{Cint}, piStartY::Ref{Cint})
ccall((:ASIGetStartPos, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{Cint}, Ref{Cint}), iCameraID, piStartX, piStartY)
end
function ASIGetDroppedFrames(iCameraID, piDropFrames)
ccall((:ASIGetDroppedFrames, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{Cint}), iCameraID, piDropFrames)
end
function ASIEnableDarkSubtract(iCameraID, pcBMPPath)
ccall((:ASIEnableDarkSubtract, libASICamera2), ASI_ERROR_CODE, (Cint, Cstring), iCameraID, pcBMPPath)
end
function ASIDisableDarkSubtract(iCameraID)
ccall((:ASIDisableDarkSubtract, libASICamera2), ASI_ERROR_CODE, (Cint,), iCameraID)
end
function ASIStartVideoCapture(iCameraID)
ccall((:ASIStartVideoCapture, libASICamera2), ASI_ERROR_CODE, (Cint,), iCameraID)
end
function ASIStopVideoCapture(iCameraID)
ccall((:ASIStopVideoCapture, libASICamera2), ASI_ERROR_CODE, (Cint,), iCameraID)
end
function ASIGetVideoData(iCameraID, pBuffer::T, lBuffSize, iWaitms) where T
if T == Matrix{UInt8}
ccall((:ASIGetVideoData, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{Cuchar}, Clong, Cint), iCameraID, pBuffer, lBuffSize, iWaitms)
elseif T == Matrix{UInt16} # explicitly handle unsafe conversion from uint16 to uint8
ccall((:ASIGetVideoData, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{Cuchar}, Clong, Cint), iCameraID, Base.unsafe_convert(Ref{Cuchar}, pBuffer), lBuffSize, iWaitms)
end
end
function ASIPulseGuideOn(iCameraID, direction)
ccall((:ASIPulseGuideOn, libASICamera2), ASI_ERROR_CODE, (Cint, Cint), iCameraID, direction)
end
function ASIPulseGuideOff(iCameraID, direction)
ccall((:ASIPulseGuideOff, libASICamera2), ASI_ERROR_CODE, (Cint, Cint), iCameraID, direction)
end
function ASIStartExposure(iCameraID, bIsDark)
ccall((:ASIStartExposure, libASICamera2), ASI_ERROR_CODE, (Cint, Cint), iCameraID, bIsDark)
end
function ASIStopExposure(iCameraID)
ccall((:ASIStopExposure, libASICamera2), ASI_ERROR_CODE, (Cint,), iCameraID)
end
function ASIGetExpStatus(iCameraID, pExpStatus)
ccall((:ASIGetExpStatus, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{ASI_EXPOSURE_STATUS}), iCameraID, pExpStatus)
end
function ASIGetDataAfterExp(iCameraID, pBuffer::T, lBuffSize) where T
if T == Matrix{UInt8}
ccall((:ASIGetDataAfterExp, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{Cuchar}, Clong), iCameraID, pBuffer, lBuffSize)
elseif T == Matrix{UInt16} # explicitly handle unsafe conversion from uint16 to uint8
ccall((:ASIGetDataAfterExp, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{Cuchar}, Clong), iCameraID, Base.unsafe_convert(Ref{Cuchar}, pBuffer), lBuffSize)
end
end
function ASIGetID(iCameraID, pID)
ccall((:ASIGetID, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{ASI_ID}), iCameraID, pID)
end
function ASISetID(iCameraID, ID)
ccall((:ASISetID, libASICamera2), ASI_ERROR_CODE, (Cint, ASI_ID), iCameraID, ID)
end
function ASIGetGainOffset(iCameraID, pOffset_HighestDR, pOffset_UnityGain, pGain_LowestRN, pOffset_LowestRN)
ccall((:ASIGetGainOffset, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{Cint}, Ref{Cint}, Ref{Cint}, Ref{Cint}), iCameraID, pOffset_HighestDR, pOffset_UnityGain, pGain_LowestRN, pOffset_LowestRN)
end
function ASIGetSDKVersion()
ccall((:ASIGetSDKVersion, libASICamera2), Cstring, ())
end
function ASIGetCameraSupportMode(iCameraID, pSupportedMode)
ccall((:ASIGetCameraSupportMode, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{_ASI_SUPPORTED_MODE}), iCameraID, pSupportedMode)
end
function ASIGetCameraMode(iCameraID, mode)
ccall((:ASIGetCameraMode, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{ASI_CAMERA_MODE}), iCameraID, mode)
end
function ASISetCameraMode(iCameraID, mode)
ccall((:ASISetCameraMode, libASICamera2), ASI_ERROR_CODE, (Cint, ASI_CAMERA_MODE), iCameraID, mode)
end
function ASISendSoftTrigger(iCameraID, bStart)
ccall((:ASISendSoftTrigger, libASICamera2), ASI_ERROR_CODE, (Cint, Cint), iCameraID, bStart)
end
function ASIGetSerialNumber(iCameraID, pSN)
ccall((:ASIGetSerialNumber, libASICamera2), ASI_ERROR_CODE, (Cint, Ref{ASI_SN}), iCameraID, pSN)
end
function ASISetTriggerOutputIOConf(iCameraID, pin, bPinHigh, lDelay, lDuration)
ccall((:ASISetTriggerOutputIOConf, libASICamera2), ASI_ERROR_CODE, (Cint, ASI_TRIG_OUTPUT_PIN, Cint, Clong, Clong), iCameraID, pin, bPinHigh, lDelay, lDuration)
end
function ASIGetTriggerOutputIOConf(iCameraID, pin, bPinHigh, lDelay, lDuration)
ccall((:ASIGetTriggerOutputIOConf, libASICamera2), ASI_ERROR_CODE, (Cint, ASI_TRIG_OUTPUT_PIN, Ref{Cint}, Ref{Clong}, Ref{Clong}), iCameraID, pin, bPinHigh, lDelay, lDuration)
end
| LibASICamera | https://github.com/AlfTetzlaff/LibASICamera.jl.git |
|
[
"MIT"
] | 0.1.0 | 655dc935ae8cfe92c07c1b414e629b774e0b42dc | code | 23481 | include(joinpath(@__DIR__, "LibASICamera_types.jl"))
include(joinpath(@__DIR__, "LibASICamera_ccalls.jl"))
"""
ASICamera
The struct which contains information about the camera.
Has fields .info and .control_caps.
"""
struct ASICamera
info::ASI_CAMERA_INFO
control_caps::Vector{ASI_CONTROL_CAPS}
end
"""
allocate_buffer(width::Integer, height::Integer, img_type::ASI_IMG_TYPE)
Allocates an image buffer for the camera to write to.
# Args:
width: Image width
height: Image height
img_type: One of
-ASI_IMG_RAW8
-ASI_IMG_Y8
-ASI_IMG_RAW16
-ASI_IMG_RAW24
# Returns:
A zero-initialized array of the appropriate shape.
# Throws:
ASIWrapperError if an unsupported image type is given.
"""
function allocate_buffer(width::Integer, height::Integer, img_type::ASI_IMG_TYPE)
if img_type==ASI_IMG_RAW8 || img_type==ASI_IMG_Y8
return zeros(UInt8, width, height)
elseif img_type==ASI_IMG_RAW16
return zeros(UInt16, width, height)
elseif img_type==ASI_IMG_RAW24
return zeros(UInt8, width, height, 3)
else
throw(ASIWrapperError("Image type $img_type not implemented."))
end
end
# This allows to use an ellipsis: allocate_buffer(get_roi_format(cam)...)
allocate_buffer(width::Integer, height::Integer, unused, img_type::ASI_IMG_TYPE) =
allocate_buffer(width, height, img_type)
"""
get_num_connected_cameras()
This function returns the count of connected cameras and should be called first.
"""
get_num_connected_cameras() = ASIGetNumOfConnectedCameras()
"""
get_camera_property(id::Integer)
Fetches the camera properties for a given ID.
# Args:
id: Camera id
# Returns:
ASI_CAMERA_INFO object
# Throws:
ASIError in case of failure
"""
function get_camera_property(id::Integer)
camera_info = _ASI_CAMERA_INFO()
err = ASIGetCameraProperty(camera_info, id)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return ASI_CAMERA_INFO(camera_info) # convert to human-readable type
end
get_camera_property(cam::ASICamera) = get_camera_property(cam.info.CameraID)
"""
open_camera(id::Integer)
Opens the ASI camera connection.
Open the camera before any interaction with the camera,
this will not affect the camera which is capturing.
Then you must call init_camera() to perform any actions.
# Args:
id: Camera ID
# Throws:
ASIError
"""
function open_camera(id::Integer)
err = ASIOpenCamera(id)
if err != ASI_SUCCESS
print("[ERROR] Could not connect to camera. Make sure you can access the camera without being root by calling
\"sudo install asi.rules /lib/udev/rules.d\" from the lib subdir of the SDK
and then relogging / rebooting.")
throw(ASIError(err))
end
end
open_camera(cam::ASICamera) = open_camera(cam.info.CameraID)
"""
init_camera(id::Integer)
Initialize the camera. Needs to be called before capturing any data.
# Args:
id: Camera id
# Throws:
ASIError
"""
function init_camera(id::Integer)
err = ASIInitCamera(id)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
init_camera(cam::ASICamera) = init_camera(cam.info.CameraID)
"""
close_camera(id::Integer)
Closes the ASI camera connection.
# Args:
id: Camera id
# Throws:
ASIError
"""
function close_camera(id::Integer)
err = ASICloseCamera(id)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
close_camera(cam::ASICamera) = close_camera(cam.info.CameraID)
"""
get_control_caps(id::Integer)
Returns the control properties available for this camera.
The camera needs to be open.
# Args:
id: Camera id
# Returns:
Vector of ASI_CONTROL_CAPS structs.
# Throws:
ASIError
"""
function get_control_caps(id::Integer)
num_controls = Ref{Cint}(0)
err = ASIGetNumOfControls(id, num_controls)
if err != ASI_SUCCESS
throw(ASIError(err))
end
control_caps = Vector{ASI_CONTROL_CAPS}(undef, num_controls.x)
for i in 1:num_controls.x
cap = _ASI_CONTROL_CAPS()
err = ASIGetControlCaps(id, i-1, cap)
if err != ASI_SUCCESS
throw(ASIError(err))
end
control_caps[i] = ASI_CONTROL_CAPS(cap) # convert to human-readable type
end
return control_caps
end
get_control_caps(cam::ASICamera) = get_control_caps(cam.info.CameraID)
"""
get_connected_devices()
Returns a list of the connected devices.
"""
function get_connected_devices()
num_cameras = get_num_connected_cameras()
if num_cameras == 0
throw(ASIWrapperError("No cameras found."))
end
cameras = Vector{ASICamera}(undef, num_cameras)
for i in 0:num_cameras-1
open_camera(i)
init_camera(i)
info = get_camera_property(i)
control_caps = get_control_caps(i)
cameras[i+1] = ASICamera(info, control_caps)
end
return cameras
end
"""
get_control_value(id::Integer, control_type::ASI_CONTROL_TYPE)
Fetches the current setting of the control value, e.g. exposure or gain.
# Args:
id: Camera id
control_type: The control type to fetch, e.g. exposure or gain.
# Returns:
A tuple (value, is_auto)
# Throws:
ASIError
"""
function get_control_value(id::Integer, control_type::ASI_CONTROL_TYPE)
value = Ref{Clong}(0)
auto = Ref{ASI_BOOL}(ASI_FALSE)
err = ASIGetControlValue(id, control_type, value, auto)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return (value[], Bool(auto[]))
end
get_control_value(cam::ASICamera, control_type::ASI_CONTROL_TYPE) = get_control_value(cam.info.CameraID, control_type)
get_temperature(id) = get_control_value(id, ASI_TEMPERATURE)[1] * 0.1
"""
set_control_value(id::Integer, control_type::ASI_CONTROL_TYPE, value, auto::Bool=false)
Sets a control (e.g. exposure) to the given value. Automatically sets the
minimum or maximum if the given value is out of bounds.
# Args:
id: Camera id
control_type: The control type to set, e.g. exposure or gain.
value: The value to which the control is set.
auto: Whether or not the control should be automatically set.
Check if this is supported for the given control beforehand.
# Throws:
ASIError
"""
function set_control_value(id::Integer, control_type::ASI_CONTROL_TYPE, value, auto::Bool=false)
err = ASISetControlValue(id, control_type, value, auto)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
set_control_value(cam::ASICamera, control_type::ASI_CONTROL_TYPE, value, auto::Bool=false) = set_control_value(cam.info.CameraID, control_type, value, auto)
set_gain(id, gain, auto=false) = set_control_value(id, ASI_GAIN, gain, auto)
set_exposure(id, exposure_μs, auto=false) = set_control_value(id, ASI_EXPOSURE, exposure_μs, auto)
set_gamma(id, gamma, auto=false) = set_control_value(id, ASI_GAMMA, gamma, auto)
set_bandwidth(id, bandwidth, auto=false) = set_control_value(id, ASI_BANDWIDTHOVERLOAD, bandwidth, auto)
set_flip(id, flip) = set_control_value(id, ASI_FLIP, flip)
set_autoexp_max_gain(id, val) = set_control_value(id, ASI_AUTO_MAX_GAIN, val)
set_autoexp_max_exp(id, exposure_ms) = set_control_value(id, ASI_AUTO_MAX_EXP, exposure_ms)
set_autoexp_target_brightness(id, brightness) = set_control_value(id, ASI_AUTO_MAX_BRIGHTNESS, brightness)
set_highspeed_mode(id, active) = set_control_value(id, ASI_HIGH_SPEED_MODE, active)
# ...
"""
get_status(id::Integer)
Returns the status of all camera parameters.
"""
function get_status(id::Integer)
control_caps = get_control_caps(id)
ret = []
for t in control_caps
push!(ret, (t.Name, get_control_value(id, t.ControlType)[1]))
end
return ret
end
get_status(cam::ASICamera) = get_status(cam.info.CameraID)
"""
set_roi_format(id::Integer, width, height, binning, img_type::ASI_IMG_TYPE)
Sets the region of interest (roi). Do so before capturing.
The width and height are the values *after* binning, i.e. you need to set the
width to 640 and the height to 480 if you want to run at 640x480 @ BIN2.
ASI120's data size must be a multiple of 1024 which means width*height%1024==0.
# Args:
id: Camera id
width: ROI width
height: ROI height
binning: The binning mode; 2 means to read out 2x2 pixels together. Check
which binning values are supported in the ASI_CAMERA_INFO struct of the
camera struct or by calling get_camera_property(id).
# Throws:
ASIError
"""
function set_roi_format(id::Integer, width, height, binning, img_type::ASI_IMG_TYPE)
if width%8 != 0
throw("Width must be a multiple of 8.")
end
if height%2 != 0
throw("Height must be a multiple of 2.")
end
if (width*height)%1024 != 0 && get_camera_property(id).Name in ["ZWO ASI 120MM", "ZWO ASI 120MC"]
throw("Width times height must be a multiple of 2.")
end
err = ASISetROIFormat(id, width, height, binning, img_type)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
set_roi_format(cam::ASICamera, width, height, binning, img_type::ASI_IMG_TYPE) = set_roi_format(cam.info.CameraID, width, height, binning, img_type)
"""
get_roi_format(id::Integer)
Fetches the current region of interest settings.
"""
function get_roi_format(id::Integer)
width = Ref{Cint}(0)
height = Ref{Cint}(0)
binning = Ref{Cint}(false)
img_type = Ref{ASI_IMG_TYPE}(ASI_IMG_RAW8)
err = ASIGetROIFormat(id, width, height, binning, img_type)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return (width.x, height.x, binning.x, img_type.x)
end
get_roi_format(cam::ASICamera) = get_roi_format(cam.info.CameraID)
"""
set_roi_start(id::Integer, startx, starty)
Sets the position of the top-left corner of the region of interest.
You can call this while the camera is streaming to move the ROI. By default,
the ROI will be centered. In binned mode, the start values are relative to the
binned sensor size.
# Throws:
ASIError
"""
function set_roi_start(id::Integer, startx, starty)
err = ASISetStartPos(id, startx, starty)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
set_roi_start(cam::ASICamera, startx, starty) = set_roi_start(cam.info.CameraID, startx, starty)
"""
get_roi_start(id::Integer)
Returns the region of interest start position (start_x, start_y).
"""
function get_roi_start(id::Integer)
startx = Ref{Cint}(0)
starty = Ref{Cint}(0)
err = ASIGGetStartPos(id, startx, starty)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return (startx[], starty[])
end
get_roi_start(cam::ASICamera) = get_roi_start(cam.info.CameraID)
"""
get_dropped_frames(id::Integer)
Returns the number of dropped frames.
Frames are dropped when the USB is bandwidth is low or the
harddisk write speed is slow. The count is reset to 0 after capturing stops.
"""
function get_dropped_frames(id::Integer)
dropped_frames = Ref{Cint}(0)
err = ASIGetDroppedFrames(id, dropped_frames)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
get_dropped_frames(cam::ASICamera) = get_dropped_frames(cam.info.CameraID)
"""
"""
function enable_dark_subtract(id::Integer, path)
err = ASIEnableDarkSubtract(id, path)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
enable_dark_subtract(cam::ASICamera) = enable_dark_subtract(cam.info.CameraID)
"""
"""
function disable_dark_subtract(id::Integer)
err = ASIDisableDarkSubtract(id)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
disable_dark_subtract(cam::ASICamera) = disable_dark_subtract(cam.info.CameraID)
"""
start_video(id::Integer)
Start video capture.
# Throws:
ASIError
"""
function start_video(id::Integer)
err = ASIStartVideoCapture(id)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
start_video(cam::ASICamera) = start_video(cam.info.CameraID)
"""
stop_video(id::Integer)
Stops a running video capture.
# Throws:
ASIError
"""
function stop_video(id::Integer)
err = ASIStopVideoCapture(id)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
stop_video(cam::ASICamera) = stop_video(cam.info.CameraID)
"""
get_video_data!(id::Integer, buffer, timeout_ms)
Writes a video frame to the given buffer. Make sure the buffer is large
enough to fit the frame. Call this as fast as possible in a loop and check
whether the return value equals ASI_SUCCESS.
# Args:
id: Camera id
buffer: A buffer to write the video frame to.
timeout_ms: Time to wait for a frame. Recommendation: 2 * exposure_μs + 500 ms <- inconsistent units?!
# Returns:
An ASI_ERROR_CODE, which should be ASI_SUCCESS.
"""
function get_video_data!(id::Integer, buffer, timeout_ms=500)
return ASIGetVideoData(id, buffer, sizeof(buffer), Int32(round(timeout_ms)))
end
get_video_data!(cam::ASICamera, buffer, timeout_ms) = get_video_data!(cam.info.CameraID, buffer, timeout_ms)
"""
pulse_guide_on(id::Integer, direction::ASI_GUIDE_DIRECTION)
Activates the pulse guide in the given direction.
# Args:
id: Camera id
direction: Guiding direction; call 'instances(ASI_GUIDE_DIRECTION)'
# Throws:
ASIError
"""
function pulse_guide_on(id::Integer, direction::ASI_GUIDE_DIRECTION)
err = ASIPulseGuideOn(id, direction)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
pulse_guide_on(cam::ASICamera) = pulse_guide_on(cam.info.CameraID)
"""
pulse_guide_off(id::Integer, direction::ASI_GUIDE_DIRECTION)
Deactivates the pulse guide in the given direction.
# Args:
id: Camera id
direction: Guiding direction; call 'instances(ASI_GUIDE_DIRECTION)' for options.
# Throws:
ASIError
"""
function pulse_guide_off(id::Integer, direction::ASI_GUIDE_DIRECTION)
err = ASIPulseGuideOff(id, direction)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
pulse_guide_off(cam::ASICamera) = pulse_guide_off(cam.info.CameraID)
"""
start_exposure(id::Integer, is_dark=false)
Starts an exposure. All relevant parameters (exposure time, gain) have to be
set beforehand by calling set_control_value(...) or e.g. set_gain(...).
"""
function start_exposure(id::Integer, is_dark=false)
err = ASIStartExposure(id, is_dark)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
start_exposure(cam::ASICamera, is_dark=false) = start_exposure(cam.info.CameraID, is_dark)
"""
stop_exposure(id::Integer)
Stops an ongoing exposure.
"""
function stop_exposure(id::Integer)
err = ASIStopExposure(id)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
stop_exposure(cam::ASICamera) = stop_exposure(cam.info.CameraID)
"""
get_exp_status(id::Integer)
Returns the status of an ongoing exposure.
See 'instances(ASI_EXP_STATUS)'.
# Throws:
ASIError
"""
function get_exp_status(id::Integer)
status = Ref{ASI_EXPOSURE_STATUS}(ASI_EXP_IDLE)
err = ASIGetExpStatus(id, status)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return status[]
end
get_exp_status(cam::ASICamera) = get_exp_status(cam.info.CameraID)
"""
get_data_after_exp!(id::Integer, buffer)
Fetches the data after a successful exposure and writes it into buffer.
"""
function get_data_after_exp!(id::Integer, buffer)
err = ASIGetDataAfterExp(id, buffer, sizeof(buffer))
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
get_data_after_exp!(cam::ASICamera, buffer) = get_data_after_exp!(cam.info.CameraID, buffer)
"""
get_id(id::Integer)
Returns the camera id stored in flash, only available for USB3 cameras.
"""
function get_id(id::Integer)
camera_id = ASI_ID()
err = ASIGetID(id, camera_id)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
get_id(cam::ASICamera) = get_id(cam.info.CameraID)
"""
capture_still(id::Integer)
Captures a still image. You have to set gain, exposure etc. beforehand using
set_control_value(...).
# Returns:
An array containing the image.
# Throws:
ASIWrapperError if the image format is not supported by the wrapper, or
ASIError in other unfortunate cases
"""
function capture_still(id::Integer)
exposure_μs, _ = get_control_value(id, ASI_EXPOSURE)
width, height, binning, img_type = get_roi_format(id)
buffer = allocate_buffer(width, height, img_type)
start_exposure(id, false)
sleep(0.05)
# option 2: wait almost the entire exposure time instead of polling
# sleep(exposure_μs/1000*0.9)
while get_exp_status(id) == ASI_EXP_WORKING
sleep(0.01)
end
if get_exp_status(id) == ASI_EXP_SUCCESS
get_data_after_exp!(id, buffer)
return buffer[end:-1:1, :]
else
throw("Exposure failed")
end
end
capture_still(cam::ASICamera) = capture_still(cam.info.CameraID)
"""
get_gain_offset(id::Integer)
Get the presets for offset and gain values at different "sweet spots".
# Args:
id: Camera id
# Returns:
A dictionary containing:
1. The offset at highest dynamic range
2. The offset at unity gain
3. The gain with lowest readout noise
4. The offset with lowest readout noise
# Throws:
ASIError
"""
function get_gain_offset(id::Integer)
offset_highest_dr = Ref{Cint}(0) # Offset at highest dynamic range
offset_unity_gain = Ref{Cint}(0) # Offset at unity gain
gain_lowest_rn = Ref{Cint}(0) # Gain at lowest readout noise
offset_lowest_rn = Ref{Cint}(0) # Offset at lowest readout noise
err = ASIGetGainOffset(id, offset_highest_dr, offset_unity_gain, gain_lowest_rn, offset_lowest_rn)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return Dict(["offset_highest_dr" => offset_highest_dr[],
"offset_unity_gain" => offset_unity_gain[],
"gain_lowest_rn" => gain_lowest_rn[],
"offset_lowest_rn" => offset_lowest_rn[]])
end
get_gain_offset(cam::ASICamera) = get_gain_offset(cam.info.CameraID)
"""
get_sdk_version()
Returns the SDK version.
"""
function get_sdk_version()
return unsafe_string(ASIGetSDKVersion())
end
"""
get_supported_modes(id::Integer)
Returns the supported camera modes, only need to call when the
IsTriggerCam in the CameraInfo is true.
# Throws:
ASIError
"""
function get_supported_modes(id::Integer)
supported_modes = ASI_SUPPORTED_MODE()
err = ASIGetCameraSupportMode(id, supported_modes)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return [m for m in supported_modes.SupportedCameraModes if m > ASI_MODE_END]
end
get_supported_modes(cam::ASICamera) = get_supported_modes(cam.info.CameraID)
"""
get_camera_mode(id::Integer)
Get the current camera mode, only needed to call when the IsTriggerCam
in the CameraInfo is true.
"""
function get_camera_mode(id::Integer)
mode = Ref{ASI_CAMERA_MODE}(ASI_MODE_END)
err = ASIGetCameraMode(id, mode)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return mode[]
end
get_camera_mode(cam::ASICamera) = get_camera_mode(cam.info.CameraID)
"""
set_camera_mode(id::Integer, mode::ASI_CAMERA_MODE)
Set the camera mode, only needed to call when the IsTriggerCam
in the CameraInfo is true.
"""
function set_camera_mode(id::Integer, mode::ASI_CAMERA_MODE)
err = ASISetCameraMode(id, mode)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
set_camera_mode(cam::ASICamera) = set_camera_mode(cam.info.CameraID)
"""
send_soft_trigger(id::Integer, start::ASI_BOOL)
From original docs: Send a softTrigger. For edge trigger, it only need to set
true which means send a rising trigger to start exposure. For level trigger,
it need to set true first means start exposure, and set false means stop
exposure. Only needed to call when the IsTriggerCam in the CameraInfo is true.
"""
function send_soft_trigger(id::Integer, start::ASI_BOOL)
err = ASISendSoftTrigger(id, start)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
send_soft_trigger(cam::ASICamera) = send_soft_trigger(cam.info.CameraID)
"""
get_serial_number(id::Integer)
Returns the camera serial number.
"""
function get_serial_number(id::Integer)
sn = ASI_SN()
err = ASIGetSerialNumber(id, sn)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return unsafe_string(sn.id)
end
get_serial_number(cam::ASICamera) = get_serial_number(cam.info.CameraID)
"""
set_trigger_output_config(id::Integer, pin::ASI_TRIG_OUTPUT_PIN, high::ASI_BOOL, delay, duration)
Configure the output pin (A or B) of Trigger port. If duration <= 0,
this output pin will be closed. Only need to call when the IsTriggerCam
in the CameraInfo is true.
# Args:
id: Camera id
pin: Select the pin for output
high: If true, the selected pin will output a high level as a signal
when it is effective.
delay: The delay between the camera receiving a trigger signal and the
output of the valid level. From 0 μs - 2,000,000,000 μs.
duration: The duration of the valid level output. Same range as delay.
"""
function set_trigger_output_config(id::Integer, pin::ASI_TRIG_OUTPUT_PIN, high::ASI_BOOL, delay_μs, duration_μs)
err = ASISetTriggerOutputIOConf(id, pin, high, delay_μs, duration_μs)
if err != ASI_SUCCESS
throw(ASIError(err))
end
end
set_trigger_output_config(cam::ASICamera) = set_trigger_output_config(cam.info.CameraID)
"""
get_trigger_output_config(id::Integer)
Get the output pin configuration, only needed to call when the IsTriggerCam
in the CameraInfo is true.
"""
function get_trigger_output_config(id::Integer)
pin = ASI_TRIG_OUTPUT_NONE
high = ASI_FALSE
delay = Ref{Clong}(0)
duration = Ref{Clong}(0)
err = ASIGetTriggerOutputIOConf(id, pin, high, delay, duration)
if err != ASI_SUCCESS
throw(ASIError(err))
end
return Dict(["pin" => pin,
"high" => high,
"delay" => delay,
"duration" => duration])
end
get_trigger_output_config(cam::ASICamera) = get_trigger_output_config(cam.info.CameraID)
# """
# capture_video(id)
#
# Starts capturing a video in a while loop, displaying it in a Makie scene.
#
# Args:
# id: Camera object or int
#
# Throws:
# An error when the camera returns an image type which is unsupported by this package.
# """
# function capture_video(id)
# # Camera stuff setup
# exposure_μs, _ = get_control_value(id, ASI_EXPOSURE)
# width, height, binning, img_type = get_roi_format(id)
#
# buffer = allocate_buffer(width, height, img_type)
#
# # Makie scene setup
# scene = Scene() #resolution = (size(buffer,2),size(buffer,1)))
# im = image!(scene, buffer, show_axis = false, scale_plot = false, colorrange=(0,255))[end]
# display(scene)
#
# function video_loop()
# while isopen(scene)
# get_video_data!(cam, buffer, 0.2*exposure_μs+500)
# im[1] = buffer[end:-1:1, :] # flip x axis for some reason...
# yield()
# end
# end
#
# start_video(id)
#
# try
# video_loop()
# catch err
# rethrow(err)
# finally
# stop_video(id)
# end
#
# return nothing
# end
#
# capture_video(cam::ASICamera, callback::Function) = capture_video(cam.info.CameraID, callback)
| LibASICamera | https://github.com/AlfTetzlaff/LibASICamera.jl.git |
|
[
"MIT"
] | 0.1.0 | 655dc935ae8cfe92c07c1b414e629b774e0b42dc | code | 7177 | const ASICAMERA_ID_MAX = 128
# Type and error enumerations
@cenum ASI_CONTROL_TYPE::UInt32 begin
ASI_GAIN = 0
ASI_EXPOSURE = 1 # Exposure time in μs
ASI_GAMMA = 2 # 1-100, default: 50
ASI_WB_R = 3 # white balance, red component
ASI_WB_B = 4 # white balance, blue
ASI_OFFSET = 5 # pixel value offset / bias
ASI_BANDWIDTHOVERLOAD = 6 # data transfer rate percentage
ASI_OVERCLOCK = 7
ASI_TEMPERATURE = 8 # 10 times the actual temperature
ASI_FLIP = 9
ASI_AUTO_MAX_GAIN = 10 # Maximum gain when auto adjust
ASI_AUTO_MAX_EXP = 11 # Maximum exposure time when auto adjust, μs
ASI_AUTO_TARGET_BRIGHTNESS = 12 # Target brightness when auto adjust
ASI_HARDWARE_BIN = 13
ASI_HIGH_SPEED_MODE = 14
ASI_COOLER_POWER_PERC = 15
ASI_TARGET_TEMP = 16 # °C, don't multiply by 10
ASI_COOLER_ON = 17
ASI_MONO_BIN = 18 # lead to a smaller grid at software bin mode for color camera?!
ASI_FAN_ON = 19
ASI_PATTERN_ADJUST = 20 # currently only supported by 1600 mono camera
ASI_ANTI_DEW_HEATER = 21
end
const ASI_BRIGHTNESS = ASI_OFFSET
const ASI_AUTO_MAX_BRIGHTNESS = ASI_AUTO_TARGET_BRIGHTNESS
@cenum ASI_BAYER_PATTERN::UInt32 begin
ASI_BAYER_RG = 0
ASI_BAYER_BG = 1
ASI_BAYER_GR = 2
ASI_BAYER_GB = 3
end
@cenum ASI_IMG_TYPE::Int32 begin
ASI_IMG_RAW8 = 0
ASI_IMG_RGB24 = 1
ASI_IMG_RAW16 = 2
ASI_IMG_Y8 = 3
ASI_IMG_END = -1
end
@cenum ASI_GUIDE_DIRECTION::UInt32 begin
ASI_GUIDE_NORTH = 0
ASI_GUIDE_SOUTH = 1
ASI_GUIDE_EAST = 2
ASI_GUIDE_WEST = 3
end
@cenum ASI_FLIP_STATUS::UInt32 begin
ASI_FLIP_NONE = 0
ASI_FLIP_HORIZ = 1
ASI_FLIP_VERT = 2
ASI_FLIP_BOTH = 3
end
@cenum ASI_CAMERA_MODE::Int32 begin
ASI_MODE_NORMAL = 0
ASI_MODE_TRIG_SOFT_EDGE = 1
ASI_MODE_TRIG_RISE_EDGE = 2
ASI_MODE_TRIG_FALL_EDGE = 3
ASI_MODE_TRIG_SOFT_LEVEL = 4
ASI_MODE_TRIG_HIGH_LEVEL = 5
ASI_MODE_TRIG_LOW_LEVEL = 6
ASI_MODE_END = -1
end
@cenum ASI_TRIG_OUTPUT::Int32 begin
ASI_TRIG_OUTPUT_PINA = 0
ASI_TRIG_OUTPUT_PINB = 1
ASI_TRIG_OUTPUT_NONE = -1
end
const ASI_TRIG_OUTPUT_PIN = ASI_TRIG_OUTPUT
@cenum ASI_ERROR_CODE::UInt32 begin
ASI_SUCCESS = 0
ASI_ERROR_INVALID_INDEX = 1
ASI_ERROR_INVALID_ID = 2
ASI_ERROR_INVALID_CONTROL_TYPE = 3
ASI_ERROR_CAMERA_CLOSED = 4
ASI_ERROR_CAMERA_REMOVED = 5
ASI_ERROR_INVALID_PATH = 6
ASI_ERROR_INVALID_FILEFORMAT = 7
ASI_ERROR_INVALID_SIZE = 8
ASI_ERROR_INVALID_IMGTYPE = 9
ASI_ERROR_OUTOF_BOUNDARY = 10
ASI_ERROR_TIMEOUT = 11
ASI_ERROR_INVALID_SEQUENCE = 12
ASI_ERROR_BUFFER_TOO_SMALL = 13
ASI_ERROR_VIDEO_MODE_ACTIVE = 14
ASI_ERROR_EXPOSURE_IN_PROGRESS = 15
ASI_ERROR_GENERAL_ERROR = 16
ASI_ERROR_INVALID_MODE = 17
ASI_ERROR_END = 18
end
struct ASIError <: Exception
code::ASI_ERROR_CODE
end
Base.showerror(io::IO, err::ASIError) = print(io, err.code)
struct ASIWrapperError <: Exception
message::String
end
Base.showerror(io::IO, err::ASIWrapperError) = print(io, err.message)
@cenum ASI_BOOL::UInt32 begin
ASI_FALSE = 0
ASI_TRUE = 1
end
ASI_BOOL(b::Bool) = b ? ASI_TRUE : ASI_FALSE
@cenum ASI_EXPOSURE_STATUS::UInt32 begin
ASI_EXP_IDLE = 0
ASI_EXP_WORKING = 1
ASI_EXP_SUCCESS = 2
ASI_EXP_FAILED = 3
end
# Structs
# kept mutable for now, has to be checked
# added constructors
mutable struct _ASI_CAMERA_INFO
Name::NTuple{64, Cchar}
CameraID::Cint
MaxHeight::Clong
MaxWidth::Clong
IsColorCam::ASI_BOOL
BayerPattern::ASI_BAYER_PATTERN
SupportedBins::NTuple{16, Cint}
SupportedVideoFormat::NTuple{8, ASI_IMG_TYPE}
PixelSize::Cdouble
MechanicalShutter::ASI_BOOL
ST4Port::ASI_BOOL
IsCoolerCam::ASI_BOOL
IsUSB3Host::ASI_BOOL
IsUSB3Camera::ASI_BOOL
ElecPerADU::Cfloat
BitDepth::Cint
IsTriggerCam::ASI_BOOL
Unused::NTuple{16, UInt8}
end
_ASI_CAMERA_INFO() = _ASI_CAMERA_INFO(
NTuple{64, Cchar}([0 for i in 1:64]),
0,0,0,
ASI_FALSE,
ASI_BAYER_RG,
NTuple{16, Cint}([0 for i in 1:16]),
NTuple{8, ASI_IMG_TYPE}([ASI_IMG_END for i in 1:8]),
0,
ASI_FALSE,
ASI_FALSE,
ASI_FALSE,
ASI_FALSE,
ASI_FALSE,
1.,
0,
ASI_FALSE,
NTuple{16, UInt8}([0 for i in 1:16])
)
# human-readable type
struct ASI_CAMERA_INFO
Name::String
CameraID::Cint
MaxHeight::Clong
MaxWidth::Clong
IsColorCam::ASI_BOOL
BayerPattern::ASI_BAYER_PATTERN
SupportedBins::Vector
SupportedVideoFormat::Vector
PixelSize::Cdouble
MechanicalShutter::ASI_BOOL
ST4Port::ASI_BOOL
IsCoolerCam::ASI_BOOL
IsUSB3Host::ASI_BOOL
IsUSB3Camera::ASI_BOOL
ElecPerADU::Cfloat
BitDepth::Cint
IsTriggerCam::ASI_BOOL
end
ASI_CAMERA_INFO(info::_ASI_CAMERA_INFO) = ASI_CAMERA_INFO(
split(String([Char(c) for c in info.Name]), "\0")[1],
info.CameraID,
info.MaxHeight,
info.MaxWidth,
info.IsColorCam,
info.BayerPattern,
[i for i in info.SupportedBins if i > 0],
[i for i in info.SupportedVideoFormat if i > ASI_IMG_END],
info.PixelSize,
info.MechanicalShutter,
info.ST4Port,
info.IsCoolerCam,
info.IsUSB3Host,
info.IsUSB3Camera,
info.ElecPerADU,
info.BitDepth,
info.IsTriggerCam
)
mutable struct _ASI_CONTROL_CAPS
Name::NTuple{64, Cchar}
Description::NTuple{128, UInt8}
MaxValue::Clong
MinValue::Clong
DefaultValue::Clong
IsAutoSupported::ASI_BOOL
IsWritable::ASI_BOOL
ControlType::ASI_CONTROL_TYPE
Unused::NTuple{32, UInt8}
end
_ASI_CONTROL_CAPS() = _ASI_CONTROL_CAPS(
NTuple{64, Cchar}([0 for i in 1:64]), # Name
NTuple{128, Cchar}([0 for i in 1:128]), # Description
0, 0, 0, # Max, Min, Default
ASI_FALSE, # IsAutoSupported
ASI_FALSE, # IsWritable
ASI_GAIN, # ControlType; gain corresponds to 0
NTuple{32, UInt8}([0 for i in 1:32]) # Unused
)
# human-readable type
struct ASI_CONTROL_CAPS
Name::String
Description::String
MaxValue::Clong
MinValue::Clong
DefaultValue::Clong
IsAutoSupported::ASI_BOOL
IsWritable::ASI_BOOL
ControlType::ASI_CONTROL_TYPE
end
ASI_CONTROL_CAPS(control_caps::_ASI_CONTROL_CAPS) = ASI_CONTROL_CAPS(
split(String([Char(c) for c in control_caps.Name]), "\0")[1], # Name
split(String([Char(c) for c in control_caps.Description]), "\0")[1], # Description
control_caps.MaxValue, control_caps.MinValue, control_caps.DefaultValue, # Max, Min, Default
control_caps.IsAutoSupported, # IsAutoSupported
control_caps.IsWritable, # IsWritable
control_caps.ControlType # ControlType; gain corresponds to 0
)
# const ASI_CONTROL_CAPS = _ASI_CONTROL_CAPS
mutable struct _ASI_ID
id::NTuple{8, Cuchar}
end
_ASI_ID() = _ASI_ID(NTuple{8, Cuchar}(zeros(Cuchar, 10)))
const ASI_ID = _ASI_ID
const ASI_SN = ASI_ID
mutable struct _ASI_SUPPORTED_MODE
SupportedCameraModes::NTuple{16, ASI_CAMERA_MODE}
end
_ASI_SUPPORTED_MODE() = _ASI_SUPPORTED_MODE(
NTuple{16, ASI_CAMERA_MODE}(fill(ASI_MODE_END, 16))
)
const ASI_SUPPORTED_MODE = _ASI_SUPPORTED_MODE
| LibASICamera | https://github.com/AlfTetzlaff/LibASICamera.jl.git |
|
[
"MIT"
] | 0.1.0 | 655dc935ae8cfe92c07c1b414e629b774e0b42dc | code | 890 | using Test
using LibASICamera
devices = []
try
devices = get_connected_devices()
catch err
println("\nConnect the camera for testing and make sure you can access the camera
without being root by calling \"sudo install asi.rules /lib/udev/rules.d\"
from the lib subdir of the SDK and then relogging / rebooting.\n")
rethrow(err)
end
@testset "$(cam.info.Name)" for cam in devices
control_caps = get_control_caps(cam)
@testset "set/get $(cap.Name)" for cap in control_caps
default = cap.DefaultValue
control_type = cap.ControlType
if cap.IsWritable == ASI_TRUE
set_control_value(cam, control_type, default, auto = false)
@test default == get_control_value(cam, control_type)[1]
end
end
@testset "Capture Still" begin
@test isa(capture_still(cam), Array)
end
close_camera(cam)
end
| LibASICamera | https://github.com/AlfTetzlaff/LibASICamera.jl.git |
|
[
"MIT"
] | 0.1.0 | 655dc935ae8cfe92c07c1b414e629b774e0b42dc | docs | 5562 | # <img src="/docs/LibASICamera_logo.svg?raw=true&sanitize=true" width="5%"> LibASICamera.jl
[](https://alftetzlaff.github.io/LibASICamera.jl/dev/)
[](https://astronomy-imaging-camera.com/)
A julia wrapper for the ASI Camera interface.
Please note that this is my first julia project, so suggestions for improvements are welcome!
## Installation
To install this package, spin up julia, hit the ']' key to enter the package manager, then type:
```julia
pkg> add LibASICamera # works, as soon as this package is registered
#or
pkg> add https://github.com/AlfTetzlaff/LibASICamera.jl
```
### Linux specific steps
The ZWO ASI SDK will be downloaded in the background. Please note that (on Linux) you have to install the udev rules for the cameras. Run
```julia
pkg> build -v LibASICamera
```
to get the command to run in order to install the udev rules.
Or in your terminal, run:
```
sudo install /path/to/asi.rules /lib/udev/rules.d
```
### Windows specific steps
Download and install the camera driver from [here](https://astronomy-imaging-camera.com/software-drivers).
### Test
The wrapper was written and tested on Linux. In principle it should work on Windows and Mac as well, but I couldn't test it so far.
You can then connect the camera and run partial tests on functionality by typing in the package manager:
```julia
pkg> test LibASICamera
```
## Usage
Get the connected devices and open them:
```julia
devices = get_connected_devices()
cam = devices[1]
```
Query information about the camera, like resolution or pixel size:
```julia
@show get_camera_property(cam)
#or
@show cam.info
```
Get the parameters, which can be controlled or queried by the user, like gain, exposure or temperature:
```julia
@show get_control_caps(cam)
# or
@show cam.control_caps
```
Get and set a control value, for some, special shorthand functions exist:
```julia
value, is_auto_controlled = get_control_value(cam, ASI_GAIN)
set_control_value(cam, ASI_GAIN, value, is_auto_controlled)
set_gain(cam, value)
get_temperature(cam)
```
## Still image
Take a still image:
```julia
set_gain(cam, 30) # example values
set_exposure(cam, 500)
img = capture_still(cam)
```
## Video
Take a video using Makie:
```julia
using LibASICamera
using Makie
devices = get_connected_devices()
cam = devices[1]
set_gain(cam, 30, true) # example values
set_exposure(cam, 500, true)
function capture_video(cam::ASICamera)
# Camera stuff setup
width, height, binning, img_type = get_roi_format(cam)
buffer = allocate_buffer(width, height, img_type)
# Makie scene setup
colorrange = img_type == ASI_IMG_RAW16 ? 2^16-1 : 255
scene = Scene()
img = image!(scene, buffer, show_axis = false, scale_plot = false, colorrange=(0,colorrange))[end]
display(scene)
function video_loop()
err = ASI_SUCCESS
while isopen(scene) && err == ASI_SUCCESS
err = get_video_data!(cam, buffer, 5000)
img[1] = buffer[end:-1:1, :] # for some reason we have to flip x
yield()
end
println(err)
end
start_video(cam)
video_loop()
stop_video(cam)
end
@async t = capture_video(cam)
stop_video(cam)
# Always close the camera at the end
close_camera(cam)
```
The above example runs the video capturing asynchronously in the main _thread_. You might notice that the REPL input gets sluggish under certain circumstances (exposure times, bandwidth settings and depending on your hardware). This can be resolved by moving the video capturing to another _process_ using Distributed.jl:
```julia
using Distributed
addprocs(1)
nprocs()
#%%
@everywhere using LibASICamera
@everywhere using Makie
#%%
@everywhere function main()
cam = get_connected_devices()[1]
set_exposure(cam, 500, true)
set_gain(cam, 30)
set_control_value(cam, ASI_BANDWIDTHOVERLOAD, 90)
set_control_value(cam, ASI_HIGH_SPEED_MODE, false)
set_roi_format(cam, 1280, 960, 1, ASI_IMG_RAW8)
# set_roi_format(cam, 640, 480, 2, ASI_IMG_RAW8)
# set_roi_format(cam, 640, 480, 1, ASI_IMG_RAW8)
# set_roi_format(cam, 320, 240, 1, ASI_IMG_RAW8)
# set_roi_format(cam, 168, 128, 1, ASI_IMG_RAW8)
function capture_video(cam::ASICamera)
# Camera stuff setup
width, height, binning, img_type = get_roi_format(cam)
buffer = allocate_buffer(width, height, img_type)
# Makie scene setup
colorrange = img_type == ASI_IMG_RAW16 ? 2^16-1 : 255
scene = Scene()
img = image!(scene, buffer, show_axis = false, scale_plot = false, colorrange=(0,colorrange))[end]
t = text!(scene, "0 FPS", color=:yellow, position=(width, height), align=(:top, :right), textsize=Int(height/16))
display(scene)
function video_loop(cam, buffer, img, t)
err = ASI_SUCCESS
while isopen(scene) && err == ASI_SUCCESS
t0 = time_ns()
err = get_video_data!(cam, buffer, 5000)
img[1] = buffer[end:-1:1, :] # for some reason we have to flip x
t1 = time_ns()
t[end][1] = string(round(1. /(Float64(t1-t0)/1E9), digits=1), " FPS")
yield()
end
println(err)
end
start_video(cam)
video_loop(cam, buffer, img, t)
stop_video(cam)
end
capture_video(cam)
close_camera(cam)
end
remotecall(main, 2)
```
If you encounter any issues, don't hesitate to ask!
| LibASICamera | https://github.com/AlfTetzlaff/LibASICamera.jl.git |
|
[
"MIT"
] | 0.1.0 | 655dc935ae8cfe92c07c1b414e629b774e0b42dc | docs | 91 | # LibASICamera API
```@autodocs
Modules = [LibASICamera]
Order = [:function, :type]
```
| LibASICamera | https://github.com/AlfTetzlaff/LibASICamera.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 166 | using NeighbourLists
using JuLIP
using BenchmarkTools
using PyCall
using ASE
include("profile_pairlist.jl")
include("profile_nbody.jl")
include("profile_forces.jl")
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
|
[
"MIT"
] | 0.5.8 | 9a2694230a5866647c83138168a70350d10e5e36 | code | 4080 |
using NeighbourLists
using JuLIP, StaticArrays
# ==================================
# Lennard-Jones Test
# ==================================
function lj_iter(nlist, V)
Es = zeros(nsites(nlist))
for (i, _1, r, _2) in pairs(nlist)
Es[i] += V(r)
end
dE = zeros(eltype(nlist.R), nsites(nlist))
for (i, j, r, R) in pairs(nlist)
dV = (@D V(r)) * (R/r)
dE[j] += dV
dE[i] -= dV
end
return Es, dE
end
function lj_mapreduce{T}(nlist::PairList{T}, V)
Es = maptosites!( (r,R) -> V(r), zeros(T, nsites(nlist)),
pairs(nlist) )
dE = maptosites_d!((r,R) -> (@D V(r)), zeros(JVec{T}, nsites(nlist)),
pairs(nlist) )
end
function lj_nbody{T}(nlist::PairList{T}, V)
Es = maptosites!(r -> V(r[1]), zeros(T, nsites(nlist)),
nbodies(2, nlist) )
dE = maptosites_d!(r -> (@D V(r[1])), zeros(JVec{T}, nsites(nlist)),
nbodies(2, nlist) )
end
println("----------------------------------------")
println("Lennard-Jones Test")
println("----------------------------------------")
r0 = rnn(:Fe)
cutoff = r0 * 2.7
lj = LennardJones(r0, 1.0) * C1Shift(cutoff)
for L in (2, 5, 10, 20)
at = bulk(:Fe, cubic=true) * L
println("Bulk Fe, Nat = $(length(at))")
println("PairList construction:")
@time nlist = PairList(positions(at), cutoff, cell(at), pbc(at))
@time nlist = PairList(positions(at), cutoff, cell(at), pbc(at))
println("Energy + Force assembly Iterator:")
@time lj_iter(nlist, lj)
@time lj_iter(nlist, lj)
println("Energy + Force assembly MapReduce:")
@time lj_mapreduce(nlist, lj)
@time lj_mapreduce(nlist, lj)
println("Energy + Force assembly nbody MapReduce:")
@time lj_nbody(nlist, lj)
@time lj_nbody(nlist, lj)
end
# # ==================================
# # EAM Test
# # ==================================
#
#
# function eam_iter{T}(nlist::PairList{T}, V)
# Es = zeros(T, nsites(nlist))
# for (i, _1, r, R) in NeighbourLists.sites(nlist)
# Es[i] += V(r, R)
# end
# dE = zeros(JVec{T}, nsites(nlist))
# for (i, j, r, R) in NeighbourLists.sites(nlist)
# dV = @D V(r, R)
# dE[j] += dV
# dE[i] -= sum(dV)
# end
# return Es, dE
# end
#
# function eam_iter!{T}(nlist::PairList{T}, V)
# Es = zeros(T, nsites(nlist))
# for (i, _1, r, R) in NeighbourLists.sites(nlist)
# Es[i] += V(r, R)
# end
# dE = zeros(JVec{T}, nsites(nlist))
# ndv = maximum(length(j) for (i, j, r, R) in NeighbourLists.sites(nlist))
# dV = zeros(JVec{T}, ndv)
# for (i, j, r, R) in NeighbourLists.sites(nlist)
# fill!(dV, zero(JVec{T}))
# JuLIP.Potentials.evaluate_d!(dV, V, r, R)
# for a = 1:length(j)
# dE[j[a]] += dV[a]
# dE[i] -= dV[a]
# end
# end
# return Es, dE
# end
#
# function eam_mapreduce{T}(nlist::PairList{T}, V)
# Es = map!(V, zeros(T, nsites(nlist)), NeighbourLists.sites(nlist))
# dE = map_cfd!((r, R) -> (@D V(r,R)), zeros(JVec{T}, nsites(nlist)),
# NeighbourLists.sites(nlist))
# end
#
# println("----------------------------------------")
# println("Analytic EAM Test")
# println("----------------------------------------")
# r0 = rnn("Fe")
# cutoff = r0 * 2.7
# ϕ = (@analytic r -> 1/r) * C1Shift(cutoff)
# ρ = (@analytic r -> exp(-r/3)) * C1Shift(cutoff)
# eam = EAM(ϕ, ρ, @analytic t -> sqrt(1+t))
#
# for L in (5, 10, 20)
# at = bulk("Fe", cubic=true) * L
# println("Bulk Fe, Nat = $(length(at))")
# println("PairList construction:")
# @time nlist = PairList(positions(at), cutoff, cell(at), pbc(at))
# @time nlist = PairList(positions(at), cutoff, cell(at), pbc(at))
# println("Energy + Force assembly Iterator:")
# @time eam_iter(nlist, eam)
# @time eam_iter(nlist, eam)
# println("Energy + Force assembly MapReduce:")
# @time eam_mapreduce(nlist, eam)
# @time eam_mapreduce(nlist, eam)
# println("Energy + Force assembly In-place Iterator:")
# @time eam_iter!(nlist, eam)
# @time eam_iter!(nlist, eam)
# end
| NeighbourLists | https://github.com/JuliaMolSim/NeighbourLists.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.