File: galaxy_example_test.go

package info (click to toggle)
golang-gonum-v1-gonum 0.15.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,792 kB
  • sloc: asm: 6,252; fortran: 5,271; sh: 377; ruby: 211; makefile: 98
file content (83 lines) | stat: -rw-r--r-- 1,820 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright ©2019 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package barneshut_test

import (
	"log"

	"golang.org/x/exp/rand"

	"gonum.org/v1/gonum/spatial/barneshut"
	"gonum.org/v1/gonum/spatial/r2"
)

type mass struct {
	d r2.Vec
	v r2.Vec
	m float64
}

func (m *mass) Coord2() r2.Vec { return m.d }
func (m *mass) Mass() float64  { return m.m }
func (m *mass) move(f r2.Vec) {
	m.v = r2.Add(m.v, r2.Scale(1/m.m, f))
	m.d = r2.Add(m.d, m.v)
}

func Example_galaxy() {
	rnd := rand.New(rand.NewSource(1))

	// Make 1000 stars in random locations.
	stars := make([]*mass, 1000)
	p := make([]barneshut.Particle2, len(stars))
	for i := range stars {
		s := &mass{
			d: r2.Vec{
				X: 100 * rnd.Float64(),
				Y: 100 * rnd.Float64(),
			},
			v: r2.Vec{
				X: rnd.NormFloat64(),
				Y: rnd.NormFloat64(),
			},
			m: 10 * rnd.Float64(),
		}
		stars[i] = s
		p[i] = s
	}
	vectors := make([]r2.Vec, len(stars))

	// Make a plane to calculate approximate forces
	plane := barneshut.Plane{Particles: p}

	// Run a simulation for 100 updates.
	for i := 0; i < 1000; i++ {
		// Build the data structure. For small systems
		// this step may be omitted and ForceOn will
		// perform the naive quadratic calculation
		// without building the data structure.
		err := plane.Reset()
		if err != nil {
			log.Fatal(err)
		}

		// Calculate the force vectors using the theta
		// parameter...
		const theta = 0.5
		// and an imaginary gravitational constant.
		const G = 10
		for j, s := range stars {
			vectors[j] = r2.Scale(G, plane.ForceOn(s, theta, barneshut.Gravity2))
		}

		// Update positions.
		for j, s := range stars {
			s.move(vectors[j])
		}

		// Rendering stars is left as an exercise for
		// the reader.
	}
}