Exemple #1
0
// randomSchurCanonical returns a random, general matrix in Schur canonical
// form, that is, block upper triangular with 1×1 and 2×2 diagonal blocks where
// each 2×2 diagonal block has its diagonal elements equal and its off-diagonal
// elements of opposite sign.
func randomSchurCanonical(n, stride int, rnd *rand.Rand) blas64.General {
	t := randomGeneral(n, n, stride, rnd)
	// Zero out the lower triangle.
	for i := 0; i < t.Rows; i++ {
		for j := 0; j < i; j++ {
			t.Data[i*t.Stride+j] = 0
		}
	}
	// Randomly create 2×2 diagonal blocks.
	for i := 0; i < t.Rows; {
		if i == t.Rows-1 || rnd.Float64() < 0.5 {
			// 1×1 block.
			i++
			continue
		}
		// 2×2 block.
		// Diagonal elements equal.
		t.Data[(i+1)*t.Stride+i+1] = t.Data[i*t.Stride+i]
		// Off-diagonal elements of opposite sign.
		c := rnd.NormFloat64()
		if math.Signbit(c) == math.Signbit(t.Data[i*t.Stride+i+1]) {
			c *= -1
		}
		t.Data[(i+1)*t.Stride+i] = c
		i += 2
	}
	return t
}
func testRandomSimplex(t *testing.T, nTest int, pZero float64, maxN int, rnd *rand.Rand) {
	// Try a bunch of random LPs
	for i := 0; i < nTest; i++ {
		n := rnd.Intn(maxN) + 2 // n must be at least two.
		m := rnd.Intn(n-1) + 1  // m must be between 1 and n
		if m == 0 || n == 0 {
			continue
		}
		randValue := func() float64 {
			//var pZero float64
			v := rnd.Float64()
			if v < pZero {
				return 0
			}
			return rnd.NormFloat64()
		}
		a := mat64.NewDense(m, n, nil)
		for i := 0; i < m; i++ {
			for j := 0; j < n; j++ {
				a.Set(i, j, randValue())
			}
		}
		b := make([]float64, m)
		for i := range b {
			b[i] = randValue()
		}

		c := make([]float64, n)
		for i := range c {
			c[i] = randValue()
		}

		testSimplex(t, nil, c, a, b, convergenceTol)
	}
}
Exemple #3
0
// L883
func newTieredMergePolicy(r *rand.Rand) *index.TieredMergePolicy {
	tmp := index.NewTieredMergePolicy()
	if Rarely(r) {
		log.Println("Use crazy value for max merge at once")
		tmp.SetMaxMergeAtOnce(NextInt(r, 2, 9))
		tmp.SetMaxMergeAtOnceExplicit(NextInt(r, 2, 9))
	} else {
		tmp.SetMaxMergeAtOnce(NextInt(r, 10, 50))
		tmp.SetMaxMergeAtOnceExplicit(NextInt(r, 10, 50))
	}
	if Rarely(r) {
		log.Println("Use crazy value for max merge segment MB")
		tmp.SetMaxMergedSegmentMB(0.2 + r.Float64()*100)
	} else {
		tmp.SetMaxMergedSegmentMB(r.Float64() * 100)
	}
	tmp.SetFloorSegmentMB(0.2 + r.Float64()*2)
	tmp.SetForceMergeDeletesPctAllowed(0 + r.Float64()*30)
	if Rarely(r) {
		log.Println("Use crazy value for max merge per tire")
		tmp.SetSegmentsPerTier(float64(NextInt(r, 2, 20)))
	} else {
		tmp.SetSegmentsPerTier(float64(NextInt(r, 10, 50)))
	}
	configureRandom(r, tmp)
	tmp.SetReclaimDeletesWeight(r.Float64() * 4)
	return tmp
}
Exemple #4
0
// Parenthood crossover combines two individuals (the parents) into one (the
// offspring). Each parent's contribution to the DNA is determined by the toss
// of a coin. The offspring can inherit from it's mother's genes (coin <= 0.33),
// from it's father's genes (0.33 < coin <= 0.66) or from a random mix of both
// (0.66 < coin <= 1). A coin is thrown for each gene. With this method only the
// two first selected individuals are considered, hence the CrossSize parameter
// should be set to 2.
func Parenthood(indis Individuals, generator *rand.Rand) Individual {
	var mother = indis[0]
	var father = indis[1]
	// Create an individual with an empty DNA
	var offspring = Individual{make([]float64, len(mother.Dna)), 0.0}
	// For every gene in the parent's DNA
	for i := range offspring.Dna {
		// Flip a coin and decide what to do
		var coin = rand.Float64()
		switch {
		// The offspring receives the mother's gene
		case coin <= 0.33:
			offspring.Dna[i] = mother.Dna[i]
		// The offspring receives the father's gene
		case coin <= 0.66:
			offspring.Dna[i] = father.Dna[i]
		// The offspring receives a mixture of his parent's genes
		default:
			// Random weight for each individual
			var pMother = generator.Float64()
			var pFather = 1 - pMother
			offspring.Dna[i] = pMother*mother.Dna[i] + pFather*father.Dna[i]
		}
	}
	return offspring
}
Exemple #5
0
// Mutate is a convenience function for mutating each individual in a slice of individuals.
func (indis Individuals) Mutate(mutator Mutator, mutRate float64, rng *rand.Rand) {
	for i := range indis {
		if rng.Float64() < mutRate {
			indis[i].Mutate(mutator, rng)
		}
	}
}
Exemple #6
0
func randomCircle(r *rand.Rand) {
	colors := [12]string{
		"#ff66cc",
		"#ff6680",
		"#ff9966",
		"#ffe666",
		"#ccff66",
		"#80ff66",
		"#66ff99",
		"#66ffe6",
		"#66ccff",
		"#6680ff",
		"#9966ff",
		"#e566ff",
	}
	x := int(r.Float64()*width + 1)
	y := int(r.Float64()*height + 1)
	radius := int((r.Float64() * width / 5) + 1)
	strokeColor := colors[r.Intn(len(colors))]
	strokeWidth := 4
	color := colors[r.Intn(len(colors))]

	fmt.Printf("<circle cx='%d' cy='%d' r='%d' stroke='%s' "+
		"stroke-width='%d' fill='%s' />\n", x, y, radius,
		strokeColor, strokeWidth, color)
}
Exemple #7
0
// return the sample index to the other public functions
func sample(x index, n int, replace bool, weights vector, rnd *rand.Rand) ([]uint, error) {
	if weights != nil && len(x) != len(weights) {
		return nil, fmt.Errorf("length of x (%d) unequal to length of weights (%d)", len(x), len(weights))
	}

	if !replace && n > len(x) {
		return nil, fmt.Errorf("cannot sample with replacement when n (%d) is greater than x (%d)", n, len(x))
	}

	// cumulative probabilities
	var cumprob vector
	if weights != nil {
		cumprob = weights.CumProb()
	} else {
		cumprob = make(vector, len(x))
		nx := float64(len(x))
		for i, _ := range x {
			cumprob[i] = float64(i) / nx
		}
	}

	results := make([]uint, n)
	for i := 0; i < n; i++ {
		index := uint(Find(cumprob, rnd.Float64()))
		results[i] = x[index]

		// if sampling w/o replacement, remove the index and re-scale weights
		if !replace {
			x = x.Remove(index)
			cumprob = cumprob.Remove(index).Scale()
		}
	}

	return results, nil
}
Exemple #8
0
func random_gradient(r *rand.Rand) Vec2 {
	v := r.Float64() * PI * 2
	return Vec2{
		float32(math.Cos(v)),
		float32(math.Sin(v)),
	}
}
Exemple #9
0
// RandMat returns a new matrix random values.
func RandMat(r *rand.Rand) *Mat4 {
	m := Mat4{}
	for i := 0; i < len(m); i++ {
		m[i] = r.Float64()
	}
	return &m
}
Exemple #10
0
func randomFloatAsString(val string, r *rand.Rand) string {
	// val should be in the format: [lo-]hi[ format]
	var lo, hi float64
	var err error
	format := "%.0f"
	// If there's a space in the string, we also have a format.
	sp := strings.Index(val, " ")
	if sp != -1 {
		format = strings.TrimSpace(val[sp:])
		val = val[:sp]
	}
	// If there's a dash in var, we have a range lo-hi, rather than just 0-hi.
	if dash := strings.Index(val, "-"); dash != -1 {
		if lo, err = strconv.ParseFloat(val[:dash], 32); err != nil {
			lo = 0
		}
		if hi, err = strconv.ParseFloat(val[dash+1:], 32); err != nil {
			hi = 0
		}
	} else {
		lo = 0
		if hi, err = strconv.ParseFloat(val, 32); err != nil {
			hi = 0
		}
	}
	rnd := r.Float64()*(hi-lo) + lo
	return fmt.Sprintf(format, rnd)
}
Exemple #11
0
// Picks a random index from a, with a probability proportional to its value.
// Using a local random-generator to prevent waiting on rand's default source.
func pickRandom(a []float64, rnd *rand.Rand) int {
	if len(a) == 0 {
		panic("Cannot pick element from an empty distribution.")
	}

	sum := float64(0)
	for i := range a {
		if a[i] < 0 {
			panic(fmt.Sprintf("Got negative value in distribution: %v", a[i]))
		}
		sum += a[i]
	}
	if sum == 0 {
		return rnd.Intn(len(a))
	}

	r := rnd.Float64() * sum
	i := 0
	for i < len(a) && r > a[i] {
		r -= a[i]
		i++
	}
	if i == len(a) {
		i--
	}
	return i
}
Exemple #12
0
func (m *Multinomial) Sample(n int, rng *rand.Rand) map[string]int {
	ret := make(map[string]int)

	// We have to copy keys out from map m.Hist to a slice and sort
	// them. Otherwise, we would have to access m.Hist directly using
	// range, which introduces randomness and leads to random output
	// even given a fix-seeded rng.
	keys := make([]string, 0, len(m.Hist))
	for k, _ := range m.Hist {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	for i := 0; i < n; i++ {
		p := rng.Float64() * m.Sum
		sum := 0.0
		for _, k := range keys {
			sum += m.Hist[k]
			if p < sum {
				ret[k]++
				break
			}
		}
	}
	return ret
}
Exemple #13
0
func uniform(r *rand.Rand) float64 {
	if r == nil {
		return rand.Float64()
	} else {
		return r.Float64()
	}
}
Exemple #14
0
func recordToSink(sink EventSink, event *api.Event, eventCorrelator *EventCorrelator, randGen *rand.Rand, sleepDuration time.Duration) {
	// Make a copy before modification, because there could be multiple listeners.
	// Events are safe to copy like this.
	eventCopy := *event
	event = &eventCopy
	result, err := eventCorrelator.EventCorrelate(event)
	if err != nil {
		utilruntime.HandleError(err)
	}
	if result.Skip {
		return
	}
	tries := 0
	for {
		if recordEvent(sink, result.Event, result.Patch, result.Event.Count > 1, eventCorrelator) {
			break
		}
		tries++
		if tries >= maxTriesPerEvent {
			glog.Errorf("Unable to write event '%#v' (retry limit exceeded!)", event)
			break
		}
		// Randomize the first sleep so that various clients won't all be
		// synced up if the master goes down.
		if tries == 1 {
			time.Sleep(time.Duration(float64(sleepDuration) * randGen.Float64()))
		} else {
			time.Sleep(sleepDuration)
		}
	}
}
Exemple #15
0
// Adds a new connection to the genome
//
// In the add connection mutation, a single new connection gene is added connecting two previously
// unconnected nodes. (Stanley, 35)
func (m *Complexify) addConn(rng *rand.Rand, g *neat.Genome) {

	// Identify two unconnected nodes
	conns := make(map[int]neat.Connection)
	c := 0
	for _, src := range g.Nodes {
		for _, tgt := range g.Nodes {
			if src.Y >= tgt.Y {
				continue // do not allow recurrent
			}
			found := false
			for _, c2 := range g.Conns {
				if c2.Source == src.Innovation && c2.Target == tgt.Innovation {
					found = true
					break
				}
			}
			if !found {
				conns[c] = neat.Connection{Source: src.Innovation, Target: tgt.Innovation}
				c += 1
			}
		}
	}

	// Go's range over maps is random, so take the first, if any, availble connection
	for _, conn := range conns {
		conn.Enabled = true
		conn.Weight = (rng.Float64()*2.0 - 1.0) * m.WeightRange()
		conn.Innovation = m.ctx.Innovation(neat.ConnInnovation, conn.Key())
		g.Conns[conn.Innovation] = conn
		break
	}
}
Exemple #16
0
func (s *Scene) Sample(r Ray, emission bool, samples, depth int, rnd *rand.Rand) Color {
	if depth < 0 {
		return Color{}
	}
	hit := s.Intersect(r)
	if !hit.Ok() {
		return s.color
	}
	info := hit.Info(r)
	result := Color{}
	if emission {
		result = result.Add(info.Color.MulScalar(info.Material.Emittance * float64(samples)))
	}
	n := int(math.Sqrt(float64(samples)))
	for u := 0; u < n; u++ {
		for v := 0; v < n; v++ {
			p := rnd.Float64()
			fu := (float64(u) + rnd.Float64()) / float64(n)
			fv := (float64(v) + rnd.Float64()) / float64(n)
			newRay, reflected := r.Bounce(&info, p, fu, fv)
			indirect := s.Sample(newRay, reflected, 1, depth-1, rnd)
			if reflected {
				tinted := indirect.Mix(info.Color.Mul(indirect), info.Material.Tint)
				result = result.Add(tinted)
			} else {
				direct := s.DirectLight(info.Ray, rnd)
				result = result.Add(info.Color.Mul(direct.Add(indirect)))
			}
		}
	}
	return result.DivScalar(float64(n * n))
}
Exemple #17
0
// Do one insert operation. Because it will be called concurrently from
// multiple client goroutines, this function must be routine safe.
// However, avoid synchronized, or the goroutines will block waiting
// for each other, and it will be difficult to reach the target thoughput.
// Ideally, this function would have no side effects other than DB operations.
func (self *CoreWorkload) DoInsert(db DB, object interface{}) bool {
	keyNumber := self.keySequence.NextInt()
	dbKey := self.buildKeyName(keyNumber)
	values := self.buildValues(dbKey)

	var status StatusType
	numberOfRetries := int64(0)
	var random *rand.Rand
	for {
		status = db.Insert(self.table, dbKey, values)
		if status == StatusOK {
			break
		}
		// Retry if configured. Without retrying, the load process will fail
		// even if one single insertion fails. User can optionally configure
		// an insertion retry limit(default is 0) to enable retry.
		numberOfRetries++
		if numberOfRetries < self.insertionRetryLimit {
			if random == nil {
				random = rand.New(rand.NewSource(time.Now().UnixNano()))
			}
			// sleep for a random number between
			// [0.8, 1.2) * InsertionRetryInterval
			sleepTime := int64(float64(1000*self.insertionRetryInterval) * (0.8 + 0.4*random.Float64()))
			time.Sleep(time.Duration(sleepTime))
		} else {
			// error inserting, not retrying any more
			break
		}
	}
	return (status == StatusOK)
}
Exemple #18
0
// generate anisotropic random unit vector
func randomDir(rng *rand.Rand) data.Vector {
	theta := 2 * rng.Float64() * math.Pi
	z := 2 * (rng.Float64() - 0.5)
	b := math.Sqrt(1 - z*z)
	x := b * math.Cos(theta)
	y := b * math.Sin(theta)
	return data.Vector{x, y, z}
}
Exemple #19
0
func (tspmut tspMutator) Apply(indi *gago.Individual, generator *rand.Rand) {
	if generator.Float64() < 0.35 {
		permute.Apply(indi, generator)
	}
	if generator.Float64() < 0.45 {
		splice.Apply(indi, generator)
	}
}
Exemple #20
0
func RandU(data []float64, m, n int64, random *rand.Rand) {
	var i, j int64
	for i = 0; i < m; i++ {
		for j = 0; j < n; j++ {
			data[i*n+j] = random.Float64()
		}
	}
}
Exemple #21
0
// Normal mutation individual modifies an individual's gene if a coin toss is
// under a defined mutation rate. It does so for each gene. The new gene value
// is a random value sampled from a normal distribution centered on the gene's
// current value and with the intensity parameter as it's standard deviation.
func Normal(indi *Individual, mutRate, mutIntensity float64, generator *rand.Rand) {
	for i := range indi.Dna {
		// Flip a coin and decide to mutate or not
		if generator.Float64() <= mutRate {
			indi.Dna[i] *= generator.NormFloat64() * mutIntensity
		}
	}
}
Exemple #22
0
func (tspmut tspMutator) Apply(indi *gago.Individual, rng *rand.Rand) {
	if rng.Float64() < 0.35 {
		permute.Apply(indi, rng)
	}
	if rng.Float64() < 0.45 {
		splice.Apply(indi, rng)
	}
}
func getPointInUnitDisc(r *rand.Rand) (float64, float64) {
	x := 2 * (r.Float64() - 0.5)
	y := 2 * (r.Float64() - 0.5)
	if x*x+y*y < 1 {
		return x, y
	}
	return getPointInUnitDisc(r)
}
Exemple #24
0
func InvRandN(data []float64, m, n int64, mu, vari float64, random *rand.Rand) {
	var i, j int64
	sd := float64(math.Sqrt(vari))
	for i = 0; i < m; i++ {
		for j = 0; j < n; j++ {
			data[i*n+j] = mu + sd*float64(MoroInvCND(random.Float64()))
		}
	}
}
Exemple #25
0
// Apply normal mutation.
func (mut MutNormalF) Apply(indi *Individual, generator *rand.Rand) {
	for i := range indi.Genome {
		// Flip a coin and decide to mutate or not
		if generator.Float64() < mut.Rate {
			// Sample from a normal distribution
			indi.Genome[i] = indi.Genome[i].(float64) * generator.NormFloat64() * mut.Std
		}
	}
}
Exemple #26
0
func (pointSlice) Generate(r *rand.Rand, size int) reflect.Value {
	ps := make([]Point, size)
	for i := range ps {
		for j := range ps[i] {
			ps[i][j] = r.Float64()
		}
	}
	return reflect.ValueOf(ps)
}
Exemple #27
0
func generateA(r *rand.Rand) *A {
	return &A{
		Name:     randString(r, 16),
		BirthDay: r.Int63(),
		Phone:    randString(r, 10),
		Siblings: r.Int31n(5),
		Spouse:   r.Intn(2) == 1,
		Money:    r.Float64(),
	}
}
Exemple #28
0
func newDNA(r *rand.Rand) []bool {
	l_dna := ((N_INPUT+1)*N_HNEURON +
		(N_HNEURON+1)*N_HNEURON*(N_HLAYER-1) +
		(N_HNEURON+1)*N_OUTPUT) * P_DNA
	dna := make([]bool, l_dna)
	for i := range dna {
		dna[i] = (r.Float64() < 0.5)
	}
	return dna
}
// genBiasedWeights generates a non-uniform weight list, similar to the
// ScrambleSuit prob_dist module.
func (w *WeightedDist) genBiasedWeights(rng *rand.Rand) {
	w.weights = make([]float64, len(w.values))

	culmProb := 0.0
	for i := range w.weights {
		p := (1.0 - culmProb) * rng.Float64()
		w.weights[i] = p
		culmProb += p
	}
}
Exemple #30
0
// Section 3.1.3 Step 3: Choosing the parent species (Stanley, p.4)
func (g *RealTime) pickSpecies(pool map[int]Improvements, ftot float64, rng *rand.Rand) int {
	ftgt := rng.Float64() * ftot
	fsum := 0.0
	for i, list := range pool {
		fsum += list.Improvement()
		if fsum >= ftgt {
			return i
		}
	}
	return -1 // Shouldn't get here
}