-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsim.py
More file actions
162 lines (137 loc) · 5.77 KB
/
sim.py
File metadata and controls
162 lines (137 loc) · 5.77 KB
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
from time import time
from student_pid_class import PID
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import argparse
import sys
import yaml
class VerticalDrone:
def __init__(self, axes, histaxes, pid_terms=[0, 0, 0, 0],
step_size=0, latency=0, drag_coeff=0, mass=460, sensor_noise=0):
self.axes = axes
self.histaxes = histaxes
self.x = 0
self.xsp = 0
self.g = -9.81
self.step_size = step_size / 100.
self.latency = latency
self.drag_coeff = drag_coeff
self.mass = mass
self.sensor_noise = sensor_noise / 100.
self.pid = PID(pid_terms[0], pid_terms[1], pid_terms[2], pid_terms[3])
self.start = time()
self.reset()
def init_animation(self):
self.linesp, = self.axes.plot([], [], 'x-', lw=2, c='red')
self.line, = self.axes.plot([], [], 'o-', lw=2)
self.history, = self.histaxes.plot([0], [0], '-', lw=2)
self.text = self.axes.text(0.05, 0.8, '', transform=self.axes.transAxes)
return self.linesp, self.line, self.text
def step(self, t):
dt = t - self.lastt # update time
self.lastt = t
self.error = self.setpoint - self.z # update error
self.interror += self.error
self.deriverror = self.lasterror - self.error
self.lasterror = self.error
noise = np.random.normal(scale=self.sensor_noise) if self.sensor_noise > 0 else 0
pwm = self.pid.step(self.error + noise, t) # calc forces
self.latent_thrusts.append(self.pwm_to_thrust(pwm))
thrust = self.latent_thrusts.pop(0)
drag = - np.sign(self.vz) * self.vz ** 2 * self.drag_coeff
# TODO - add ground effect
self.az = self.g + (drag + thrust) / self.mass # update drone
self.vz += + self.az * dt
self.z += self.vz * dt
if self.z <= 0:
self.z = 0
self.vz = 0
def animate(self, fig):
t = time() - self.start
self.step(t)
self.linesp.set_data([self.xsp], [self.setpoint])
self.line.set_data([self.x], [self.z])
self.text.set_text("z: %.3f\nvz: %.3f\naz: %.3f\nerror: %.3f\nintegrated error: %.3f\nderiv of error: %.3f" %
(self.z, self.vz, self.az, self.error, self.interror, self.deriverror))
self.times.append(t)
self.errors.append(self.error)
self.history.set_data(self.times, self.errors)
return self.linesp, self.line, self.text, self.history
def press(self, event):
if event.key == 'up':
self.setpoint += self.step_size
elif event.key == 'down':
if self.setpoint > 0: self.setpoint -= self.step_size
elif event.key == 'r':
self.reset()
elif event.key == 'q':
plt.close('all')
sys.exit(0)
def reset(self):
self.lastt = time() - self.start
self.times = []
self.errors = []
self.latent_thrusts = [1100] * self.latency
self.z = 0
self.vz = 0
self.az = 0
self.setpoint = 0
self.interror = 0
self.lasterror = 0
self.pid.reset()
def pwm_to_thrust(self, pwm):
max_thrust = 420 * 4 * 9.81 # max thrust in newtons
pwm_min = 1100.
pwm_max = 1900.
pwm = max(pwm_min, min(pwm, pwm_max)) # bound the pwm between 1100 and 1900
throttle_fraction = (pwm - pwm_min) / (pwm_max - pwm_min) # rescale between 0 and 1
return throttle_fraction * max_thrust
def main():
parser = argparse.ArgumentParser(description='''
This PID simulator simulates gravity acting on a hovering drone.
Drag, latency, and sensor noise are disabled by default, but can be
enabled with the flags below.
For a more realistic sim of a snap-setpoint takeoff to 30cm try
python sim.py -l 2 -n 0.5 -d 0.02 -s 30
''')
parser.add_argument('-s', '--step', type=int, default=1,
help='the size of a command step in centimeters')
parser.add_argument('-d', '--drag', type=float, default=0,
help='the amount of drag in the simulation')
parser.add_argument('-m', '--mass', type=int, default=460,
help='the mass of the simulated drone')
parser.add_argument('-n', '--noise', type=float, default=0)
parser.add_argument('-l', '--latency', type=int, default=0,
help='the number of timesteps of latency (in 40ms increments)')
args = parser.parse_args()
pid_terms = []
with open("z_pid.yaml", 'r') as stream:
try:
yaml_data = yaml.safe_load(stream)
print yaml_data
pid_terms = [yaml_data['Kp'], yaml_data['Ki'], yaml_data['Kd'], yaml_data['K']]
except yaml.YAMLError as exc:
print exc
print 'Failed to load PID terms! Exiting.'
sys.exit(1)
fig = plt.figure()
ax = fig.add_subplot(121, autoscale_on=False, xlim=(-10, 10), ylim=(-0, 1))
plt.title("1D Drone")
ax2 = fig.add_subplot(122, autoscale_on=False, xlim=(0, 100), ylim=(-1, 1))
plt.title("Error history")
sim = VerticalDrone(ax, ax2,
pid_terms=pid_terms,
step_size=max(args.step, 0),
latency=max(args.latency, 0),
drag_coeff=max(args.drag, 0),
mass=max(args.mass, 0),
sensor_noise=max(args.noise, 0))
fig.canvas.mpl_connect('key_press_event', sim.press)
ani = animation.FuncAnimation(fig, sim.animate,
interval=25, blit=True, init_func=sim.init_animation)
plt.show()
if __name__ == "__main__":
main()