define _-prefaced versions of mean, maximum, minimum, extrema

This commit is contained in:
Michael K. Borregaard 2017-05-25 12:01:31 +02:00
parent da6a103649
commit 528be0e29a
13 changed files with 71 additions and 63 deletions

View File

@ -10,7 +10,6 @@ using Base.Meta
@reexport using PlotThemes
import Showoff
import StatsBase
import NaNMath: extrema, maximum, minimum
export
grid,
@ -107,6 +106,15 @@ export
# ---------------------------------------------------------
import NaNMath
# define functions (e.g. `_extrema`, that uses the NaNMath version (which ignores NaNs)) when the type is applicable
for fun in (:extrema, :minimum, :maximum, :mean)
@eval $(Symbol(string("_",fun)))(x) = Base.$(fun)(x)
@eval $(Symbol(string("_",fun))){F <: AbstractFloat}(x::AbstractVector{F}) = NaNMath.$(fun)(x)
end
# ---------------------------------------------------------
import Measures
import Measures: Length, AbsoluteLength, Measure, BoundingBox, mm, cm, inch, pt, width, height, w, h
const BBox = Measures.Absolute2DBox

View File

@ -118,7 +118,7 @@ Base.show(io::IO, axis::Axis) = dumpdict(axis.d, "Axis", true)
# Base.getindex(axis::Axis, k::Symbol) = getindex(axis.d, k)
Base.setindex!(axis::Axis, v, ks::Symbol...) = setindex!(axis.d, v, ks...)
Base.haskey(axis::Axis, k::Symbol) = haskey(axis.d, k)
extrema(axis::Axis) = (ex = axis[:extrema]; (ex.emin, ex.emax)) #This is the NaNMath version, not the Base version
_extrema(axis::Axis) = (ex = axis[:extrema]; (ex.emin, ex.emax))
const _scale_funcs = Dict{Symbol,Function}(
@ -349,11 +349,11 @@ function expand_extrema!(sp::Subplot, d::KW)
bw = d[:bar_width]
if bw == nothing
bw = d[:bar_width] = mean(diff(data))
bw = d[:bar_width] = _mean(diff(data))
end
axis = sp.attr[Symbol(dsym, :axis)]
expand_extrema!(axis, maximum(data) + 0.5maximum(bw))
expand_extrema!(axis, minimum(data) - 0.5minimum(bw))
expand_extrema!(axis, _maximum(data) + 0.5_maximum(bw))
expand_extrema!(axis, _minimum(data) - 0.5_minimum(bw))
end
end

View File

@ -75,7 +75,7 @@ function tick_padding(axis::Axis)
vals, labs = ticks
isempty(labs) && return 0mm
# ptsz = axis[:tickfont].pointsize * pt
longest_label = maximum(length(lab) for lab in labs)
longest_label = _maximum(length(lab) for lab in labs)
# generalize by "rotating" y labels
rot = axis[:rotation] + (axis[:letter] == :y ? 90 : 0)

View File

@ -218,7 +218,7 @@ end
function gl_marker(shape::Shape)
points = Point2f0[Vec{2,Float32}(p) for p in zip(shape.x, shape.y)]
bb = GeometryTypes.AABB(points)
mini, maxi = minimum(bb), maximum(bb)
mini, maxi = _minimum(bb), _maximum(bb)
w3 = maxi-mini
origin, width = Point2f0(mini[1], mini[2]), Point2f0(w3[1], w3[2])
map!(p -> ((p - origin) ./ width) - 0.5f0, points) # normalize and center
@ -347,7 +347,7 @@ function extract_any_color(d, kw_args)
kw_args[:color_norm] = Vec2f0(clims)
end
elseif clims == :auto
kw_args[:color_norm] = Vec2f0(extrema(d[:y]))
kw_args[:color_norm] = Vec2f0(_extrema(d[:y]))
end
end
else
@ -358,7 +358,7 @@ function extract_any_color(d, kw_args)
kw_args[:color_norm] = Vec2f0(clims)
end
elseif clims == :auto
kw_args[:color_norm] = Vec2f0(extrema(d[:y]))
kw_args[:color_norm] = Vec2f0(_extrema(d[:y]))
else
error("Unsupported limits: $clims")
end
@ -513,7 +513,7 @@ function hover(to_hover, to_display, window)
end
GLVisualize._view(robj, popup, camera = cam)
bb = GLAbstraction.boundingbox(robj).value
mini = minimum(bb)
mini = _minimum(bb)
w = GeometryTypes.widths(bb)
wborder = w * 0.08f0 #8 percent border
bb = GeometryTypes.AABB{Float32}(mini - wborder, w + 2 * wborder)
@ -525,7 +525,7 @@ function hover(to_hover, to_display, window)
end
function extract_extrema(d, kw_args)
xmin, xmax = extrema(d[:x]); ymin, ymax = extrema(d[:y])
xmin, xmax = extrema(d[:x]); ymin, ymax = _extrema(d[:y])
kw_args[:primitive] = GeometryTypes.SimpleRectangle{Float32}(xmin, ymin, xmax-xmin, ymax-ymin)
nothing
end
@ -552,7 +552,7 @@ function extract_colornorm(d, kw_args)
else
d[:y]
end
kw_args[:color_norm] = Vec2f0(extrema(z))
kw_args[:color_norm] = Vec2f0(_extrema(z))
kw_args[:intensity] = map(Float32, collect(z))
end
end
@ -824,7 +824,7 @@ function gl_bar(d, kw_args)
# compute half-width of bars
bw = nothing
hw = if bw == nothing
mean(diff(x))
_mean(diff(x))
else
Float64[cycle(bw,i)*0.5 for i=1:length(x)]
end
@ -907,7 +907,7 @@ function gl_boxplot(d, kw_args)
end
# change q1 and q5 to show outliers
# using maximum and minimum values inside the limits
q1, q5 = extrema(inside)
q1, q5 = _extrema(inside)
end
# Box
if notch
@ -1361,7 +1361,7 @@ function gl_contour(x, y, z, kw_args)
T = eltype(z)
levels = Contour.contours(map(T, x), map(T, y), z, h)
result = Point2f0[]
zmin, zmax = get(kw_args, :limits, Vec2f0(extrema(z)))
zmin, zmax = get(kw_args, :limits, Vec2f0(_extrema(z)))
cmap = get(kw_args, :color_map, get(kw_args, :color, RGBA{Float32}(0,0,0,1)))
colors = RGBA{Float32}[]
for c in levels.contours
@ -1382,7 +1382,7 @@ end
function gl_heatmap(x,y,z, kw_args)
get!(kw_args, :color_norm, Vec2f0(extrema(z)))
get!(kw_args, :color_norm, Vec2f0(_extrema(z)))
get!(kw_args, :color_map, Plots.make_gradient(cgrad()))
delete!(kw_args, :intensity)
I = GLVisualize.Intensity{1, Float32}
@ -1425,7 +1425,7 @@ function label_scatter(d, w, ho)
if isapprox(bbw[3], 0)
bbw = Vec3f0(bbw[1], bbw[2], 1)
end
mini = minimum(bb)
mini = _minimum(bb)
m = GLAbstraction.translationmatrix(-mini)
m *= GLAbstraction.scalematrix(1 ./ bbw)
kw[:primitive] = m * p

View File

@ -262,7 +262,7 @@ end
normalize_zvals(zv::Void) = zv
function normalize_zvals(zv::AVec)
vmin, vmax = extrema(zv)
vmin, vmax = _extrema(zv)
if vmin == vmax
zeros(length(zv))
else
@ -637,7 +637,7 @@ function gr_display(sp::Subplot{GRBackend}, w, h, viewport_canvas)
elseif ispolar(sp)
r = gr_set_viewport_polar()
rmin, rmax = GR.adjustrange(minimum(r), maximum(r))
rmin, rmax = GR.adjustrange(_minimum(r), _maximum(r))
# rmin, rmax = axis_limits(sp[:yaxis])
gr_polaraxes(rmin, rmax)
@ -822,7 +822,7 @@ function gr_display(sp::Subplot{GRBackend}, w, h, viewport_canvas)
# create the colorbar of contour levels
if sp[:colorbar] != :none
gr_set_viewport_cmap(sp)
l = round(Int32, 1000 + (h - minimum(h)) / (maximum(h) - minimum(h)) * 255)
l = round(Int32, 1000 + (h - _minimum(h)) / (_maximum(h) - _minimum(h)) * 255)
GR.setwindow(xmin, xmax, zmin, zmax)
GR.cellarray(xmin, xmax, zmax, zmin, 1, length(l), l)
ztick = 0.5 * GR.tick(zmin, zmax)

View File

@ -546,7 +546,7 @@ function plotly_series(plt::Plot, series::Series)
else
# grad = ColorGradient(series[:markercolor], alpha=series[:markeralpha])
grad = as_gradient(series[:markercolor], series[:markeralpha])
zmin, zmax = extrema(series[:marker_z])
zmin, zmax = _extrema(series[:marker_z])
zrange = zmax == zmin ? 1 : zmax - zmin # if all marker_z values are the same, plot all markers same color (avoids division by zero in next line)
[rgba_string(grad[(zi - zmin) / zrange]) for zi in series[:marker_z]]
end

View File

@ -705,11 +705,11 @@ function py_add_series(plt::Plot{PyPlotBackend}, series::Series)
# contours on the axis planes
if series[:contours]
for (zdir,mat) in (("x",x), ("y",y), ("z",z))
offset = (zdir == "y" ? maximum : minimum)(mat)
offset = (zdir == "y" ? _maximum : _minimum)(mat)
handle = ax[:contourf](x, y, z, levelargs...;
zdir = zdir,
cmap = py_fillcolormap(series),
offset = (zdir == "y" ? maximum : minimum)(mat) # where to draw the contour plane
offset = (zdir == "y" ? _maximum : _minimum)(mat) # where to draw the contour plane
)
push!(handles, handle)
needs_colorbar = true
@ -778,7 +778,7 @@ function py_add_series(plt::Plot{PyPlotBackend}, series::Series)
end
clims = sp[:clims]
zmin, zmax = extrema(z)
zmin, zmax = _extrema(z)
extrakw[:vmin] = (is_2tuple(clims) && isfinite(clims[1])) ? clims[1] : zmin
extrakw[:vmax] = (is_2tuple(clims) && isfinite(clims[2])) ? clims[2] : zmax
@ -926,7 +926,7 @@ function py_compute_axis_minval(axis::Axis)
for series in series_list(sp)
v = series.d[axis[:letter]]
if !isempty(v)
minval = min(minval, minimum(abs(v)))
minval = min(minval, _minimum(abs(v)))
end
end
end

View File

@ -501,7 +501,7 @@ immutable ZValues
zrange::Tuple{Float64,Float64}
end
function zvalues{T<:Real}(values::AVec{T}, zrange::Tuple{T,T} = (minimum(values), maximum(values)))
function zvalues{T<:Real}(values::AVec{T}, zrange::Tuple{T,T} = (_minimum(values), _maximum(values)))
ZValues(collect(float(values)), map(Float64, zrange))
end
@ -645,8 +645,8 @@ function (bc::BezierCurve)(t::Real)
p
end
Base.mean(x::Real, y::Real) = 0.5*(x+y)
Base.mean{N,T<:Real}(ps::FixedSizeArrays.Vec{N,T}...) = sum(ps) / length(ps)
_mean(x::Real, y::Real) = 0.5*(x+y)
_mean{N,T<:Real}(ps::FixedSizeArrays.Vec{N,T}...) = sum(ps) / length(ps)
@deprecate curve_points coords
@ -659,7 +659,7 @@ function directed_curve(args...; kw...)
end
function extrema_plus_buffer(v, buffmult = 0.2)
vmin,vmax = extrema(v)
vmin,vmax = _extrema(v)
vdiff = vmax-vmin
buffer = vdiff * buffmult
vmin - buffer, vmax + buffer

View File

@ -301,10 +301,10 @@ bottompad(layout::GridLayout) = layout.minpad[4]
function _update_min_padding!(layout::GridLayout)
map(_update_min_padding!, layout.grid)
layout.minpad = (
maximum(map(leftpad, layout.grid[:,1])),
maximum(map(toppad, layout.grid[1,:])),
maximum(map(rightpad, layout.grid[:,end])),
maximum(map(bottompad, layout.grid[end,:]))
_maximum(map(leftpad, layout.grid[:,1])),
_maximum(map(toppad, layout.grid[1,:])),
_maximum(map(rightpad, layout.grid[:,end])),
_maximum(map(bottompad, layout.grid[end,:]))
)
end
@ -349,10 +349,10 @@ function update_child_bboxes!(layout::GridLayout, minimum_perimeter = [0mm,0mm,0
# get the max horizontal (left and right) padding over columns,
# and max vertical (bottom and top) padding over rows
# TODO: add extra padding here
pad_left = maximum(minpad_left, 1)
pad_top = maximum(minpad_top, 2)
pad_right = maximum(minpad_right, 1)
pad_bottom = maximum(minpad_bottom, 2)
pad_left = _maximum(minpad_left, 1)
pad_top = _maximum(minpad_top, 2)
pad_right = _maximum(minpad_right, 1)
pad_bottom = _maximum(minpad_bottom, 2)
# make sure the perimeter match the parent
pad_left[1] = max(pad_left[1], minimum_perimeter[1])
@ -642,7 +642,7 @@ end
function create_grid_vcat(expr::Expr)
rowsizes = map(rowsize, expr.args)
rmin, rmax = extrema(rowsizes)
rmin, rmax = _extrema(rowsizes)
if rmin > 0 && rmin == rmax
# we have a grid... build the whole thing
# note: rmin is the number of columns

View File

@ -153,7 +153,7 @@ function _add_smooth_kw(kw_list::Vector{KW}, kw::KW)
if get(kw, :smooth, false)
x, y = kw[:x], kw[:y]
β, α = convert(Matrix{Float64}, [x ones(length(x))]) \ convert(Vector{Float64}, y)
sx = [minimum(x), maximum(x)]
sx = [_minimum(x), _maximum(x)]
sy = β * sx + α
push!(kw_list, merge(copy(kw), KW(
:seriestype => :path,

View File

@ -225,7 +225,7 @@ end
fr = if yaxis[:scale] == :identity
0.0
else
min(axis_limits(yaxis)[1], minimum(y))
min(axis_limits(yaxis)[1], _minimum(y))
end
end
newx, newy = zeros(3n), zeros(3n)
@ -338,7 +338,7 @@ end
# compute half-width of bars
bw = d[:bar_width]
hw = if bw == nothing
0.5mean(diff(procx))
0.5_mean(diff(procx))
else
Float64[0.5cycle(bw,i) for i=1:length(procx)]
end
@ -414,8 +414,8 @@ end
function _preprocess_binbarlike_weights{T<:AbstractFloat}(::Type{T}, w, wscale::Symbol)
w_adj = _scale_adjusted_values(T, w, wscale)
w_min = minimum(w_adj)
w_max = maximum(w_adj)
w_min = _minimum(w_adj)
w_max = _maximum(w_adj)
baseline = _binbarlike_baseline(w_min, wscale)
w_adj, baseline
end
@ -550,7 +550,7 @@ Plots.@deps stepbins path
function _auto_binning_nbins{N}(vs::NTuple{N,AbstractVector}, dim::Integer; mode::Symbol = :auto)
_cl(x) = max(ceil(Int, x), 1)
_iqr(v) = quantile(v, 0.75) - quantile(v, 0.25)
_span(v) = maximum(v) - minimum(v)
_span(v) = _maximum(v) - _minimum(v)
n_samples = length(linearindices(first(vs)))
# Estimator for number of samples in one row/column of bins along each axis:
@ -920,7 +920,7 @@ end
# get the joined vector
function get_xy(v::AVec{OHLC}, x = 1:length(v))
xdiff = 0.3mean(abs(diff(x)))
xdiff = 0.3_mean(abs(diff(x)))
x_out, y_out = zeros(0), zeros(0)
for (i,ohlc) in enumerate(v)
ox,oy = get_xy(ohlc, x[i], xdiff)
@ -985,8 +985,8 @@ end
yflip := true
aspect_ratio := 1
rs, cs, zs = findnz(z.surf)
xlim := extrema(cs)
ylim := extrema(rs)
xlim := _extrema(cs)
ylim := _extrema(rs)
if d[:markershape] == :none
markershape := :circle
end
@ -1007,7 +1007,7 @@ end
"Adds a+bx... straight line over the current plot"
function abline!(plt::Plot, a, b; kw...)
plot!(plt, [extrema(plt)...], x -> b + a*x; kw...)
plot!(plt, [_extrema(plt)...], x -> b + a*x; kw...)
end
abline!(args...; kw...) = abline!(current(), args...; kw...)

View File

@ -3,7 +3,7 @@ calcMidpoints(edges::AbstractVector) = Float64[0.5 * (edges[i] + edges[i+1]) for
"Make histogram-like bins of data"
function binData(data, nbins)
lo, hi = extrema(data)
lo, hi = _extrema(data)
edges = collect(linspace(lo, hi, nbins+1))
midpoints = calcMidpoints(edges)
buckets = Int[max(2, min(searchsortedfirst(edges, x), length(edges)))-1 for x in data]
@ -109,7 +109,7 @@ function regressionXY(x, y)
β, α = convert(Matrix{Float64}, [x ones(length(x))]) \ convert(Vector{Float64}, y)
# make a line segment
regx = [minimum(x), maximum(x)]
regx = [_minimum(x), _maximum(x)]
regy = β * regx + α
regx, regy
end
@ -187,7 +187,7 @@ type SegmentsIterator
end
function iter_segments(args...)
tup = Plots.wraptuple(args)
n = maximum(map(length, tup))
n = _maximum(map(length, tup))
SegmentsIterator(tup, n)
end
@ -283,7 +283,7 @@ unzip{T}(xyuv::FixedSizeArrays.Vec{4,T}) = T[xyuv[1]], T[xyuv[2]], T[xyuv[
# given 2-element lims and a vector of data x, widen lims to account for the extrema of x
function _expand_limits(lims, x)
try
e1, e2 = extrema(x)
e1, e2 = _extrema(x)
lims[1] = min(lims[1], e1)
lims[2] = max(lims[2], e2)
# catch err
@ -334,17 +334,17 @@ sortedkeys(d::Dict) = sort(collect(keys(d)))
"create an (n+1) list of the outsides of heatmap rectangles"
function heatmap_edges(v::AVec)
vmin, vmax = extrema(v)
vmin, vmax = _extrema(v)
extra = 0.5 * (vmax-vmin) / (length(v)-1)
vcat(vmin-extra, 0.5 * (v[1:end-1] + v[2:end]), vmax+extra)
end
function calc_r_extrema(x, y)
xmin, xmax = extrema(x)
ymin, ymax = extrema(y)
xmin, xmax = _extrema(x)
ymin, ymax = _extrema(y)
r = 0.5 * min(xmax - xmin, ymax - ymin)
extrema(r)
_extrema(r)
end
function convert_to_polar(x, y, r_extrema = calc_r_extrema(x, y))
@ -644,8 +644,8 @@ end
# ---------------------------------------------------------------
# used in updating an existing series
extendSeriesByOne(v::UnitRange{Int}, n::Int = 1) = isempty(v) ? (1:n) : (minimum(v):maximum(v)+n)
extendSeriesByOne(v::AVec, n::Integer = 1) = isempty(v) ? (1:n) : vcat(v, (1:n) + maximum(v))
extendSeriesByOne(v::UnitRange{Int}, n::Int = 1) = isempty(v) ? (1:n) : (_minimum(v):_maximum(v)+n)
extendSeriesByOne(v::AVec, n::Integer = 1) = isempty(v) ? (1:n) : vcat(v, (1:n) + _maximum(v))
extendSeriesData{T}(v::Range{T}, z::Real) = extendSeriesData(float(collect(v)), z)
extendSeriesData{T}(v::Range{T}, z::AVec) = extendSeriesData(float(collect(v)), z)
extendSeriesData{T}(v::AVec{T}, z::Real) = (push!(v, convert(T, z)); v)
@ -871,9 +871,9 @@ mm2px(mm::Real) = float(px / MM_PER_PX)
"Smallest x in plot"
xmin(plt::Plot) = minimum([minimum(series.d[:x]) for series in plt.series_list])
xmin(plt::Plot) = _minimum([_minimum(series.d[:x]) for series in plt.series_list])
"Largest x in plot"
xmax(plt::Plot) = maximum([maximum(series.d[:x]) for series in plt.series_list])
xmax(plt::Plot) = _maximum([_maximum(series.d[:x]) for series in plt.series_list])
"Extrema of x-values in plot"
Base.extrema(plt::Plot) = (xmin(plt), xmax(plt))
_extrema(plt::Plot) = (xmin(plt), xmax(plt))

View File

@ -78,12 +78,12 @@ facts("Axes") do
@fact typeof(axis) --> Plots.Axis
@fact Plots.discrete_value!(axis, "HI") --> (0.5, 1)
@fact Plots.discrete_value!(axis, :yo) --> (1.5, 2)
@fact extrema(axis) --> (0.5,1.5)
@fact Plots._extrema(axis) --> (0.5,1.5)
@fact axis[:discrete_map] --> Dict{Any,Any}(:yo => 2, "HI" => 1)
Plots.discrete_value!(axis, ["x$i" for i=1:5])
Plots.discrete_value!(axis, ["x$i" for i=0:2])
@fact extrema(axis) --> (0.5, 7.5)
@fact Plots.extrema(axis) --> (0.5, 7.5)
end