Пример #1
0
// Draw the plotinum logo.
func Example_logo() *plot.Plot {
	p, err := plot.New()
	if err != nil {
		panic(err)
	}

	plotter.DefaultLineStyle.Width = vg.Points(1)
	plotter.DefaultGlyphStyle.Radius = vg.Points(3)

	p.Y.Tick.Marker = plot.ConstantTicks([]plot.Tick{
		{0, "0"}, {0.25, ""}, {0.5, "0.5"}, {0.75, ""}, {1, "1"},
	})
	p.X.Tick.Marker = plot.ConstantTicks([]plot.Tick{
		{0, "0"}, {0.25, ""}, {0.5, "0.5"}, {0.75, ""}, {1, "1"},
	})

	pts := plotter.XYs{{0, 0}, {0, 1}, {0.5, 1}, {0.5, 0.6}, {0, 0.6}}
	line := must(plotter.NewLine(pts)).(*plotter.Line)
	scatter := must(plotter.NewScatter(pts)).(*plotter.Scatter)
	p.Add(line, scatter)

	pts = plotter.XYs{{1, 0}, {0.75, 0}, {0.75, 0.75}}
	line = must(plotter.NewLine(pts)).(*plotter.Line)
	scatter = must(plotter.NewScatter(pts)).(*plotter.Scatter)
	p.Add(line, scatter)

	pts = plotter.XYs{{0.5, 0.5}, {1, 0.5}}
	line = must(plotter.NewLine(pts)).(*plotter.Line)
	scatter = must(plotter.NewScatter(pts)).(*plotter.Scatter)
	p.Add(line, scatter)

	return p
}
Пример #2
0
func plotLine(xy plotter.XYs) (image.Image, error) {

	p, err := plot.New()
	if err != nil {
		return nil, err
	}
	p.HideAxes()
	p.BackgroundColor = &color.RGBA{0, 0, 0, 255}

	//s, err := NewSparkLines(xy)
	s, err := plotter.NewLine(xy)
	if err != nil {
		return nil, err
	}
	s.Color = &color.RGBA{0, 255, 0, 128}
	p.Add(s)

	// Draw the plot to an in-memory image.
	// _, rows, _ := terminal.GetSize(0)
	charWidth := optCharWidth
	charHeight := optCharHeight
	//width := cols * charWidth
	height := optRows * charHeight

	img := image.NewRGBA(image.Rect(0, 0, 5+(len(xy)*charWidth), height))
	canvas := vgimg.NewImage(img)
	da := plot.MakeDrawArea(canvas)
	p.Draw(da)

	return img, nil
}
Пример #3
0
func plotData(name string, xs, ys []float64) {
	p, err := plot.New()
	if err != nil {
		fmt.Printf("Cannot create new plot: %s\n", err)
		return
	}
	p.Title.Text = "Chernoff lower bound"
	p.X.Label.Text = "Sigma"
	p.X.Min = 0.2
	p.X.Max = 0.5
	p.Y.Label.Text = "Probability of correct detection"
	p.Y.Min = 0.9
	p.Y.Max = 1.0
	p.Add(plotter.NewGrid())

	l := plotter.NewLine(dataset(xs, ys))
	l.LineStyle.Width = vg.Points(1)
	//l.LineStyle.Dashes = []vg.Length(vg.Points(5), vg.Points(5))
	l.LineStyle.Color = color.RGBA{B: 255, A: 255}

	p.Add(l)
	if err := p.Save(4, 4, name); err != nil {
		fmt.Printf("Save to '%s' failed: %s\n", name, err)
	}
}
Пример #4
0
// AddLines adds Line plotters to a plot.
// The variadic arguments must be either strings
// or plotter.XYers.  Each plotter.XYer is added to
// the plot using the next color and dashes
// shape via the Color and Dashes functions.
// If a plotter.XYer is immediately preceeded by
// a string then a legend entry is added to the plot
// using the string as the name.
//
// If an error occurs then none of the plotters are added
// to the plot, and the error is returned.
func AddLines(plt *plot.Plot, vs ...interface{}) error {
	var ps []plot.Plotter
	names := make(map[*plotter.Line]string)
	name := ""
	var i int
	for _, v := range vs {
		switch t := v.(type) {
		case string:
			name = t

		case plotter.XYer:
			l, err := plotter.NewLine(t)
			if err != nil {
				return err
			}
			l.Color = Color(i)
			l.Dashes = Dashes(i)
			i++
			ps = append(ps, l)
			if name != "" {
				names[l] = name
				name = ""
			}

		default:
			panic(fmt.Sprintf("AddLines handles strings and plotter.XYers, got %T", t))
		}
	}
	plt.Add(ps...)
	for p, n := range names {
		plt.Legend.Add(n, p)
	}
	return nil
}
Пример #5
0
// draw is a generic plotter of labelled lines.
func draw(lines graph, title, xLabel, yLabel string) error {
	p, err := plot.New()
	if err != nil {
		return fmt.Errorf(err.Error())
	}

	p.Title.Text = title
	p.X.Label.Text = xLabel
	p.Y.Label.Text = yLabel

	i := 0
	for legend, data := range lines {
		i = i + 1
		l, err := plotter.NewLine(xys(data))
		if err != nil {
			return fmt.Errorf(err.Error())
		}

		p.Add(l)
		p.Legend.Add(legend, l)
		l.LineStyle.Color = getColor(i)
	}

	if err != nil {
		return fmt.Errorf(err.Error())
	}

	name := strings.Replace(strings.ToLower(title), " ", "-", -1)
	filename := fmt.Sprintf("strategy-%s.svg", name)
	if err := p.Save(8, 8, filename); err != nil {
		return fmt.Errorf(err.Error())
	}

	return nil
}
Пример #6
0
// createLine creates a line graph from provided x,y data and title
func createLine(xdat, ydat [][]float64, ylab []string, title string) {
	p, err := plot.New()
	if err != nil {
		panic(err)
	}
	p.Add(plotter.NewGrid())
	p.Title.Text = title
	p.Legend.Top = true
	p.Legend.XOffs = -10.0
	p.Legend.YOffs = -10.0

	var scatdata xyer
	var s *plotter.Line
	for i, _ := range ydat {
		scatdata = xyer{xdat[i], ydat[i]}
		s = plotter.NewLine(scatdata)
		s.LineStyle.Width = 2
		s.LineStyle.Color = cols[i]
		p.Add(s)
		p.Legend.Add(ylab[i], s)
	}
	p.X.Max = 2.5
	p.Y.Max = 3.5
	p.X.Label.Text = "Time / ps"
	p.Y.Label.Text = "Probability density"

	if err := p.Save(5, 5, "out/"+title+".png"); err != nil {
		panic(err)
	}
}
Пример #7
0
func plotData(name string, us, ys, ts, fs []float64) {
	p, err := plot.New()
	if err != nil {
		fmt.Printf("Cannot create new plot: %s\n", err)
		return
	}
	p.Title.Text = "Least-square fit of convex function"
	p.X.Min = -0.1
	p.X.Max = 2.3
	p.Y.Min = -1.1
	p.Y.Max = 7.2
	p.Add(plotter.NewGrid())

	pts := plotter.NewScatter(dataset(us, ys))
	pts.GlyphStyle.Color = color.RGBA{R: 255, A: 255}

	fit := plotter.NewLine(dataset(ts, fs))
	fit.LineStyle.Width = vg.Points(1)
	fit.LineStyle.Color = color.RGBA{B: 255, A: 255}

	p.Add(pts)
	p.Add(fit)
	if err := p.Save(4, 4, name); err != nil {
		fmt.Printf("Save to '%s' failed: %s\n", name, err)
	}
}
Пример #8
0
func PlotBands(symbol string, all []bands.Band) {
	dclose := make(plotter.XYs, len(all))
	dsma := make(plotter.XYs, len(all))
	dup := make(plotter.XYs, len(all))
	ddown := make(plotter.XYs, len(all))

	for i, b := range all {
		dclose[i].X = float64(-1 * i)
		dclose[i].Y = b.Close

		dsma[i].X = float64(-1 * i)
		dsma[i].Y = b.SMA

		dup[i].X = float64(-1 * i)
		dup[i].Y = b.Up

		ddown[i].X = float64(-1 * i)
		ddown[i].Y = b.Down
	}

	p, _ := plot.New()

	p.Title.Text = fmt.Sprintf("Bollinger Bands: %s", symbol)
	p.X.Label.Text = "Time (Days)"
	p.Y.Label.Text = "Value"

	p.Add(plotter.NewGrid())

	lclose, _ := plotter.NewLine(dclose)

	lsma, _ := plotter.NewLine(dsma)
	lsma.LineStyle.Color = color.RGBA{B: 255, A: 255}

	lup, _ := plotter.NewLine(dup)
	lup.LineStyle.Color = color.RGBA{R: 255, A: 255}

	ldown, _ := plotter.NewLine(ddown)
	ldown.LineStyle.Color = color.RGBA{G: 255, A: 255}

	p.Add(lclose, lsma, lup, ldown)
	p.Legend.Add("Closing", lclose)
	p.Legend.Add("SMA", lsma)
	p.Legend.Add("Up", lup)
	p.Legend.Add("Down", ldown)

	p.Save(16, 9, fmt.Sprintf("%s.png", symbol))
}
Пример #9
0
func main() {
	fmt.Println("Running...")
	start := time.Now()

	count := 0
	pt = make([]plotter.XYs, 0)
	for n := nMin; n <= nMax; n *= 2 {
		y1 = make([]float64, n)
		y2 = make([]float64, n)
		pt = append(pt, make(plotter.XYs, n))

		y1[0] = 1.0
		y2[0] = 3.0
		h = (tMax - tMin) / float64(n-1)

		for i := 1; i < n; i++ {
			y1[i] = y1[i-1] + 2*y1[i-1]*(1-y2[i-1])*h
			y2[i] = y2[i-1] - y2[i-1]*(1-y1[i-1])*h
		}

		for i := 0; i < n; i++ {
			pt[count][i].X = y1[i]
			pt[count][i].Y = y2[i]
		}
		count++
	}
	p, err := plot.New()
	if err != nil {
		panic(err)
	}
	p.Title.Text = fmt.Sprintf("Enright and Pryce #B1:Euler")
	p.Y.Label.Text = "y2(t)"
	p.X.Label.Text = "y1(t)"

	n := nMin
	for i := 0; i < count; i++ {
		l := plotter.NewLine(pt[i])
		l.LineStyle.Width = vg.Points(1)
		l.LineStyle.Color = color.RGBA{R: 255 / uint8(i+1), G: 255 / uint8(i+1),
			B: 255 / uint8(i+1), A: 255}
		p.Add(l)
		n *= 2
	}
	p.X.Min = 0
	p.X.Max = 6.5
	p.Y.Min = 0
	p.Y.Max = 6.5

	// Save the plot to a PNG file.
	if err := p.Save(6, 6, "euler_test.png"); err != nil {
		panic(err)
	}

	fmt.Println(time.Since(start))
	fmt.Println("...program terminated successfully!")
}
Пример #10
0
func DataTableToPng(b *bytes.Buffer, dt *db.DataTable, title string, width, height float64, xLabel string) error {
	p, err := plot.New()
	if err != nil {
		return err
	}

	p.Title.Text = title
	p.X.Label.Text = xLabel
	p.Y.Label.Text = "msec" // TODO: Fix this.

	// TODO: need new ticker function to handle equalX (while keeping xLabel as selected)
	if xLabel == common.TimeName {
		p.X.Tick.Marker = TimeTicks
	}
	p.Legend.Top = true

	numColumns := len(dt.ColumnNames)
	lines := make([]plotter.XYs, numColumns-1) // Skip X column.

	for _, dRow := range dt.Data {
		xp := (*dRow)[0]
		if xp != nil {
			for col := 1; col < numColumns; col++ { // Skip X column.
				yp := (*dRow)[col]
				if yp != nil {
					lines[col-1] = append(lines[col-1], struct{ X, Y float64 }{X: *xp, Y: *yp})
				}
			}
		}
	}

	colorList := getColors(numColumns - 1) // Skip X column.

	for i, line := range lines {
		columnName := dt.ColumnNames[i+1]
		l, err := plotter.NewLine(line)
		if err != nil {
			return err
		}
		if strings.Index(columnName, common.RegressNamePrefix) == 0 { // If regression value.
			l.LineStyle.Color = color.RGBA{255, 0, 0, 255}
			l.LineStyle.Width = vg.Points(2.0)
		} else {
			l.LineStyle.Color = colorList[i]
			l.LineStyle.Width = vg.Points(1.5)
		}
		p.Add(l)
		p.Legend.Add(columnName, l)
	}

	tPng := time.Now()
	drawPng(b, p, width, height)
	glog.V(3).Infof("PERF: makePng time: %v", time.Now().Sub(tPng))
	return nil
}
Пример #11
0
func linesPlot() *plot.Plot {
	// Get some random points
	rand.Seed(int64(0))
	n := 10
	scatterData := randomPoints(n)
	lineData := randomPoints(n)
	linePointsData := randomPoints(n)

	// Create a new plot, set its title and
	// axis labels.
	p, err := plot.New()
	if err != nil {
		panic(err)
	}
	p.Title.Text = "Points Example"
	p.X.Label.Text = "X"
	p.Y.Label.Text = "Y"
	// Draw a grid behind the data
	p.Add(plotter.NewGrid())

	// Make a scatter plotter and set its style.
	s, err := plotter.NewScatter(scatterData)
	if err != nil {
		panic(err)
	}
	s.GlyphStyle.Color = color.RGBA{R: 255, B: 128, A: 255}

	// Make a line plotter and set its style.
	l, err := plotter.NewLine(lineData)
	if err != nil {
		panic(err)
	}
	l.LineStyle.Width = vg.Points(1)
	l.LineStyle.Dashes = []vg.Length{vg.Points(5), vg.Points(5)}
	l.LineStyle.Color = color.RGBA{B: 255, A: 255}

	// Make a line plotter with points and set its style.
	lpLine, lpPoints, err := plotter.NewLinePoints(linePointsData)
	if err != nil {
		panic(err)
	}
	lpLine.Color = color.RGBA{G: 255, A: 255}
	lpPoints.Shape = plot.PyramidGlyph{}
	lpPoints.Color = color.RGBA{R: 255, A: 255}

	// Add the plotters to the plot, with a legend
	// entry for each
	p.Add(s, l, lpLine, lpPoints)
	p.Legend.Add("scatter", s)
	p.Legend.Add("line", l)
	p.Legend.Add("line points", lpLine, lpPoints)
	return p
}
Пример #12
0
func main() {
	tests := []*Test{}
	// if file, err := os.Open("results.txt"); err != nil {
	if file, err := os.Stdin, error(nil); err != nil {
		log.Fatal(err)
	} else {
		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			test, err := ParseLine(scanner.Text())
			if err != nil {
				continue
			}
			test.Calculate()
			tests = append(tests, test)
		}
	}
	if len(tests) == 0 {
		log.Fatal("No tests found.")
	}
	if plt, err := plot.New(); err != nil {
		log.Fatal(err)
	} else {
		for i, test := range tests {
			xys := test.ToXY(100000.0)
			line, err := plotter.NewLine(xys)
			if err != nil {
				log.Fatal(err)
			}
			line.Color, line.Dashes = plotutil.Color(i), plotutil.Dashes(0)
			plt.Add(line)
			{
				name := fmt.Sprintf("%s (%d)", test.Name, int(test.Stats.Mean/100000))
				plt.Legend.Add(name, line)
			}
		}
		// plt.Legend.Font.Size = vg.Inches(plt.Legend.Font.Size * 0.75)
		plt.Legend.Font.Size *= 0.65
		plt.Legend.Top = true
		plt.Legend.Left = true
		// plt.Legend.YOffs = vg.Inches(-1.12)
		// plt.Legend.XOffs = vg.Inches(1)
		plt.HideX()
		// plt.X.Padding = 20
		plt.Y.Min = 0
		plt.Y.Max = 1600
		plt.Title.Text = fmt.Sprintf("Speed Test (averaged over %d runs and %d tests)", 100000, 100)
		plt.Y.Label.Text = "Cycles"
		plt.Save(6, 4, "number-parse.svg")
	}
}
Пример #13
0
// AddStackedAreaPlots adds stacked area plot plotters to a plot.
// The variadic arguments must be either strings
// or plotter.Valuers.  Each valuer adds a stacked area
// plot to the plot below the stacked area plots added
// before it.  If a plotter.Valuer is immediately
// preceeded by a string then the string value is used to
// label the legend.
// Plots should be added in order of tallest to shortest,
// because they will be drawn in the order they are added
// (i.e. later plots will be painted over earlier plots).
//
// If an error occurs then none of the plotters are added
// to the plot, and the error is returned.
func AddStackedAreaPlots(plt *plot.Plot, xs plotter.Valuer, vs ...interface{}) error {
	var ps []plot.Plotter
	names := make(map[*plotter.Line]string)
	name := ""
	var i int

	for _, v := range vs {
		switch t := v.(type) {
		case string:
			name = t

		case plotter.Valuer:
			if xs.Len() != t.Len() {
				return errors.New("X/Y length mismatch")
			}

			// Make a line plotter and set its style.
			l, err := plotter.NewLine(combineXYs{xs: xs, ys: t})
			if err != nil {
				return err
			}

			l.LineStyle.Width = vg.Points(0)
			color := Color(i)
			i++
			l.ShadeColor = &color

			ps = append(ps, l)

			if name != "" {
				names[l] = name
				name = ""
			}

		default:
			panic(fmt.Sprintf("AddStackedAreaPlots handles strings and plotter.Valuers, got %T", t))
		}
	}

	plt.Add(ps...)
	for p, n := range names {
		plt.Legend.Add(n, p)
	}

	return nil
}
Пример #14
0
func plotBehind(sp *raw.SpicePlot, scale_vector *raw.SpiceVector, typemap map[string][]*raw.SpiceVector) PlotMap {
	m := findMultiplicity(scale_vector.Data)
	c := int(sp.NPoints) / m
	plots := PlotMap{}
	for vector_type, vectors := range typemap {
		plot, err := plot.New()
		if err != nil {
			log.Fatal(err)
		}
		for i, vector := range vectors {
			xys := SpiceToXY(scale_vector, vector)
			for j := 0; j < m; j++ {
				line, err := plotter.NewLine(xys[j*c : (j+1)*c])
				if err != nil {
					log.Fatal(err)
				}
				line.Color = plotutil.Color(i)
				line.Dashes = plotutil.Dashes(0)
				plot.Add(line)
				// plot.Legend.Add(vector.Name, line)
				// plot.Legend.Add(fmt.Sprintf("%s-%d", vector.Name, j), line)
				if j == 0 {
					plot.Legend.Add(vector.Name, line)
				}
			}
			// xys := SpiceToXY(scale_vector, vector)
			// line, err := plotter.NewLine(xys)
			// if err != nil {
			// 	log.Fatal(err)
			// }
			// line.Color = plotutil.Color(i + 1)
			// line.Dashes = plotutil.Dashes(0)
			// plot.Add(line)
			// plot.Legend.Add(vector.Name, line)
		}
		plot.Title.Text = sp.Title + ": " + sp.Name
		plot.X.Label.Text = scale_vector.Name
		plot.Y.Label.Text = vector_type
		// plots = append(plots, plot)
		plots[vector_type] = plot
	}
	return plots
}
Пример #15
0
// Example_points draws some scatter points, a line,
// and a line with points.
func Example_points() *plot.Plot {
	rand.Seed(int64(0))

	n := 15
	scatterData := randomPoints(n)
	lineData := randomPoints(n)
	linePointsData := randomPoints(n)

	p, err := plot.New()
	if err != nil {
		panic(err)
	}
	p.Title.Text = "Points Example"
	p.X.Label.Text = "X"
	p.Y.Label.Text = "Y"
	p.Add(plotter.NewGrid())

	s := must(plotter.NewScatter(scatterData)).(*plotter.Scatter)
	s.GlyphStyle.Color = color.RGBA{R: 255, B: 128, A: 255}
	s.GlyphStyle.Radius = vg.Points(3)

	l := must(plotter.NewLine(lineData)).(*plotter.Line)
	l.LineStyle.Width = vg.Points(1)
	l.LineStyle.Dashes = []vg.Length{vg.Points(5), vg.Points(5)}
	l.LineStyle.Color = color.RGBA{B: 255, A: 255}

	lpLine, lpPoints, err := plotter.NewLinePoints(linePointsData)
	if err != nil {
		panic(err)
	}
	lpLine.Color = color.RGBA{G: 255, A: 255}
	lpPoints.Shape = plot.CircleGlyph{}
	lpPoints.Color = color.RGBA{R: 255, A: 255}

	p.Add(s, l, lpLine, lpPoints)
	p.Legend.Add("scatter", s)
	p.Legend.Add("line", l)
	p.Legend.Add("line points", lpLine, lpPoints)

	return p
}
Пример #16
0
// Report builds up a plot of the response times of the requests
// in SVG format and writes it to out
func (r *TimingsPlotReporter) Report(out io.Writer) error {
	timestamps := make([]time.Time, 0)
	timings := make([]time.Duration, 0)

	for e := r.responses.Front(); e != nil; e = e.Next() {
		r := e.Value.(*result)
		timestamps = append(timestamps, r.timestamp)
		timings = append(timings, r.timing)
	}

	p, err := plot.New()
	if err != nil {
		return err
	}
	pts := make(plotter.XYs, len(timestamps))
	for i := 0; i < len(pts); i++ {
		pts[i].X = timestamps[i].Sub(timestamps[0]).Seconds()
		pts[i].Y = timings[i].Seconds() * 1000
	}

	line, err := plotter.NewLine(pts)
	if err != nil {
		return err
	}
	line.Color = plotutil.Color(1)

	p.Add(line)
	p.X.Padding = vg.Length(3.0)
	p.X.Label.Text = "Time elapsed"
	p.Y.Padding = vg.Length(3.0)
	p.Y.Label.Text = "Latency (ms)"

	w, h := vg.Millimeters(float64(len(timestamps))), vg.Centimeters(12.0)
	canvas := vgsvg.New(w, h)
	p.Draw(plot.MakeDrawArea(canvas))

	_, err = canvas.WriteTo(out)
	return err
}
Пример #17
0
// AddLines adds Line plotters to a plot.
// The variadic arguments must be either strings
// or plotter.XYers.  Each plotter.XYer is added to
// the plot using the next color and dashes
// shape via the Color and Dashes functions.
// If a plotter.XYer is immediately preceeded by
// a string then a legend entry is added to the plot
// using the string as the name.
func AddLines(plt *plot.Plot, vs ...interface{}) {
	name := ""
	var i int
	for _, v := range vs {
		switch t := v.(type) {
		case string:
			name = t

		case plotter.XYer:
			l := plotter.NewLine(t)
			l.Color = Color(i)
			l.Dashes = Dashes(i)
			i++
			plt.Add(l)
			if name != "" {
				plt.Legend.Add(name, l)
				name = ""
			}

		default:
			panic(fmt.Sprintf("AddLines handles strings and plotter.XYers, got %T", t))
		}
	}
}
Пример #18
0
// Writes step data and position to a graph
func WriteStepsToChart(stepData <-chan int8) {

	maxNumberSteps := 1500

	leftVel := make(chartplotter.XYs, maxNumberSteps)
	rightVel := make(chartplotter.XYs, maxNumberSteps)
	leftPos := make(chartplotter.XYs, maxNumberSteps)
	rightPos := make(chartplotter.XYs, maxNumberSteps)

	var byteDataL, byteDataR int8
	stepIndex := 0
	for stepDataOpen := true; stepDataOpen; {

		byteDataL, stepDataOpen = <-stepData
		byteDataR, stepDataOpen = <-stepData

		leftVel[stepIndex].X = float64(stepIndex)
		leftVel[stepIndex].Y = float64(byteDataL) * Settings.StepSize_MM / (32.0 * 0.002)

		rightVel[stepIndex].X = float64(stepIndex)
		rightVel[stepIndex].Y = float64(byteDataR) * Settings.StepSize_MM / (32.0 * 0.002)

		leftPos[stepIndex].X = float64(stepIndex)
		if stepIndex > 0 {
			leftPos[stepIndex].Y = leftPos[stepIndex-1].Y + (leftVel[stepIndex].Y * .002)
		} else {
			leftPos[stepIndex].Y = 0
		}

		rightPos[stepIndex].X = float64(stepIndex)
		if stepIndex > 0 {
			rightPos[stepIndex].Y = rightPos[stepIndex-1].Y + (rightVel[stepIndex].Y * .002)
		} else {
			rightPos[stepIndex].Y = 0
		}

		stepIndex++
		if stepIndex >= maxNumberSteps {
			break
		}
	}

	// chop down slices if maxNumberSteps wasn't needed
	if stepIndex < maxNumberSteps {
		leftVel = leftVel[:stepIndex]
		rightVel = rightVel[:stepIndex]
		leftPos = leftPos[:stepIndex]
		rightPos = rightPos[:stepIndex]
	}

	// Create a new plot, set its title and
	// axis labels.
	p, err := chart.New()
	if err != nil {
		panic(err)
	}
	p.Title.Text = "Polargraph Position & Velocity"
	p.X.Label.Text = "2ms Slice"
	p.Y.Label.Text = "Position(mm) / Velocity (mm/s)"

	// Draw a grid behind the data
	p.Add(chartplotter.NewGrid())

	leftPosLine, _ := chartplotter.NewLine(leftPos)
	leftPosLine.LineStyle.Width = vg.Points(1)
	leftPosLine.LineStyle.Color = color.RGBA{B: 255, A: 255}

	rightPosLine, _ := chartplotter.NewLine(rightPos)
	rightPosLine.LineStyle.Width = vg.Points(1)
	rightPosLine.LineStyle.Color = color.RGBA{R: 255, A: 255}

	leftVelLine, _ := chartplotter.NewLine(leftVel)
	leftVelLine.LineStyle.Width = vg.Points(1)
	leftVelLine.LineStyle.Color = color.RGBA{B: 150, G: 150, A: 255}

	rightVelLine, _ := chartplotter.NewLine(rightVel)
	rightVelLine.LineStyle.Width = vg.Points(1)
	rightVelLine.LineStyle.Color = color.RGBA{R: 150, G: 150, A: 255}

	p.Add(leftPosLine, rightPosLine)
	p.Legend.Add("Left Pos", leftPosLine)
	p.Legend.Add("Right Pos", rightPosLine)

	p.Add(leftVelLine, rightVelLine)
	p.Legend.Add("Left Vel", leftVelLine)
	p.Legend.Add("Right Vel", rightVelLine)

	// Save the plot to a PNG file.
	if err := p.Save(14, 8.5, "chart.png"); err != nil {
		panic(err)
	}
}
Пример #19
0
func RunServer(config *Config) {
	// manually load fonts from resource
	for _, fontasset := range AssetNames() {
		if strings.HasPrefix(fontasset, "res/fonts/") {
			fontname := strings.TrimSuffix(path.Base(fontasset), path.Ext(fontasset))
			fontbytes, err := Asset(fontasset)
			if err != nil {
				panic(err)
			}
			fontreader := bytes.NewReader(fontbytes)
			vg.LoadFont(fontname, fontreader)
		}
	}

	// create memory caches
	homeCache := cache.New(10*time.Minute, 5*time.Minute)
	categoryCache := cache.New(30*time.Minute, 30*time.Minute)
	detailCache := cache.New(15*time.Minute, 10*time.Minute)

	initialCheck := func(w http.ResponseWriter, r *http.Request) bool {
		// clear cache if requested
		nocache := r.Form.Get("nocache")
		if nocache == "1" {
			homeCache.Flush()
			categoryCache.Flush()
			detailCache.Flush()
		}

		return true
	}

	http.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "Not found", 404)
	})
	http.HandleFunc("/favicon.png", func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "Not found", 404)
	})

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		//config.Logger.Printf("Connection: %s\n", r.URL.String())

		var err error

		r.ParseForm()

		if !initialCheck(w, r) {
			return
		}

		csession := config.Session.Clone()
		defer csession.Close()

		cat := r.Form.Get("category")
		chart := r.Form.Get("chart")
		p_page := r.Form.Get("pg")
		page := 1
		if p_page != "" {
			t_page, err := strconv.ParseInt(p_page, 10, 32)
			if err != nil {
				http.Error(w, err.Error(), 500)
				return
			}
			page = int(t_page)
		}
		if page < 1 {
			page = 1
		}

		i := fstopinfo.NewInfo(config.Logger, csession)
		i.Database = config.Database

		// load categories
		var c fstopinfo.FSCategoryList

		catcache, catfound := categoryCache.Get("category")
		if catfound {
			c = catcache.(fstopinfo.FSCategoryList)
		}

		if c == nil {
			c, err = i.Categories()
			if err != nil {
				http.Error(w, err.Error(), 500)
				return
			}
			if c != nil {
				categoryCache.Set("category", c, 0)
			}
		}

		if c == nil {
			http.Error(w, "Could not load categories", 500)
			return
		}

		// load home
		var d fstopimp.FSTopStatsList

		var dcache interface{}
		var dfound bool
		var dname string
		if cat == "" {
			dname = "index"
		} else {
			// check if category exists
			if !c.Exists(cat) {
				http.Error(w, "Category not found", 404)
				return
			}
			dname = cat
		}
		dcache, dfound = homeCache.Get(dname)
		if dfound {
			d = dcache.(fstopimp.FSTopStatsList)
		}

		// data not on cache, load
		if d == nil {
			if cat == "" {
				d, err = i.Top(config.TopId)
			} else {
				d, err = i.TopCategory(config.TopId, cat)
			}
			if err != nil {
				http.Error(w, err.Error(), 500)
				return
			}
			if len(d) > 0 {
				homeCache.Set(dname, d, 0)
			}
		}

		pagecount := d.PageCount(config.PageSize)
		d = d.Paged(page, config.PageSize)

		w.Header().Add("Content-Type", "text/html; charset=utf-8")

		var body *bytes.Buffer = new(bytes.Buffer)

		tmpldata := map[string]interface{}{
			"Title":      config.Title,
			"page":       page,
			"categories": c,
		}

		fmt.Fprintln(body, "<table class=\"main\">")

		fmt.Fprintln(body, "<tr><th>Chart</th><th>Title</th><th width=\"8%\">Added</th><th width=\"5%\">Score</th><th width=\"5%\">Count</th><th width=\"5%\">Comm.</th></tr>")

		for _, ii := range d {
			fmt.Fprintf(body, "<tr>\n")

			if chart == "" {
				fmt.Fprintf(body, "<td><img style=\"height: 107px;\" src=\"/chart?id=%s&size=short\"></td>",
					ii.Id)
			}

			fmt.Fprintf(body, "<td><a href=\"%s\">%s</a> <a href=\"/view?id=%s\">[data]</a> <a href=\"/chart?id=%s\">[chart]</a></td>"+
				"<td align=\"center\" style=\"%s\">%s</td>"+
				"<td align=\"right\">%d</td><td align=\"center\">%d</td><td align=\"center\">%d</td>\n",
				ii.Link, ii.Title, ii.Id, ii.Id,
				StyleAddDate(ii.Last.AddDate), FormatAddDate(ii.Last.AddDate), ii.Score, ii.Count, ii.Last.Comments)

			fmt.Fprintf(body, "</tr>\n")

			if chart == "1" {
				fmt.Fprintf(body, "<tr><td colspan=\"5\" align=\"center\"><img src=\"/chart?id=%s&size=small\"/></td></tr>\n", ii.Id)
			}
		}
		fmt.Fprintln(body, "</table>")

		pageparams := url.Values{}
		if cat != "" {
			pageparams.Add("category", cat)
		}
		if page > 1 {
			pageparams.Set("pg", "1")
			tmpldata["page_first"] = fmt.Sprintf("/?%s", pageparams.Encode())
		}
		if page > 1 {
			pageparams.Set("pg", strconv.Itoa(page-1))
			tmpldata["page_prev"] = fmt.Sprintf("/?%s", pageparams.Encode())
		}
		if len(d) > 0 && page < pagecount {
			pageparams.Set("pg", strconv.Itoa(page+1))
			tmpldata["page_next"] = fmt.Sprintf("/?%s", pageparams.Encode())
		}
		if page != pagecount {
			pageparams.Set("pg", strconv.Itoa(pagecount))
			tmpldata["page_last"] = fmt.Sprintf("/?%s", pageparams.Encode())
		}

		tmpl := LoadTemplates("index")
		tmpldata["Body"] = template.HTML(body.String())

		err = tmpl.ExecuteTemplate(w, "index", tmpldata)
		if err != nil {
			http.Error(w, "Error processing template", 500)
			return
		}

	})

	http.HandleFunc("/view", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		if !initialCheck(w, r) {
			return
		}

		csession := config.Session.Clone()
		defer csession.Close()

		w.Header().Add("Content-Type", "text/html; charset=utf-8")

		id := r.Form.Get("id")
		if id == "" {
			http.Error(w, "ID not sent", 500)
			return
		}

		i := fstopinfo.NewInfo(config.Logger, csession)
		i.Database = config.Database

		var d []*fstopinfo.FSInfoHistory
		var err error

		dcache, found := detailCache.Get(id)
		if found {
			d = dcache.([]*fstopinfo.FSInfoHistory)
		}

		if d == nil {
			d, err = i.History(id, config.HistoryDays)
			if err != nil {
				http.Error(w, err.Error(), 500)
				return
			}
			if d != nil {
				detailCache.Set(id, d, 0)
			}
		}

		if d == nil {
			http.Error(w, "Not found", 500)
			return
		}

		var body *bytes.Buffer = new(bytes.Buffer)

		fmt.Fprintln(body, "<table class=\"main\" border=\"1\">")

		fmt.Fprintln(body, "<tr><th>Date</th><th>Hour</th><th>Seeders</th><th>Leechers</th><th>Complete</th><th>Comments</th></tr>")

		var last *fstopinfo.FSInfoHistory
		first := true

		for _, ii := range d {
			//if ii.Item != nil {
			if ii.Item != nil && first {
				fmt.Fprintf(body, "<tr><td colspan=\"7\">%s <a href=\"%s\">[goto]</a></td></tr>", strings.TrimSpace(ii.Item.Title), ii.Item.Link)
				first = false
			}

			if last != nil {
				if ii.Item != nil && last.Item != nil {
					//fmt.Printf("%s - [%d] [%d] [%d]\n", item.Title, pi.Seeders-item.Last.Seeders,
					//pi.Leechers-item.Last.Leechers, pi.Complete-item.Last.Complete)

					seeders := int64(ii.Item.Seeders - last.Item.Seeders)
					leechers := int64(ii.Item.Leechers - last.Item.Leechers)
					complete := int64(ii.Item.Complete - last.Item.Complete)
					comments := int64(ii.Item.Comments - last.Item.Comments)

					fmt.Fprintf(body, "<tr><td>%s</td><td>%d</td><td>%d (%d)</td><td>%d (%d)</td><td>%d (%d)</td><td>%d (%d)</td></tr>",
						ii.Date, ii.Hour,
						ii.Item.Seeders, seeders,
						ii.Item.Leechers, leechers,
						ii.Item.Complete, complete,
						ii.Item.Comments, comments)
				} else if ii.Item != nil && last.Item == nil {
					fmt.Fprintf(body, "<tr><td>%s</td><td>%d</td><td>%d (-)</td><td>%d (-)</td><td>%d (-)</td><td>%d (-)</td></tr>",
						ii.Date, ii.Hour,
						ii.Item.Seeders,
						ii.Item.Leechers,
						ii.Item.Complete,
						ii.Item.Comments)
				} else {
					fmt.Fprintf(body, "<tr><td>%s</td><td>%d</td></tr>",
						ii.Date, ii.Hour)
				}
			}

			last = ii
			//}
		}

		fmt.Fprintln(body, "</table>")

		tmpl := LoadTemplates("base")
		tmpldata := map[string]interface{}{
			"Title": config.Title,
			"Body":  template.HTML(body.String()),
		}
		err = tmpl.ExecuteTemplate(w, "base", tmpldata)
		if err != nil {
			http.Error(w, "Error processing template", 500)
			return
		}
	})

	http.HandleFunc("/chart", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		if !initialCheck(w, r) {
			return
		}

		csession := config.Session.Clone()
		defer csession.Close()

		id := r.Form.Get("id")
		if id == "" {
			w.Header().Add("Content-Type", "text/html; charset=utf-8")
			http.Error(w, "ID not sent", 500)
			return
		}
		size := r.Form.Get("size")

		i := fstopinfo.NewInfo(config.Logger, csession)
		i.Database = config.Database

		var d []*fstopinfo.FSInfoHistory
		var err error

		dcache, found := detailCache.Get(id)
		if found {
			d = dcache.([]*fstopinfo.FSInfoHistory)
		}

		if d == nil {
			d, err = i.History(id, config.HistoryDays)
			if err != nil {
				w.Header().Add("Content-Type", "text/html; charset=utf-8")
				http.Error(w, err.Error(), 500)
				return
			}
			if d != nil {
				detailCache.Set(id, d, 0)
			}
		}

		if d == nil {
			w.Header().Add("Content-Type", "text/html; charset=utf-8")
			http.Error(w, "Not found", 500)
			return
		}

		p, err := plot.New()
		if err != nil {
			panic(err)
		}

		p.Title.Text = "Chart"
		p.X.Label.Text = "Time"
		p.Y.Label.Text = "Amount"

		c_seeders := make(plotter.XYs, 0)
		c_leechers := make(plotter.XYs, 0)
		c_complete := make(plotter.XYs, 0)
		c_comments := make(plotter.XYs, 0)

		var last *fstopinfo.FSInfoHistory
		first := true
		cttotal := int32(0)

		for _, ii := range d {
			if ii.Item != nil {
				cttotal++

				if first {
					p.Title.Text = strings.TrimSpace(ii.Item.Title)
					first = false
				}

				if last != nil && last.Item != nil {
					c_seeders = append(c_seeders, struct{ X, Y float64 }{float64(cttotal), float64(ii.Item.Seeders)})
					c_leechers = append(c_leechers, struct{ X, Y float64 }{float64(cttotal), float64(ii.Item.Leechers)})
					c_complete = append(c_complete, struct{ X, Y float64 }{float64(cttotal), float64(ii.Item.Complete - last.Item.Complete)})
					c_comments = append(c_comments, struct{ X, Y float64 }{float64(cttotal), float64(ii.Item.Comments)})
				}

				last = ii
			}
		}

		w.Header().Add("Content-Type", "image/png")

		pl_seeders, err := plotter.NewLine(c_seeders)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		pl_seeders.LineStyle.Width = vg.Length(1)
		pl_seeders.LineStyle.Color = color.RGBA{R: 255, A: 255}
		p.Add(pl_seeders)
		p.Legend.Add("Seeders", pl_seeders)

		pl_leechers, err := plotter.NewLine(c_leechers)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		pl_leechers.LineStyle.Width = vg.Length(1)
		pl_leechers.LineStyle.Color = color.RGBA{G: 255, A: 255}
		p.Add(pl_leechers)
		p.Legend.Add("Leechers", pl_leechers)

		pl_complete, err := plotter.NewLine(c_complete)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		pl_complete.LineStyle.Width = vg.Length(1)
		pl_complete.LineStyle.Color = color.RGBA{B: 255, A: 255}
		p.Add(pl_complete)
		p.Legend.Add("@Complete", pl_complete)

		pl_comments, err := plotter.NewLine(c_comments)
		if err != nil {
			http.Error(w, err.Error(), 500)
			return
		}
		pl_comments.LineStyle.Width = vg.Length(1)
		pl_comments.LineStyle.Color = color.RGBA{R: 255, B: 255, A: 255}
		p.Add(pl_comments)
		p.Legend.Add("Comments", pl_comments)

		width := vg.Length(640)
		height := vg.Length(480)
		if size == "small" {
			width = vg.Length(640)
			height = vg.Length(160)
		} else if size == "short" {
			width = vg.Length(200)
			height = vg.Length(80)
			p.Title.Text = ""
			p.X.Label.Text = ""
			p.Y.Label.Text = ""
		}

		c := vgimg.PngCanvas{vgimg.New(width, height)}
		p.Draw(plot.MakeDrawArea(c))
		c.WriteTo(w)
	})

	http.HandleFunc("/res/", func(w http.ResponseWriter, r *http.Request) {
		p := strings.Replace(path.Clean(r.URL.Path), "/res/", "res/files/", 1)

		d, err := Asset(p)
		if err != nil {
			http.Error(w, "Error loading resource", 500)
			return
		}

		w.Header().Add("Content-Type", mime.TypeByExtension(path.Ext(p)))
		w.Write(d)

		//fmt.Fprintf(w, "RES %s\n", p)
	})

	http.ListenAndServe(fmt.Sprintf("localhost:%d", config.Port), nil)

}
Пример #20
0
func main() {
	fmt.Println("Running...")
	start := time.Now()
	var a float64 = -1.0 //lower limit of range
	var b float64 = 1.0  //upper limit of range
	var err plotter.XYs
	err = make(plotter.XYs, nstop-nstart)
	var maxerr float64
	var interp [4]plotter.XYs

	for i := range interp {
		interp[i] = make(plotter.XYs, np+1)
	}
	var k int = 0
	for n := nstart; n < nstop; n++ {
		maxerr = 0
		err[n-nstart].X = float64(n)
		var x []float64 = make([]float64, n+1)
		var dx float64 = (b - a) / float64(n)
		for i := range x {
			x[i] = a + dx*float64(i)
		}
		dx = (b - a) / float64(np-1)
		var j int = 1
		for i := 0; i < np+1; i++ {
			tx := a + dx*float64(i)
			if tx > x[j] && j < n {
				j++
			}
			z := (tx - x[j-1]) / (x[j] - x[j-1])
			ty := F(x[j-1])*(1-z)*(1-2*z) + 4*F((x[j-1]+x[j])/2.0)*z*(1-z) + F(x[j])*z*(2*z-1)
			maxerr = math.Max(maxerr, math.Abs(ty-F(tx)))

			if k < 4 {
				if n == plotValues[k] {
					interp[k][i].X = tx
					interp[k][i].Y = ty
				}
			}
		}
		if k < 4 {
			if n == plotValues[k] {
				k++
			}
		}
		err[n-nstart].Y = math.Log(maxerr)
	}
	//Plotting
	pi, e0 := plot.New()
	if e0 != nil {
		panic(e0)
	}
	pi.Title.Text = "Maximum Error of Spline Interpolation of Runge's Function"
	pi.X.Label.Text = "N"
	pi.Y.Label.Text = "Log(Error)"

	// Make a line plotter and set its style.
	l := plotter.NewLine(err)
	l.LineStyle.Width = vg.Points(1)
	l.LineStyle.Dashes = []vg.Length{vg.Points(5), vg.Points(5)}
	l.LineStyle.Color = color.RGBA{B: 255, A: 255}

	pi.Add(l)

	// Save the plot to a PNG file.
	if err := pi.Save(6, 4, "runge_error.png"); err != nil {
		panic(err)
	}

	pi, e0 = plot.New()
	if e0 != nil {
		panic(e0)
	}

	pi.Title.Text = "Spline Interpolation of Runge's Function"
	pi.X.Label.Text = "N"
	pi.Y.Label.Text = "Log(Error)"
	plotutil.AddLinePoints(pi, interp[2], interp[1], interp[0])
	//Set plot bounds
	pi.X.Min = 0
	pi.X.Max = 0.5

	// Save the plot to a PNG file.
	if err := pi.Save(6, 4, "runge_interp.png"); err != nil {
		panic(err)
	}
	fmt.Println(time.Since(start))
	fmt.Println("...program terminated successfully!")
}
Пример #21
0
func TestServiceEpsilonGreedy(t *testing.T) {
	var (
		horizon  = 250
		epsilons = []float32{0.1, 0.5, 0.9}
		hosts    = map[string]bernouilliExperiment{
			echo1: 0.1,
			echo2: 0.1,
			echo3: 0.9,
		}
	)

	e1 := newEchoServer(t, echo1)
	defer e1.close()
	e2 := newEchoServer(t, echo2)
	defer e2.close()
	e3 := newEchoServer(t, echo3)
	defer e3.close()

	p, err := plot.New()
	if err != nil {
		t.Fatal(err)
	}
	p.Add(plotter.NewGrid())
	p.X.Label.Text = "trials"
	p.Y.Label.Text = "average score"
	p.X.Max = float64(horizon)
	p.Y.Min = 0
	p.Y.Max = 1

	for _, e := range epsilons {
		means := make(plotter.XYs, horizon)

		s := NewService("echo", &ServiceConfig{
			BanditStrategy:       NewEpsilonGreedy(e),
			MemoizeScoreDuration: 1 * time.Millisecond,
		})
		s.Add(echo1)
		s.Add(echo2)
		s.Add(echo3)
		time.Sleep(1 * time.Millisecond) // wait for propagation

		for i := 0; i < horizon; i++ {
			c, err := s.GetConn()
			if err != nil {
				t.Error(err)
				continue
			}

			if i == 0 {
				means[i].X = 0
				means[i].Y = c.host.Score()
			} else {
				n := means[i-1].X + 1
				m := means[i-1].Y
				means[i].X = float64(i)
				means[i].Y = m + (c.host.Score()-m)/(n+1)
			}

			a := c.Address()
			if err := c.Release(nil, hosts[a].trial()); err != nil {
				t.Error(err)
				continue
			}
			time.Sleep(1 * time.Millisecond) // wait for memoization
		}
		s.Close()

		l, err := plotter.NewLine(means)
		if err != nil {
			t.Fatal(err)
		}
		l.LineStyle.Color = color.RGBA{B: uint8(255 * e), A: 255}
		p.Legend.Add("epsilon "+strconv.FormatFloat(float64(e), 'f', 1, 32), l)
		p.Add(l)
	}

	if err := p.Save(7, 7, "egreedy_test.svg"); err != nil {
		t.Fatal(err)
	}
}