Ejemplo n.º 1
0
func (ss *SessionScenario) NextCall(rg *rand.Rand) (*Call, error) {
	for {
		if i := rg.Intn(ss.SessionAmount); i >= 0 {
			select {
			case st := <-ss._sessions[i].StepLock:
				switch st {
				case STEP1:
					if ss._sessions[i]._calls[st].GenParam != nil {
						ss._sessions[i]._calls[st].Method, ss._sessions[i]._calls[st].Type, ss._sessions[i]._calls[st].URL, ss._sessions[i]._calls[st].Body = ss._sessions[i]._calls[st].GenParam()
					}
					// execute session call for the first time
					return ss._sessions[i]._calls[st], nil
				default:
					// choose a non-initialized call randomly
					ss._sessions[i].StepLock <- REST
					q := rg.Float32() * ss._sessions[i]._totalWeight
					for j := STEP1 + 1; j < ss._sessions[i]._count; j++ {
						if q <= ss._sessions[i]._calls[j].RandomWeight {
							if ss._sessions[i]._calls[j].GenParam != nil {
								ss._sessions[i]._calls[j].Method, ss._sessions[i]._calls[j].Type, ss._sessions[i]._calls[j].URL, ss._sessions[i]._calls[j].Body = ss._sessions[i]._calls[j].GenParam()
							}
							return ss._sessions[i]._calls[j], nil
						}
					}
				}
			default:
				continue
			}
		}
	}

	log.Fatal("what? should never reach here")
	return nil, errors.New("all sessions are being initialized")
}
Ejemplo n.º 2
0
func doOneStep(sys *StressLattice, alpha, stressNoise float32, R uint8, Ran *rand.Rand) uint {
	maxLoc := sys.FindMaxAllStress()
	currStress := sys.GetStress(maxLoc)
	sys.LoadSystem(sys.failureStress - currStress)
	currStress = sys.failureStress
	newStress := (stressNoise * (Ran.Float32()*2.0 - 1.0)) + sys.residualStress
	stressDistOut := (1.0 - alpha) * (currStress - newStress)

	//distribute stress
	sys.RangedDistStress(maxLoc, stressDistOut, newStress, R, sys.dim)
	eventSize := uint(1)

	// distribute until no more failed sites exist
	for sys.DistributeFailedSites() {
		maxLoc = sys.FindLargestDistributeFail()
		// stress change
		currStress = sys.GetStress(maxLoc)
		newStress = (stressNoise * (Ran.Float32()*2.0 - 1.0)) + sys.residualStress
		// stress to be distributed
		stressDistOut = (1.0 - alpha) * (currStress - newStress)
		sys.RangedDistStress(maxLoc, stressDistOut, newStress, R, sys.dim)
		eventSize = eventSize + 1
	}
	return eventSize
}
Ejemplo n.º 3
0
func MonteCarloPixel(results chan Result, scene *geometry.Scene, diffuseMap /*, causticsMap*/ *kd.KDNode, start, rows int, rand *rand.Rand) {
	samples := Config.NumRays
	var px, py, dy, dx geometry.Float
	var direction, contribution geometry.Vec3

	for y := start; y < start+rows; y++ {
		py = scene.Height - scene.Height*2*geometry.Float(y)/geometry.Float(scene.Rows)
		for x := 0; x < scene.Cols; x++ {
			px = -scene.Width + scene.Width*2*geometry.Float(x)/geometry.Float(scene.Cols)
			var colourSamples geometry.Vec3
			if x >= Config.Skip.Left && x < scene.Cols-Config.Skip.Right &&
				y >= Config.Skip.Top && y < scene.Rows-Config.Skip.Bottom {
				for sample := 0; sample < samples; sample++ {
					dy, dx = geometry.Float(rand.Float32())*scene.PixH, geometry.Float(rand.Float32())*scene.PixW
					direction = geometry.Vec3{
						px + dx - scene.Camera.Origin.X,
						py + dy - scene.Camera.Origin.Y,
						-scene.Camera.Origin.Z,
					}.Normalize()

					contribution = Radiance(geometry.Ray{scene.Camera.Origin, direction}, scene, diffuseMap /*causticsMap,*/, 0, 1.0, rand)
					colourSamples.AddInPlace(contribution)
				}
			}
			results <- Result{x, y, colourSamples.Mult(1.0 / geometry.Float(samples))}
		}
	}
}
Ejemplo n.º 4
0
func (d *DelayAction) RandDuration(r *rand.Rand) time.Duration {
	t := d.Time
	if d.Rand {
		t *= r.Float32()
	}

	return (time.Duration)(t * 1000000000)
}
Ejemplo n.º 5
0
func (r *RequestsHandler) buildResponse(rd *rand.Rand, req *openrtb.Request) openrtb.Response {
	cur := "RUB"
	pr := rd.Float32()
	return openrtb.Response{
		Id:      req.Id,
		Seatbid: []openrtb.Seatbid{openrtb.Seatbid{Bid: []openrtb.Bid{openrtb.Bid{Id: req.Imp[0].Id, Adm: &r.Markup, Price: &pr, Impid: req.Imp[0].Id}}}},
		Cur:     &cur,
	}
}
Ejemplo n.º 6
0
func RandomRatPercent(randgen *rand.Rand) uint {
	if randgen == nil {
		return 10
	}
	if randgen.Float32() < 0.40 {
		return uint(randgen.Intn(21) + 10)
	}
	return 0
}
Ejemplo n.º 7
0
func RandomCave(world *world, r *rand.Rand) {
	for row := range world.cells {
		for col := range world.cells[row] {
			if r.Float32() < 0.5 {
				world.cells[row][col] = NewTile(floor)
			} else {
				world.cells[row][col] = NewTile(wall)
			}
		}
	}
}
Ejemplo n.º 8
0
// From -1 to 1
func gaussianRandom(r *rand.Rand) float32 {
	// Add n numbers from r, this will give us a gaussian distribution
	// then we just need to set the variance and mean correctly
	const n = 25
	value := float32(0.0)
	for i := 0; i < n; i++ {
		value += r.Float32()
	}
	value -= n / 2.0
	value *= 2.0 / n
	return value
}
Ejemplo n.º 9
0
func (s *Scenario) NextCall(rg *rand.Rand) (*Call, error) {
	r := rg.Float32() * s._totalWeight
	for i := 0; i < s._count; i++ {
		if r <= s._calls[i].RandomWeight {
			if s._calls[i].GenParam != nil {
				s._calls[i].Method, s._calls[i].Type, s._calls[i].URL, s._calls[i].Body = s._calls[i].GenParam()
			}
			return s._calls[i], nil
		}
	}

	return nil, errors.New("something wrong with randomize number")
}
Ejemplo n.º 10
0
func randNextGps(last *GPSData, rander *rand.Rand) *GPSData {
	last.Time += 500 + int64(rander.Float32()*1000)
	last.Latitude += (rander.Float64()*2 - 1) * 0.0001
	last.Longitude += (rander.Float64()*2 - 1) * 0.0001

	if last.Speed < 1 {
		last.Speed += (rander.Float64()*2 - 0.5) * 1
	} else if last.Speed > 8 {
		last.Speed += (rander.Float64()*2 - 1.5) * 1
	} else {
		last.Speed += (rander.Float64()*2 - 1) * 2
	}
	if last.Speed <= 0 {
		last.Speed = rander.Float64() * 2
	}
	fmt.Println("{\"lng\":" + strconv.FormatFloat(last.Longitude, 'f', 6, 64) +
		",\"lat\":" + strconv.FormatFloat(last.Latitude, 'f', 6, 64) + ",\"count\":1},")
	return last
}
Ejemplo n.º 11
0
func (b bytesize) Generate(rand *rand.Rand, size int) reflect.Value {
	suffix := ""
	number := 1 + rand.Int31n(int32(size))
	chance := rand.Float32()
	if chance < 0.1 {
		suffix = "k"
	}
	// Can't test `kb`-style suffixes in darwin…
	return reflect.ValueOf(bytesize(fmt.Sprintf("%d%s", number, suffix)))
}
Ejemplo n.º 12
0
func (ss *HCScenario) NextCall(rg *rand.Rand) (*Call, error) {
	for {
		if i := rg.Intn(ss.SessionAmount); i >= 0 {
			select {
			case st := <-ss._sessions[i].StepLock:
				switch st {
				case STEP1, STEP2, STEP3:
					// execute session call for the first time
					if ss._sessions[i]._calls[st].GenParam != nil {
						ss._sessions[i]._calls[st].Method, ss._sessions[i]._calls[st].Type, ss._sessions[i]._calls[st].URL, ss._sessions[i]._calls[st].Body = ss._sessions[i]._calls[st].GenParam(ss._sessions[i].Storage["seq"], ss._sessions[i].Storage["player_id"])
					}

					return ss._sessions[i]._calls[st], nil
				default:
					// choose a non-initialized call randomly
					ss._sessions[i].StepLock <- REST
					q := rg.Float32() * ss._sessions[i]._totalWeight
					//for j := STEP2 + 1; j < ss._sessions[i]._count; j++ {
					for j := STEP3 + 1; j < ss._sessions[i]._count; j++ {
						if q <= ss._sessions[i]._calls[j].RandomWeight {
							// add 1 to seq
							ss._sessions[i].InternalLock.Lock()
							seq, _ := strconv.ParseInt(ss._sessions[i].Storage["seq"], 10, 64)
							atomic.AddInt64(&seq, 1)
							ss._sessions[i].Storage["seq"] = strconv.FormatInt(seq, 10)
							if ss._sessions[i]._calls[j].GenParam != nil {
								ss._sessions[i]._calls[j].Method, ss._sessions[i]._calls[j].Type, ss._sessions[i]._calls[j].URL, ss._sessions[i]._calls[j].Body = ss._sessions[i]._calls[j].GenParam(ss._sessions[i].Storage["seq"], ss._sessions[i].Storage["player_id"])
							}
							ss._sessions[i].InternalLock.Unlock()
							return ss._sessions[i]._calls[j], nil
						}
					}
				}
			default:
				continue
			}
		}
	}

	log.Fatal("what? should never reach here")
	return nil, errors.New("all sessions are being initialized")
}
Ejemplo n.º 13
0
func makeRoutes(ps []place, r *rand.Rand) {
	for i := range ps {
		p := &ps[i]
		others := r.Perm(len(ps))
		percentageToConnectTo := r.Float32()
		next := i + 1
		if next == len(ps) {
			next = 0
		}
		p.neighbours = append(p.neighbours, dist{to: int32(next), cost: calcDist(p, &ps[next])})
		for _, o := range others {
			var newNeighbour dist
			if r.Float32() < percentageToConnectTo && o != next && o != i {
				newNeighbour = dist{to: int32(o), cost: calcDist(p, &ps[o])}
			} else {
				newNeighbour = dist{-1, -1}
			}
			p.neighbours = append(p.neighbours, newNeighbour)
		}
	}
}
Ejemplo n.º 14
0
func (self *Triangle) SamplePoint(r *rand.Rand) Vector3f {
	/* get two randoms */
	sqr1 := math32.Sqrt(r.Float32())
	r2 := r.Float32()

	/* make barycentric coords */
	c0 := 1.0 - sqr1
	c1 := (1.0 - r2) * sqr1

	/* make barycentric axes */
	a0 := self.Vertexs[1].Sub(self.Vertexs[0])
	a1 := self.Vertexs[2].Sub(self.Vertexs[0])

	/* scale axes by coords */
	ac0 := a0.Mulf(c0)
	ac1 := a1.Mulf(c1)

	/* sum scaled components, and offset from corner */
	sum := ac0.Add(ac1)
	return sum.Add(self.Vertexs[0])
}
Ejemplo n.º 15
0
func randNextHR(last *HeartRateData, rander *rand.Rand) *HeartRateData {
	last.Time += 500 + int64(rander.Float32()*1000)

	if last.HeartRate < 80 {
		last.HeartRate += int((rander.Float32()*2 - 0.5) * 10)
	} else if last.HeartRate < 160 {
		last.HeartRate += int((rander.Float32()*2 - 1.5) * 10)
	} else {
		last.HeartRate += int((rander.Float32()*2 - 1) * 10)
	}
	if last.HeartRate < 80 {
		last.HeartRate = 86
	}
	return last
}
Ejemplo n.º 16
0
// Make a network of nodes with random topology
func makeRandomModel(params *TestParams, r *rand.Rand, t *testing.T) *Model {
	m := Model{
		t:          t,
		r:          r,
		quorum:     params.nodeCount/2 + 1,
		nodes:      make([]TestNode, params.nodeCount),
		readyLinks: []*Link{},
		nextID:     params.nodeCount + 1,
	}

	for i := range m.nodes {
		m.nodes[i].Node = NewNode(router.PeerName(i/2+1),
			router.PeerUID(r.Int63()), m.quorum)
		m.nodes[i].Propose()
	}

	for i := 1; i < len(m.nodes); i++ {
		// was node i connected to the other nodes yet?
		connected := false

		for j := 0; j < i; j++ {
			if r.Float32() < params.connectedProb {
				connected = true
				m.addLink(&m.nodes[i], &m.nodes[j])
			}
		}

		if !connected {
			// node i must be connected into the graph
			// somewhere.  So if we didn't connect it
			// already, this is a last resort.
			m.addLink(&m.nodes[i], &m.nodes[r.Intn(i)])
		}
	}

	return &m
}
Ejemplo n.º 17
0
/*
ReproduceRand takes a *Genome and returns a new *Genome with a single point
mutation, using the passed *Rand for randomness.
*/
func ReproduceRand(parent *Genome, rand *rand.Rand) *Genome {
	if len(*parent) == 0 {
		panic(InvalidGenomeError(*parent))
	}
	child := make(Genome, len(*parent))
	copy(child, *parent)
	i := rand.Intn(len(child))
	pos := rand.Float32() < 0.5
	if pos {
		child[i] += 1
	} else {
		child[i] -= 1
	}
	return &child
}
Ejemplo n.º 18
0
func DiffusePhoton(scene []*geometry.Shape, emitter *geometry.Shape, ray geometry.Ray, colour geometry.Vec3, result chan<- PhotonHit, alpha geometry.Float, depth int, rand *rand.Rand) {
	if geometry.Float(rand.Float32()) > alpha {
		return
	}
	if shape, distance := ClosestIntersection(scene, ray); shape != nil {
		impact := ray.Origin.Add(ray.Direction.Mult(distance))

		if depth == 0 && emitter == shape {
			// Leave the emitter first
			nextRay := geometry.Ray{impact, ray.Direction}
			DiffusePhoton(scene, emitter, nextRay, colour, result, alpha, depth, rand)
		} else {
			normal := shape.NormalDir(impact).Normalize()
			reverse := ray.Direction.Mult(-1)
			outgoing := normal
			if normal.Dot(reverse) < 0 {
				outgoing = normal.Mult(-1)
			}
			strength := colour.Mult(alpha / (1 + distance))
			result <- PhotonHit{impact, strength, ray.Direction, uint8(depth)}

			if shape.Material == geometry.DIFFUSE {
				// Random bounce for color bleeding
				u := normal.Cross(reverse).Normalize().Mult(geometry.Float(rand.NormFloat64() * 0.5))
				v := u.Cross(normal).Normalize().Mult(geometry.Float(rand.NormFloat64() * 0.5))
				bounce := geometry.Vec3{
					u.X + outgoing.X + v.X,
					u.Y + outgoing.Y + v.Y,
					u.Z + outgoing.Z + v.Z,
				}
				bounceRay := geometry.Ray{impact, bounce.Normalize()}
				bleedColour := colour.MultVec(shape.Colour).Mult(alpha / (1 + distance))
				DiffusePhoton(scene, shape, bounceRay, bleedColour, result, alpha*0.66, depth+1, rand)
			}
			// Store Shadow Photons
			shadowRay := geometry.Ray{impact, ray.Direction}
			DiffusePhoton(scene, shape, shadowRay, geometry.Vec3{0, 0, 0}, result, alpha*0.66, depth+1, rand)
		}
	}
}
Ejemplo n.º 19
0
func (self *SurfacePoint) NextDirection(r *rand.Rand,
	inDirection Vector3f,
	outDirection_o *Vector3f,
	colour *Vector3f) bool {
	reflectivityMean := self.Tri.Reflectivity.Dot(VECTOR_ONE) / 3.0

	/* russian-roulette for reflectance 'magnitude' */
	isAlive := r.Float32() < reflectivityMean

	if !isAlive {
		return false
	}

	/* cosine-weighted importance sample hemisphere */
	_2pr1 := math32.Pi * 2.0 * r.Float32()
	sr2 := math32.Sqrt(r.Float32())

	/* make coord frame coefficients (z in normal direction) */
	x := math32.Cos(_2pr1) * sr2
	y := math32.Sin(_2pr1) * sr2
	z := math32.Sqrt(1.0 - (sr2 * sr2))

	/* make coord frame */
	t := self.Tri.Tangent()
	n := self.Tri.Normal()
	var c Vector3f
	/* put normal on inward ray side of surface (preventing transmission) */
	if n.Dot(inDirection) < 0.0 {
		n.Neg()
	}
	c = n.Cross(t)

	/* scale frame by coefficients */
	tx := t.Mulf(x)
	cy := c.Mulf(y)
	nz := n.Mulf(z)

	/* make direction from sum of scaled components */
	sum := tx.Add(cy)
	*outDirection_o = sum.Add(nz)

	/* make color by dividing-out mean from reflectivity */
	*colour = self.Tri.Reflectivity.Mulf(1.0 / reflectivityMean)

	/* discluding degenerate result direction */
	return isAlive && !outDirection_o.Is_Zero()
}
Ejemplo n.º 20
0
Archivo: get.go Proyecto: polluxx/yard
func ReturnRand(volume int64, r *rand.Rand) string {
	return fmt.Sprintf("%v%v", r.Int63n(volume), strings.Replace(fmt.Sprintf("%v", r.Float32()), "0", "", 1))
}
Ejemplo n.º 21
0
func RandomPlagueHappened(randgen *rand.Rand, year uint) bool {
	if randgen == nil {
		return (year%4 == 0)
	}
	return (randgen.Float32() > 0.85)
}