about summary refs log tree commit diff
path: root/quadtree.go
blob: 5ba232bdce8b199af5f61191e94509e259f534a7 (plain)
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
package structs

import (
	"fmt"
	"io/ioutil"
	"log"
	"math"
	"os"
	"os/exec"
)

type Node struct {
	Boundry      BoundingBox // Spatial outreach of the quadtree
	CenterOfMass Vec2        // Center of mass of the cell
	TotalMass    float64     // Total mass of all the stars in the cell
	Depth        int         // Depth of the cell in the tree

	Star Star2D // The actual star

	// NW, NE, SW, SE
	Subtrees [4]*Node // The child subtrees
}

// NewRoot returns a pointer to a node defined as a root node. It taks the with of the BoundingBox as an argument
// resulting in a node that should (in theory) fit the whole galaxy if defined correctly.
func NewRoot(BoundingBoxWidth float64) *Node {
	return &Node{
		Boundry: BoundingBox{
			Center: Vec2{0, 0},
			Width:  BoundingBoxWidth,
		},
		CenterOfMass: Vec2{},
		TotalMass:    0,
		Depth:        0,
		Star:         Star2D{},
		Subtrees:     [4]*Node{},
	}
}

// Create a new new node using the given bounding box
func NewNode(bounadry BoundingBox) *Node {
	return &Node{Boundry: bounadry}
}

// Subdivide the tree
func (n *Node) Subdivide() {

	// define new values defining the new BoundaryBoxes
	newBoundaryWidth := n.Boundry.Width / 2
	newBoundaryPosX := n.Boundry.Center.X + (newBoundaryWidth / 2)
	newBoundaryPosY := n.Boundry.Center.Y + (newBoundaryWidth / 2)
	newBoundaryNegX := n.Boundry.Center.X - (newBoundaryWidth / 2)
	newBoundaryNegY := n.Boundry.Center.Y - (newBoundaryWidth / 2)

	// define the new Subtrees
	n.Subtrees[0] = NewNode(BoundingBox{Vec2{newBoundaryNegX, newBoundaryPosY}, newBoundaryWidth})
	n.Subtrees[1] = NewNode(BoundingBox{Vec2{newBoundaryPosX, newBoundaryPosY}, newBoundaryWidth})
	n.Subtrees[2] = NewNode(BoundingBox{Vec2{newBoundaryNegX, newBoundaryNegY}, newBoundaryWidth})
	n.Subtrees[3] = NewNode(BoundingBox{Vec2{newBoundaryPosX, newBoundaryNegY}, newBoundaryWidth})
}

// Insert inserts the given star into the Node or the tree it is called on
func (n *Node) Insert(star Star2D) error {

	// if the subtree does not contain a node, insert the star
	if n.Star == (Star2D{}) {

		// if a subtree is present, insert the star into that subtree
		if n.Subtrees != [4]*Node{} {
			fmt.Printf("[ A ]\n")
			QuadrantBlocking := star.getRelativePositionInt(n.Boundry)
			err := n.Subtrees[QuadrantBlocking].Insert(star)
			if err != nil {
				fmt.Println(err)
			}

			// directly insert the star into the node
		} else {
			fmt.Printf("[ B ] (Direct insert if (%f, %f)\n)", star.C.X, star.C.Y)
			n.Star = star
			return nil
		}

		// Move the star blocking the slot into it's subtree using a recursive call on this function
		// and add the star to the slot
	} else {

		// if the node does not all ready have child nodes, subdivide it
		if n.Subtrees == ([4]*Node{}) {
			fmt.Printf("[ C ] Sudivision\n")
			n.Subdivide()
		}

		// Insert the blocking star into it's subtree
		QuadrantBlocking := n.Star.getRelativePositionInt(n.Boundry)
		err := n.Subtrees[QuadrantBlocking].Insert(n.Star)
		if err != nil {
			fmt.Println(err)
		}
		n.Star = Star2D{}

		// Insert the blocking star into it's subtree
		QuadrantBlockingNew := star.getRelativePositionInt(n.Boundry)
		err = n.Subtrees[QuadrantBlockingNew].Insert(star)
		if err != nil {
			fmt.Println(err)
		}
		star = Star2D{}
	}

	// fmt.Println("Done inserting %v, the tree looks like this: %v", star, n)
	return nil
}

// GenForestTree draws the subtree it is called on. If there is a star inside of the root node, the node is drawn
// The method returns a string depicting the tree in latex forest structure
func (n Node) GenForestTree(node *Node) string {

	returnstring := "["

	// if there is a star in the node, add the stars coordinates to the return string
	if n.Star != (Star2D{}) {
		returnstring += fmt.Sprintf("%.0f %.0f", n.Star.C.X, n.Star.C.Y)
	}

	// iterate over all the subtrees and call the GenForestTree method on the subtrees containing children
	for i := 0; i < len(n.Subtrees); i++ {
		if n.Subtrees[i] != nil {
			returnstring += n.Subtrees[i].GenForestTree(n.Subtrees[i])
		} else {
			returnstring += "[]"
		}
	}

	// Post-tree brace
	returnstring += "]"

	return returnstring
}

// DrawTreeLaTeX writes the tree it is called on to a texfile defined by the outpath parameter and
// calls lualatex to build the tex-file
func (n Node) DrawTreeLaTeX(outpath string) {
	// define all the stuff in front of the tree
	preamble := `\documentclass{article}
\usepackage{tikz}
\usepackage{forest}
\usepackage{adjustbox}

\begin{document}

\begin{adjustbox}{max size={\textwidth}{\textheight}}
\begin{forest}
for tree={,draw, s sep+=0.25em}
`

	// define all the stuff after the tree
	poststring := `
\end{forest}
\end{adjustbox}

\end{document}
`

	// combine all the strings
	data := []byte(fmt.Sprintf("%s%s%s", preamble, n.GenForestTree(&n), poststring))

	// write them to a file
	writeerr := ioutil.WriteFile(outpath, data, 0644)
	if writeerr != nil {
		panic(writeerr)
	}

	// build the pdf
	cmd := exec.Command("lualatex", outpath)
	runerr := cmd.Run()
	if runerr != nil {
		panic(runerr)
	}
}

// GetAllStars returns all the stars in the tree it is called on in an array
func (n Node) GetAllStars() []Star2D {

	// define a list to store the stars
	listOfNodes := []Star2D{}

	// if there is a star in the node, append the star to the list
	if n.Star != (Star2D{}) {
		listOfNodes = append(listOfNodes, n.Star)
	}

	// iterate over all the subtrees
	for i := 0; i < len(n.Subtrees); i++ {
		if n.Subtrees[i] != nil {

			// insert all the stars from the subtrees into the list of nodes
			for _, star := range n.Subtrees[i].GetAllStars() {
				listOfNodes = append(listOfNodes, star)
			}
		}
	}

	return listOfNodes
}

// CalcCenterOfMass calculates the center of mass for every node in the tree
func (n *Node) calcCenterOfMass() Vec2 {

	nominatorX := 0.0
	denominatorX := 0.0

	nominatorY := 0.0
	denominatorY := 0.0

	// if the subtrees are not empty
	if n.Subtrees != ([4]*Node{}) {
		for _, star := range n.Subtrees {
			fmt.Println(star)
		}
		for i := 0; i < len(n.Subtrees); i++ {
			nominatorX += n.Subtrees[i].calcCenterOfMass().X * n.Subtrees[i].TotalMass
			denominatorX += n.Subtrees[i].TotalMass

			nominatorY += n.Subtrees[i].calcCenterOfMass().Y * n.Subtrees[i].TotalMass
			denominatorY += n.Subtrees[i].TotalMass
		}
	}

	if n.Star != (Star2D{}) {
		n.CenterOfMass = n.Star.C
		fmt.Println(n.Star)
	}

	comX := nominatorX / denominatorX
	comY := nominatorY / denominatorY
	fmt.Printf("nomX: %f \t denomX: %f\n", nominatorX, denominatorX)
	fmt.Printf("nomY: %f \t denomY: %f\n", nominatorY, denominatorY)

	n.CenterOfMass = Vec2{comX, comY}

	return n.CenterOfMass
}

func (n *Node) CalcCenterOfMass() Vec2 {
	tree := n.GenForestTree(n)
	fmt.Println(tree)
	centerOfMass := n.calcCenterOfMass()
	return centerOfMass
}

// CalcTotalMass calculates the total mass for every node in the tree
func (n *Node) CalcTotalMass() float64 {

	// if the subtrees are not empty
	if n.Subtrees != ([4]*Node{}) {
		for i := 0; i < len(n.Subtrees); i++ {
			n.TotalMass += n.Subtrees[i].CalcTotalMass()
		}
	}

	// if the star in the subtree is not empty
	if n.Star != (Star2D{}) {
		n.TotalMass += n.Star.M
	}

	return n.TotalMass
}

// CalcAllForces calculates the force acting in between the given star and all the other stars using the given theta.
// It gets all the other stars from the root node it is called on
func (n Node) CalcAllForces(star Star2D, theta float64) Vec2 {
	log.SetOutput(os.Stderr)

	// initialize a variable storing the overall force
	var localForce Vec2 = Vec2{}
	log.Printf("[CalcAllforces] Boundary Width: %f", n.Boundry.Width)

	// calculate the local theta
	var tmpX float64 = math.Pow(star.C.X-n.Star.C.X, 2)
	var tmpY float64 = math.Pow(star.C.Y-n.Star.C.Y, 2)
	var distance float64 = math.Sqrt(tmpX + tmpY)

	log.Printf("[CalcAllforces] n.Boundary.Width=%f", n.Boundry.Width)
	log.Printf("[CalcAllforces] distance=%f", distance)
	var localtheta float64 = n.Boundry.Width / distance
	log.Printf("[CalcAllforces] localtheta=%f", localtheta)

	// if the subtree is not empty...
	if n.Subtrees != ([4]*Node{}) {

		// if the local theta is smaller than the given theta threshold...
		if localtheta < theta {
			log.Printf("[CalcAllforces] not recursing deeper ++++++++++++++++++++++++ ")
			// don't recurse further into the tree
			// calculate the forces in between the star and the node

			// define a new star using the center of mass of the new stars
			nodeStar := Star2D{
				C: Vec2{
					X: n.CenterOfMass.X,
					Y: n.CenterOfMass.Y,
				},
				V: Vec2{
					X: 0,
					Y: 0,
				},
				M: n.TotalMass,
			}

			// if the star is not equal to the node star, calculate the forces
			if star != nodeStar {
				log.Printf("[CalcAllforces] (%v) < +++++++ > (%v)\n", star, nodeStar)

				// calculate the force on the individual star
				force := CalcForce(star, nodeStar)
				localForce.X += force.X
				localForce.Y += force.Y
			}

			// the local theta is bigger than the given theta -> recurse deeper
		} else {
			log.Printf("[CalcAllforces] recursing deeper ----------------------------")

			// iterate over all the subtrees
			for i := 0; i < len(n.Subtrees); i++ {
				force := n.Subtrees[i].CalcAllForces(star, theta)
				localForce.X += force.X
				localForce.Y += force.Y
			}
		}

		// if the subtree is empty
	} else {

		// make sure the star in the subtree is not empty
		if n.Star != (Star2D{}) {

			// if the star is not the star on which the forces should be calculated
			if star != n.Star {

				log.Printf("[CalcAllforces] not recursing deeper ====================== ")
				log.Printf("[CalcAllforces] (%v) < ------- > (%v)\n", star, n.Star)

				// calculate the forces acting on the star
				force := CalcForce(star, n.Star)
				localForce.X += force.X
				localForce.Y += force.Y
			}
		}
	}

	log.Printf("[CalcAllforces] localforce: %v +-+-+-+-+-+-+-+-+-+- ", localForce)

	// return the overall acting force
	return localForce
}

// CalcForce calculates the force exerted on s1 by s2 and returns a vector representing that force
func CalcForce(s1 Star2D, s2 Star2D) Vec2 {
	G := 6.6726 * math.Pow(10, -11)

	// calculate the force acting
	var combinedMass float64 = s1.M * s2.M
	var distance float64 = math.Sqrt(math.Pow(math.Abs(s1.C.X-s2.C.X), 2) + math.Pow(math.Abs(s1.C.Y-s2.C.Y), 2))
	fmt.Printf("\t- combinedMass: %f\n", combinedMass)
	fmt.Printf("\t- distance: %f\n", distance)
	fmt.Printf("\t- distance squared: %f\n", math.Pow(distance, 2))
	fmt.Printf("\t- combinedMass / distance: %f\n", combinedMass/math.Pow(distance, 2))

	var scalar float64 = G * ((combinedMass) / math.Pow(distance, 2))
	fmt.Printf("\t- Scalar: %f\n", scalar)

	// define a unit vector pointing from s1 to s2
	var vector Vec2 = Vec2{s2.C.X - s1.C.X, s2.C.Y - s1.C.Y}
	var UnitVector Vec2 = Vec2{vector.X / distance, vector.Y / distance}
	fmt.Printf("\t- Vector: %v\n", vector)
	fmt.Printf("\t- UnitVector: %v\n", UnitVector)

	// multiply the vector with the force to get a vector representing the force acting
	var force Vec2 = UnitVector.Multiply(scalar)
	fmt.Printf("\t- force: %v\n", force)

	// return the force exerted on s1 by s2
	return force
}