-
Notifications
You must be signed in to change notification settings - Fork 10
/
UnitfulRecipes.jl
224 lines (200 loc) · 7.22 KB
/
UnitfulRecipes.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
module UnitfulRecipes
using RecipesBase
using Unitful: Quantity, unit, ustrip, Unitful, dimension, Units
export @P_str
#==========
Main recipe
==========#
@recipe function f(::Type{T}, x::T) where T <: AbstractArray{<:Union{Missing,<:Quantity}}
axisletter = plotattributes[:letter] # x, y, or z
fixaxis!(plotattributes, x, axisletter)
end
function fixaxis!(attr, x, axisletter)
# Attribute keys
axislabel = Symbol(axisletter, :guide) # xguide, yguide, zguide
axislims = Symbol(axisletter, :lims) # xlims, ylims, zlims
err = Symbol(axisletter, :error) # xerror, yerror, zerror
axisunit = Symbol(axisletter, :unit) # xunit, yunit, zunit
axis = Symbol(axisletter, :axis) # xaxis, yaxis, zaxis
# Get the unit
u = pop!(attr, axisunit, unit(eltype(x)))
# If the subplot already exists, get unit from its axis label
sp = get(attr, :subplot, 1)
if sp ≤ length(attr[:plot_object])
label = attr[:plot_object][sp][axis][:guide]
if label isa UnitfulString
u = label.unit
end
# If label was not given as an argument, reuse
get!(attr, axislabel, label)
end
# Fix the attributes: labels, lims, marker/line stuff, etc.
append_unit_if_needed!(attr, axislabel, u)
ustripattribute!(attr, axislims, u)
ustripattribute!(attr, err, u)
fixmarkercolor!(attr)
fixmarkersize!(attr)
fixlinecolor!(attr)
# Strip the unit
ustrip.(u, x)
end
# Recipe for (x::AVec, y::AVec, z::Surface) types
const AVec = AbstractVector
const AMat{T} = AbstractArray{T,2} where T
@recipe function f(x::AVec, y::AVec, z::AMat{T}) where T <: Quantity
u = get(plotattributes, :zunit, unit(eltype(z)))
z = fixaxis!(plotattributes, z, :z)
append_unit_if_needed!(plotattributes, :colorbar_title, u)
x, y, z
end
# Recipe for vectors of vectors
@recipe function f(::Type{T}, x::T) where T <: AbstractVector{<:AbstractVector{<:Union{Missing,<:Quantity}}}
axisletter = plotattributes[:letter] # x, y, or z
[fixaxis!(plotattributes, x, axisletter) for x in x]
end
# Recipes for functions
@recipe function f(f::Function, x::T) where T <: AVec{<:Union{Missing,<:Quantity}}
x, f.(x)
end
@recipe function f(x::T, f::Function) where T <: AVec{<:Union{Missing,<:Quantity}}
x, f.(x)
end
@recipe function f(x::T, y::AVec, f::Function) where T <: AVec{<:Union{Missing,<:Quantity}}
x, y, f.(x',y)
end
@recipe function f(x::AVec, y::T, f::Function) where T <: AVec{<:Union{Missing,<:Quantity}}
x, y, f.(x',y)
end
@recipe function f(x::T1, y::T2, f::Function) where {T1<:AVec{<:Union{Missing,<:Quantity}}, T2<:AVec{<:Union{Missing,<:Quantity}}}
x, y, f.(x',y)
end
@recipe function f(f::Function, u::Units)
uf = UnitFunction(f, [u])
recipedata = RecipesBase.apply_recipe(plotattributes, uf)
(_, xmin, xmax) = recipedata[1].args
return f, xmin*u, xmax*u
end
"""
```julia
UnitFunction
```
A function, bundled with the assumed units of each of its inputs.
```julia
f(x, y) = x^2 + y
uf = UnitFunction(f, u"m", u"m^2")
uf(3, 2) == f(3u"m", 2u"m"^2) == 7u"m^2"
```
"""
struct UnitFunction <: Function
f::Function
u::Vector{Units}
end
(f::UnitFunction)(args...) = f.f((args .* f.u)...)
#===============
Attribute fixing
===============#
# Markers / lines
function fixmarkercolor!(attr)
u = ustripattribute!(attr, :marker_z)
ustripattribute!(attr, :clims, u)
u == Unitful.NoUnits || append_unit_if_needed!(attr, :colorbar_title, u)
end
fixmarkersize!(attr) = ustripattribute!(attr, :markersize)
fixlinecolor!(attr) = ustripattribute!(attr, :line_z)
# strip unit from attribute[key]
function ustripattribute!(attr, key)
if haskey(attr, key)
v = attr[key]
u = unit(eltype(v))
attr[key] = ustrip.(u, v)
return u
else
return Unitful.NoUnits
end
end
# If supplied, use the unit (optional 3rd argument)
function ustripattribute!(attr, key, u)
if haskey(attr, key)
v = attr[key]
if eltype(v) <: Quantity
attr[key] = ustrip.(u, v)
end
end
u
end
#=======================================
Label string containing unit information
=======================================#
abstract type AbstractProtectedString <: AbstractString end
struct ProtectedString{S} <: AbstractProtectedString
content::S
end
struct UnitfulString{S,U} <: AbstractProtectedString
content::S
unit::U
end
# Minimum required AbstractString interface to work with Plots
const S = AbstractProtectedString
Base.iterate(n::S) = iterate(n.content)
Base.iterate(n::S, i::Integer) = iterate(n.content, i)
Base.codeunit(n::S) = codeunit(n.content)
Base.ncodeunits(n::S) = ncodeunits(n.content)
Base.isvalid(n::S, i::Integer) = isvalid(n.content, i)
Base.pointer(n::S) = pointer(n.content)
Base.pointer(n::S, i::Integer) = pointer(n.content, i)
"""
P_str(s)
Creates a string that will be Protected from recipe passes.
Example:
```julia
julia> plot(rand(10)*u"m", xlabel=P"This label is protected")
julia> plot(rand(10)*u"m", xlabel=P"This label is not")
```
"""
macro P_str(s)
return ProtectedString(s)
end
#=====================================
Append unit to labels when appropriate
=====================================#
function append_unit_if_needed!(attr, key, u::Unitful.Units)
label = get(attr, key, nothing)
append_unit_if_needed!(attr, key, label, u)
end
# dispatch on the type of `label`
append_unit_if_needed!(attr, key, label::ProtectedString, u) = nothing
append_unit_if_needed!(attr, key, label::UnitfulString, u) = nothing
function append_unit_if_needed!(attr, key, label::Nothing, u)
attr[key] = UnitfulString(string(u), u)
end
function append_unit_if_needed!(attr, key, label::S, u) where {S <: AbstractString}
if !isempty(label)
attr[key] = UnitfulString(S(format_unit_label(label, u, get(attr, :unitformat, :round))), u)
end
end
#=============================================
Surround unit string with specified delimiters
=============================================#
format_unit_label(l, u, f::Nothing) = string(l, ' ', u)
format_unit_label(l, u, f::Function) = f(l, u)
format_unit_label(l, u, f::AbstractString) = string(l, f, u)
format_unit_label(l, u, f::NTuple{2, <:AbstractString}) = string(l, f[1], u, f[2])
format_unit_label(l, u, f::NTuple{3, <:AbstractString}) = string(f[1], l, f[2], u, f[3])
format_unit_label(l, u, f::Char) = string(l, ' ', f, ' ', u)
format_unit_label(l, u, f::NTuple{2, Char}) = string(l, ' ', f[1], u, f[2])
format_unit_label(l, u, f::NTuple{3, Char}) = string(f[1], l, ' ', f[2], u, f[3])
format_unit_label(l, u, f::Bool) = f ? format_unit_label(l, u, :round) : format_unit_label(l, u, nothing)
const UNIT_FORMATS = Dict(
:round => ('(', ')'),
:square => ('[', ']'),
:curly => ('{', '}'),
:angle => ('<', '>'),
:slash => '/',
:slashround => (" / (", ")"),
:slashsquare => (" / [", "]"),
:slashcurly => (" / {", "}"),
:slashangle => (" / <", ">"),
:verbose => " in units of ",
)
format_unit_label(l, u, f::Symbol) = format_unit_label(l,u,UNIT_FORMATS[f])
end # module