Exemplo n.º 1
0
func (l Line) WeightedIterator() (pix []WeightedPoint) {

	max_delta := 2.0 * l.radius // will miss prob mass outside of 2 std dev
	normalizer := 1.0 / math.Sqrt(2.0*math.Pi*l.radius*l.radius)

	var p image.Point
	cur := l.left
	iter := int(math.Fmax(math.Fabs(l.Dx()), math.Fabs(l.Dy()))) + 1
	dx := l.Dx() / float64(iter)
	dy := l.Dy() / float64(iter)

	for i := 0; i < iter; i++ {
		for d := -max_delta; d < max_delta; d += 1.0 {

			if dx > dy { // vertical sweeps
				p = image.Point{int(cur.X), int(cur.Y + d)}
			} else { // horizontal sweeps
				p = image.Point{int(cur.X + d), int(cur.Y)}
			}

			fp := NewFloat64Point(p)
			dist := l.Distance(fp.X, fp.Y)
			dist = math.Fmin(dist, Distance(fp, l.left))
			dist = math.Fmin(dist, Distance(fp, l.right))
			weight := normalizer * math.Exp(-dist*dist/(2.0*l.radius*l.radius))

			pix = append(pix, WeightedPoint{p, weight})
		}
		cur.X += dx
		cur.Y += dy
	}
	return pix
}
Exemplo n.º 2
0
// calculate the closest distance between to locations
func (m *Map) Distance(srcLoc, destLoc Location) float64 {
	row1, col1 := m.FromLocation(srcLoc)
	row2, col2 := m.FromLocation(destLoc)
	dCol := math.Fmin(math.Fabs(float64(col1-col2)), float64(m.Cols)-math.Fabs(float64(col1-col2)))
	dRow := math.Fmin(math.Fabs(float64(row1-row2)), float64(m.Rows)-math.Fabs(float64(row1-row2)))
	return dCol + dRow
}
Exemplo n.º 3
0
func DrawTable(r io.Writer, t *DataTable, w uint, h uint) os.Error {

	var minVal float64
	var maxVal float64

	for _, v := range t.Values {
		if v != nil {
			f64 := float64(v.Float64Value())
			minVal = math.Fmin(minVal, f64)
			maxVal = math.Fmax(maxVal, f64)
		}
	}

	i := image.NewRGBA(int(w), int(h))
	gc := draw2d.NewGraphicContext(i)
	dx := float64(w-1) / (float64(t.End) - float64(t.Start))
	dy := float64(h-1) / (maxVal - minVal)

	gc.SetLineWidth(1)
	for i, v := range t.Values {
		if v == nil {
			continue
		}
		x := dx * float64(int64(i)*t.Resolution)
		y := dy * (float64(v.Float64Value()) - minVal)
		gc.MoveTo(x+0.45, y+0.5)
		gc.ArcTo(x+0.5, y+0.5, 0.1, 0.1, 0, -math.Pi*2)
		gc.Stroke()
	}

	return png.Encode(r, i)
}
Exemplo n.º 4
0
func (s *Statistics) ComputeScore(c *Combat) {
	// we are more aggresive towards players we outnumber esp if
	// we have the most ant however if we have not seen much of the
	// map we are risk averse
	if s.LTS == nil {
		return
	}
	// fraction of map seen
	vis := .1
	if c != nil {
		vis = float64(c.Size()-s.LTS.Horizon) / float64(c.Size())
	}

	frac := float64(s.LTS.Seen[0]) / float64(s.LTS.SeenAll)

	for i := range s.LTS.Seen {
		if TurnGet() < 60 { // MAGIC
			s.LTS.Score[i] = .4
		} else {
			frace := float64(s.LTS.Seen[i]) / float64(s.LTS.SeenAll)
			s.LTS.Score[i] = math.Fmax(math.Fmin(frac*vis*vis/frace, 2.0), .3)
		}
	}
	s.LTS.Score[0] = -1.5

	if Debug[DBG_Scoring] {
		log.Print("Score per player is ", s.LTS.Score[0:s.NP])
	}
}
Exemplo n.º 5
0
func (this *northEastHandle) InvokeStep(x, y, anchorX, anchorY int, view DrawingView) {
	r := this.owner.GetDisplayBox()
	this.owner.SetDisplayBox(
		this.owner,
		&Point{r.X, int(math.Fmin(float64(r.Y+r.Height), float64(y)))},
		&Point{int(math.Fmax(float64(r.X), float64(x))), r.Y + r.Height})
}
Exemplo n.º 6
0
func (node *Node) recalc() {
	if node.Visits == 10 {
		node.value = 1 + 0.1*rand.Float64()
		return
	}
	node.Mean = node.Wins / node.Visits
	node.blendedMean = node.Mean
	rave := node.config.AMAF || node.config.Neighbors || node.config.Ancestor
	if rave {
		beta := math.Sqrt(node.config.RAVE / (3*node.Visits + node.config.RAVE))
		if beta > 0 {
			node.amafMean = node.amafWins / node.amafVisits
			node.ancestorMean = node.ancestorWins / node.ancestorVisits
			if math.IsNaN(node.Mean) {
				node.Mean = 0
			}
			if math.IsNaN(node.amafMean) {
				node.amafMean = 0
			}
			if math.IsNaN(node.ancestorMean) {
				node.ancestorMean = 0
			}
			estimatedMean := 0.0
			Samples := 0.0
			if node.config.AMAF {
				estimatedMean += node.amafMean
				Samples++
			}
			if node.config.Neighbors {
				neighborWins := 0.0
				neighborVisits := 0.0
				for sibling := node.parent.Child; sibling != nil; sibling = sibling.Sibling {
					if sibling.Vertex != node.Vertex {
						neighborWins += sibling.Wins
						neighborVisits += sibling.Visits
					}
				}
				estimatedMean += neighborWins / neighborVisits
			}
			if node.config.Ancestor {
				estimatedMean += node.ancestorMean
				Samples++
			}
			estimatedMean /= Samples
			if math.IsNaN(estimatedMean) {
				estimatedMean = 0
			}
			node.blendedMean = beta*estimatedMean + (1-beta)*node.Mean
		}
	}
	r := math.Log1p(node.parent.Visits) / node.Visits
	v := 1.0
	if node.config.Var {
		v = math.Fmin(0.25, node.blendedMean-(node.blendedMean*node.blendedMean)+math.Sqrt(2*r))
	}
	node.value = node.blendedMean + node.config.Explore*math.Sqrt(r*v)
}
Exemplo n.º 7
0
func fit(trans []*affine.Affine) (x1, y1, x2, y2 float64) {
	org := trans[0].GetOrigin()
	x2 = org.Get(0, 0)
	x1 = x2
	y2 = org.Get(1, 0)
	y1 = y2
	nx1, ny1, nx2, ny2 := x1, y1, x2, y2
	done := false
	for !done {
		//print (x1,x2,y1,y2,"\n")
		for i := 0; i < 4; i++ {
			xx := x1
			yy := y1
			if i%2 == 0 {
				xx = x2
			}
			if i > 1 {
				yy = y2
			}
			for _, t := range trans {
				x, y := t.Trans(xx, yy)
				nx1 = math.Fmin(nx1, x)
				nx2 = math.Fmax(nx2, x)
				ny1 = math.Fmin(ny1, y)
				ny2 = math.Fmax(ny2, y)
			}
		}
		if nx1 > x1 && nx2 < x2 && ny1 > y1 && ny2 < y2 {
			done = true
		}
		x1, y1, x2, y2 = nx1, ny1, nx2, ny2
		dx := nx2 - nx1
		const f = .001
		x1 -= dx * f
		x2 += dx * f
		dy := ny2 - ny1
		y1 -= dy * f
		y2 += dy * f

	}
	return
}
Exemplo n.º 8
0
func genArray(n int) []interface{} {
	f := int(math.Fabs(rand.NormFloat64()) * math.Fmin(10, float64(n/2)))
	if f > n {
		f = n
	}
	x := make([]interface{}, int(f))
	for i := range x {
		x[i] = genValue(((i+1)*n)/f - (i*n)/f)
	}
	return x
}
Exemplo n.º 9
0
func MakeACGenEdit(Gp [][]string, c []float64) func(string, string) float64 {
	Proot := MakeLinkedGoto(Gp[0])
	MakeLinkedFail(Proot)
	Troot := MakeLinkedGoto(Gp[1])
	MakeLinkedFail(Troot)
	G := make([][]*utf8.String, len(Gp))
	for i, _ := range G {
		G[i] = make([]*utf8.String, len(Gp[i]))
		for j, _ := range G[i] {
			G[i][j] = utf8.NewString(Gp[i][j])
		}
	}

	return func(pattern string, text string) float64 {
		P := utf8.NewString(pattern + " ")
		PLen := P.RuneCount() - 1
		T := utf8.NewString(text + " ")
		TLen := T.RuneCount() - 1
		d := makeMatrix(TLen+1, PLen+1)
		p := NewBitArray(len(Gp[0]))

		Pstate := Proot
		Tstate := Troot

		for x := 0; x <= PLen; x++ {
			Tstate = Troot
			for y := 0; y <= TLen; y++ {
				if x == 0 && y == 0 {
					d[y][x] = 0
				} else {
					d[y][x] = math.Inf(1)
					if x > 0 && y > 0 && Pstate.symbol == Tstate.symbol {
						d[y][x] = d[y-1][x-1]
					}
					if len(Pstate.output) > 0 && len(Tstate.output) > 0 {
						p = p.Intersection(Pstate.output, Tstate.output)
						p.ForEach(func(i int) {
							a := x - G[0][i].RuneCount()
							b := y - G[1][i].RuneCount()
							d[y][x] = math.Fmin(d[y][x], d[b][a]+c[i])
						})
					}
				}
				Tstate = Tstate.Push(T.At(y))
			}
			Pstate = Pstate.Push(P.At(x))
		}

		return d[TLen][PLen]
	}
}
Exemplo n.º 10
0
func genMap(n int) map[string]interface{} {
	f := int(math.Fabs(rand.NormFloat64()) * math.Fmin(10, float64(n/2)))
	if f > n {
		f = n
	}
	if n > 0 && f == 0 {
		f = 1
	}
	x := make(map[string]interface{})
	for i := 0; i < f; i++ {
		x[genString(10)] = genValue(((i+1)*n)/f - (i*n)/f)
	}
	return x
}
Exemplo n.º 11
0
func MakeBasicGenEdit(G [][]string, c []float64) func(string, string) float64 {
	cost := func(A string, B string, pi int, d [][]float64) float64 {
		a := len(A) - len(G[pi][0])
		b := len(B) - len(G[pi][1])
		if a >= 0 && b >= 0 && A[a:] == G[pi][0] && B[b:] == G[pi][1] {
			return d[b][a] + c[pi]
		}
		return math.Inf(1)
	}

	return func(Ap string, Bp string) float64 {
		A := utf8.NewString(Ap)
		B := utf8.NewString(Bp)
		d := makeMatrix(B.RuneCount()+1, A.RuneCount()+1)

		for x := 0; x <= A.RuneCount(); x++ {
			for y := 0; y <= B.RuneCount(); y++ {
				if x == 0 && y == 0 {
					d[y][x] = 0
				} else {
					min := math.Inf(1)
					if x > 0 && y > 0 && A.At(x-1) == B.At(y-1) {
						min = d[y-1][x-1]
					}
					for pi, _ := range G {
						min = math.Fmin(min,
							cost(A.Slice(0, x),
								B.Slice(0, y),
								pi,
								d))
					}

					d[y][x] = min
				}
			}
		}

		return d[B.RuneCount()][A.RuneCount()]
	}
}
Exemplo n.º 12
0
func RemoveServer(serv *server) os.Error {
	log.Printf("master: RemoveServer: server heap pre removal:\n%s\n", sHeap.printPresent())

	//Remove the Server
	sHeap.Remove(serv)
	log.Printf("master: RemoveServer: server heap post removal:\n%s\n", sHeap.printPresent())

	for i := 0; i < sHeap.vec.Len(); i++ {
		if sHeap.vec.At(i).(*server).id == serv.id {
			log.Printf("master: RemoveServer: remove didn't actually remove server %d! Busto Rhymes\n", serv.id)
			return nil
		}
	}
	str := fmt.Sprintf("%s:%d", serv.addr.IP.String(), serv.addr.Port)

	servers[serv.id] = &server{}, false
	addrToServerMap[str] = &server{}, false

	str1 := fmt.Sprintf("removing server %s:%d", serv.addr.IP.String(), serv.addr.Port)
	log.Printf("master: RemoveServer: begin %s\n", str1)

	network_size := float64(sHeap.vec.Len())
	if network_size <= 0 {
		return nil
	}
	//chunk_size := serv.chunks.Len()
	rep_factor := .9

	//map the size of the network to some fraction of that size to replicate to
	if network_size < 10 {
		rep_factor = .5
	} else {
		rep_factor = .3
	}

	rep_size := int(math.Fmin(math.Ceil(rep_factor*network_size), network_size))

	//for each chunk in the server, make a replication call
	sanity_threshhold1 := 4
	sanity_threshhold2 := 10
	sanity_count := 0

	targetServerMap := make(map[string](bool))

ChunkReplicate:
	for cnt := 0; cnt < serv.chunks.Len(); {

		var index int
		if sanity_count > sanity_threshhold1 {
			index = rand.Intn(rep_size)
		} else {
			index = rand.Intn(sHeap.vec.Len())
		}

		otherserver := sHeap.vec.At(index).(*server)
		chunk := serv.chunks.At(cnt).(*chunk)

		str := fmt.Sprintf("%s:%d", otherserver.addr.IP.String(), otherserver.addr.Port)

		sCnt := chunk.servers.Len()

		if sCnt >= len(servers) {
			log.Printf("master: RemoveServer: abort replication req for chunk %d; all active servers already hold replicas\n", chunk.chunkID)
			cnt++
			sanity_count = 0
			targetServerMap = make(map[string](bool))
		}

		if targetServerMap[str] == true {
			continue
		}

		for ijk := 0; ijk < sCnt; ijk++ {
			if chunk.servers.At(ijk).(*server) == otherserver {
				targetServerMap[str] = true

				if len(targetServerMap) >= len(servers) {
					log.Printf("master: RemoveServer: abort replication req for chunk %d; all active servers already hold replicas\n", chunk.chunkID)
					cnt++
					sanity_count = 0
					targetServerMap = make(map[string](bool))
				}

				continue ChunkReplicate
			}
		}

		log.Printf("master: RemoveServer: attempting to replicate chunk %d to server %s\n", chunk.chunkID, str)

		//log.Printf("master: RemoveServer: dialing %s to replicate\n", str)

		client, err := rpc.Dial("tcp", str)

		if err != nil {
			log.Printf("master: RemoveServer: unable to dial %s\n", str)
			sanity_count = sanity_count + 1
			continue
		} else {
			log.Printf("master: RemoveServer: dial %s succeeded\n", str)
		}

		if sanity_count > sanity_threshhold2 {
			log.Printf("master: RemoveServer: tried %d times to dial servers to replicate, and gave up!!!!\n", sanity_threshhold2)
			break

		}

		//populate chunk location vector
		chunklist := make([]net.TCPAddr, chunk.servers.Len())
		for cnt1 := 0; cnt1 < chunk.servers.Len(); cnt1++ {
			chunklist[cnt1] = chunk.servers.At(cnt1).(*server).addr
		}

		//send rpc call off
		args := &sfs.ReplicateChunkArgs{chunk.chunkID, chunklist}
		reply := new(sfs.ReplicateChunkReturn)
		log.Printf("master: RemoveServer: issuing replication req to %s\n", str)
		err = client.Call("Server.ReplicateChunk", args, reply)
		if err != nil {
			log.Printf("master: RemoveServer: unable to call %s\n", str)
			client.Close()
			continue
		}
		//log.Printf("%s", reply)
		client.Close()
		cnt++
		sanity_count = 0
		targetServerMap = make(map[string](bool))
	}

	log.Printf("master: RemoveServer: finished %s\n", str1)
	log.Printf("master: RemoveServer: server heap post replication:\n%s\n", sHeap.printPresent())

	str2 := fmt.Sprintf("%s:%d", serv.addr.IP.String(), serv.addr.Port)
	_, test1 := servers[serv.id]
	_, test2 := addrToServerMap[str2]

	if test1 == true || test2 == true {
		log.Printf("REMOVESERVER :: server (%s) with id (%d) :: serverMap (%v)  :: addrMap (%v)", str1, serv.id, test1, test2)
	}
	return nil
}
Exemplo n.º 13
0
func resizeImage(src string) {
	fmt.Println(src)
	file, err := os.Open(src)
	if err != nil {
		panic(err.String())
	}
	defer file.Close()

	//img,format, err := image.Decode(file)
	i, err := jpeg.Decode(file)
	if err != nil {
		panic(err.String())
	}
	//fmt.Println(i)
	// Grab the image data
	/*var buf bytes.Buffer
	io.Copy(&buf, f)
	i, _, err := image.Decode(&buf)
	check(err)*/

	// Resize if too large, for more efficient moustachioing.
	// We aim for less than 1200 pixels in any dimension; if the
	// picture is larger than that, we squeeze it down to 600.
	const xmax, ymax = float64(900), float64(900)
	ratio := float64(1.0)

	b := i.Bounds()
	dx := float64(b.Dx())
	dy := float64(b.Dy())

	if dx > xmax {
		ratio = xmax / dx
	}
	if dy > ymax {
		ratio = math.Fmin(ymax/dy, ratio)
	}

	w := int(ratio * dx)
	h := int(ratio * dy)
	fmt.Println(ratio, w, h, dx, dy)
	i, _ = scale.Rescale(i, w, h)

	// Encode as a new JPEG image.
	var buf bytes.Buffer
	//buf.Reset()
	err = jpeg.Encode(&buf, i, nil)
	if err != nil {
		panic(err.String())
	}

	file2, err2 := os.Create(src + ".2.jpg")

	if err2 != nil {
		panic(err2.String())
	}

	file2.Write(buf.Bytes())

	defer file2.Close()

}
Exemplo n.º 14
0
func col(v, maxv float64) uint8 {
	v = math.Log2(v / fill)
	v = v * 255 / maxv
	return uint8(math.Fmax(0, math.Fmin(255, v)))
}
Exemplo n.º 15
0
func (this *northWestHandle) InvokeStep(x, y, anchorX, anchorY int, view DrawingView) {
	r := this.owner.GetDisplayBox()
	topLeft := &Point{int(math.Fmin(float64(r.X+r.Width), float64(x))), int(math.Fmin(float64(r.Y+r.Height), float64(y)))}
	bottomRight := &Point{r.X + r.Width, r.Y + r.Height}
	this.owner.SetDisplayBox(this.owner, topLeft, bottomRight)
}
Exemplo n.º 16
0
func (this *westHandle) InvokeStep(x, y, anchorX, anchorY int, view DrawingView) {
	r := this.owner.GetDisplayBox()
	this.owner.SetDisplayBox(this.owner,
		&Point{int(math.Fmin(float64(r.X+r.Width), float64(x))), r.Y},
		&Point{r.X + r.Width, r.Y + r.Height})
}