Example #1
1
// randomSlice allocates a new slice of length n filled with random values.
func randomSlice(n int, rnd *rand.Rand) []float64 {
	s := make([]float64, n)
	for i := range s {
		s[i] = rnd.NormFloat64()
	}
	return s
}
Example #2
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
}
Example #3
0
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)
	}
}
Example #4
0
// genrand returns a general r×c matrix with random entries.
func genrand(r, c int, rnd *rand.Rand) []float64 {
	m := make([]float64, r*c)
	for i := range m {
		m[i] = rnd.NormFloat64()
	}
	return m
}
func (d *Director) makeLatency(rng *rand.Rand, intensity float64) uint {
	l := int((20 + rng.NormFloat64()*10) * intensity)
	if l < 1 {
		return 1
	} else {
		return uint(l)
	}
}
Example #6
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
		}
	}
}
Example #7
0
func randomFactor(n int, r *rand.Rand) Factor {

	f := NewFactor(n)
	for i, _ := range f {
		f[i] = r.NormFloat64()
	}
	return f
}
Example #8
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
		}
	}
}
Example #9
0
func (n NormalDist) Rand(r *rand.Rand) float64 {
	var x float64
	if r == nil {
		x = rand.NormFloat64()
	} else {
		x = r.NormFloat64()
	}
	return x*n.Sigma + n.Mu
}
Example #10
0
// hessrand returns a Hessenberg matrix of order n with random non-zero entries
// in column-major format.
func hessrand(n int, rnd *rand.Rand) []float64 {
	h := make([]float64, n*n)
	for j := 0; j < n; j++ {
		for i := 0; i <= min(j+1, n-1); i++ {
			h[i+j*n] = rnd.NormFloat64()
		}
	}
	return h
}
Example #11
0
// GenU generates points p₀,p₁,... spread uniformly on the unit sphere S².
func GenU(r *rand.Rand, p []Geo) {
	for i := range p {
		x := r.NormFloat64()
		y := r.NormFloat64()
		z := r.NormFloat64()
		v := vec{x, y, z}
		p[i] = Geo{v.hat()}
	}
}
Example #12
0
File: trait.go Project: NioTeX/neat
func (m *Trait) mutateTrait(rng *rand.Rand, t neat.Trait, v *float64) {
	tv := *v
	tv += rng.NormFloat64()
	if tv < t.Min {
		tv = t.Min
	} else if tv > t.Max {
		tv = t.Max
	}
}
Example #13
0
// randomGeneral allocates a new r×c general matrix filled with random
// numbers. Out-of-range elements are filled with NaN values.
func randomGeneral(r, c, stride int, rnd *rand.Rand) blas64.General {
	ans := nanGeneral(r, c, stride)
	for i := 0; i < r; i++ {
		for j := 0; j < c; j++ {
			ans.Data[i*ans.Stride+j] = rnd.NormFloat64()
		}
	}
	return ans
}
Example #14
0
// Returns a modified weight
func (m Weight) mutateWeight(rng *rand.Rand, c *neat.Connection) {
	c.Weight += rng.NormFloat64()
	/*
		if w < -m.WeightRange*2 {
			w = -m.WeightRange * 2
		} else if w > m.WeightRange*2 {
			w = m.WeightRange * 2
		}
	*/
}
Example #15
0
func randomGaussian(r *rand.Rand, id string, dim int) *gm.Model {

	var mean, sd []float64
	startSD := 40.0
	for i := 0; i < dim; i++ {
		mean = append(mean, float64(r.Intn(10)*100.0))
		a := r.NormFloat64()*0.2 + 1.0 // pert 0.8 to 1.2
		sd = append(sd, startSD*a)
	}
	return gm.NewModel(dim, gm.Name(id), gm.Mean(mean), gm.StdDev(sd))
}
Example #16
0
// creates a random gaussian by adding a perturbation to an existing gaussian.
func initGaussian(r *rand.Rand, m model.Modeler) *gm.Model {

	g := m.(*gm.Model)
	var mean, sd []float64
	for i := 0; i < g.ModelDim; i++ {
		a := r.NormFloat64()*0.2 + 1.0 // pert 0.8 to 1.2
		mean = append(mean, g.Mean[i]*a)
		sd = append(sd, g.StdDev[i]*a)
	}
	return gm.NewModel(g.ModelDim, gm.Name(g.ModelName), gm.Mean(mean), gm.StdDev(sd))
}
Example #17
0
// RandVector sets z to a random vector of unit length using r as the source of normally distributed random numbers
// and returns z.
func (z Vector) RandVector(r *rand.Rand) Vector {
	for {
		for i := range z {
			z[i] = r.NormFloat64()
		}
		z.Hat(z)
		if !z.Zero() {
			break
		}
	}
	return z
}
Example #18
0
// randomHessenberg allocates a new n×n Hessenberg matrix filled with zeros
// under the first subdiagonal and with random numbers elsewhere. Out-of-range
// elements are filled with NaN values.
func randomHessenberg(n, stride int, rnd *rand.Rand) blas64.General {
	ans := nanGeneral(n, n, stride)
	for i := 0; i < n; i++ {
		for j := 0; j < i-1; j++ {
			ans.Data[i*ans.Stride+j] = 0
		}
		for j := max(0, i-1); j < n; j++ {
			ans.Data[i*ans.Stride+j] = rnd.NormFloat64()
		}
	}
	return ans
}
Example #19
0
// unbalancedSparseGeneral returns an m×n dense matrix with a random sparse
// structure consisting of nz nonzero elements. The matrix will be unbalanced by
// multiplying each element randomly by its row or column index.
func unbalancedSparseGeneral(m, n, stride int, nonzeros int, rnd *rand.Rand) blas64.General {
	a := zeros(m, n, stride)
	for k := 0; k < nonzeros; k++ {
		i := rnd.Intn(n)
		j := rnd.Intn(n)
		if rnd.Float64() < 0.5 {
			a.Data[i*stride+j] = float64(i+1) * rnd.NormFloat64()
		} else {
			a.Data[i*stride+j] = float64(j+1) * rnd.NormFloat64()
		}
	}
	return a
}
Example #20
0
// RandNormalVector returns a random observation.
func RandNormalVector(r *rand.Rand, mean, std []float64) []float64 {

	if len(mean) != len(std) {
		panic(fmt.Errorf("Cannot generate random vectors because length of mean [%d] and std [%d] don't match.",
			len(mean), len(std)))
	}
	vector := make([]float64, len(mean))
	for i, _ := range mean {
		v := r.NormFloat64()*std[i] + mean[i]
		vector[i] = v
	}

	return vector
}
Example #21
0
// Returns a random vector using the mean and sd vectors.
func RandomVector(mean, sd []float64, r *rand.Rand) []float64 {

	nrows := len(mean)
	if !floats.EqualLengths(mean, sd) {
		panic(floatx.ErrLength)
	}

	vec := make([]float64, nrows)
	for i := 0; i < nrows; i++ {
		v := r.NormFloat64()*sd[i] + mean[i]
		vec[i] = v
	}
	return vec
}
Example #22
0
func testDlarfx(t *testing.T, impl Dlarfxer, side blas.Side, m, n, extra int, rnd *rand.Rand) {
	const tol = 1e-13

	c := randomGeneral(m, n, n+extra, rnd)
	cWant := randomGeneral(m, n, n+extra, rnd)
	tau := rnd.NormFloat64()

	var (
		v []float64
		h blas64.General
	)
	if side == blas.Left {
		v = randomSlice(m, rnd)
		h = eye(m, m+extra)
	} else {
		v = randomSlice(n, rnd)
		h = eye(n, n+extra)
	}
	blas64.Ger(-tau, blas64.Vector{Inc: 1, Data: v}, blas64.Vector{Inc: 1, Data: v}, h)
	if side == blas.Left {
		blas64.Gemm(blas.NoTrans, blas.NoTrans, 1, h, c, 0, cWant)
	} else {
		blas64.Gemm(blas.NoTrans, blas.NoTrans, 1, c, h, 0, cWant)
	}

	var work []float64
	if h.Rows > 10 {
		// Allocate work only if H has order > 10.
		if side == blas.Left {
			work = make([]float64, n)
		} else {
			work = make([]float64, m)
		}
	}

	impl.Dlarfx(side, m, n, v, tau, c.Data, c.Stride, work)

	prefix := fmt.Sprintf("Case side=%v, m=%v, n=%v, extra=%v", side, m, n, extra)

	// Check any invalid modifications of c.
	if !generalOutsideAllNaN(c) {
		t.Errorf("%v: out-of-range write to C\n%v", prefix, c.Data)
	}

	if !equalApproxGeneral(c, cWant, tol) {
		t.Errorf("%v: unexpected C\n%v", prefix, c.Data)
	}
}
Example #23
0
func randVector32(rand *rand.Rand, length int) []float32 {
	result := make([]float32, length)
	for i := 0; i < length; i++ {
		result[i] = float32(rand.NormFloat64())
	}
	return result
}
Example #24
0
// randomTriangular allocates a new r×c triangular matrix filled with random
// numbers. Out-of-triangle elements are filled with NaN values.
func randomTriangular(uplo blas.Uplo, n, stride int, rnd *rand.Rand) blas64.Triangular {
	ans := nanTriangular(uplo, n, stride)
	if uplo == blas.Upper {
		for i := 0; i < n; i++ {
			for j := i; j < n; j++ {
				ans.Data[i*ans.Stride+j] = rnd.NormFloat64()
			}
		}
		return ans
	}
	for i := 0; i < n; i++ {
		for j := 0; j <= i; j++ {
			ans.Data[i*ans.Stride+j] = rnd.NormFloat64()
		}
	}
	return ans
}
Example #25
0
func MutateEqn_Vanilla(eqn Expr, egp *prob.TreeParams, rng *rand.Rand, sysvals []float64) {
	mut := false
	for !mut {
		s2 := rng.Intn(eqn.Size())
		s2_tmp := s2
		e2 := eqn.GetExpr(&s2_tmp)

		t := e2.ExprType()

		switch t {
		case CONSTANTF:
			if egp.NumSys == 0 {
				e2.(*ConstantF).F += rng.NormFloat64()
			} else {
				// mod coeff
				if rng.Intn(2) == 0 {
					e2.(*ConstantF).F += rng.NormFloat64()
				} else {
					// coeff -> system
					var mul Mul
					s := &System{P: rng.Intn(egp.NumSys)}
					e2.(*ConstantF).F /= sysvals[s.P]
					mul.CS[0] = s
					mul.CS[1] = e2.(*ConstantF)
					e2 = &mul
				}
			}
			mut = true
		case SYSTEM:
			e2.(*System).P = rng.Int() % egp.NumSys
			mut = true
		case VAR:
			p := egp.UsableVars[rng.Intn(len(egp.UsableVars))]
			e2.(*Var).P = p

			// r := rng.Intn(len(egp.UsableVars))
			// e2.(*Var).P = egp.UsableVars[r]
			mut = true
		case ADD:

		case MUL:

		}
	}
}
Example #26
0
// RandDatum generates a random Datum of the given type.
// If null is true, the datum can be DNull.
func RandDatum(rng *rand.Rand, typ ColumnType_Kind, null bool) parser.Datum {
	if null && rng.Intn(10) == 0 {
		return parser.DNull
	}
	switch typ {
	case ColumnType_BOOL:
		return parser.MakeDBool(rng.Intn(2) == 1)
	case ColumnType_INT:
		return parser.NewDInt(parser.DInt(rng.Int63()))
	case ColumnType_FLOAT:
		return parser.NewDFloat(parser.DFloat(rng.NormFloat64()))
	case ColumnType_DECIMAL:
		d := &parser.DDecimal{}
		d.Dec.SetScale(inf.Scale(rng.Intn(40) - 20))
		d.Dec.SetUnscaled(rng.Int63())
		return d
	case ColumnType_DATE:
		return parser.NewDDate(parser.DDate(rng.Intn(10000)))
	case ColumnType_TIMESTAMP:
		return &parser.DTimestamp{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
	case ColumnType_INTERVAL:
		return &parser.DInterval{Duration: duration.Duration{Months: rng.Int63n(1000),
			Days:  rng.Int63n(1000),
			Nanos: rng.Int63n(1000000),
		}}
	case ColumnType_STRING:
		// Generate a random ASCII string.
		p := make([]byte, rng.Intn(10))
		for i := range p {
			p[i] = byte(1 + rng.Intn(127))
		}
		return parser.NewDString(string(p))
	case ColumnType_BYTES:
		p := make([]byte, rng.Intn(10))
		_, _ = rng.Read(p)
		return parser.NewDBytes(parser.DBytes(p))
	case ColumnType_TIMESTAMPTZ:
		return &parser.DTimestampTZ{Time: time.Unix(rng.Int63n(1000000), rng.Int63n(1000000))}
	case ColumnType_INT_ARRAY:
		// TODO(cuongdo): we don't support for persistence of arrays yet
		return parser.DNull
	default:
		panic(fmt.Sprintf("invalid type %s", typ))
	}
}
Example #27
0
// shiftpairs generates k real and complex conjugate shift pairs. That is, the
// length of sr and si is 2*k.
func shiftpairs(k int, rnd *rand.Rand) (sr, si []float64) {
	sr = make([]float64, 2*k)
	si = make([]float64, 2*k)
	for i := 0; i < len(sr); {
		if rnd.Float64() < 0.5 || i == len(sr)-1 {
			sr[i] = rnd.NormFloat64()
			i++
			continue
		}
		// Generate a complex conjugate pair.
		r := rnd.NormFloat64()
		c := rnd.NormFloat64()
		sr[i] = r
		si[i] = c
		sr[i+1] = r
		si[i+1] = -c
		i += 2
	}
	return sr, si
}
Example #28
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)
		}
	}
}
Example #29
0
func EmitterSampling(point, normal geometry.Vec3, shapes []*geometry.Shape, rand *rand.Rand) geometry.Vec3 {
	incomingLight := geometry.Vec3{0, 0, 0}

	for _, shape := range shapes {
		if !shape.Emission.IsZero() {
			// It's a light source
			direction := shape.NormalDir(point).Mult(-1)
			u := direction.Cross(normal).Normalize().Mult(geometry.Float(rand.NormFloat64() * 0.3))
			v := direction.Cross(u).Normalize().Mult(geometry.Float(rand.NormFloat64() * 0.3))

			direction.X += u.X + v.X
			direction.Y += u.Y + v.Y
			direction.Z += u.Z + v.Z
			ray := geometry.Ray{point, direction.Normalize()}

			if object, distance := ClosestIntersection(shapes, ray); object == shape {
				incomingLight.AddInPlace(object.Emission.Mult(direction.Dot(normal) / (1 + distance)))
			}
		}
	}
	return incomingLight
}
Example #30
0
// Generate a random 64-bit bitstring and pad to 80 bits with zeros.
func (bs BitString) Generate(rand *rand.Rand, size int) reflect.Value {
	var bits string
	for i := 0; i < 64; i++ {
		if rand.NormFloat64() > 0.5 {
			bits += "1"
		} else {
			bits += "0"
		}
	}

	bits += strings.Repeat("0", 16)

	return reflect.ValueOf(BitString(bits))
}