Example #1
0
func main() {
	rand.Seed(time.Nanoseconds())
	m := ga.NewGAGaussianMutator(0.4, 0)
	b := new(ga.GA2PointBreeder)
	s := ga.NewGATournamentSelector(0.2, 5)

	i := new(ga.GARandomInitializer)
	gao := ga.NewGA(i, s, m, b)
	gao.PMutate = 0.5 //Chance of mutation
	gao.PBreed = 0.2  //Chance of breeding

	fmt.Printf("%s\n", gao)
	genome := ga.NewFloatGenome(make([]float64, 20), rosenbrock, 1, -1)
	gao.Init(100, genome) //Total population
	stopFunc := func(bestGenome ga.GAGenome) bool {
		return bestGenome.Score() <= 1e-2
	}
	generations := ga.OptimizeBest(gao, stopFunc, 1000) // Run genetic algorithm for 20 generations.
	/**
	for {
		ga.OptimizeNgenerations(gao, 100) // Run genetic algorithm for 20 generations.
		best := gao.Best().(*ga.GAFloatGenome)
		fmt.Printf("%s = %f\n", best, best.Score())
	}
	*/
	fmt.Printf("%s = %f\n", gao.Best(), gao.Best().Score())
	fmt.Printf("Number of generations = %d\n", generations)
	fmt.Printf("Calls to score = %d\n", scores)
}
Example #2
0
func main() {
	context, _ := zmq.NewContext()
	socket, _ := context.NewSocket(zmq.PUB)
	defer context.Close()
	defer socket.Close()
	socket.Bind("tcp://*:5556")
	socket.Bind("ipc://weather.ipc")

	// Seed the random number generator
	rand.Seed(time.Nanoseconds())

	// loop for a while aparently
	for {

		//  make values that will fool the boss
		zipcode := rand.Intn(100000)
		temperature := rand.Intn(215) - 80
		relhumidity := rand.Intn(50) + 10

		msg := fmt.Sprintf("%d %d %d", zipcode, temperature, relhumidity)

		//  Send message to all subscribers
		socket.Send([]byte(msg), 0)
	}
}
Example #3
0
func main() {
	rand.Seed(time.Nanoseconds())

	param := ga.GAParameter{
		Initializer: new(ga.GARandomInitializer),
		Selector:    ga.NewGATournamentSelector(0.2, 5),
		Breeder:     new(ga.GA2PointBreeder),
		Mutator:     ga.NewGAGaussianMutator(0.4, 0),
		PMutate:     0.5,
		PBreed:      0.2}

	// Second parameter is the number of Optimize Processes.
	gao := ga.NewGAParallel(param, 4)

	genome := ga.NewFloatGenome(make([]float64, 20), rosenbrock, 1, -1)

	gao.Init(100, genome) //Total population

	gao.OptimizeUntil(func(best ga.GAGenome) bool {
		return best.Score() < 1e-3
	})

	best := gao.Best().(*ga.GAFloatGenome)
	fmt.Printf("%s = %f\n", best, best.Score())
	fmt.Printf("Calls to score = %d\n", scores)
}
Example #4
0
func main() {
	rand.Seed(time.Seconds())
	nums := rand.Perm(MAX)[:COUNT]
	for _, val := range nums {
		fmt.Println(val)
	}
}
Example #5
0
func main() {
	rand.Seed(time.Nanoseconds())

	m := ga.NewMultiMutator()
	msh := new(ga.GAShiftMutator)
	msw := new(ga.GASwitchMutator)
	m.Add(msh)
	m.Add(msw)

	param := ga.GAParameter{
		Initializer: new(ga.GARandomInitializer),
		Selector:    ga.NewGATournamentSelector(0.7, 5),
		Breeder:     new(ga.GA2PointBreeder),
		Mutator:     m,
		PMutate:     0.2,
		PBreed:      0.7}

	gao := ga.NewGA(param)

	genome := ga.NewOrderedIntGenome([]int{10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, score)

	gao.Init(200, genome) //Total population

	gao.Optimize(20) // Run genetic algorithm for 20 generations.
	gao.PrintTop(10)
	fmt.Printf("Calls to score = %d\n", scores)
	fmt.Printf("%s\n", m.Stats())
}
Example #6
0
func main() {
	duplicate := 0
	unknown := 0

	rand.Seed(time.Nanoseconds())

	m := hashmap.New()

	for i := 0; i < N; i++ {
		r := rand.Intn(S)
		if m.Has(Integer(r)) {
			duplicate++
		} else {
			m.Insert(Integer(r), true)
		}
	}

	for i := 0; i < N; i++ {
		r := rand.Intn(S)
		if m.Has(Integer(r)) {
			m.Remove(Integer(r))
		} else {
			unknown++
		}
	}

	fmt.Printf("%d insertions, %d duplicates\n", N, duplicate)
	fmt.Printf("%d removals, %d unknown\n", N, unknown)
	fmt.Printf("%d left\n", m.Len())
}
Example #7
0
func main() {
	rand.Seed(time.Nanoseconds())
	//m := new(ga.GASwitchMutator);
	m := ga.NewMultiMutator()
	msh := new(ga.GAShiftMutator)
	msw := new(ga.GASwitchMutator)
	m.Add(msh)
	m.Add(msw)
	b := new(ga.GA2PointBreeder)

	s := new(ga.GATournamentSelector)
	s.Contestants = 5 //Contestants in Tournament
	s.PElite = 0.7    //Chance of best contestant winning, chance of next is PElite^2 and so on.

	i := new(ga.GARandomInitializer)
	gao := ga.NewGA(i, s, m, b)
	gao.PMutate = 0.2 //Chance of mutation
	gao.PBreed = 0.2  //Chance of breeding

	fmt.Printf("%s\n", gao)
	genome := ga.NewOrderedIntGenome([]int{10, 11, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, score)
	gao.Init(200, genome) //Total population

	ga.OptimizeNgenerations(gao, 20) // Run genetic algorithm for 20 generations.
	gao.PrintTop(10)
	fmt.Printf("Calls to score = %d\n", scores)
	fmt.Printf("%s\n", m.Stats())
}
Example #8
0
func Generate(m *Mchain, count int) string {
	rand.Seed(time.Nanoseconds())
	t := m.Beginnings[rand.Intn(len(m.Beginnings)-1)]
	first, second := t.First, t.Second

	ret := make([]string, count, count)
	ret[0] = t.First
	ret[1] = t.Second

	var word string
	for i := 2; i < count; i++ {
		t := &triple{first, second, "", nil}
		word = m.getThird(t)
		first, second = second, word
		ret[i] = word
		if word == "" {
			return strings.Join(ret, " ")
		}
		if char := word[len(word)-1]; char == '.' {
			if i+WORDS_IN_SENTANCE >= count {
				break
			}
		}
	}
	return strings.Join(ret, " ")
}
Example #9
0
func setEpidemic(index int) {
	for i := 0; i < 4; i++ {
		for {
			rand.Seed(time.Nanoseconds())
			diseasenum := rand.Intn(len(diseases))
			curnum := 0
			found := false
			var diseasename string
			for diseasename, _ = range diseases {
				if curnum == diseasenum {
					for _, dname := range epidemics {
						if diseasename == dname {
							found = true
						}
					}
					break
				}
				curnum++
			}
			if !found {
				epidemics[index] = diseasename
				return
			}
		}
	}
}
Example #10
0
func main() {
	flag.Parse()
	if !CheckFlagsValid() {
		fmt.Printf("Stop training due to invalid flag setting.\n")
		return
	}

	rand.Seed(time.Nanoseconds())

	corpus, err := lda.LoadCorpus(*corpus_file, 2)
	if err != nil {
		fmt.Printf("Error in loading: " + *corpus_file + ", due to " + err.String())
		return
	}

	model := lda.CreateModel(*num_topics, corpus)
	accum_model := lda.NewModel(*num_topics)
	sampler := lda.NewSampler(*topic_prior, *word_prior, model, accum_model)

	for iter := 0; iter < *burn_in_iterations+*accumulate_iterations; iter++ {
		fmt.Printf("Iteration %d ... ", iter)
		if *compute_loglikelihood {
			fmt.Printf("log-likelihood: %f\n", sampler.CorpusLogLikelihood(corpus))
		} else {
			fmt.Printf("\n")
		}
		sampler.CorpusGibbsSampling(corpus, true, iter < *burn_in_iterations)
	}

	if err := accum_model.SaveModel(*model_file); err != nil {
		fmt.Printf("Cannot save model due to " + err.String())
	}

	return
}
Example #11
0
func makeVector(size int, shape string) vector.Vector {

	var v vector.Vector

	switch shape {

	case "xor":
		for i := 0; i < size; i++ {
			v.Push(&record{0xff & (i ^ 0xab), i})
		}

	case "sorted":
		for i := 0; i < size; i++ {
			v.Push(&record{i, i})
		}

	case "revsorted":
		for i := 0; i < size; i++ {
			v.Push(&record{size - i, i})
		}

	case "random":
		rand.Seed(1)

		for i := 0; i < size; i++ {
			v.Push(&record{rand.Int(), i})
		}

	default:
		panic(shape)
	}

	return v
}
Example #12
0
func main() {
	var ret int
	rand.Seed(12345)

	master := flag.String("m", "", "specify a master!")
	flag.Parse()

	client.Initialize(*master)

	//create file
	fd := client.Open("/newfile.txt", client.O_RDWR|client.O_CREATE)
	if fd < 0 {
		panic("could not create new file")
	}
	//close
	ret = client.Close(fd)
	if ret != client.WIN {
		panic("close failed")
	}

	if client.Delete("/newfile.txt") != 0 {
		panic("Delete failed")
	}

	fd = client.Open("/newfile.txt", client.O_RDWR)
	if fd != -1 {
		panic("open succeeded on deleted file")
	}

	fmt.Printf("\n{{{{{pass}}}}}\n")
	os.Exit(0)
}
Example #13
0
func main() {
	q, q2 := new(queue), new(queue)
	q.qs, q2.qs = new(stat), new(stat)
	//	q.in, q.out = make(chan float), make(chan float);
	repeat := 10000
	rand.Seed(2)
	in1, in2, in3, out := make(chan float), make(chan float), make(chan float), make(chan float)
	//	middle1 := make(chan float);
	middle2 := make(chan float)
	middle3 := make(chan float)
	out2 := make(chan float, 100)
	out3, out4 := make(chan float, 100), make(chan float)
	end := make(chan bool)
	generate(in1, repeat)
	generate(in2, repeat)
	generate(in3, repeat)
	combine2(middle3, []<-chan float{in1, in2, in3}, repeat)
	double([]chan<- float{middle2, out2}, middle3, 3*repeat)
	go q.pass(out, middle2, 3*repeat)
	double([]chan<- float{out3, out4}, out, 3*repeat)
	go q2.qs.delay_count(end, out2, out3, 3*repeat)
	for j := 0; j < 3*repeat; j++ {
		<-out4 /* <-out; fmt.Printf("%f\n", <- out)*/
	}
	<-end
	ave := q.qs.interval_sum / float(q.qs.out_num)
	fmt.Printf("Ave %f\nVar %f\n", ave, q.qs.interval_sqsum/float(q.qs.out_num)-ave*ave)
	fmt.Printf("Queued Num Ave %d\n", float(q2.qs.queued_num)/float(q2.qs.out_num))
}
Example #14
0
func main() {
	deposit := []Element{
		{10, 5},
		{9, 7},
		{8, 3},
		{7, 1},
		{6, 5},
		{5, 2},
		{6, 3},
		{11, 9}}

	args := flag.Args()
	rand.Seed(time.Nanoseconds() % 1e9)
	if len(args) != 1 {
		fmt.Println("Do you miss to specify value for the space in the sack?")
		return
	}

	for _, x := range deposit {
		fmt.Println(x)
	}

	fmt.Println("============================")
	target, _ := strconv.Atoi(args[0])
	tmp := genetic_choose(deposit[0:], target)

	fmt.Println(len(tmp))
	for _, x := range tmp {
		fmt.Println(x)
	}
}
Example #15
0
func main() {
	if len(os.Args) <= 3 {
		log.Fatal("usage: portforward local remote1 remote2 remote3 ...")
	}
	localAddrString := os.Args[1]
	remoteAddrStrings := os.Args[2:]
	localAddr, err := net.ResolveTCPAddr("tcp", localAddrString)
	if localAddr == nil {
		log.Fatalf("net.ResolveTCPAddr failed: %s", err)
	}
	local, err := net.ListenTCP("tcp", localAddr)
	if local == nil {
		log.Fatalf("portforward: %s", err)
	}
	log.Printf("portforward listen on %s", localAddr)

	rand.Seed(time.Nanoseconds())
	for {
		conn, err := local.Accept()
		if conn == nil {
			log.Fatalf("accept failed: %s", err)
		}
		go forward(conn, remoteAddrStrings)
	}
}
Example #16
0
func main() {
	chunkCount := 3
	rand.Seed(12345)

	master := flag.String("m", "", "specify a master!")
	flag.Parse()

	client.Initialize(*master)

	fd := client.Open("/newfile.txt", client.O_RDWR|client.O_CREATE)
	if fd < 0 {
		panic("could not create new file")
	}

	s := ""
	for i := 0; i < chunkCount*sfs.CHUNK_SIZE; i++ {
		var c [1]byte
		c[0] = uint8(65 + rand.Intn(25))
		s = s + string(c[:])
	}

	fmt.Printf("String: %s\n", s)
	buf := []byte(s)

	ret := client.Write(fd, buf)
	if ret != 0 {
		panic("write failed")
	}

	//read data
	for i := 0; i < chunkCount; i++ {
		ret = client.Seek(fd, i*sfs.CHUNK_SIZE, client.SEEK_SET)
		if ret != i*sfs.CHUNK_SIZE {
			panic("seek failed")
		}

		data, err := client.Read(fd, sfs.CHUNK_SIZE)
		if err != 0 {
			panic("read failed")
		}

		s_ret := string(data)
		fmt.Printf("Got back: '%s'\n", s_ret)

		if s_ret != s[i*sfs.CHUNK_SIZE:(i+1)*sfs.CHUNK_SIZE] {
			fmt.Printf("Got %s but expected %s\n", s_ret, s[i*sfs.CHUNK_SIZE:(i+1)*sfs.CHUNK_SIZE])
			panic("strings differ")
		}
	}

	//close
	ret = client.Close(fd)
	if ret != client.WIN {
		panic("close failed")
	}

	fmt.Printf("\n{{{{{pass}}}}}\n")
	os.Exit(0)
}
Example #17
0
func init() {
	rand.Seed(time.Nanoseconds())

	// TODO: This should end up in a configuration file
	schema = &grapher.Schema{FileSchemas: map[string]*grapher.FileSchema{
		"application/x-lightwave-book": &grapher.FileSchema{EntitySchemas: map[string]*grapher.EntitySchema{
			"application/x-lightwave-entity-chapter": &grapher.EntitySchema{FieldSchemas: map[string]*grapher.FieldSchema{
				"after": &grapher.FieldSchema{Type: grapher.TypeEntityBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone},
				"title": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest},
				"color": &grapher.FieldSchema{Type: grapher.TypeInt64, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest}}},
			"application/x-lightwave-entity-page": &grapher.EntitySchema{FieldSchemas: map[string]*grapher.FieldSchema{
				"after":   &grapher.FieldSchema{Type: grapher.TypeEntityBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone},
				"title":   &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest},
				"chapter": &grapher.FieldSchema{Type: grapher.TypeEntityBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone},
				"page":    &grapher.FieldSchema{Type: grapher.TypePermaBlobRef, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone}}}}},
		"application/x-lightwave-page": &grapher.FileSchema{EntitySchemas: map[string]*grapher.EntitySchema{
			"application/x-lightwave-entity-content": &grapher.EntitySchema{FieldSchemas: map[string]*grapher.FieldSchema{
				"layout":   &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationNone},
				"style":    &grapher.FieldSchema{Type: grapher.TypeMap, ElementType: grapher.TypeNone, Transformation: grapher.TransformationMerge},
				"cssclass": &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationLatest},
				"text":     &grapher.FieldSchema{Type: grapher.TypeString, ElementType: grapher.TypeNone, Transformation: grapher.TransformationMerge}}}}}}}

	frontPageTmpl = template.New(nil)
	frontPageTmpl.SetDelims("{{", "}}")
	if err := frontPageTmpl.ParseFile("notebook.html"); err != nil {
		frontPageTmplErr = fmt.Errorf("tmpl.ParseFile failed: %v", err)
		return
	}

	appLoginPageTmpl = template.New(nil)
	appLoginPageTmpl.SetDelims("{{", "}}")
	if err := appLoginPageTmpl.ParseFile("applogin.html"); err != nil {
		appLoginPageTmplErr = fmt.Errorf("tmpl.ParseFile failed: %v", err)
		return
	}

	http.HandleFunc("/", handleFrontPage)
	http.HandleFunc("/private/submit", handleSubmit)
	http.HandleFunc("/private/open", handleOpen)
	http.HandleFunc("/private/close", handleClose)
	http.HandleFunc("/private/listpermas", handleListPermas)
	http.HandleFunc("/private/listinbox", handleListInbox)
	http.HandleFunc("/private/listunread", handleListUnread)
	http.HandleFunc("/private/invitebymail", handleInviteByMail)
	http.HandleFunc("/private/inboxitem", handleInboxItem)
	http.HandleFunc("/private/markasread", handleMarkAsRead)
	http.HandleFunc("/private/markasarchived", handleMarkAsArchived)
	http.HandleFunc("/signup", handleSignup)
	http.HandleFunc("/logout", handleLogout)
	http.HandleFunc("/login", handleLogin)
	http.HandleFunc("/applogin", handleAppLogin)

	http.HandleFunc("/internal/notify", handleDelayedNotify)

	http.HandleFunc("/_ah/channel/connected/", handleConnect)
	http.HandleFunc("/_ah/channel/disconnected/", handleDisconnect)

	//  http.HandleFunc("/import", handleImport)
}
Example #18
0
//Start takes the initial parameters from stdin
func (s *State) Start() os.Error {

	for {
		line, err := stdin.ReadString('\n')
		if err != nil {
			return err
		}
		line = line[:len(line)-1] //remove the delimiter

		if line == "" {
			continue
		}

		if line == "ready" {
			break
		}

		words := strings.SplitN(line, " ", 2)
		if len(words) != 2 {
			panic(`"` + line + `"`)
			return os.NewError("invalid command format: " + line)
		}

		param, _ := strconv.Atoi(words[1])

		switch words[0] {
		case "loadtime":
			s.LoadTime = (int64)(param)
		case "turntime":
			s.TurnTime = (int64)(param)
		case "rows":
			s.Rows = param
		case "cols":
			s.Cols = param
		case "turns":
			s.Turns = param
		case "viewradius2":
			s.ViewRadius2 = param
		case "attackradius2":
			s.AttackRadius2 = param
		case "spawnradius2":
			s.SpawnRadius2 = param
		case "player_seed":
			param64, _ := strconv.Atoi64(words[1])
			rand.Seed(param64)
		case "turn":
			s.Turn = param

		default:
			Log.Panicf("unknown command: %s", line)
		}
	}

	// TODO this init stuff should probably go elsewhere
	s.CreateSquares()
	s.Stats = new(Stats)

	return nil
}
Example #19
0
func (ra *RmaxFSSSAgent) AgentMessage(message string) string {
	tokens := strings.Split(message, " ", -1)
	if tokens[0] == "seed" {
		seed, _ := strconv.Atoi64(tokens[1])
		rand.Seed(seed)
	}
	return ""
}
Example #20
0
func (this *Env) EnvMessage(message string) (reply string) {
	tokens := strings.Split(message, " ", -1)
	if tokens[0] == "seed" {
		seed, _ := strconv.Atoi64(tokens[1])
		rand.Seed(seed)
	}
	return ""
}
Example #21
0
func main() {
	fmt.Printf("GoStats Demo\n\n")

	rand.Seed(time.Nanoseconds())

	incrementalRegressionDemo()
	batchRegressionDemo()
}
Example #22
0
// Test rand module
func TestRandModule(t *testing.T) {
	rand.Seed(1234567890)
	var p int
	for i := 0; i < 10; i++ {
		p = rand.Int()
		println("Rand.Int() returns ", p)
	}
}
func main() {
	fmt.Printf("GoStats Demo\n\n")

	rand.Seed(time.Nanoseconds())

	incrementalDemo()
	batchDemo()
	normalDistributionDemo()
}
Example #24
0
func main() {
	rand.Seed(time.Nanoseconds() % 1e9)
	canvas.Start(width, height)
	canvas.Rect(0, 0, width, height, "fill:black")
	canvas.Gstyle("fill:none;stroke:pink")
	wave()
	canvas.Gend()
	canvas.End()
}
Example #25
0
func generate() *guess {
	rand.Seed(time.Nanoseconds())
	rnd := rand.Perm(10)
	tmp := new(guess)
	for i := range tmp.nmbr {
		tmp.nmbr[i] = rnd[i]
	}
	return tmp
}
Example #26
0
func (b *ConwaySim) Randomize(seed int64) {
	rand.Seed(seed)
	for i := 0; i < b.Rows; i++ {
		for j := 0; j < b.Cols; j++ {
			b.Cells[i][j] = (rand.Intn(2) == 0)
		}
	}
	return
}
Example #27
0
func main() {
	rand.Seed(time.Nanoseconds())
	worldhandler := new(WorldHandler)
	go worldhandler.Main()
	BServer.Setup()
	go BServer.Main()
	server := new(Listener)

	server.Main()
}
Example #28
0
func main() {
	rand.Seed(time.Nanoseconds() % 1e9)
	canvas.Start(width, height)
	canvas.Gstyle("fill:black;fill-opacity:0.5")
	canvas.Gtransform(fmt.Sprintf("translate(%d,%d)", width/2, height))
	seed1(12, radians(270), 0, 0)
	canvas.Gend()
	canvas.Gend()
	canvas.End()
}
Example #29
0
func RandStrings(N int) string {
	rand.Seed(time.Nanoseconds())

	buf := make([]byte, N+1)

	for i := 0; i < N; i++ {
		buf[i] = chars[rand.Intn(len(chars))]
	}
	return string(buf[0:N])
}
Example #30
0
func main() {
	rand.Seed(time.Nanoseconds())
	coef = ReadCoef()
	perc := CoefPercent(coef)
	fmt.Printf("%0.2f\t%0.2f\t%0.2f\t=%0.2f\n", perc[0], perc[1], perc[2], Sum(perc))

	init := GenPopulation(POPULATION)

	GenerationNext(init, 15, coef)
}