-
Notifications
You must be signed in to change notification settings - Fork 0
/
euler.py
169 lines (130 loc) · 3.96 KB
/
euler.py
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
import sys
import time
import math
import numpy as np
G = 1.0
class Body:
def __init__(self, r, v, m):
self.r = r
self.v = v
self.m = m
def __repr__(self):
return f"{self.r}:{self.v}:{self.m}"
def load(fn):
bodies = []
with open(fn, "rb") as f:
G = float(f.readline())
nbodies = int(f.readline())
for i in range(nbodies):
v = f.readline().split()
rad = np.array([
float(v[1]),
float(v[2]),
float(v[3])
], dtype=float)
vel = np.array([
float(v[4]),
float(v[5]),
float(v[6])
], dtype=float)
m = float(v[7])
b = Body(rad, vel, m)
bodies.append(b)
return bodies
class Euler:
def __init__(self, bodies, dt):
self.bodies = bodies
self.positions = np.array([b.r for b in self.bodies])
self.velocities = np.array([b.v for b in self.bodies])
self.masses = np.array([b.m for b in self.bodies])
self.dt = dt
def update(self):
# Расчет разностей координат для каждой пары тел
r_ij = self.positions[np.newaxis, :, :] - self.positions[:, np.newaxis, :]
R_ij = np.linalg.norm(r_ij, axis=2) # Евклидово расстояние между парами тел
np.fill_diagonal(R_ij, np.inf)
# eps = 0.1
# R_ij[R_ij < eps] = eps # Замена слишком малых расстояний на eps
R_ij = R_ij[:, :, np.newaxis]
# Вычисление сил
F_ij = G * self.masses[:, np.newaxis, np.newaxis] * self.masses[np.newaxis, :, np.newaxis] * r_ij / (R_ij**3)
# Сумма всех сил, действующих на каждое тело
F_total = np.sum(F_ij, axis=1) # Сумма по второй оси
# Обновление скоростей и позиций
accelerations = F_total / self.masses[:, np.newaxis] # Ускорения
self.velocities += self.dt * accelerations # Обновление скоростей
self.positions += self.dt * self.velocities # Обновление позиций
def kepler(dt):
bodies = []
G = 1
MM = 1e5
bodies.append(
Body(
np.array([0.0, 0.0, 0.0, 0.0], dtype=float),
np.array([0.0, 0.0, 0.0, 0.0], dtype=float),
MM
)
)
bodies.append(
Body(
np.array([0.0, 1.0, 0.0, 0.0], dtype=float),
np.array([math.sqrt(G * MM), 0.0, 0.0, 0.0], dtype=float),
1
)
)
max_err = 0
euler = Euler(bodies, dt)
T = 0.1
t = 0
while t < T:
euler.update()
r = np.linalg.norm(euler.positions[1])
err = math.fabs(r - 1.0)
if max_err < err:
max_err = err
t += dt
return max_err
def test():
print("Test")
err1 = kepler(0.001)
err2 = kepler(0.0001)
err3 = kepler(0.00001)
print(f"{err1} {err2} {err3}")
print(f"{err1 / err2} {err1 / err3}")
print(err1 < 0.3)
print(err2 < 0.02)
print(err3 < 0.002)
def bench(fn):
dt = 0.0001
bodies = load(fn)
euler = Euler(bodies, dt)
t = 0.0
t0 = time.time()
while t < 0.01: # TODO: incr t to 0.1
euler.update()
t += dt
t1 = time.time()
print(f"Elapsed: {t1-t0}")
def main():
test_mode = False
bench_mode = False
fn = ""
i = 1
nargs = len(sys.argv)
while i < nargs:
if i < nargs - 1 and sys.argv[i] == "--input":
i = i + 1
fn = sys.argv[i]
elif sys.argv[i] == "--test":
test_mode = True
elif sys.argv[i] == "--bench":
bench_mode = True
i = i + 1
if test_mode:
test()
return
if bench_mode:
bench(fn)
return
if __name__ == "__main__":
main()