feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+55
View File
@@ -0,0 +1,55 @@
package chart
import (
"fmt"
"math"
"testing"
"github.com/egoist/mygo/ui"
)
// BenchmarkLine constructs three linear paths of 15,000 samples, without rendering.
func BenchmarkLine(b *testing.B) {
xs, ys := make([]float32, 15000), make([]float32, 15000)
for i := range xs {
xs[i] = float32(i) / 14999
ys[i] = float32(math.Sin(float64(i)))
}
r := ui.Rect{W: 1280, H: 720}
b.ReportAllocs()
for b.Loop() {
for range 3 {
Line(r, xs, ys, CurveLinear)
}
}
}
// BenchmarkStreamingFrame includes build, layout, paint and CPU fallback at 1x/2x.
// The desktop example measures GPU submission and actual frame scheduling instead.
func BenchmarkStreamingFrame(b *testing.B) {
for _, scale := range []float32{1, 2} {
b.Run(fmt.Sprintf("%gx", scale), func(b *testing.B) {
xs, ys := make([]float32, 15000), make([]float32, 15000)
var dx, dy []float32
frame := 0
tt := ui.NewTester(func(c *ui.Context) {
for i := range xs {
xs[i] = float32(i) / 14999
ys[i] = .5 + .3*float32(math.Sin(float64(i+frame)/20))
}
ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
dx, dy = MinMax(dx, dy, xs, ys, int(r.W*p.Scale()))
for range 3 {
p.StrokePath(Line(r, dx, dy, CurveLinear), 2, ui.RGB(30, 100, 220))
}
})
}, 1280, 720)
tt.SetScale(scale)
b.ReportAllocs()
for b.Loop() {
frame++
tt.Frame()
}
})
}
}
+300
View File
@@ -0,0 +1,300 @@
// Package chart builds charts in native UI without a look of their own,
// as headless libraries do on the web: scales that map data onto a plot
// and pick round ticks, a plot with axes around it, marks that are
// elements you style as any other, paths of lines, areas and pie slices
// for Draw functions, stacking, and a selection that the pointer and the
// keyboard move.
//
// x := chart.NewBand(months...).Padding(0.3, 0.15)
// y := chart.NewLinear(0, 120).Nice(4)
// chart.Plot(c, chart.Axes{Left: y.Ticks(4), Bottom: x.Ticks()}, func(area ui.Element) {
// for i, v := range sales {
// chart.Rect(c, x.Band(i), y.Span(0, v)).Background(t.Accent).Radius(4)
// }
// }).Height(200).Gap(6)
//
// Positions along a plot are fractions of it, from 0 to 1: along x from its
// left edge, and along y from its bottom up, the way values grow. Marks
// place themselves in percentages of the plot, so they need no layout to
// be built, follow the plot as it resizes, and move smoothly with a
// Transition as the data changes; Draw functions get the plot's box, and
// X and Y turn fractions into points in it.
//
// See docs/ui/chart.md.
package chart
import (
"slices"
"github.com/egoist/mygo/ui"
)
// Side is a side of a plot, where an axis goes.
type Side int
const (
Left Side = iota
Right
Top
Bottom
)
// Axes are the ticks along the sides of a plot, whose labels go beside it:
// a scale's Ticks, or ticks of your own.
type Axes struct {
Left, Right, Top, Bottom []Tick
// Label builds the label of a tick on a side, centered on the tick;
// nil shows its Label as text. Labels sit in boxes of no width or
// height, so keep their text on one line with NoWrap.
Label func(side Side, t Tick)
}
// Plot builds a plot with the axes around it: a grid whose middle cell is
// the plot's area, which build gets to style, as with a background or a
// Draw function painting grid lines, and to add marks to. Give the plot a
// height, and Gap to keep the labels away from the area:
//
// chart.Plot(c, chart.Axes{Left: y.Ticks(5)}, func(area ui.Element) {
// area.Draw(func(p *ui.Painter, r ui.Rect) {
// for _, tick := range y.Ticks(5) {
// p.Line(r.X, chart.Y(r, tick.At), r.X+r.W, chart.Y(r, tick.At), 1, t.Border)
// }
// })
// }).Height(160).Gap(8)
//
// Name the plot for assistive technology with Label, and describe what it
// shows with Description.
func Plot(c *ui.Context, axes Axes, build func(area ui.Element)) ui.Element {
label := axes.Label
if label == nil {
label = func(_ Side, t Tick) { ui.Text(c, t.Label).NoWrap() }
}
cols := []ui.Track{ui.Fr(1)}
rows := []ui.Track{ui.Fr(1)}
col, row := 1, 1
if len(axes.Left) > 0 {
cols = append([]ui.Track{ui.FitContent()}, cols...)
col = 2
}
if len(axes.Right) > 0 {
cols = append(cols, ui.FitContent())
}
if len(axes.Top) > 0 {
rows = append([]ui.Track{ui.FitContent()}, rows...)
row = 2
}
if len(axes.Bottom) > 0 {
rows = append(rows, ui.FitContent())
}
return ui.Grid(c).ColumnTracks(cols...).RowTracks(rows...).Children(func() {
area := ui.Box(c).ColumnStart(col).RowStart(row)
area.Children(func() { build(area) })
if len(axes.Left) > 0 {
axis(c, Left, axes.Left, label).ColumnStart(1).RowStart(row)
}
if len(axes.Right) > 0 {
axis(c, Right, axes.Right, label).ColumnStart(col + 1).RowStart(row)
}
if len(axes.Top) > 0 {
axis(c, Top, axes.Top, label).ColumnStart(col).RowStart(1)
}
if len(axes.Bottom) > 0 {
axis(c, Bottom, axes.Bottom, label).ColumnStart(col).RowStart(row + 1)
}
})
}
// axis lays out the labels of ticks along a side of the plot: each in a
// box of no width (or height) at its tick, which centers it there, with
// spaces between them that grow by the fractions of the plot between the
// ticks. The labels stay in the layout, so the axis is as wide (or as
// high) as they need.
func axis(c *ui.Context, side Side, ticks []Tick, label func(Side, Tick)) ui.Element {
vertical := side == Left || side == Right
// Where each tick is from the axis's start: the left, or the top.
pos := func(t Tick) float32 {
if vertical {
return 1 - t.At
}
return t.At
}
sorted := slices.Clone(ticks)
slices.SortStableFunc(sorted, func(a, b Tick) int {
switch pa, pb := pos(a), pos(b); {
case pa < pb:
return -1
case pa > pb:
return 1
}
return 0
})
const eps = 1e-4
var e ui.Element
if vertical {
e = ui.Column(c)
} else {
e = ui.Row(c)
}
return e.Children(func() {
prev := float32(0)
for _, t := range sorted {
p := pos(t)
if p < -eps || p > 1+eps {
continue
}
p = max(prev, min(1, p))
ui.Box(c).Basis(0).Grow(p - prev)
var slot ui.Element
switch side {
case Left:
slot = ui.Row(c).Height(0).AlignItems(ui.Center).Justify(ui.End)
case Right:
slot = ui.Row(c).Height(0).AlignItems(ui.Center)
case Top:
slot = ui.Column(c).Width(0).AlignItems(ui.Center).Justify(ui.End)
default:
slot = ui.Column(c).Width(0).AlignItems(ui.Center)
}
slot.Children(func() { label(side, t) })
prev = p
}
ui.Box(c).Basis(0).Grow(1 - prev)
})
}
// percent turns a fraction into a percentage.
func percent(f float32) float32 { return 100 * f }
// Rect places a mark over the stretch x along the plot and y up it, as a
// bar, a band of a range or a cell of a heat map: an element in the plot's
// area, which you style as any other, and name for assistive technology.
// Build it in the function of Plot.
//
// chart.Rect(c, x.Band(i), y.Span(0, v)).Background(t.Accent).Radius(4).Tooltip(label)
func Rect(c *ui.Context, x, y Span) ui.Element {
x0, x1 := min(x.Lo, x.Hi), max(x.Lo, x.Hi)
y0, y1 := min(y.Lo, y.Hi), max(y.Lo, y.Hi)
return ui.Box(c).Absolute().
LeftPercent(percent(x0)).WidthPercent(percent(x1 - x0)).
TopPercent(percent(1 - y1)).HeightPercent(percent(y1 - y0))
}
// Point places a mark of w by h DIPs centered on the point at x along the
// plot and y up it, as a dot of a scatter plot or the point a selection is
// on.
//
// chart.Point(c, x.At(v.Weight), y.At(v.Height), 8, 8).Radius(4).Background(t.Accent)
func Point(c *ui.Context, x, y, w, h float32) ui.Element {
return ui.Box(c).Absolute().LeftPercent(percent(x)).TopPercent(percent(1-y)).
Size(w, h).Margin(-h/2, 0, 0, -w/2)
}
// RuleX places a vertical line of width DIPs across the plot at x along
// it, as a threshold or the selection of a line chart; RuleY a horizontal
// one at y up it. Color them with Background.
func RuleX(c *ui.Context, x, width float32) ui.Element {
return ui.Box(c).Absolute().LeftPercent(percent(x)).Top(0).Bottom(0).
Width(width).Margin(0, 0, 0, -width/2)
}
// RuleY places a horizontal line of height DIPs across the plot at y up
// it.
func RuleY(c *ui.Context, y, height float32) ui.Element {
return ui.Box(c).Absolute().TopPercent(percent(1-y)).Left(0).Right(0).
Height(height).Margin(-height/2, 0, 0, 0)
}
// Anchor builds what build adds at the point at x along the plot and y up
// it, of any size: as a label over a bar, or a tooltip by the selection.
// h and v place it: Center centers it on the point, Start puts its left
// (h) or top (v) edge there, and End its right or bottom edge, so that
// End, End shows it above and to the left of the point.
//
// chart.Anchor(c, x.At(i), y.At(v), ui.Center, ui.End, func() {
// ui.Text(c, label).NoWrap().Margin(0, 0, 4, 0)
// })
func Anchor(c *ui.Context, x, y float32, h, v ui.Align, build func()) ui.Element {
return ui.Row(c).Absolute().LeftPercent(percent(x)).TopPercent(percent(1-y)).
Size(0, 0).AlignItems(v).Children(func() {
ui.Column(c).Width(0).AlignItems(h).Children(build)
})
}
// selection is the state Select keeps in the area.
type selection struct {
hovering bool
x float32 // where the pointer was
last int // the choice in the last frame
}
// Select makes the plot's area choose one of the points at xs, fractions
// along it in ascending order: *index is the one nearest the pointer while
// it is over the area, and -1, none, once it leaves. The area takes the
// keyboard focus, as one stop of Tab, where the left and right arrows,
// Home and End move the choice, and Escape clears it. Changed reports a
// new choice.
//
// describe tells assistive technology about a point, "March: 42 sales",
// which it reads as the area's value, and as the arrows come to the point.
// Show the choice with marks, as a rule, a point and a label by it:
//
// if chart.Select(c, area, &app.selected, xs, describe) { ... }
// if i := app.selected; i >= 0 {
// chart.RuleX(c, xs[i], 1).Background(t.Border)
// chart.Point(c, xs[i], ys[i], 8, 8).Radius(4).Background(t.Accent)
// }
func Select(c *ui.Context, area ui.Element, index *int, xs []float32, describe func(i int) string) bool {
area.Focusable()
st := ui.Local(area, "chart.Select", func() selection { return selection{last: -1} })
old := *index
n := len(xs)
if *index >= n {
*index = -1
}
announce := false
move := func(i int) {
*index = max(0, min(n-1, i))
announce = true
}
switch {
case n == 0:
case area.Shortcut(0, ui.KeyRight):
if *index < 0 {
move(0)
} else {
move(*index + 1)
}
case area.Shortcut(0, ui.KeyLeft):
if *index < 0 {
move(n - 1)
} else {
move(*index - 1)
}
case area.Shortcut(0, ui.KeyHome):
move(0)
case area.Shortcut(0, ui.KeyEnd):
move(n - 1)
case *index >= 0 && area.Shortcut(0, ui.KeyEscape):
*index = -1
}
// The pointer chooses as it comes and moves, not while it rests where
// it was as the keys move the choice.
if x, _, over := area.PointerPosition(); over {
if w := area.Bounds().W; w > 0 && n > 0 && !announce && (!st.hovering || x != st.x) {
*index = Nearest(xs, x/w)
}
st.hovering, st.x = true, x
} else if st.hovering {
st.hovering = false
*index = -1
}
if *index >= 0 && describe != nil {
desc := describe(*index)
area.Value(desc)
if announce && *index != st.last {
c.Announce(desc)
}
}
st.last = *index
return *index != old
}
+435
View File
@@ -0,0 +1,435 @@
package chart
import (
"math"
"slices"
"strings"
"testing"
"time"
"github.com/egoist/mygo/ui"
)
// The expected values below are d3's (d3-array 3.2.4, d3-scale 4.0.2,
// d3-shape 3.2.0) for the same input; times its scaleTime's, in UTC.
func TestTicks(t *testing.T) {
for _, tc := range []struct {
lo, hi float64
count int
want []float64
}{
{0, 1, 10, []float64{0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1}},
{0, 100, 5, []float64{0, 20, 40, 60, 80, 100}},
{0, 87, 5, []float64{0, 20, 40, 60, 80}},
{-3.2, 7.9, 6, []float64{-2, 0, 2, 4, 6}},
{0.0012, 0.0047, 5, []float64{0.0015, 0.002, 0.0025, 0.003, 0.0035, 0.004, 0.0045}},
{1e6, 3.4e6, 4, []float64{1e6, 1.5e6, 2e6, 2.5e6, 3e6}},
{10, 0, 5, []float64{10, 8, 6, 4, 2, 0}},
{0.1, 0.9, 3, []float64{0.2, 0.4, 0.6, 0.8}},
{1, 1, 5, []float64{1}},
{0, 1, 1, []float64{0, 1}},
} {
got := ticks(tc.lo, tc.hi, float64(tc.count))
if !slices.Equal(got, tc.want) {
t.Errorf("ticks(%v, %v, %d) = %v, want %v", tc.lo, tc.hi, tc.count, got, tc.want)
}
}
}
func TestNice(t *testing.T) {
for _, tc := range []struct {
lo, hi float64
count int
want [2]float64
}{
{0, 87, 5, [2]float64{0, 100}},
{0, 87, 10, [2]float64{0, 90}},
{0, 87, 2, [2]float64{0, 100}},
{-3.2, 7.9, 6, [2]float64{-4, 8}},
{0.0012, 0.0047, 5, [2]float64{0.001, 0.005}},
{13, 1042, 10, [2]float64{0, 1100}},
{90, 3, 5, [2]float64{100, 0}},
} {
s := NewLinear(tc.lo, tc.hi).Nice(tc.count)
if got := [2]float64{s.Lo, s.Hi}; got != tc.want {
t.Errorf("NewLinear(%v, %v).Nice(%d) = %v, want %v", tc.lo, tc.hi, tc.count, got, tc.want)
}
}
}
func TestTickLabels(t *testing.T) {
labels := func(ts []Tick) string {
var out []string
for _, t := range ts {
out = append(out, t.Label)
}
return strings.Join(out, " ")
}
for _, tc := range []struct {
s Linear
count int
want string
}{
{NewLinear(0, 1), 5, "0.0 0.2 0.4 0.6 0.8 1.0"},
{NewLinear(0, 100), 5, "0 20 40 60 80 100"},
{NewLinear(0.0012, 0.0047), 5, "0.0015 0.0020 0.0025 0.0030 0.0035 0.0040 0.0045"},
{NewLinear(-1, 1), 4, "-1.0 -0.5 0.0 0.5 1.0"},
{Linear{Lo: 0, Hi: 1, Format: func(v float64) string { return "x" }}, 1, "x x"},
} {
if got := labels(tc.s.Ticks(tc.count)); got != tc.want {
t.Errorf("%v.Ticks(%d) = %q, want %q", tc.s, tc.count, got, tc.want)
}
}
if ts := NewLinear(0, 200).Ticks(2); ts[1].At != 0.5 || ts[1].Value != 100 {
t.Errorf("ticks of 0 to 200: %+v", ts)
}
}
func TestLinear(t *testing.T) {
s := NewLinear(-10, 30)
if s.At(0) != 0.25 || s.Invert(0.75) != 20 {
t.Errorf("At(0) = %v, Invert(0.75) = %v", s.At(0), s.Invert(0.75))
}
if sp := s.Span(0, 10); sp != (Span{0.25, 0.5}) {
t.Errorf("Span(0, 10) = %v", sp)
}
s.Clamp = true
if s.At(50) != 1 || s.Invert(-1) != -10 {
t.Errorf("clamped: At(50) = %v, Invert(-1) = %v", s.At(50), s.Invert(-1))
}
if NewLinear(3, 3).At(3) != 0.5 {
t.Error("an empty domain maps to the middle")
}
if lo, hi := Extent(4, math.NaN(), -2, 9); lo != -2 || hi != 9 {
t.Errorf("Extent = %v, %v", lo, hi)
}
}
func TestBand(t *testing.T) {
b := NewBand("a", "b", "c", "d").Padding(0.2, 0.1)
want := []float32{0.025, 0.275, 0.525, 0.775}
for i, w := range want {
if got := b.Band(i).Lo; math.Abs(float64(got-w)) > 1e-6 {
t.Errorf("band %d starts at %v, want %v", i, got, w)
}
}
if w := b.Width(); math.Abs(float64(w-0.2)) > 1e-6 {
t.Errorf("Width = %v, want 0.2", w)
}
for _, tc := range []struct {
f float32
i int
ok bool
}{{0.01, 0, true}, {0.1, 0, true}, {0.249, 0, true}, {0.251, 1, true}, {0.99, 3, true}, {-0.01, 0, false}, {1.01, 0, false}} {
if i, ok := b.Index(tc.f); i != tc.i || ok != tc.ok {
t.Errorf("Index(%v) = %d, %v, want %d, %v", tc.f, i, ok, tc.i, tc.ok)
}
}
if ts := b.Ticks(); len(ts) != 4 || ts[2].Label != "c" || ts[2].At != b.At(2) {
t.Errorf("Ticks = %+v", ts)
}
}
func TestTimeTicks(t *testing.T) {
parse := func(s string) time.Time {
v, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
t.Fatal(err)
}
return v
}
for _, tc := range []struct {
from, to string
count int
want []string
labels string
}{
{"2026-01-01T00:00:00Z", "2026-12-31T00:00:00Z", 6,
[]string{"2026-01-01T00:00:00Z", "2026-04-01T00:00:00Z", "2026-07-01T00:00:00Z", "2026-10-01T00:00:00Z"},
"2026 Apr Jul Oct"},
{"2026-03-01T00:00:00Z", "2026-03-08T00:00:00Z", 7,
[]string{"2026-03-01T00:00:00Z", "2026-03-02T00:00:00Z", "2026-03-03T00:00:00Z", "2026-03-04T00:00:00Z", "2026-03-05T00:00:00Z", "2026-03-06T00:00:00Z", "2026-03-07T00:00:00Z", "2026-03-08T00:00:00Z"},
"Mar Mar 2 Mar 3 Mar 4 Mar 5 Mar 6 Mar 7 Mar 8"},
{"2026-03-05T09:13:00Z", "2026-03-05T17:40:00Z", 5,
[]string{"2026-03-05T10:00:00Z", "2026-03-05T11:00:00Z", "2026-03-05T12:00:00Z", "2026-03-05T13:00:00Z", "2026-03-05T14:00:00Z", "2026-03-05T15:00:00Z", "2026-03-05T16:00:00Z", "2026-03-05T17:00:00Z"},
"10:00 11:00 12:00 13:00 14:00 15:00 16:00 17:00"},
{"2026-03-05T09:13:07Z", "2026-03-05T09:14:51Z", 6,
[]string{"2026-03-05T09:13:15Z", "2026-03-05T09:13:30Z", "2026-03-05T09:13:45Z", "2026-03-05T09:14:00Z", "2026-03-05T09:14:15Z", "2026-03-05T09:14:30Z", "2026-03-05T09:14:45Z"},
":15 :30 :45 09:14 :15 :30 :45"},
{"2010-06-01T00:00:00Z", "2026-06-01T00:00:00Z", 5,
[]string{"2015-01-01T00:00:00Z", "2020-01-01T00:00:00Z", "2025-01-01T00:00:00Z"},
"2015 2020 2025"},
{"2026-01-29T00:00:00Z", "2026-02-12T00:00:00Z", 8,
[]string{"2026-01-29T00:00:00Z", "2026-01-31T00:00:00Z", "2026-02-01T00:00:00Z", "2026-02-03T00:00:00Z", "2026-02-05T00:00:00Z", "2026-02-07T00:00:00Z", "2026-02-09T00:00:00Z", "2026-02-11T00:00:00Z"},
"Jan 29 Jan 31 Feb Feb 3 Feb 5 Feb 7 Feb 9 Feb 11"},
{"2026-03-01T00:00:00Z", "2026-03-29T00:00:00Z", 4, // Sundays
[]string{"2026-03-01T00:00:00Z", "2026-03-08T00:00:00Z", "2026-03-15T00:00:00Z", "2026-03-22T00:00:00Z", "2026-03-29T00:00:00Z"},
"Mar Mar 8 Mar 15 Mar 22 Mar 29"},
{"2026-01-01T00:00:00.120Z", "2026-01-01T00:00:00.870Z", 5,
[]string{"2026-01-01T00:00:00.2Z", "2026-01-01T00:00:00.4Z", "2026-01-01T00:00:00.6Z", "2026-01-01T00:00:00.8Z"},
".200 .400 .600 .800"},
} {
s := NewTime(parse(tc.from), parse(tc.to))
var got, labels []string
for _, tick := range s.Ticks(tc.count) {
got = append(got, time.UnixMilli(int64(tick.Value)).UTC().Format(time.RFC3339Nano))
labels = append(labels, tick.Label)
}
if !slices.Equal(got, tc.want) {
t.Errorf("ticks of %s to %s: %v, want %v", tc.from, tc.to, got, tc.want)
}
if l := strings.Join(labels, " "); l != tc.labels {
t.Errorf("labels of %s to %s: %q, want %q", tc.from, tc.to, l, tc.labels)
}
}
// Ticks fall on round times of the times' location.
tokyo := time.FixedZone("JST", 9*3600)
s := NewTime(time.Date(2026, 3, 1, 0, 0, 0, 0, tokyo), time.Date(2026, 3, 4, 0, 0, 0, 0, tokyo))
if ts := s.Ticks(3); len(ts) != 4 || ts[1].Label != "Mar 2" {
t.Errorf("ticks in Tokyo: %+v", ts)
}
}
func TestStack(t *testing.T) {
seg := func(v [][][2]float64) [][]Segment {
out := make([][]Segment, len(v))
for s := range v {
for _, p := range v[s] {
out[s] = append(out[s], Segment{p[0], p[1]})
}
}
return out
}
check := func(name string, got [][]Segment, want [][][2]float64) {
t.Helper()
w := seg(want)
for s := range w {
for i := range w[s] {
if math.Abs(got[s][i].Lo-w[s][i].Lo) > 1e-9 || math.Abs(got[s][i].Hi-w[s][i].Hi) > 1e-9 {
t.Errorf("%s: [%d][%d] = %v, want %v", name, s, i, got[s][i], w[s][i])
}
}
}
}
// d3's stackOffsetDiverging, stackOffsetExpand and stackOffsetSilhouette.
check("standard", Stack([][]float64{{3, -1, 2}, {4, 2, -5}, {1, 1, 1}}, StackStandard),
[][][2]float64{{{0, 3}, {-1, 0}, {0, 2}}, {{3, 7}, {0, 2}, {-5, 0}}, {{7, 8}, {2, 3}, {2, 3}}})
pos := [][]float64{{3, 1, 2}, {4, 2, 5}, {1, 1, 1}}
check("normalized", Stack(pos, StackNormalized),
[][][2]float64{{{0, 0.375}, {0, 0.25}, {0, 0.25}}, {{0.375, 0.875}, {0.25, 0.75}, {0.25, 0.875}}, {{0.875, 1}, {0.75, 1}, {0.875, 1}}})
check("center", Stack(pos, StackCenter),
[][][2]float64{{{-4, -1}, {-2, -1}, {-4, -2}}, {{-1, 3}, {-1, 1}, {-2, 3}}, {{3, 4}, {1, 2}, {3, 4}}})
// Shorter series and NaN take no room.
got := Stack([][]float64{{1, math.NaN()}, {2}}, StackStandard)
if got[0][1] != (Segment{0, 0}) || got[1][1] != (Segment{0, 0}) || got[1][0] != (Segment{1, 3}) {
t.Errorf("ragged stack: %v", got)
}
}
func TestPie(t *testing.T) {
want := [][2]float64{{0, 0.6383185307179586}, {0.6383185307179586, 1.8949555921538759}, {1.8949555921538759, 3.7699111843077517}, {3.7699111843077517, 3.7899111843077518}, {3.7899111843077518, 6.283185307179586}}
got := Pie([]float64{1, 2, 3, 0, 4}, 0.02)
for i, w := range want {
if math.Abs(got[i].Start-w[0]) > 1e-9 || math.Abs(got[i].End-w[1]) > 1e-9 {
t.Errorf("slice %d = %v, want %v", i, got[i], w)
}
}
// Twelve o'clock, three, six and nine.
slices := Pie([]float64{1, 1, 1, 1}, 0)
for i, p := range [][2]float32{{1, -10}, {10, 1}, {-1, 10}, {-10, -1}} {
if j, ok := SliceAt(slices, p[0], p[1], 5, 20); !ok || j != i {
t.Errorf("SliceAt(%v) = %d, %v, want %d", p, j, ok, i)
}
}
if _, ok := SliceAt(slices, 1, 1, 5, 20); ok {
t.Error("the hole of a donut has no slice")
}
if x, y := Polar(0, 0, 10, math.Pi/2); math.Abs(float64(x-10)) > 1e-5 || math.Abs(float64(y)) > 1e-5 {
t.Errorf("Polar at a quarter turn = %v, %v", x, y)
}
}
func TestNearest(t *testing.T) {
xs := []float32{0, 0.25, 0.5, 1}
for _, tc := range []struct {
f float32
i int
}{{-1, 0}, {0.1, 0}, {0.125, 0}, {0.2, 1}, {0.4, 2}, {0.8, 3}, {2, 3}} {
if i := Nearest(xs, tc.f); i != tc.i {
t.Errorf("Nearest(%v) = %d, want %d", tc.f, i, tc.i)
}
}
if Nearest(nil, 0.5) != -1 {
t.Error("no points, no nearest")
}
}
func TestCurves(t *testing.T) {
pts := [][2]float32{{0, 0}, {10, 10}, {20, 10}, {30, 0}}
// Monotone never goes past the values of the points it joins: at the
// flat stretch, the control points stay at its height.
segs := curve(pts, CurveMonotone)
if len(segs) != 3 || !segs[1].cubic || segs[1].c1[1] != 10 || segs[1].c2[1] != 10 {
t.Errorf("monotone: %+v", segs)
}
if segs := curve(pts, CurveStepAfter); len(segs) != 6 || segs[0].to != [2]float32{10, 0} {
t.Errorf("step after: %+v", segs)
}
if segs := curve(pts, CurveStepBefore); segs[0].to != [2]float32{0, 10} {
t.Errorf("step before: %+v", segs)
}
if segs := curve(pts, CurveStep); len(segs) != 9 || segs[0].to != [2]float32{5, 0} || segs[1].to != [2]float32{5, 10} {
t.Errorf("step: %+v", segs)
}
if segs := curve(pts[:2], CurveMonotone); len(segs) != 1 || segs[0].cubic {
t.Errorf("two points join straight: %+v", segs)
}
}
// pixel reads the color at (x, y) of a tester's frame, at scale 1.
func pixel(tt *ui.Tester, x, y int) [4]uint8 {
c := tt.Image().RGBAAt(x, y)
return [4]uint8{c.R, c.G, c.B, c.A}
}
func TestPaths(t *testing.T) {
red := ui.RGB(255, 0, 0)
xs := []float32{0, 0.5, 1}
view := func(c *ui.Context) {
ui.Box(c).Size(100, 100).Draw(func(p *ui.Painter, r ui.Rect) {
// An area under a line from (0, 0.5) up to (1, 1), broken
// nowhere, and a line with a gap.
p.FillPath(Area(r, xs, nil, []float32{0.5, 0.75, 1}, CurveLinear), red)
})
ui.Box(c).Size(100, 100).Draw(func(p *ui.Painter, r ui.Rect) {
p.FillPath(Sector(r.X+50, r.Y+50, 20, 40, Slice{Start: 0, End: math.Pi}), red)
})
}
tt := ui.NewTester(view, 100, 200)
for _, tc := range []struct {
x, y int
in bool
}{{50, 90, true}, {10, 40, false}, {90, 20, true}, {50, 30, true}, // the area
{80, 150, true}, {50, 150, false}, {20, 150, false}, {50, 105, false}, {50, 195, false}} { // the right half of a donut
if got := pixel(tt, tc.x, tc.y) == [4]uint8{255, 0, 0, 255}; got != tc.in {
t.Errorf("(%d, %d) filled %v, want %v", tc.x, tc.y, got, tc.in)
}
}
// A NaN breaks a line into two.
var path *ui.Path
ui.Render(func(c *ui.Context) {
ui.Box(c).Size(10, 10).Draw(func(p *ui.Painter, r ui.Rect) {
path = Line(r, []float32{0, 0.25, 0.5, 0.75}, []float32{0, 1, float32(math.NaN()), 1}, CurveLinear)
})
}, 10, 10, 1)
if path == nil {
t.Fatal("not drawn")
}
}
func TestPlotLayout(t *testing.T) {
x := NewBand("Mon", "Tue", "Wed", "Thu").Padding(0.2, 0)
y := NewLinear(0, 100)
view := func(c *ui.Context) {
Plot(c, Axes{Left: y.Ticks(2), Bottom: x.Ticks()}, func(area ui.Element) {
area.Label("area")
Rect(c, x.Band(1), y.Span(0, 50)).Label("bar")
Point(c, 0.5, 0.5, 10, 10).Label("dot")
RuleY(c, 1, 2).Label("top rule")
Anchor(c, 1, 0, ui.End, ui.End, func() { ui.Text(c, "corner").NoWrap() })
}).Size(400, 200).Margin(20)
}
tt := ui.NewTester(view, 440, 240)
area, _ := tt.Find("area")
label100, _ := tt.Find("100")
mon, _ := tt.Find("Mon")
if area.X != 20+label100.W || label100.X != 20 {
t.Errorf("the area starts at %v, after the widest label, %+v", area.X, label100)
}
if mid := label100.Y + label100.H/2; math.Abs(float64(mid-area.Y)) > 0.5 {
t.Errorf("the label 100 is centered at %v, not on the top of the area at %v", mid, area.Y)
}
if area.Y+area.H != mon.Y || area.Y+area.H+mon.H != 220 {
t.Errorf("the area %+v and the labels below it %+v", area, mon)
}
b := x.Band(0)
if mid := mon.X + mon.W/2; math.Abs(float64(mid-(area.X+area.W*b.Mid()))) > 0.5 {
t.Errorf("Mon is centered at %v, not on its band at %v", mid, area.X+area.W*b.Mid())
}
bar, _ := tt.Find("bar")
b = x.Band(1)
want := ui.Rect{X: area.X + area.W*b.Lo, Y: area.Y + area.H/2, W: area.W * (b.Hi - b.Lo), H: area.H / 2}
if math.Abs(float64(bar.X-want.X)) > 0.5 || math.Abs(float64(bar.Y-want.Y)) > 0.5 || math.Abs(float64(bar.W-want.W)) > 0.5 || math.Abs(float64(bar.H-want.H)) > 0.5 {
t.Errorf("bar at %+v, want %+v", bar, want)
}
dot, _ := tt.Find("dot")
if dot.X+5 != area.X+area.W/2 || dot.Y+5 != area.Y+area.H/2 {
t.Errorf("dot at %+v, not centered in %+v", dot, area)
}
rule, _ := tt.Find("top rule")
if rule.Y != area.Y-1 || rule.W != area.W || rule.H != 2 {
t.Errorf("rule at %+v", rule)
}
corner, _ := tt.Find("corner")
if math.Abs(float64(corner.X+corner.W-(area.X+area.W))) > 0.5 || math.Abs(float64(corner.Y+corner.H-(area.Y+area.H))) > 0.5 {
t.Errorf("corner at %+v, not ending at the bottom right of %+v", corner, area)
}
}
func TestSelect(t *testing.T) {
xs := []float32{0.1, 0.5, 0.9}
selected := -1
changes := 0
view := func(c *ui.Context) {
Plot(c, Axes{}, func(area ui.Element) {
area.Label("plot")
if Select(c, area, &selected, xs, func(i int) string { return []string{"one", "two", "three"}[i] }) {
changes++
}
}).Size(200, 100)
}
tt := ui.NewTester(view, 200, 100)
tt.Move(95, 50)
if selected != 1 {
t.Fatalf("pointer at the middle chose %d", selected)
}
tt.Move(190, 50)
if selected != 2 {
t.Fatalf("pointer at the right chose %d", selected)
}
tt.Move(300, 50) // out of the window, and of the plot
if selected != -1 {
t.Fatalf("pointer gone, still %d", selected)
}
if changes != 3 {
t.Errorf("%d changes, want 3", changes)
}
// The keyboard, once the plot has the focus.
tt.Key(0, ui.KeyTab)
if !tt.Focused("plot") {
t.Fatal("Tab does not focus the plot")
}
tt.Key(0, ui.KeyRight)
tt.Key(0, ui.KeyRight)
if selected != 1 {
t.Errorf("two rights chose %d", selected)
}
tt.Key(0, ui.KeyEnd)
tt.Key(0, ui.KeyRight) // stays at the last
if selected != 2 {
t.Errorf("End chose %d", selected)
}
tt.Key(0, ui.KeyHome)
if a := tt.Announcements(); !slices.Equal(a, []string{"one", "two", "three", "one"}) {
t.Errorf("announced %q", a)
}
tt.Key(0, ui.KeyEscape)
if selected != -1 {
t.Errorf("Escape left %d", selected)
}
tt.Key(0, ui.KeyLeft) // from none, to the last
if selected != 2 {
t.Errorf("left from none chose %d", selected)
}
}
+76
View File
@@ -0,0 +1,76 @@
package chart
import (
"math"
"sort"
)
// MinMax reduces a line of many points to the lowest and highest of each
// pixel column of the plot, in their order, and the ends of each run of
// defined points, so that a line through them looks the same and narrow
// spikes still show. xs and ys are fractions, as for Line; xs must not
// decrease, or the columns come out wrong, and a NaN or infinite value
// breaks the line. Points left or right of the plot go, but for the
// nearest one on each side. pixelWidth is the plot's width in pixels,
// ceil(r.W * p.Scale()).
//
// MinMax appends to dstX[:0] and dstY[:0] and returns them, so that a
// view keeping them reduces every frame without allocating; they must not
// share memory with xs or ys. Keep the points themselves for selections
// and readings.
func MinMax(dstX, dstY, xs, ys []float32, pixelWidth int) ([]float32, []float32) {
dstX, dstY = dstX[:0], dstY[:0]
if pixelWidth <= 0 {
return dstX, dstY
}
n := min(len(xs), len(ys))
finite := func(v float32) bool { return !math.IsNaN(float64(v)) && !math.IsInf(float64(v), 0) }
appendPoint := func(i int) { dstX = append(dstX, xs[i]); dstY = append(dstY, ys[i]) }
runs(n, func(i int) bool { return finite(xs[i]) && finite(ys[i]) }, func(from, to int) {
// Binary search leaves at most one point beyond either visible edge.
lo := from + sort.Search(to-from, func(i int) bool { return xs[from+i] >= 0 })
if lo == to {
return
}
hi := from + sort.Search(to-from, func(i int) bool { return xs[from+i] > 1 })
if lo == from && lo == hi {
return
}
if lo > from {
lo--
}
if hi < to {
hi++
}
if len(dstX) > 0 {
dstX = append(dstX, float32(math.NaN()))
dstY = append(dstY, float32(math.NaN()))
}
last := -1
emit := func(i int) {
if i != last {
appendPoint(i)
last = i
}
}
emit(lo)
for i := lo; i < hi; {
bucket := int(math.Floor(float64(xs[i]) * float64(pixelWidth)))
low, high := i, i
i++
for i < hi && xs[i] >= 0 && xs[i] <= 1 && bucket == int(math.Floor(float64(xs[i])*float64(pixelWidth))) {
if ys[i] < ys[low] {
low = i
}
if ys[i] > ys[high] {
high = i
}
i++
}
emit(min(low, high))
emit(max(low, high))
}
emit(hi - 1)
})
return dstX, dstY
}
+84
View File
@@ -0,0 +1,84 @@
package chart
import (
"math"
"slices"
"testing"
)
func TestMinMax(t *testing.T) {
nan := float32(math.NaN())
for _, tc := range []struct {
name string
xs, ys []float32
width int
indices []int
}{
{"extrema order", []float32{0, .01, .02, .03, .04, .05, .06}, []float32{3, 8, 2, 9, 0, 4, 5}, 1, []int{0, 3, 4, 6}},
{"two per bucket", []float32{0, .1, .2, .3, .4, .5, .6, .7, .8, .9}, []float32{2, 0, 4, 3, 2, 2, 0, 4, 3, 2}, 2, []int{0, 1, 2, 6, 7, 9}},
{"sparse", []float32{0, .3, .6, 1}, []float32{1, 2, 3, 4}, 100, []int{0, 1, 2, 3}},
{"duplicate x", []float32{.5, .5, .5, .5, .5}, []float32{2, 0, 3, 1, 2}, 10, []int{0, 1, 2, 4}},
{"edges", []float32{-2, -1, 0, .5, 1, 2, 3}, []float32{0, 1, 2, 3, 4, 5, 6}, 10, []int{1, 2, 3, 4, 5}},
{"crossing viewport", []float32{-2, -1, 2, 3}, []float32{0, 1, 2, 3}, 10, []int{1, 2}},
{"outside left", []float32{-2, -1}, []float32{0, 1}, 10, nil},
{"outside right", []float32{2, 3}, []float32{0, 1}, 10, nil},
{"empty", nil, nil, 10, nil},
{"zero width", []float32{0}, []float32{0}, 0, nil},
{"length mismatch", []float32{0, .5, 1}, []float32{1, 2}, 10, []int{0, 1}},
{"constant", []float32{0, .01, .02, .03}, []float32{1, 1, 1, 1}, 1, []int{0, 3}},
{"gap", []float32{0, .1, .2, .3, .4}, []float32{1, 2, nan, 3, 4}, 1, []int{0, 1, -1, 3, 4}},
{"infinity", []float32{0, .1, .2}, []float32{1, float32(math.Inf(1)), 2}, 1, []int{0, -1, 2}},
} {
t.Run(tc.name, func(t *testing.T) {
x, y := MinMax(nil, nil, tc.xs, tc.ys, tc.width)
if len(x) != len(tc.indices) || len(y) != len(x) {
t.Fatalf("got %v %v", x, y)
}
for j, i := range tc.indices {
if i < 0 {
if !math.IsNaN(float64(x[j])) || !math.IsNaN(float64(y[j])) {
t.Fatal("missing break")
}
continue
}
if x[j] != tc.xs[i] || y[j] != tc.ys[i] {
t.Fatalf("point %d: %v %v", j, x, y)
}
}
})
}
}
func TestMinMaxReuseAndDensity(t *testing.T) {
xs, ys := make([]float32, 15000), make([]float32, 15000)
for i := range xs {
xs[i] = float32(i) / 14999
ys[i] = float32(math.Sin(float64(i)))
}
dx, dy := make([]float32, 0, 15000), make([]float32, 0, 15000)
if a := testing.AllocsPerRun(20, func() { dx, dy = MinMax(dx, dy, xs, ys, 1280) }); a != 0 {
t.Fatalf("%v allocations", a)
}
first := slices.Clone(dx)
dx, dy = MinMax(dx, dy, xs, ys, 2560)
if len(dx) <= len(first) || len(dx) > 2*2560+3 {
t.Fatal("wrong density", len(dx), len(first))
}
}
// BenchmarkMinMax reduces 45,000 samples into physical pixel buckets, reusing output.
func BenchmarkMinMax(b *testing.B) {
xs, ys := make([]float32, 15000), make([]float32, 15000)
for i := range xs {
xs[i] = float32(i) / 14999
ys[i] = float32(math.Sin(float64(i)))
}
var dx, dy []float32
dx, dy = MinMax(dx, dy, xs, ys, 1280)
b.ReportAllocs()
for b.Loop() {
for range 3 {
dx, dy = MinMax(dx, dy, xs, ys, 1280)
}
}
}
+206
View File
@@ -0,0 +1,206 @@
package chart
import (
"math"
"math/bits"
"sort"
)
// MinMaxIndex keeps extrema of completed blocks for repeated MinMax queries.
// The zero value is empty. Update borrows the input; keep indexed samples
// unchanged, and call Reset before replacing or dropping history. Do not
// copy a populated index or access it concurrently. Raw samples remain available to
// the caller for exact selections.
type MinMaxIndex struct {
xs, ys []float32
runs [][2]int
levels [][][2]int // level l holds extrema of completed 16<<l sample blocks
work []float32
}
const minMaxBlock = 16
// Below this density, scanning beats the hierarchy's boundary visits.
const minMaxScan = 4 * minMaxBlock
// Reset releases the borrowed data and all index storage.
func (s *MinMaxIndex) Reset() { *s = MinMaxIndex{} }
// Update indexes the appended suffix of xs and ys, up to their shorter length.
// Pass the entire retained history each time. X must be nondecreasing within
// each finite run, as for MinMax. Changing existing samples requires Reset.
func (s *MinMaxIndex) Update(xs, ys []float32) {
n, old := min(len(xs), len(ys)), len(s.xs)
if n < old {
panic("chart: Reset MinMaxIndex before dropping samples")
}
s.xs, s.ys = xs[:n], ys[:n]
for i := old; i < n; i++ {
if !indexFinite(xs[i]) || !indexFinite(ys[i]) {
continue
}
if len(s.runs) > 0 && s.runs[len(s.runs)-1][1] == i {
s.runs[len(s.runs)-1][1]++
} else {
s.runs = append(s.runs, [2]int{i, i + 1})
}
}
if len(s.levels) == 0 {
s.levels = append(s.levels, nil)
}
for b := old / minMaxBlock; b < n/minMaxBlock; b++ {
e := [2]int{b * minMaxBlock, b * minMaxBlock}
for i := b*minMaxBlock + 1; i < (b+1)*minMaxBlock; i++ {
e = s.merge(e, [2]int{i, i})
}
s.levels[0] = append(s.levels[0], e)
for level := 0; len(s.levels[level])%2 == 0; level++ {
v := s.levels[level]
if level+1 == len(s.levels) {
s.levels = append(s.levels, nil)
}
s.levels[level+1] = append(s.levels[level+1], s.merge(v[len(v)-2], v[len(v)-1]))
}
}
}
func indexFinite(v float32) bool { return !math.IsNaN(float64(v)) && !math.IsInf(float64(v), 0) }
func (s *MinMaxIndex) merge(a, b [2]int) [2]int {
if s.ys[b[0]] < s.ys[a[0]] {
a[0] = b[0]
}
if s.ys[b[1]] > s.ys[a[1]] {
a[1] = b[1]
}
return a
}
// Query returns MinMax of the fractions (x-lo)/(hi-lo), without transforming
// the whole input. Y values are unchanged. lo and hi must be finite with
// lo < hi and a finite float32 difference; otherwise the output is empty.
// As with MinMax, output buffers must not alias input and are reused.
// Resize, pan and zoom need only another Query, not an index rebuild.
func (s *MinMaxIndex) Query(dstX, dstY []float32, lo, hi float32, pixelWidth int) ([]float32, []float32) {
dstX, dstY = dstX[:0], dstY[:0]
span := hi - lo
if pixelWidth <= 0 || !indexFinite(lo) || !indexFinite(hi) || !indexFinite(span) || !(span > 0) {
return dstX, dstY
}
x := func(i int) float32 { return (s.xs[i] - lo) / span }
// With dense gaps there is little hierarchy to skip. One scan avoids
// paying for a separate query per run when the whole history is visible.
scan := len(s.xs)/minMaxScan <= pixelWidth || len(s.runs) > max(64, pixelWidth/minMaxBlock)
if scan && len(s.xs) > 0 && x(0) >= 0 && x(len(s.xs)-1) <= 1 {
return s.scan(dstX, dstY, 0, len(s.xs), lo, span, pixelWidth)
}
bucket := func(i int) float64 { return math.Floor(float64(x(i)) * float64(pixelWidth)) }
for _, run := range s.runs {
from, to := run[0], run[1]
// Normalization can overflow even when the original X is finite.
from += sort.Search(to-from, func(i int) bool { return x(from+i) > float32(math.Inf(-1)) })
to = from + sort.Search(to-from, func(i int) bool { return x(from+i) >= float32(math.Inf(1)) })
a := from + sort.Search(to-from, func(i int) bool { return x(from+i) >= 0 })
if a == to {
continue
}
b := from + sort.Search(to-from, func(i int) bool { return x(from+i) > 1 })
if a == from && a == b {
continue
}
if a > from {
a--
}
if b < to {
b++
}
if len(dstX) > 0 {
dstX = append(dstX, float32(math.NaN()))
dstY = append(dstY, float32(math.NaN()))
}
// At low density scanning is cheaper than visiting the hierarchy.
if (b-a)/minMaxScan <= pixelWidth {
n := len(dstX)
xs, ys := s.scan(dstX[n:], dstY[n:], a, b, lo, span, pixelWidth)
dstX = append(dstX[:n], xs...)
dstY = append(dstY[:n], ys...)
continue
}
last := -1
emit := func(i int) {
if i != last {
dstX = append(dstX, x(i))
dstY = append(dstY, s.ys[i])
last = i
}
}
emit(a)
low, high, col := a, a, bucket(a)
flush := func() { emit(min(low, high)); emit(max(low, high)) }
add := func(i, j int) {
c := bucket(i)
if c != col || x(i) < 0 || x(i) > 1 {
flush()
low, high, col = i, i, c
}
if s.ys[i] < s.ys[low] {
low = i
}
if s.ys[j] < s.ys[low] {
low = j
}
if s.ys[i] > s.ys[high] {
high = i
}
if s.ys[j] > s.ys[high] {
high = j
}
}
var visit func(start, level int)
visit = func(start, level int) {
end := start + (minMaxBlock << level)
if x(start) >= 0 && x(end-1) <= 1 && bucket(start) == bucket(end-1) {
e := s.levels[level][start/(minMaxBlock<<level)]
// Feed in time order so equal extrema retain their first sample.
add(min(e[0], e[1]), max(e[0], e[1]))
return
}
if level == 0 {
for i := start; i < end; i++ {
add(i, i)
}
return
}
visit(start, level-1)
visit(start+(minMaxBlock<<(level-1)), level-1)
}
for i := a; i < b; {
if i%minMaxBlock != 0 || b-i < minMaxBlock {
add(i, i)
i++
continue
}
block := i / minMaxBlock
level := bits.Len(uint((b-i)/minMaxBlock)) - 1
if block != 0 {
level = min(level, bits.TrailingZeros(uint(block)))
}
visit(i, level)
i += minMaxBlock << level
}
flush()
emit(b - 1)
}
return dstX, dstY
}
func (s *MinMaxIndex) scan(dstX, dstY []float32, from, to int, lo, span float32, width int) ([]float32, []float32) {
if cap(s.work) < to-from {
s.work = make([]float32, to-from)
}
s.work = s.work[:to-from]
for i := range s.work {
s.work[i] = (s.xs[from+i] - lo) / span
}
return MinMax(dstX, dstY, s.work, s.ys[from:to], width)
}
+306
View File
@@ -0,0 +1,306 @@
package chart
import (
"fmt"
"math"
"math/rand/v2"
"slices"
"sort"
"testing"
)
func TestMinMaxIndexReference(t *testing.T) {
rng := rand.New(rand.NewPCG(17, 42))
for trial := 0; trial < 100; trial++ {
var index MinMaxIndex
var xs, ys, dx, dy []float32
for frame := 0; frame < 40; frame++ {
for range rng.IntN(40) {
x := float32(0)
if len(xs) > 0 {
x = xs[len(xs)-1]
}
x += float32(rng.IntN(4))
y := float32(rng.IntN(9) - 4)
if rng.IntN(20) == 0 {
y = float32(math.NaN())
}
if rng.IntN(40) == 0 {
y = float32(math.Inf(2*rng.IntN(2) - 1))
}
xs = append(xs, x)
ys = append(ys, y)
}
index.Update(xs, ys)
lo := float32(rng.IntN(1000) - 200)
hi := lo + float32(rng.IntN(1500)+1)
width := []int{0, 1, 2, 16, 1280, 1600, 2560}[rng.IntN(7)]
normalized := make([]float32, len(xs))
for i, x := range xs {
normalized[i] = (x - lo) / (hi - lo)
}
wx, wy := MinMax(nil, nil, normalized, ys, width)
dx, dy = index.Query(dx, dy, lo, hi, width)
equal := func(a, b float32) bool { return a == b || math.IsNaN(float64(a)) && math.IsNaN(float64(b)) }
if !slices.EqualFunc(dx, wx, equal) || !slices.EqualFunc(dy, wy, equal) {
t.Fatalf("trial %d frame %d [%g,%g] width %d\ngot %v %v\nwant %v %v", trial, frame, lo, hi, width, dx, dy, wx, wy)
}
}
index.Reset()
if index.xs != nil || index.levels != nil || index.runs != nil {
t.Fatal("Reset retains storage")
}
}
}
func TestMinMaxIndexReuse(t *testing.T) {
xs, ys := indexSignal(10000, "noise")
var index MinMaxIndex
index.Update(xs, ys)
dx, dy := index.Query(nil, nil, 0, 9999, 1280)
if a := testing.AllocsPerRun(20, func() { index.Update(xs, ys); dx, dy = index.Query(dx, dy, 0, 9999, 1280) }); a != 0 {
t.Fatal(a)
}
index.Reset()
index.Update(xs[:1], ys[:1])
dx, dy = index.Query(dx, dy, 0, 1, 10)
if len(dx) != 1 || dy[0] != ys[0] {
t.Fatal(dx, dy)
}
}
func TestMinMaxIndexDense(t *testing.T) {
rng := rand.New(rand.NewPCG(9, 11))
for _, kind := range []string{"sine", "noise", "spikes", "constant", "step", "duplicate", "uneven", "gapped"} {
xs, ys := indexSignal(100000, kind)
// Distinct X positions make every selected sample identifiable, even
// when Y extrema tie. Duplicate X is checked separately by values.
for _, width := range []int{1, 16, 1280, 1600, 2560, 3840} {
var index MinMaxIndex
for _, n := range []int{0, 1, 2, 15, 16, 17, 1023, 65535, 100000} {
index.Update(xs[:n], ys[:n])
for range 4 {
lo := float32(rng.IntN(50000) - 10000)
hi := lo + float32(rng.IntN(100000)+1)
checkIndex(t, &index, xs[:n], ys[:n], lo, hi, width)
}
}
}
}
for _, kind := range []string{"noise", "spikes"} {
xs, ys := indexSignal(1000000, kind)
var index MinMaxIndex
index.Update(xs, ys)
for _, width := range []int{1280, 1600, 2560, 3840} {
for _, bounds := range [][2]float32{{0, 999999}, {.25, 999990.5}, {333333, 777777}, {990000, 1000001}} {
checkIndex(t, &index, xs, ys, bounds[0], bounds[1], width)
}
}
}
}
func checkIndex(t *testing.T, index *MinMaxIndex, xs, ys []float32, lo, hi float32, width int) {
t.Helper()
work := make([]float32, len(xs))
for i, x := range xs {
work[i] = (x - lo) / (hi - lo)
}
wx, wy := MinMax(nil, nil, work, ys, width)
dx, dy := index.Query(nil, nil, lo, hi, width)
equal := func(a, b float32) bool { return a == b || math.IsNaN(float64(a)) && math.IsNaN(float64(b)) }
if !slices.EqualFunc(dx, wx, equal) || !slices.EqualFunc(dy, wy, equal) {
t.Fatalf("reference mismatch: n=%d width=%d lo=%g hi=%g\ngot %v %v\nwant %v %v", len(xs), width, lo, hi, dx, dy, wx, wy)
}
}
func TestMinMaxIndexEdges(t *testing.T) {
inf, nan := float32(math.Inf(1)), float32(math.NaN())
for _, xs := range [][]float32{nil, {0}, {-2, 2}, {-2, -1}, {2, 3}, {0, 0, 0, 0}, {0, nan, .5, inf, 1}, {-math.MaxFloat32, 0, math.MaxFloat32}} {
ys := make([]float32, len(xs))
for i := range ys {
ys[i] = float32(i % 3)
}
var index MinMaxIndex
index.Update(xs, ys)
for _, bounds := range [][2]float32{{0, 1}, {-2, -1}, {1, 2}, {math.MaxFloat32 / 2, math.MaxFloat32}, {0, math.SmallestNonzeroFloat32}} {
checkIndex(t, &index, xs, ys, bounds[0], bounds[1], 1)
}
}
}
func TestMinMaxIndexInvalidAndRebuild(t *testing.T) {
var index MinMaxIndex
xs, ys := []float32{0, .5, 1}, []float32{1, 2}
index.Update(xs, ys)
checkIndex(t, &index, xs, ys, 0, 1, 10)
for _, bounds := range [][2]float32{{0, 0}, {1, 0}, {0, float32(math.NaN())}, {0, float32(math.Inf(1))}, {-math.MaxFloat32, math.MaxFloat32}} {
dx, dy := index.Query(nil, nil, bounds[0], bounds[1], 10)
if len(dx) != 0 || len(dy) != 0 {
t.Fatal("invalid bounds produce output", bounds)
}
}
func() {
defer func() {
if recover() == nil {
t.Error("dropping samples without Reset must panic")
}
}()
index.Update(xs[:1], ys[:1])
}()
index.Reset()
xs[0] = .25
ys[0] = -1
index.Update(xs[1:], ys[1:])
checkIndex(t, &index, xs[1:], ys[1:], 0, 1, 10)
}
func indexSignal(n int, kind string) ([]float32, []float32) {
xs, ys := make([]float32, n), make([]float32, n)
for i := range xs {
xs[i] = float32(i)
switch kind {
case "noise":
ys[i] = float32(uint32(i)*1664525+1013904223) / math.MaxUint32
case "spikes":
if i%997 == 0 {
ys[i] = 1
}
case "constant":
ys[i] = 1
case "step":
ys[i] = float32((i / 100) % 2)
default:
ys[i] = float32(math.Sin(float64(i) / 20))
}
if kind == "duplicate" {
xs[i] = float32(i / 4)
}
if kind == "uneven" {
xs[i] = float32(i) * float32(i) / float32(n)
}
if kind == "gapped" && i%997 == 0 {
ys[i] = float32(math.NaN())
}
}
return xs, ys
}
var indexSink float32
// Query timings include normalization for the stateless implementations.
func BenchmarkIndexQuery(b *testing.B) {
for _, n := range []int{15000, 100000, 1000000} {
for _, kind := range []string{"sine", "noise", "spikes", "constant", "step", "duplicate", "uneven", "gapped"} {
for _, fraction := range []float32{1, .01} {
name := fmt.Sprintf("%d/%s/visible%g", n, kind, fraction)
xs, ys := indexSignal(n, kind)
lo, hi := xs[n-1]*(1-fraction), xs[n-1]
for _, mode := range []string{"MinMax", "Slice", "Index"} {
b.Run(name+"/"+mode, func(b *testing.B) {
var index MinMaxIndex
index.Update(xs, ys)
work := make([]float32, n)
dx, dy := make([]float32, 0, n), make([]float32, 0, n)
b.ReportAllocs()
if mode == "Index" {
dx, dy = index.Query(dx, dy, lo, hi, 1280)
}
for b.Loop() {
if mode == "Index" {
dx, dy = index.Query(dx, dy, lo, hi, 1280)
} else {
a, z := 0, n
if mode == "Slice" {
a = max(0, sort.Search(n, func(i int) bool { return xs[i] >= lo })-1)
z = min(n, sort.Search(n, func(i int) bool { return xs[i] > hi })+1)
}
for i := a; i < z; i++ {
work[i] = (xs[i] - lo) / (hi - lo)
}
dx, dy = MinMax(dx, dy, work[a:z], ys[a:z], 1280)
}
if len(dy) > 0 {
indexSink = dy[len(dy)-1]
}
}
})
}
}
}
}
}
func BenchmarkIndexBuild(b *testing.B) {
xs, ys := indexSignal(1000000, "noise")
b.ReportAllocs()
for b.Loop() {
var index MinMaxIndex
index.Update(xs, ys)
indexSink = ys[index.levels[0][0][0]]
bytes := cap(index.runs)*16 + cap(index.work)*4
for _, level := range index.levels {
bytes += cap(level) * 16
}
b.ReportMetric(float64(bytes), "index-B")
}
}
// BenchmarkIndexStreaming includes suffix updates, scrolling/zooming queries,
// and a bounded-history rebuild every 4096 samples. Build is not free.
func BenchmarkIndexStreaming(b *testing.B) {
for _, n := range []int{15000, 100000, 1000000} {
for _, width := range []int{1280, 1600, 2560, 3840} {
for _, mode := range []string{"MinMax", "Index"} {
b.Run(fmt.Sprintf("%d/%d/%s", n, width, mode), func(b *testing.B) {
xs, ys := indexSignal(n+4096, "noise")
work := make([]float32, len(xs))
dx, dy := make([]float32, 0, n), make([]float32, 0, n)
var index MinMaxIndex
index.Update(xs[:n], ys[:n])
dx, dy = index.Query(dx, dy, 0, float32(n-1), width)
frame := 0
b.ReportAllocs()
for b.Loop() {
frame = (frame + 1) % 256
now := n + frame*16
lo, hi := float32(frame*16), float32(now-1)
if frame%32 >= 16 {
lo += float32(n) / 2
}
if mode == "Index" {
if frame == 0 {
index.Reset()
}
index.Update(xs[:now], ys[:now])
dx, dy = index.Query(dx, dy, lo, hi, width)
} else {
for i := 0; i < now; i++ {
work[i] = (xs[i] - lo) / (hi - lo)
}
dx, dy = MinMax(dx, dy, work[:now], ys[:now], width)
}
indexSink = dy[len(dy)-1]
}
})
}
}
}
}
func BenchmarkIndexAppend(b *testing.B) {
xs, ys := indexSignal(1000000, "noise")
var index MinMaxIndex
index.Update(xs[:999984], ys[:999984])
// Restore lengths outside the operation: this measures one completed block,
// reusing allocated capacity, rather than an unbounded growing benchmark.
b.ReportAllocs()
for b.Loop() {
index.xs = index.xs[:999984]
index.ys = index.ys[:999984]
index.runs[0][1] = 999984
for l := range index.levels {
index.levels[l] = index.levels[l][:999984/(minMaxBlock<<l)]
}
index.Update(xs, ys)
}
}
+335
View File
@@ -0,0 +1,335 @@
package chart
import (
"math"
"slices"
"strconv"
)
// Log maps a domain of positive numbers, or of negative numbers, onto
// the plot with equal ratios the same distance apart, as d3.scaleLog.
// Zero and domains crossing zero are invalid; use SymLog for those.
// Lo/Hi may be reversed. An invalid domain or base produces NaN positions
// and no ticks, rather than a misleading linear plot.
type Log struct {
Lo, Hi float64
// Base selects the powers used by Nice and Ticks, 10 when zero.
// It must be finite and greater than 1. Changing it does not change At.
Base float64
Clamp bool
// Format labels every tick when set. The default uses six significant
// digits and omits crowded minor labels while retaining their ticks.
Format func(float64) string
}
// NewLog returns a logarithmic scale from lo to hi, with base 10.
func NewLog(lo, hi float64) Log { return Log{Lo: lo, Hi: hi} }
func finiteScale(v float64) bool { return !math.IsNaN(v) && !math.IsInf(v, 0) }
func clampValue(v, lo, hi float64) float64 { return max(min(lo, hi), min(max(lo, hi), v)) }
func (s Log) base() float64 {
if s.Base == 0 {
return 10
}
return s.Base
}
func (s Log) valid() bool {
b := s.base()
return finiteScale(s.Lo) && finiteScale(s.Hi) && finiteScale(b) && b > 1 &&
(s.Lo > 0 && s.Hi > 0 || s.Lo < 0 && s.Hi < 0)
}
// Normalize subnormals before Log, whose architecture-specific paths can
// otherwise lose their exponent. Scaling by a power of two is exact.
func positiveLog(v float64) float64 {
if v > 0 && v < 0x1p-1022 {
return math.Log(v*0x1p52) - 52*math.Ln2
}
return math.Log(v)
}
// logRatio avoids overflowing a ratio spanning the float64 range, and
// preserves the difference of endpoints whose logarithms round alike.
func logRatio(v, lo float64) float64 {
relative := (v - lo) / lo
if math.Abs(relative) < .5 {
return math.Log1p(relative)
}
return positiveLog(v) - positiveLog(lo)
}
// At returns where v is along the plot. Without Clamp, a value of the
// opposite sign produces NaN, and zero maps to infinity off the plot.
// NaN propagates, so chart paths can leave a gap there.
func (s Log) At(v float64) float32 {
if !s.valid() || math.IsNaN(v) {
return float32(math.NaN())
}
if s.Clamp {
v = clampValue(v, s.Lo, s.Hi)
}
if s.Lo > 0 && v < 0 || s.Lo < 0 && v > 0 {
return float32(math.NaN())
}
if s.Lo == s.Hi {
return .5
}
return float32(logRatio(math.Abs(v), math.Abs(s.Lo)) / logRatio(math.Abs(s.Hi), math.Abs(s.Lo)))
}
// Invert returns the value at a fraction of the plot.
func (s Log) Invert(f float32) float64 {
if !s.valid() || math.IsNaN(float64(f)) {
return math.NaN()
}
if s.Clamp {
f = max(0, min(1, f))
}
if f == 0 || s.Lo == s.Hi {
return s.Lo
}
if f == 1 {
return s.Hi
}
lo := math.Abs(s.Lo)
r := logRatio(math.Abs(s.Hi), lo)
var v float64
if math.Abs(r) < .5 {
v = lo + lo*math.Expm1(float64(f)*r)
} else {
v = math.Exp(positiveLog(lo) + float64(f)*r)
}
return math.Copysign(v, s.Lo)
}
// Span returns the stretch from a to b along the plot. A logarithmic bar
// needs a nonzero baseline; zero cannot be its lower edge.
func (s Log) Span(a, b float64) Span { return Span{s.At(a), s.At(b)} }
func logBase(v, base float64) float64 {
if v < 0x1p-1022 {
return positiveLog(v) / math.Log(base)
}
switch base {
case 10:
return math.Log10(v)
case 2:
return math.Log2(v)
case math.E:
return math.Log(v)
}
return math.Log(v) / math.Log(base)
}
func powerBase(exponent, base float64) float64 {
if base == 10 && exponent == math.Trunc(exponent) && exponent >= -324 && exponent <= 309 {
return math.Pow10(int(exponent))
}
if base == 2 {
return math.Exp2(exponent)
}
if base == math.E {
return math.Exp(exponent)
}
return math.Pow(base, exponent)
}
// Nice extends the domain out to powers of Base. At the float64 limits,
// an edge whose next power is zero or infinite keeps its original value.
// Invalid scales are unchanged.
func (s Log) Nice() Log {
if !s.valid() {
return s
}
lo, hi := min(math.Abs(s.Lo), math.Abs(s.Hi)), max(math.Abs(s.Lo), math.Abs(s.Hi))
a, b := powerBase(math.Floor(logBase(lo, s.base())), s.base()), powerBase(math.Ceil(logBase(hi, s.base())), s.base())
if a > 0 && finiteScale(a) && a <= lo {
lo = a
}
if b > 0 && finiteScale(b) && b >= hi {
hi = b
}
if math.Abs(s.Lo) > math.Abs(s.Hi) {
lo, hi = hi, lo
}
s.Lo, s.Hi = math.Copysign(lo, s.Lo), math.Copysign(hi, s.Hi)
return s
}
// Ticks marks powers of Base and, for integer bases on a short domain,
// their multiples, as d3.scaleLog does. Count is a density hint; minor
// ticks may outnumber it. Sparse domains fall back to round linear ticks.
// Nonpositive counts return no ticks.
func (s Log) Ticks(count int) []Tick {
if !s.valid() || count <= 0 {
return nil
}
lo, hi := min(math.Abs(s.Lo), math.Abs(s.Hi)), max(math.Abs(s.Lo), math.Abs(s.Hi))
base := s.base()
a, b := logBase(lo, base), logBase(hi, base)
var values []float64
// Bound the work of minor ticks for unusually large integer bases;
// powers still work for every valid base.
if base == math.Trunc(base) && b-a < float64(count) && base*math.Ceil(b-a+2) <= 10000 {
for exponent := math.Floor(a); exponent <= math.Ceil(b); exponent++ {
p := powerBase(exponent, base)
for k := 1.0; k < base; k++ {
v := k * p
if exponent < 0 {
if divisor := powerBase(-exponent, base); finiteScale(divisor) {
v = k / divisor
}
}
if v >= lo && v <= hi && v > 0 && finiteScale(v) {
values = append(values, v)
}
}
}
if len(values)*2 < count {
values = ticks(lo, hi, float64(count))
}
} else {
for _, e := range ticks(a, b, min(b-a, float64(count))) {
v := powerBase(e, base)
if v > 0 && finiteScale(v) {
values = append(values, v)
}
}
}
if lo == hi {
values = []float64{lo}
}
if s.Lo < 0 {
for i := range values {
values[i] = -values[i]
}
slices.Reverse(values)
}
if s.Hi < s.Lo {
slices.Reverse(values)
}
out := make([]Tick, len(values))
threshold := max(1, base*float64(count)/float64(len(values)))
for i, v := range values {
label := ""
if s.Format != nil {
label = s.Format(v)
} else {
exponent := math.Floor(logBase(math.Abs(v), base) + 1e-12)
coefficient := math.Abs(v) / powerBase(exponent, base)
if len(values) == 1 || coefficient <= threshold+1e-10 {
label = strconv.FormatFloat(v, 'g', 6, 64)
}
}
out[i] = Tick{At: s.At(v), Value: v, Label: label}
}
return out
}
// SymLog is a symmetric logarithmic scale: sign(v)*log1p(abs(v)/Constant).
// Unlike Log it includes zero and negative values. It is nearly linear
// near zero and logarithmic for larger magnitudes, as d3.scaleSymlog.
// Ticks and Nice choose round values in the original data units.
type SymLog struct {
Lo, Hi float64
// Constant sets the size of the linear region, 1 when zero. It must
// be finite and positive; a larger constant makes more of the plot linear.
Constant float64
Clamp bool
Format func(float64) string
}
// NewSymLog returns a symmetric logarithmic scale from lo to hi.
func NewSymLog(lo, hi float64) SymLog { return SymLog{Lo: lo, Hi: hi} }
func (s SymLog) constant() float64 {
if s.Constant == 0 {
return 1
}
return s.Constant
}
func (s SymLog) valid() bool {
return finiteScale(s.Lo) && finiteScale(s.Hi) && finiteScale(s.constant()) && s.constant() > 0
}
func symLog(v, c float64) float64 {
r := math.Abs(v) / c
if math.IsInf(r, 0) {
return math.Copysign(positiveLog(math.Abs(v))-positiveLog(c), v)
}
return math.Copysign(math.Log1p(r), v)
}
func symExp(v, c float64) float64 {
if math.Abs(v) > 700 {
return math.Copysign(math.Exp(positiveLog(c)+math.Abs(v)), v)
}
return math.Copysign(c*math.Expm1(math.Abs(v)), v)
}
// At returns where v is along the plot; NaN propagates as a missing value.
func (s SymLog) At(v float64) float32 {
if !s.valid() || math.IsNaN(v) {
return float32(math.NaN())
}
if s.Clamp {
v = clampValue(v, s.Lo, s.Hi)
}
a, b := symLog(s.Lo, s.constant()), symLog(s.Hi, s.constant())
if a == b {
return (Linear{Lo: s.Lo, Hi: s.Hi}).At(v)
}
return float32((symLog(v, s.constant()) - a) / (b - a))
}
// Invert returns the value at a fraction of the plot.
func (s SymLog) Invert(f float32) float64 {
if !s.valid() || math.IsNaN(float64(f)) {
return math.NaN()
}
if s.Clamp {
f = max(0, min(1, f))
}
if f == 0 || s.Lo == s.Hi {
return s.Lo
}
if f == 1 {
return s.Hi
}
a, b := symLog(s.Lo, s.constant()), symLog(s.Hi, s.constant())
if a == b {
return (Linear{Lo: s.Lo, Hi: s.Hi}).Invert(f)
}
return symExp(a+float64(f)*(b-a), s.constant())
}
// Span returns the stretch from a to b along the plot.
func (s SymLog) Span(a, b float64) Span { return Span{s.At(a), s.At(b)} }
// Nice extends the domain to round data values, as Linear.Nice does.
func (s SymLog) Nice(count int) SymLog {
if !s.valid() || count <= 0 {
return s
}
n := NewLinear(s.Lo, s.Hi).Nice(count)
if !finiteScale(n.Lo) || !finiteScale(n.Hi) {
return s
}
// Very sparse requests can fail to converge while round domains
// repeatedly expand. Keep the original domain rather than returning
// the linear helper's last intermediate result.
again := n.Nice(count)
if again.Lo != n.Lo || again.Hi != n.Hi {
return s
}
s.Lo, s.Hi = n.Lo, n.Hi
return s
}
// Ticks returns round values, spaced nonlinearly along the plot.
func (s SymLog) Ticks(count int) []Tick {
if !s.valid() {
return nil
}
out := (Linear{Lo: s.Lo, Hi: s.Hi, Format: s.Format}).Ticks(count)
for i := range out {
out[i].At = s.At(out[i].Value)
}
return out
}
+97
View File
@@ -0,0 +1,97 @@
package chart
import (
"compress/gzip"
"encoding/json"
"fmt"
"math"
"os"
"testing"
)
// Golden values come from the pinned d3-scale version recorded in the
// fixture, generated by scripts/chart-scales-golden.ts with Node.
func TestNonlinearMatchesD3(t *testing.T) {
f, err := os.Open("testdata/nonlinear_d3.json.gz")
if err != nil {
t.Fatal(err)
}
defer f.Close()
z, err := gzip.NewReader(f)
if err != nil {
t.Fatal(err)
}
defer z.Close()
var golden struct {
Version string
Cases []struct {
Kind string
Domain [2]float64
Parameter float64
Count int
Clamp bool
Values, Positions, Fractions, Inversions, Ticks []float64
Nice [2]float64
}
}
if err := json.NewDecoder(z).Decode(&golden); err != nil {
t.Fatal(err)
}
if golden.Version != "4.0.2" || len(golden.Cases) == 0 {
t.Fatalf("invalid d3-scale reference: version %q, %d cases", golden.Version, len(golden.Cases))
}
t.Logf("%d d3-scale %s cases", len(golden.Cases), golden.Version)
near := func(a, b float64) bool {
return math.Abs(a-b) <= max(4*math.SmallestNonzeroFloat64, 1e-9*math.Abs(b))
}
for i, c := range golden.Cases {
t.Run(fmt.Sprintf("%s/%d", c.Kind, i), func(t *testing.T) {
var at func(float64) float32
var invert func(float32) float64
var ts []Tick
var nice [2]float64
if c.Kind == "log" {
s := NewLog(c.Domain[0], c.Domain[1])
s.Base, s.Clamp = c.Parameter, c.Clamp
at, invert, ts = s.At, s.Invert, s.Ticks(c.Count)
n := s.Nice()
nice = [2]float64{n.Lo, n.Hi}
} else {
s := NewSymLog(c.Domain[0], c.Domain[1])
s.Constant, s.Clamp = c.Parameter, c.Clamp
at, invert, ts = s.At, s.Invert, s.Ticks(c.Count)
n := s.Nice(c.Count)
nice = [2]float64{n.Lo, n.Hi}
}
for j, v := range c.Values {
if got := float64(at(v)); !finiteScale(got) || math.Abs(got-c.Positions[j]) > 2e-6 {
t.Fatalf("At(%v)=%v want %v; %+v", v, got, c.Positions[j], c)
}
}
for j, f := range c.Fractions {
if got := invert(float32(f)); !near(got, c.Inversions[j]) {
t.Fatalf("Invert(%v)=%v want %v; domain %v, parameter %v", f, got, c.Inversions[j], c.Domain, c.Parameter)
}
}
// D3 omits the tick of a constant log domain for noninteger
// bases; keep that value, as the other MyGo scales do.
wantTicks := c.Ticks
if c.Kind == "log" && c.Domain[0] == c.Domain[1] && len(wantTicks) == 0 {
wantTicks = []float64{c.Domain[0]}
}
if len(ts) != len(wantTicks) {
t.Fatalf("Ticks(%d)=%v want %v; domain %v, base %v", c.Count, tickValues(ts), wantTicks, c.Domain, c.Parameter)
}
for j, tick := range ts {
if !near(tick.Value, wantTicks[j]) {
t.Fatalf("tick %d=%v want %v", j, tick.Value, wantTicks[j])
}
}
for j, n := range nice {
if !near(n, c.Nice[j]) {
t.Fatalf("Nice=%v want %v; domain %v, parameter %v", nice, c.Nice, c.Domain, c.Parameter)
}
}
})
}
}
+237
View File
@@ -0,0 +1,237 @@
package chart
import (
"math"
"slices"
"testing"
)
func TestLogScale(t *testing.T) {
for _, tc := range []struct {
lo, hi, v float64
want float32
}{
{1, 1000, 10, 1.0 / 3}, {1, 1000, 100, 2.0 / 3}, {1000, 1, 10, 2.0 / 3},
{-1000, -1, -10, 2.0 / 3}, {-1, -1000, -10, 1.0 / 3}, {5, 5, 100, .5},
} {
s := NewLog(tc.lo, tc.hi)
if got := s.At(tc.v); math.Abs(float64(got-tc.want)) > 1e-6 {
t.Errorf("%+v: got %v", tc, got)
}
if tc.lo != tc.hi {
if got := s.Invert(s.At(tc.v)); math.Abs((got-tc.v)/tc.v) > 1e-6 {
t.Errorf("roundtrip: %v -> %v", tc.v, got)
}
}
}
s := NewLog(1, 100)
if got := s.Span(1, 100); got != (Span{0, 1}) {
t.Fatal(got)
}
s.Clamp = true
if s.At(-10) != 0 || s.At(1000) != 1 || s.Invert(-1) != 1 || s.Invert(2) != 100 {
t.Fatal("clamp failed")
}
if got := NewLog(3, 73).Nice(); got.Lo != 1 || got.Hi != 100 {
t.Fatal(got)
}
if got := NewLog(-73, -3).Nice(); got.Lo != -100 || got.Hi != -1 {
t.Fatal(got)
}
s = NewLog(1, 100)
values := tickValues(s.Ticks(10))
want := []float64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
if !slices.Equal(values, want) {
t.Fatalf("ticks %v", values)
}
s = NewLog(1, 32)
s.Base = 2
if got := tickValues(s.Ticks(10)); !slices.Equal(got, []float64{1, 2, 4, 8, 16, 32}) {
t.Fatal(got)
}
}
func tickValues(ts []Tick) []float64 {
out := make([]float64, len(ts))
for i, t := range ts {
out[i] = t.Value
}
return out
}
func TestSymLogScale(t *testing.T) {
s := NewSymLog(-100, 100)
if s.At(0) != .5 || s.Invert(.5) != 0 {
t.Fatal("zero not at center")
}
if math.Abs(float64(s.At(1))-(.5+math.Log(2)/(2*math.Log(101)))) > 1e-6 {
t.Fatal(s.At(1))
}
if got := s.Span(-100, 100); got != (Span{0, 1}) {
t.Fatal(got)
}
if !slices.Equal(tickValues(s.Ticks(4)), []float64{-100, -50, 0, 50, 100}) {
t.Fatal(s.Ticks(4))
}
nice := NewSymLog(-3.2, 7.9).Nice(6)
if nice.Lo != -4 || nice.Hi != 8 {
t.Fatal(nice)
}
for _, constant := range []float64{.1, 1, 10} {
s.Constant = constant
for _, v := range []float64{-100, -10, -.01, 0, .01, 10, 100} {
if got := s.Invert(s.At(v)); math.Abs(got-v) > 1e-4 {
t.Errorf("constant %v: %v -> %v", constant, v, got)
}
}
}
s.Clamp = true
if s.At(-1000) != 0 || s.At(1000) != 1 || s.Invert(-1) != -100 || s.Invert(2) != 100 {
t.Fatal("clamp failed")
}
}
func TestNonlinearInvalid(t *testing.T) {
for _, s := range []Log{NewLog(0, 100), NewLog(-1, 1), NewLog(1, math.Inf(1)), {Lo: 1, Hi: 10, Base: 1}, {Lo: 1, Hi: 10, Base: -2}} {
if !math.IsNaN(float64(s.At(1))) || !math.IsNaN(s.Invert(.5)) || len(s.Ticks(5)) != 0 {
t.Fatalf("accepted invalid log %+v", s)
}
}
for _, s := range []SymLog{{Lo: -1, Hi: 1, Constant: -1}, {Lo: -1, Hi: 1, Constant: math.Inf(1)}, NewSymLog(math.NaN(), 1)} {
if !math.IsNaN(float64(s.At(0))) || !math.IsNaN(s.Invert(.5)) || len(s.Ticks(5)) != 0 {
t.Fatalf("accepted invalid symlog %+v", s)
}
}
if !math.IsNaN(float64(NewLog(1, 100).At(-1))) {
t.Fatal("wrong sign accepted")
}
if !math.IsNaN(float64(NewSymLog(-1, 1).At(math.NaN()))) {
t.Fatal("NaN did not propagate")
}
}
func TestNonlinearEdgesAndLabels(t *testing.T) {
for _, count := range []int{0, -1} {
if len(NewLog(1, 100).Ticks(count)) != 0 || len(NewSymLog(-1, 1).Ticks(count)) != 0 {
t.Fatal("nonpositive count has ticks")
}
s := NewSymLog(-1, 1).Nice(count)
if s.Lo != -1 || s.Hi != 1 {
t.Fatal("nonpositive nice count changed the domain")
}
}
for _, base := range []float64{2, math.E, 10} {
for _, value := range []float64{math.SmallestNonzeroFloat64, 5, math.MaxFloat64} {
s := NewLog(value, value)
s.Base = base
ts := s.Ticks(5)
if len(ts) != 1 || ts[0].Value != value || ts[0].At != .5 || ts[0].Label == "" {
t.Fatal("constant domain lost its tick", ts)
}
}
}
s := NewLog(1, 100)
blank := false
for _, tick := range s.Ticks(5) {
blank = blank || tick.Label == ""
}
// A denser minor grid can omit some labels, and a caller can label all.
s = NewLog(1, 100)
s.Format = func(float64) string { return "custom" }
for _, tick := range s.Ticks(5) {
if tick.Label != "custom" {
t.Fatal(tick)
}
}
if !blank {
t.Fatal("crowded minor tick labels were not suppressed")
}
sy := NewSymLog(-10, 10)
sy.Format = s.Format
for _, tick := range sy.Ticks(4) {
if tick.Label != "custom" {
t.Fatal(tick)
}
}
lo := 1e300
hi := math.Nextafter(lo, math.Inf(1))
close := NewLog(lo, hi)
if close.At(lo) != 0 || close.At(hi) != 1 || close.Invert(0) != lo || close.Invert(1) != hi {
t.Fatal("close endpoints lost precision")
}
wide := NewLog(math.SmallestNonzeroFloat64, math.MaxFloat64)
if wide.At(wide.Lo) != 0 || wide.At(wide.Hi) != 1 || !finiteScale(wide.Invert(.5)) {
t.Fatal("wide log domain failed")
}
n := wide.Nice()
if !n.valid() {
t.Fatal("nice made an extreme domain invalid")
}
for _, constant := range []float64{math.SmallestNonzeroFloat64, 1e-100, 1, math.MaxFloat64} {
s := NewSymLog(-1e300, 1e300)
s.Constant = constant
if s.At(0) != .5 || s.Invert(.5) != 0 || s.At(s.Lo) != 0 || s.At(s.Hi) != 1 {
t.Fatalf("extreme constant %v failed", constant)
}
if !finiteScale(s.Invert(.75)) {
t.Fatalf("extreme constant %v overflowed inverse", constant)
}
}
sparse := NewSymLog(-100, 100).Nice(1)
if sparse.Lo != -100 || sparse.Hi != 100 {
t.Fatal("sparse nice request expanded without converging")
}
}
func FuzzNonlinearRoundtrip(f *testing.F) {
for _, v := range [][3]float64{{-10, 20, .3}, {-300, 300, .5}, {-.001, .001, .75}, {0, 1, .25}} {
f.Add(v[0], v[1], v[2])
}
f.Fuzz(func(t *testing.T, a, b, fraction float64) {
if !finiteScale(a) || !finiteScale(b) || !finiteScale(fraction) || a < -300 || a > 300 || b < -300 || b > 300 || math.Abs(a-b) < .01 {
return
}
fraction = math.Abs(fraction - math.Trunc(fraction))
s := NewLog(math.Pow(10, a), math.Pow(10, b))
point := float32(fraction)
value := s.Invert(point)
if got := s.At(value); math.IsNaN(float64(got)) || math.Abs(float64(got-point)) > 2e-5 {
t.Fatalf("log %v %v: %v -> %v -> %v", a, b, point, value, got)
}
sy := NewSymLog(-math.Abs(a), math.Abs(b))
value = sy.Invert(point)
if got := sy.At(value); math.IsNaN(float64(got)) || math.Abs(float64(got-point)) > 2e-5 {
t.Fatalf("symlog: %v -> %v -> %v", point, value, got)
}
})
}
func TestNonlinearMappingAllocs(t *testing.T) {
logScale, signed := NewLog(.01, 1000), NewSymLog(-1000, 1000)
if n := testing.AllocsPerRun(100, func() {
logScale.At(10)
logScale.Invert(.25)
signed.At(-10)
signed.Invert(.75)
}); n != 0 {
t.Fatalf("scale mapping allocates %v times", n)
}
}
func TestNonlinearSubnormal(t *testing.T) {
// Equal binary exponent spans must map to equal distances even below
// the smallest normal float64; the midpoint is exactly 2^-537.
mid := math.Exp2(-537)
s := NewLog(math.SmallestNonzeroFloat64, 1)
if got := s.At(mid); math.Abs(float64(got)-.5) > 1e-6 {
t.Fatalf("subnormal log midpoint: %v", got)
}
if got := s.Invert(.5); math.Abs(got/mid-1) > 1e-12 {
t.Fatalf("subnormal log inverse: %g want %g", got, mid)
}
sy := NewSymLog(-1, 1)
sy.Constant = math.SmallestNonzeroFloat64
if got := sy.Invert(.75); math.Abs(got/mid-1) > 1e-12 {
t.Fatalf("subnormal symlog constant: %g want %g", got, mid)
}
}
+33
View File
@@ -0,0 +1,33 @@
package chart
import (
"bytes"
"math"
"testing"
"github.com/egoist/mygo/ui"
)
func TestLineInto(t *testing.T) {
xs := []float32{0, .1, .3, .6, .8, 1}
ys := []float32{.1, .5, .2, float32(math.NaN()), .4, .8}
var path ui.Path
for _, curve := range []Curve{CurveLinear, CurveMonotone, CurveStep, CurveStepBefore, CurveStepAfter} {
fresh := ui.Render(func(c *ui.Context) {
ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) { p.StrokePath(Line(r, xs, ys, curve), 2, ui.RGB(30, 100, 240)) })
}, 100, 100, 2)
path.MoveTo(0, 0).LineTo(90, 90).Trim(0, .1)
reused := ui.Render(func(c *ui.Context) {
ui.Box(c).Fill().Draw(func(p *ui.Painter, r ui.Rect) {
p.StrokePath(LineInto(&path, r, xs, ys, curve), 2, ui.RGB(30, 100, 240))
})
}, 100, 100, 2)
if !bytes.Equal(fresh.Pix, reused.Pix) {
t.Fatal("reuse changes geometry or retains Trim", curve)
}
}
LineInto(&path, ui.Rect{W: 100, H: 100}, xs, ys, CurveLinear)
if a := testing.AllocsPerRun(20, func() { LineInto(&path, ui.Rect{W: 100, H: 100}, xs, ys, CurveLinear) }); a != 0 {
t.Fatal("linear reuse allocates", a)
}
}
+329
View File
@@ -0,0 +1,329 @@
package chart
import (
"math"
"strconv"
)
// Span is a stretch of a chart's plot along one axis, in fractions of it:
// from the left edge (0) to the right (1) along x, and from the bottom (0)
// to the top (1) along y, the way values grow. Scales return spans for the
// marks: a bar's band along x, its stretch from 0 to its value along y.
type Span struct{ Lo, Hi float32 }
// Mid returns the middle of the span.
func (s Span) Mid() float32 { return (s.Lo + s.Hi) / 2 }
// Tick is a value a scale marks along an axis: where it is, in a fraction
// of the plot, and its label.
type Tick struct {
At float32
Value float64
Label string
}
// Linear maps numbers from Lo to Hi onto the plot, Lo at its start, as
// d3's scaleLinear and Swift Charts' automatic scales of numbers. Values
// outside the domain go outside the plot unless Clamp says otherwise.
//
// y := chart.NewLinear(0, 87).Nice(10) // 0 to 90, ticks every 10
// bar := y.Span(0, 42)
type Linear struct {
Lo, Hi float64
// Clamp keeps values outside the domain at its ends.
Clamp bool
// Format labels the ticks; nil labels them with as many decimals as
// their step needs.
Format func(v float64) string
}
// NewLinear returns a linear scale from lo to hi.
func NewLinear(lo, hi float64) Linear { return Linear{Lo: lo, Hi: hi} }
// Extent returns the smallest and the largest of values, the domain of a
// scale showing them, and 0, 1 for none. Include 0 for bars and areas:
//
// lo, hi := chart.Extent(sales...)
// y := chart.NewLinear(min(lo, 0), hi).Nice(5)
func Extent(values ...float64) (lo, hi float64) {
if len(values) == 0 {
return 0, 1
}
lo, hi = math.Inf(1), math.Inf(-1)
for _, v := range values {
if math.IsNaN(v) {
continue
}
lo, hi = min(lo, v), max(hi, v)
}
if lo > hi {
return 0, 1
}
return lo, hi
}
// At returns where v is along the plot.
func (s Linear) At(v float64) float32 {
if s.Hi == s.Lo {
return 0.5
}
f := (v - s.Lo) / (s.Hi - s.Lo)
if s.Clamp {
f = max(0, min(1, f))
}
return float32(f)
}
// Span returns the stretch from a to b along the plot, as a bar's from 0
// to its value.
func (s Linear) Span(a, b float64) Span { return Span{s.At(a), s.At(b)} }
// Invert returns the value at f along the plot, as where the pointer is.
func (s Linear) Invert(f float32) float64 {
v := s.Lo + float64(f)*(s.Hi-s.Lo)
if s.Clamp {
v = max(min(s.Lo, s.Hi), min(max(s.Lo, s.Hi), v))
}
return v
}
// Nice extends the domain to round values, those of about count ticks, as
// d3's nice: 0 to 87 becomes 0 to 90 for 10 ticks, and 0 to 100 for 5.
func (s Linear) Nice(count int) Linear {
lo, hi := s.Lo, s.Hi
reverse := hi < lo
if reverse {
lo, hi = hi, lo
}
var prev float64
for range 10 {
step := tickIncrement(lo, hi, float64(count))
if step == prev {
break
}
switch {
case step > 0:
lo, hi = math.Floor(lo/step)*step, math.Ceil(hi/step)*step
case step < 0:
lo, hi = math.Ceil(lo*step)/step, math.Floor(hi*step)/step
default:
return s
}
prev = step
}
if reverse {
lo, hi = hi, lo
}
s.Lo, s.Hi = lo, hi
return s
}
// Ticks returns about count round values within the domain, 1, 2 or 5
// times a power of ten apart, as d3's ticks and Swift Charts' automatic
// axis marks: 0, 20, 40, 60, 80 and 100 for 0 to 100 and 5.
func (s Linear) Ticks(count int) []Tick {
values := ticks(s.Lo, s.Hi, float64(count))
format := s.Format
if format == nil {
step := math.Abs(tickStep(s.Lo, s.Hi, float64(count)))
decimals := 0
if step > 0 && step < 1 {
decimals = max(0, int(-math.Floor(math.Log10(step)+1e-9)))
if step*math.Pow10(decimals) != math.Round(step*math.Pow10(decimals)) {
decimals++
}
}
format = func(v float64) string {
if v == 0 {
v = 0 // no -0
}
return strconv.FormatFloat(v, 'f', decimals, 64)
}
}
out := make([]Tick, len(values))
for i, v := range values {
out[i] = Tick{At: s.At(v), Value: v, Label: format(v)}
}
return out
}
// The tick spacing that d3-array's ticks uses: steps of 1, 2 or 5 times a
// power of ten, the closest to (hi-lo)/count.
var (
e10 = math.Sqrt(50)
e5 = math.Sqrt(10)
e2 = math.Sqrt(2)
)
// tickSpec returns the first and last tick's index and the step between
// ticks, negative for the inverse of the step (1/-inc) when it is below 1,
// so that ticks such as 0.3 come out exact.
func tickSpec(lo, hi, count float64) (i1, i2, inc float64) {
step := (hi - lo) / max(0, count)
power := math.Floor(math.Log10(step))
e := step / math.Pow(10, power)
factor := 1.0
switch {
case e >= e10:
factor = 10
case e >= e5:
factor = 5
case e >= e2:
factor = 2
}
if power < 0 {
inc = math.Pow(10, -power) / factor
i1, i2 = math.Round(lo*inc), math.Round(hi*inc)
if i1/inc < lo {
i1++
}
if i2/inc > hi {
i2--
}
inc = -inc
} else {
inc = math.Pow(10, power) * factor
i1, i2 = math.Round(lo/inc), math.Round(hi/inc)
if i1*inc < lo {
i1++
}
if i2*inc > hi {
i2--
}
}
if i2 < i1 && 0.5 <= count && count < 2 {
return tickSpec(lo, hi, count*2)
}
return i1, i2, inc
}
// ticks returns the round values between lo and hi, in their order.
func ticks(lo, hi, count float64) []float64 {
if !(count > 0) || math.IsNaN(lo) || math.IsNaN(hi) || math.IsInf(lo, 0) || math.IsInf(hi, 0) {
return nil
}
if lo == hi {
return []float64{lo}
}
reverse := hi < lo
if reverse {
lo, hi = hi, lo
}
i1, i2, inc := tickSpec(lo, hi, count)
if !(i2 >= i1) || math.IsInf(inc, 0) || math.IsNaN(inc) {
return nil
}
n := int(i2-i1) + 1
out := make([]float64, n)
for i := range n {
k := i
if reverse {
k = n - 1 - i
}
if inc < 0 {
out[i] = (i1 + float64(k)) / -inc
} else {
out[i] = (i1 + float64(k)) * inc
}
}
return out
}
// tickIncrement returns the step between ticks, or its negative inverse
// below 1, as d3-array's tickIncrement.
func tickIncrement(lo, hi, count float64) float64 {
_, _, inc := tickSpec(lo, hi, count)
return inc
}
// tickStep returns the step between ticks, signed as hi-lo.
func tickStep(lo, hi, count float64) float64 {
reverse := hi < lo
if reverse {
lo, hi = hi, lo
}
inc := tickIncrement(lo, hi, count)
if inc < 0 {
inc = 1 / -inc
}
if reverse {
return -inc
}
return inc
}
// Band divides the plot into a band for each of its labels, as d3's
// scaleBand and Swift Charts' scales of categories: the bars of a bar
// chart, one for each month.
//
// x := chart.NewBand(months...).Padding(0.2, 0.1)
// bar := x.Band(3) // April's
type Band struct {
Labels []string
// Inner is the room between bands, and Outer the room before the
// first and after the last, in fractions of a band's step.
Inner, Outer float32
// Align places the bands in the room the outer padding leaves: 0 at
// the start, 0.5 (as NewBand) in the middle, 1 at the end.
Align float32
}
// NewBand returns a band scale of labels, without padding.
func NewBand(labels ...string) Band { return Band{Labels: labels, Align: 0.5} }
// Padding sets the room between bands, and before and after them, in
// fractions of a band's step: 0.2 leaves a fifth of each step between bars.
func (b Band) Padding(inner, outer float32) Band {
b.Inner, b.Outer = max(0, min(1, inner)), max(0, outer)
return b
}
// step returns the distance from a band to the next, and where the first
// starts.
func (b Band) step() (step, start float32) {
n := float32(len(b.Labels))
step = 1 / max(1, n-b.Inner+2*b.Outer)
start = (1 - step*(n-b.Inner)) * b.Align
return step, start
}
// Band returns the stretch of the i-th band.
func (b Band) Band(i int) Span {
step, start := b.step()
lo := start + step*float32(i)
return Span{lo, lo + b.Width()}
}
// Width returns the width of a band, in a fraction of the plot.
func (b Band) Width() float32 {
step, _ := b.step()
return step * (1 - b.Inner)
}
// At returns the middle of the i-th band.
func (b Band) At(i int) float32 { return b.Band(i).Mid() }
// Index returns the band at f along the plot, the one whose step holds it,
// so that the room between bars belongs to a bar; ok is false outside of
// every band's step.
func (b Band) Index(f float32) (i int, ok bool) {
step, start := b.step()
if len(b.Labels) == 0 {
return 0, false
}
// A band's step starts half the inner padding before it.
k := (f - start + step*b.Inner/2) / step
if k < 0 || k >= float32(len(b.Labels)) {
return 0, false
}
return int(k), true
}
// Ticks returns a tick in the middle of each band, labeled with its label.
func (b Band) Ticks() []Tick {
out := make([]Tick, len(b.Labels))
for i, l := range b.Labels {
out[i] = Tick{At: b.At(i), Value: float64(i), Label: l}
}
return out
}
+406
View File
@@ -0,0 +1,406 @@
package chart
import (
"math"
"github.com/egoist/mygo/ui"
)
// X returns the x of f, a fraction along a plot's width, in r, the plot's
// box a Draw function gets.
func X(r ui.Rect, f float32) float32 { return r.X + f*r.W }
// Y returns the y of f, a fraction up a plot's height, in r: 0 is its
// bottom and 1 its top.
func Y(r ui.Rect, f float32) float32 { return r.Y + (1-f)*r.H }
// Curve is how a line goes from a point to the next, as Swift Charts'
// interpolation methods and d3's curves.
type Curve int
const (
// CurveLinear joins the points with straight lines.
CurveLinear Curve = iota
// CurveMonotone joins them with a smooth curve that keeps between the
// values of each two points, never going past them, as d3's
// curveMonotoneX (Steffen's method).
CurveMonotone
// CurveStepAfter keeps a point's value until the next point, as a value
// that holds until it changes.
CurveStepAfter
// CurveStepBefore takes on a point's value from the point before it.
CurveStepBefore
// CurveStep changes the value halfway between points.
CurveStep
)
// segment is a piece of a line, from where the one before ended to to:
// straight unless cubic, with the control points c1 and c2.
type segment struct {
cubic bool
c1, c2, to [2]float32
}
// curve returns the segments through pts, after the first point, as the
// curve goes.
func curve(pts [][2]float32, k Curve) []segment {
n := len(pts)
segs := make([]segment, 0, n)
switch k {
case CurveMonotone:
if n < 3 {
break
}
// Each point's slope, as d3's curveMonotoneX: Steffen's at the
// points inside, and at the ends one the last segment's slope and
// the neighbor's give.
m := make([]float32, n)
for i := 1; i < n-1; i++ {
m[i] = monotoneSlope(pts[i-1], pts[i], pts[i+1])
}
m[0] = endSlope(pts[0], pts[1], m[1])
m[n-1] = endSlope(pts[n-2], pts[n-1], m[n-2])
for i := 1; i < n; i++ {
p0, p1 := pts[i-1], pts[i]
dx := (p1[0] - p0[0]) / 3
segs = append(segs, segment{cubic: true,
c1: [2]float32{p0[0] + dx, p0[1] + dx*m[i-1]},
c2: [2]float32{p1[0] - dx, p1[1] - dx*m[i]},
to: p1})
}
return segs
case CurveStepAfter, CurveStepBefore, CurveStep:
for i := 1; i < n; i++ {
p0, p1 := pts[i-1], pts[i]
switch k {
case CurveStepAfter:
segs = append(segs, segment{to: [2]float32{p1[0], p0[1]}})
case CurveStepBefore:
segs = append(segs, segment{to: [2]float32{p0[0], p1[1]}})
default:
mid := (p0[0] + p1[0]) / 2
segs = append(segs, segment{to: [2]float32{mid, p0[1]}}, segment{to: [2]float32{mid, p1[1]}})
}
segs = append(segs, segment{to: p1})
}
return segs
}
for _, p := range pts[1:] {
segs = append(segs, segment{to: p})
}
return segs
}
// monotoneSlope returns the slope at b between a and c, as d3's slope3.
func monotoneSlope(a, b, c [2]float32) float32 {
h0, h1 := b[0]-a[0], c[0]-b[0]
if h0 == 0 || h1 == 0 {
return 0
}
s0, s1 := (b[1]-a[1])/h0, (c[1]-b[1])/h1
p := (s0*h1 + s1*h0) / (h0 + h1)
if math.Signbit(float64(s0)) != math.Signbit(float64(s1)) || s0 == 0 || s1 == 0 {
return 0
}
m := min(abs(s0), abs(s1), 0.5*abs(p))
if s0 < 0 {
return -2 * m
}
return 2 * m
}
// endSlope returns the slope at an end of a line, from the slope t at the
// point next to it, as d3's slope2.
func endSlope(a, b [2]float32, t float32) float32 {
h := b[0] - a[0]
if h == 0 {
return t
}
return (3*(b[1]-a[1])/h - t) / 2
}
func abs(v float32) float32 {
if v < 0 {
return -v
}
return v
}
// defined reports whether every value is a number, not NaN: a missing
// value breaks a line, as d3's line.defined.
func defined(vs ...float32) bool {
for _, v := range vs {
if v != v {
return false
}
}
return true
}
// runs calls fn with each run of points whose values are all defined.
func runs(n int, ok func(i int) bool, fn func(from, to int)) {
from := -1
for i := 0; i <= n; i++ {
if i < n && ok(i) {
if from < 0 {
from = i
}
continue
}
if from >= 0 {
fn(from, i)
from = -1
}
}
}
// Line returns the path of a line through the points at xs and ys,
// fractions along and up the plot whose box is r, joined as curve says.
// A NaN value breaks the line there. Stroke it in a Draw function of the
// plot:
//
// area.Draw(func(p *ui.Painter, r ui.Rect) {
// p.StrokePath(chart.Line(r, xs, ys, chart.CurveMonotone), 2, t.Accent)
// })
func Line(r ui.Rect, xs, ys []float32, k Curve) *ui.Path {
return LineInto(&ui.Path{}, r, xs, ys, k)
}
// LineInto replaces path with Line's geometry, reusing its storage. It also
// clears any Trim. Keep one path per series when drawing live waveforms.
func LineInto(path *ui.Path, r ui.Rect, xs, ys []float32, k Curve) *ui.Path {
path.Reset()
n := min(len(xs), len(ys))
runs(n, func(i int) bool { return defined(xs[i], ys[i]) }, func(from, to int) {
if k == CurveLinear {
path.MoveTo(X(r, xs[from]), Y(r, ys[from]))
for i := from + 1; i < to; i++ {
path.LineTo(X(r, xs[i]), Y(r, ys[i]))
}
return
}
pts := make([][2]float32, 0, to-from)
for i := from; i < to; i++ {
pts = append(pts, [2]float32{X(r, xs[i]), Y(r, ys[i])})
}
path.MoveTo(pts[0][0], pts[0][1])
addSegments(path, curve(pts, k))
})
return path
}
// Area returns the path of the area between two lines through the points
// at xs, lo below and hi above, joined as curve says, for areas and bands
// and the layers of a stack. Nil lo puts the bottom line at the bottom of
// the plot. A NaN value breaks the area there.
//
// area.Draw(func(p *ui.Painter, r ui.Rect) {
// p.FillPath(chart.Area(r, xs, nil, ys, chart.CurveMonotone), fill)
// })
func Area(r ui.Rect, xs, lo, hi []float32, k Curve) *ui.Path {
path := &ui.Path{}
n := min(len(xs), len(hi))
if lo != nil {
n = min(n, len(lo))
}
low := func(i int) float32 {
if lo == nil {
return 0
}
return lo[i]
}
runs(n, func(i int) bool { return defined(xs[i], hi[i], low(i)) }, func(from, to int) {
top := make([][2]float32, 0, to-from)
bottom := make([][2]float32, 0, to-from)
for i := from; i < to; i++ {
top = append(top, [2]float32{X(r, xs[i]), Y(r, hi[i])})
bottom = append(bottom, [2]float32{X(r, xs[i]), Y(r, low(i))})
}
path.MoveTo(top[0][0], top[0][1])
addSegments(path, curve(top, k))
// Back along the bottom line, the same curve the other way.
segs := curve(bottom, k)
last := bottom[len(bottom)-1]
path.LineTo(last[0], last[1])
for i := len(segs) - 1; i >= 0; i-- {
from := bottom[0]
if i > 0 {
from = segs[i-1].to
}
if s := segs[i]; s.cubic {
path.CubeTo(s.c2[0], s.c2[1], s.c1[0], s.c1[1], from[0], from[1])
} else {
path.LineTo(from[0], from[1])
}
}
path.Close()
})
return path
}
func addSegments(path *ui.Path, segs []segment) {
for _, s := range segs {
if s.cubic {
path.CubeTo(s.c1[0], s.c1[1], s.c2[0], s.c2[1], s.to[0], s.to[1])
} else {
path.LineTo(s.to[0], s.to[1])
}
}
}
// Nearest returns the index of the value of xs, in ascending order, that
// is nearest f, or -1 for none: the point of a line under the pointer.
func Nearest(xs []float32, f float32) int {
if len(xs) == 0 {
return -1
}
lo, hi := 0, len(xs)
for lo < hi { // the first at or after f
m := (lo + hi) / 2
if xs[m] < f {
lo = m + 1
} else {
hi = m
}
}
switch {
case lo == len(xs):
return lo - 1
case lo > 0 && f-xs[lo-1] <= xs[lo]-f:
return lo - 1
}
return lo
}
// Slice is a value's part of a pie, from the angle Start to End, in
// radians clockwise from twelve o'clock, as d3's pie and Swift Charts'
// sector marks. Pad is the gap Sector leaves between it and the next.
type Slice struct {
Start, End, Pad float64
}
// Pie divides a circle among values, in their order from twelve o'clock,
// each slice as large as its share of their sum. Pad is the angle between
// slices, in radians; values below 0, and NaN, take no room.
//
// slices := chart.Pie(shares, 0.02)
func Pie(values []float64, pad float64) []Slice {
sum := 0.0
for _, v := range values {
if v > 0 {
sum += v
}
}
n := float64(len(values))
pad = max(0, min(pad, 2*math.Pi/max(n, 1)))
k := 0.0
if sum > 0 {
k = (2*math.Pi - n*pad) / sum
}
out := make([]Slice, len(values))
a := 0.0
for i, v := range values {
end := a + pad
if v > 0 {
end += v * k
}
out[i] = Slice{Start: a, End: end, Pad: pad}
a = end
}
return out
}
// Mid returns the angle halfway through the slice, where its label goes.
func (s Slice) Mid() float64 { return (s.Start + s.End) / 2 }
// Polar returns the point at the angle a, r from the center (cx, cy), as
// where a slice's label goes.
func Polar(cx, cy, r float32, a float64) (x, y float32) {
return cx + r*float32(math.Sin(a)), cy - r*float32(math.Cos(a))
}
// Sector returns the path of a slice between the radii inner and outer
// around (cx, cy): a wedge of a pie with inner 0, of a donut otherwise.
// The slice's pad keeps a gap of the same width along it, as d3's arcs do.
//
// ring.Draw(func(p *ui.Painter, r ui.Rect) {
// cx, cy := r.X+r.W/2, r.Y+r.H/2
// for i, s := range slices {
// p.FillPath(chart.Sector(cx, cy, 40, 80, s), colors[i])
// }
// })
func Sector(cx, cy, inner, outer float32, s Slice) *ui.Path {
path := &ui.Path{}
if outer <= 0 || s.End <= s.Start {
return path
}
inner = max(0, min(inner, outer))
// The gap's width, at the radius between the two, as d3's padRadius.
gap := s.Pad * math.Sqrt(float64(inner*inner+outer*outer))
angles := func(r float32) (a0, a1 float64) {
a0, a1 = s.Start, s.End
if gap > 0 && r > 0 {
d := math.Asin(min(1, gap/2/float64(r)))
if a1-a0 > 2*d {
return a0 + d, a1 - d
}
m := (a0 + a1) / 2
return m, m
}
return a0, a1
}
a0, a1 := angles(outer)
x, y := Polar(cx, cy, outer, a0)
path.MoveTo(x, y)
arc(path, cx, cy, outer, a0, a1)
if inner > 0 {
b0, b1 := angles(inner)
x, y = Polar(cx, cy, inner, b1)
path.LineTo(x, y)
arc(path, cx, cy, inner, b1, b0)
} else {
path.LineTo(cx, cy)
}
path.Close()
return path
}
// arc adds an arc of radius r around (cx, cy) from the angle a0 to a1 to
// path, in cubic curves of up to a quarter turn.
func arc(path *ui.Path, cx, cy, r float32, a0, a1 float64) {
n := int(math.Ceil(math.Abs(a1-a0) / (math.Pi / 2)))
if n == 0 {
return
}
step := (a1 - a0) / float64(n)
k := float32(4.0 / 3 * math.Tan(step/4))
for i := range n {
b0, b1 := a0+float64(i)*step, a0+float64(i+1)*step
x0, y0 := Polar(cx, cy, r, b0)
x1, y1 := Polar(cx, cy, r, b1)
// The tangent at angle a, going clockwise, is (cos a, sin a).
t0x, t0y := float32(math.Cos(b0)), float32(math.Sin(b0))
t1x, t1y := float32(math.Cos(b1)), float32(math.Sin(b1))
path.CubeTo(x0+k*r*t0x, y0+k*r*t0y, x1-k*r*t1x, y1-k*r*t1y, x1, y1)
}
}
// SliceAt returns the slice at (x, y), relative to the center of a pie
// whose slices go from inner to outer, and whether there is one there:
// the slice under the pointer.
func SliceAt(slices []Slice, x, y, inner, outer float32) (int, bool) {
d := float32(math.Hypot(float64(x), float64(y)))
if d < inner || d > outer {
return 0, false
}
a := math.Atan2(float64(x), -float64(y))
if a < 0 {
a += 2 * math.Pi
}
for i, s := range slices {
if a >= s.Start && a < s.End {
return i, true
}
}
return 0, false
}
+80
View File
@@ -0,0 +1,80 @@
package chart
import "math"
// Segment is a value's stretch in a stack, from Lo up to Hi.
type Segment struct{ Lo, Hi float64 }
// Stacking is how Stack piles series up, as Swift Charts' stacking
// methods.
type Stacking int
const (
// StackStandard piles values up from 0, and negative values down from it.
StackStandard Stacking = iota
// StackNormalized piles them up as StackStandard does, in shares of the sum of
// their sizes: the stacks of positive values go from 0 to 1.
StackNormalized
// StackCenter piles them up around 0, as a streamgraph.
StackCenter
)
// Stack piles series up, as stacked bars and areas show them: series[s][i]
// is the i-th value of the s-th series, and the result's [s][i] is where
// it goes in the stack of the i-th values, the s-th from the bottom. NaN
// values take no room.
//
// stacked := chart.Stack([][]float64{apples, pears}, chart.StackStandard)
// for s, series := range stacked {
// for i, seg := range series {
// chart.Rect(c, x.Band(i), y.Span(seg.Lo, seg.Hi)).Background(colors[s])
// }
// }
func Stack(series [][]float64, how Stacking) [][]Segment {
n := 0
for _, s := range series {
n = max(n, len(s))
}
out := make([][]Segment, len(series))
for s := range series {
out[s] = make([]Segment, n)
}
value := func(s, i int) float64 {
if i >= len(series[s]) || math.IsNaN(series[s][i]) {
return 0
}
return series[s][i]
}
for i := range n {
up, down, total := 0.0, 0.0, 0.0
for s := range series {
v := value(s, i)
total += math.Abs(v)
switch {
case how == StackCenter:
out[s][i] = Segment{up, up + v}
up += v
case v < 0:
out[s][i] = Segment{down + v, down}
down += v
default:
out[s][i] = Segment{up, up + v}
up += v
}
}
shift, scale := 0.0, 1.0
switch how {
case StackCenter:
shift = -up / 2
case StackNormalized:
if total > 0 {
scale = 1 / total
}
}
for s := range series {
seg := &out[s][i]
seg.Lo, seg.Hi = (seg.Lo+shift)*scale, (seg.Hi+shift)*scale
}
}
return out
}
Binary file not shown.
+209
View File
@@ -0,0 +1,209 @@
package chart
import (
"math"
"sort"
"time"
)
// Time maps times from From to To onto the plot, as d3's scaleTime and
// Swift Charts' scales of dates. Its ticks fall on round times of the
// times' location, a second, a quarter of an hour, a day, the first of a
// month, chosen for the span: midnights for a week, months for a year.
//
// x := chart.NewTime(start, end)
// ticks := x.Ticks(6)
type Time struct {
From, To time.Time
// Format labels the ticks; nil labels each with what changed since
// a round time of the coarser unit, as d3's multi-scale format:
// "2026", "Mar", "Mar 5", "14:00", "14:05:30".
Format func(t time.Time) string
}
// NewTime returns a time scale from from to to.
func NewTime(from, to time.Time) Time { return Time{From: from, To: to} }
// At returns where t is along the plot.
func (s Time) At(t time.Time) float32 {
span := s.To.Sub(s.From)
if span == 0 {
return 0.5
}
return float32(float64(t.Sub(s.From)) / float64(span))
}
// Span returns the stretch from a to b along the plot.
func (s Time) Span(a, b time.Time) Span { return Span{s.At(a), s.At(b)} }
// Invert returns the time at f along the plot.
func (s Time) Invert(f float32) time.Time {
return s.From.Add(time.Duration(float64(f) * float64(s.To.Sub(s.From))))
}
// unit is a calendar unit of time ticks.
type unit int
const (
unitMilli unit = iota
unitSecond
unitMinute
unitHour
unitDay
unitWeek
unitMonth
unitYear
)
// interval is a step of ticks: every n units, about d long.
type interval struct {
u unit
n int
d time.Duration
}
const (
day = 24 * time.Hour
week = 7 * day
month = 30 * day
year = 365 * day
)
// intervals are d3-time's tick intervals, by their length.
var intervals = []interval{
{unitSecond, 1, time.Second}, {unitSecond, 5, 5 * time.Second}, {unitSecond, 15, 15 * time.Second}, {unitSecond, 30, 30 * time.Second},
{unitMinute, 1, time.Minute}, {unitMinute, 5, 5 * time.Minute}, {unitMinute, 15, 15 * time.Minute}, {unitMinute, 30, 30 * time.Minute},
{unitHour, 1, time.Hour}, {unitHour, 3, 3 * time.Hour}, {unitHour, 6, 6 * time.Hour}, {unitHour, 12, 12 * time.Hour},
{unitDay, 1, day}, {unitDay, 2, 2 * day},
{unitWeek, 1, week},
{unitMonth, 1, month}, {unitMonth, 3, 3 * month},
{unitYear, 1, year},
}
// tickInterval returns the interval of about count ticks from lo to hi,
// as d3-time's tickInterval: the one closest to the span over count, in
// years beyond them and milliseconds below them.
func tickInterval(lo, hi time.Time, count int) interval {
target := time.Duration(float64(hi.Sub(lo)) / float64(max(1, count)))
i := sort.Search(len(intervals), func(i int) bool { return intervals[i].d > target })
switch {
case i == len(intervals):
n := tickStep(float64(lo.Year()), float64(hi.Year())+float64(hi.YearDay())/366, float64(count))
return interval{unitYear, max(1, int(math.Round(n))), year}
case i == 0:
n := tickStep(0, float64(hi.Sub(lo).Milliseconds()), float64(count))
return interval{unitMilli, max(1, int(math.Round(n))), time.Millisecond}
}
if float64(target)/float64(intervals[i-1].d) < float64(intervals[i].d)/float64(target) {
return intervals[i-1]
}
return intervals[i]
}
// floor returns the latest round time of the interval at or before t, in
// t's location: the field of the unit a multiple of n, as d3-time's every.
func (iv interval) floor(t time.Time) time.Time {
y, mo, d := t.Date()
h, mi, s := t.Clock()
loc := t.Location()
switch iv.u {
case unitMilli:
ms := t.Nanosecond() / 1e6
return time.Date(y, mo, d, h, mi, s, (ms-ms%iv.n)*1e6, loc)
case unitSecond:
return time.Date(y, mo, d, h, mi, s-s%iv.n, 0, loc)
case unitMinute:
return time.Date(y, mo, d, h, mi-mi%iv.n, 0, 0, loc)
case unitHour:
return time.Date(y, mo, d, h-h%iv.n, 0, 0, 0, loc)
case unitDay:
return time.Date(y, mo, d-(d-1)%iv.n, 0, 0, 0, 0, loc)
case unitWeek: // weeks start on Sunday, as d3's timeWeek
return time.Date(y, mo, d-int(t.Weekday()), 0, 0, 0, 0, loc)
case unitMonth:
m := int(mo) - 1
return time.Date(y, time.Month(m-m%iv.n+1), 1, 0, 0, 0, 0, loc)
default:
return time.Date(y-y%iv.n, 1, 1, 0, 0, 0, 0, loc)
}
}
// next returns the round time of the interval after t, a round time.
func (iv interval) next(t time.Time) time.Time {
switch iv.u {
case unitMilli:
return t.Add(time.Duration(iv.n) * time.Millisecond)
case unitSecond, unitMinute:
return t.Add(iv.d)
case unitHour:
y, mo, d := t.Date()
return time.Date(y, mo, d, t.Hour()+iv.n, 0, 0, 0, t.Location())
case unitDay:
y, mo, d := t.Date()
n := time.Date(y, mo, d+iv.n, 0, 0, 0, 0, t.Location())
if n.Month() != mo { // days of a month count from its first
n = time.Date(n.Year(), n.Month(), 1, 0, 0, 0, 0, t.Location())
}
return n
case unitWeek:
y, mo, d := t.Date()
return time.Date(y, mo, d+7*iv.n, 0, 0, 0, 0, t.Location())
case unitMonth:
y, mo, _ := t.Date()
return time.Date(y, mo+time.Month(iv.n), 1, 0, 0, 0, 0, t.Location())
default:
return time.Date(t.Year()+iv.n, 1, 1, 0, 0, 0, 0, t.Location())
}
}
// Ticks returns about count round times within the domain.
func (s Time) Ticks(count int) []Tick {
lo, hi := s.From, s.To
if hi.Before(lo) {
lo, hi = hi, lo
}
if count <= 0 || !lo.Before(hi) {
return nil
}
iv := tickInterval(lo, hi, count)
format := s.Format
if format == nil {
format = formatTime
}
var out []Tick
t := iv.floor(lo)
for !t.After(hi) && len(out) < 1000 {
if !t.Before(lo) {
out = append(out, Tick{At: s.At(t), Value: float64(t.UnixMilli()), Label: format(t)})
}
t = iv.next(t)
}
if s.To.Before(s.From) {
for i, j := 0, len(out)-1; i < j; i, j = i+1, j-1 {
out[i], out[j] = out[j], out[i]
}
}
return out
}
// formatTime labels a tick with the finest unit it is not round in, as
// d3's multi-scale time format.
func formatTime(t time.Time) string {
_, mo, d := t.Date()
h, mi, s := t.Clock()
switch {
case t.Nanosecond() != 0:
return t.Format(".000")
case s != 0:
return t.Format(":05")
case mi != 0:
return t.Format("15:04")
case h != 0:
return t.Format("15:00")
case d != 1:
return t.Format("Jan 2")
case mo != 1:
return t.Format("Jan")
}
return t.Format("2006")
}