-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstretch.jl
88 lines (75 loc) · 2.75 KB
/
stretch.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
module VectorStretch
"Checks for a 0-index access or last-index access to a vector and returns early from a caller function"
macro interpolate_return(t, i)
return esc(quote
if ($t <= 0)
return first($i)
end
if (length($i) < $t)
return last($i)
end
end)
end
"Get the floor and ceil value of a floating point number"
limits(t::AbstractFloat)::Tuple{Int32, Int32} = (floor(t), ceil(t))
"Interpolate between discrete indices on a vector. Equivalent to regular index access"
function interpolate(i::Vector{<:Number}, t::Integer)
@interpolate_return(t, i)
return i[t]
end
"Interpolate between discrete indicies on a vector."
function interpolate(i::Vector{<:Number}, t::AbstractFloat)
@interpolate_return(t, i)
min, max = limits(t)
α, β = (i[min], i[max])
Δ = t - min
return interpolate((α, β), Δ)
end
"Interpolate between discrete indicies on a vector using an easing function."
interpolate(i::Vector{<:Number}, t::AbstractFloat, easing::Function) = interpolate(i, easing(t))
"Interpolate between two values of a tuple."
interpolate(range::Tuple{Number, Number}, t::AbstractFloat) = range[1] * (1 - t) + range[2] * t
"Interpolate between two values of a tuple using an easing function."
interpolate(range::Tuple{Number, Number}, t::AbstractFloat, easing::Function) = interpolate(range, easing(t))
"Interpolate between two numbers."
interpolate(a::Number, b::Number, t::AbstractFloat) = interpolate((a, b), t)
"Interpolate between two numbers using an easing function."
interpolate(a::Number, b::Number, t::AbstractFloat, easing::Function) = interpolate((a, b), easing(t))
"Expands a vector to a specific length, staying proportional in magnitude to the original vector."
function vector_expand(i::Vector{<:Number}, n::Int)::Vector{AbstractFloat}
len = length(i)
if (len == n)
return i
end
if (i == 0)
return []
end
return [interpolate(i, x) for x in LinRange(1, len, n)]
end
"Determine the cosine similarity of two vectors of arbitrary (and different) lengths"
function similarity(a::Vector{<:Number}, b::Vector{<:Number})
len_a, len_b = (length(a), length(b))
if (len_a == len_b)
return cosinesim(a, b)
end
if (len_a > len_b)
return cosinesim(a, vector_expand(b, len_a))
else
return cosinesim(b, vector_expand(a, len_b))
end
end
"Determine the cosine similarity of two vectors"
function cosinesim(a::Vector{<:Number}, b::Vector{<:Number})
dot = 0
mA = 0
mB = 0
for i in 1:length(a)
dot += a[i] * b[i]
mA += a[i] * a[i]
mB += b[i] * b[i]
end
mA = sqrt(mA)
mB = sqrt(mB)
return (dot) / ((mA) * mB)
end
end