Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/ZegesMenden/pyTVC
Browse files Browse the repository at this point in the history
  • Loading branch information
ZegesMenden committed May 5, 2022
2 parents 6090797 + de0505c commit 5f40290
Show file tree
Hide file tree
Showing 6 changed files with 233 additions and 167 deletions.
6 changes: 1 addition & 5 deletions pytvc/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
# external libraries
import numpy as np

# internal libraries
import pytvc.control
import pytvc.simulation
import pytvc.data
import pytvc.physics
from pytvc.physics import Vec3, Quat
from pytvc.physics import Vec3, Quat
31 changes: 17 additions & 14 deletions pytvc/control.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
from pytvc.physics import Vec3
import numpy as np


class PID:

"""PID controller class
for more information on the PID controller, see:
https://en.wikipedia.org/wiki/PID_controller"""

Expand All @@ -27,67 +28,67 @@ def __init__(self, Kp: float = 0.0, Ki: float = 0.0, Kd: float = 0.0, setpoint:
self.last_error: float = 0.0

self.output: float = 0.0

def update(self, input: float, dt: float = 1.0, input_derivitive: float = 0.0) -> None:
error = self.setpoint - input

if self.i > self.i_max:
self.i = self.i_max
elif self.i < -self.i_max:
self.i = -self.i_max

d = (error - self.last_error) / dt
self.last_error = error

if input_derivitive != 0.0:
d = input_derivitive
self.output = self.Kp * error + self.Ki * self.i + self.Kd * d

self.output = (self.Kp * error) + (self.Ki * self.i) + (self.Kd * d)

def reset(self) -> None:
self.i = 0.0
self.last_error = 0.0

def setSetpoint(self, setpoint: float) -> None:
"""setSetpoint sets the setpoint of the PID controller
Args:
setpoint (float): setpoint of the PID controller
"""
self.setpoint = setpoint

def setKp(self, Kp: float) -> None:
"""setKp sets the proportional gain of the PID controller
Args:
Kp (float): proportional gain of the PID controller
"""
self.Kp = Kp

def setKi(self, Ki: float) -> None:
"""setKi sets the integral gain of the PID controller
Args:
Ki (float): integral gain of the PID controller
"""
self.Ki = Ki

def setKd(self, Kd: float) -> None:
"""setKd sets the derivative gain of the PID controller
Args:
Kd (float): derivative gain of the PID controller
"""
self.Kd = Kd

def setImax(self, i_max: float) -> None:
"""setImax set the maximum integral value for the PID controller
Args:
i_max (float): maximum value for the integral
"""
self.i_max = i_max

def getOutput(self) -> float:
"""getOutput returns the output of the PID controller
Expand All @@ -96,6 +97,7 @@ def getOutput(self) -> float:
"""
return self.output


class torque_PID(PID):

def __init__(self, Kp: float = 0.0, Ki: float = 0.0, Kd: float = 0.0, setpoint: float = 0.0, i_max: float = 0.0, inertia: float = 1.0, lever_arm: float = 1.0) -> None:
Expand Down Expand Up @@ -127,13 +129,14 @@ def update(self, input: float, dt: float = 1.0, force: float = 1.0, input_derivi
if input_derivitive == 0.0:
super().update(input, dt)
else:
super().update(input, dt, input_derivitive)
super().update(input, dt, input_derivitive)

if force != 0.0:
calcval = super().getOutput() * self.inertia / force / self.lever_arm
calcval = ((super().getOutput() * self.inertia) / force) / self.lever_arm
print(calcval)
if abs(calcval) > 1.0:
self.output = 0.0
else:
self.output = np.arcsin(calcval)
else:
self.output = 0.0
self.output = 0.0
64 changes: 41 additions & 23 deletions pytvc/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,24 @@

# from pytvc.physics import Vec3, Quat


def progress_bar(n, maxn) -> str:

progress: str = ""
end = int(n/maxn*50)
for i in range(50):
if i > end:
progress += ' '
else:
progress += "="

for i in range(50):
if i > end:
progress += ' '
else:
if i+1 > end:
progress += '>'
else:
progress += "="

return (f"""[{progress}] Progress: {round((n/maxn)*100, 2)}%""")


class data_logger:
def __init__(self):
self.variables = 0
Expand Down Expand Up @@ -124,6 +132,7 @@ def get_var(self, variableName):
else:
raise IndexError("datapoint not initialized")


class data_visualizer:
def __init__(self):
self.allDataDescriptions = []
Expand Down Expand Up @@ -156,6 +165,7 @@ def graph_from_csv(self, datapoints, file_name):

return dataOut


class plotter:

"""Data visualization class"""
Expand Down Expand Up @@ -197,7 +207,7 @@ def create_2d_graph(self, graph_points: list, x_desc: str = "", y_desc: str = ""
else:
self.n_plots += 1
plt.figure(self.n_plots)

plot_points = self.viewer.graph_from_csv(graph_points, self.file_name)

for index, dataPoint in enumerate(plot_points):
Expand All @@ -208,7 +218,7 @@ def create_2d_graph(self, graph_points: list, x_desc: str = "", y_desc: str = ""
else:
plt.plot(plot_points[0], dataPoint)
if annotate:
plt.legend()
plt.legend()
plt.xlabel(x_desc)
plt.ylabel(y_desc)

Expand All @@ -230,7 +240,8 @@ def create_3d_graph(self, graph_points: list, size: float = 0.0, color: str = 'B
if self.n_plots == 0:
plt.figure(figsize=(16, 8))
self.n_plots += 1
plt.subplot(posArg, projection='3d', xlim=(-size, size), ylim=(-size, size), zlim=(-0, size))
plt.subplot(posArg, projection='3d', xlim=(-size, size),
ylim=(-size, size), zlim=(-0, size))
plt.plot(plot_points[2], plot_points[1], plot_points[0])
else:
self.n_plots += 1
Expand All @@ -245,16 +256,17 @@ def create_3d_graph(self, graph_points: list, size: float = 0.0, color: str = 'B
ax.set_zlim3d(0, size)

ax.scatter3D(plot_points[2], plot_points[1],
plot_points[0], c=plot_points[2], cmap=color)
plot_points[0], c=plot_points[2], cmap=color)

def create_3d_animation(self, graph_points: list, size: float, time: float = 5.0, color: str = 'Blues'):

self.n_plots += 1
fig = plt.figure(self.n_plots)

ax = p3.Axes3D(fig)

plot_position = self.viewer.graph_from_csv(graph_points, self.file_name)
plot_position = self.viewer.graph_from_csv(
graph_points, self.file_name)

ax.set_xlim3d(-size, size)
ax.set_ylim3d(-size, size)
Expand All @@ -265,35 +277,40 @@ def func(num, dataSet, line):
xcur = dataSet[2][num] - 1
numpog = 0
for index, x in enumerate(dataSet[2]):
if x >= xcur-0.1 and x <= xcur -0.1:
if x >= xcur-0.1 and x <= xcur - 0.1:
numpog = index
line.set_data(dataSet[0:2, num-20:num])
line.set_3d_properties(dataSet[2, num-20:num])
return line

# # THE DATA POINTS
t = np.array(plot_position[1]) # This would be the z-axis ('t' means time here)
# This would be the z-axis ('t' means time here)
t = np.array(plot_position[1])
x = np.array(plot_position[2])
y = np.array(plot_position[3])

numDataPoints = len(plot_position[0])
dataSet = np.array([x, y, t])

# NOTE: Can't pass empty arrays into 3d version of plot()
line = plt.plot(dataSet[0], dataSet[1], dataSet[2], lw=2, c='g')[0] # For line plot
line = plt.plot(dataSet[0], dataSet[1], dataSet[2], lw=2, c='g')[
0] # For line plot

ax.set_xlabel('y')
ax.set_ylabel('z')
ax.set_zlabel('x')
ax.set_title('Trajectory')

# Creating the Animation object
line_ani = animation.FuncAnimation(fig, func, frames=numDataPoints, fargs=(dataSet,line), interval=(time/numDataPoints), blit=False)
line_ani = animation.FuncAnimation(fig, func, frames=numDataPoints, fargs=(
dataSet, line), interval=(time/numDataPoints), blit=False)
plt.show()

def show_all_graphs(self):
"""Displays all graphs."""
plt.show()


class rocket_motor:

"""class representing a rocket motor"""
Expand All @@ -309,18 +326,19 @@ def __init__(self, filePath: str, timeStep: int, ignitionTime: float = -1.0) ->
self._ignitionTime: float = ignitionTime
self._timeStep: int = timeStep
self._data = []

if filePath != "":

tree = ET.parse(filePath)
root = tree.getroot()

eng_data = root[0][0][1]

lPoint = [0, 0, 0]

for data in eng_data:
dataTmp = [float(data.attrib['t']), float(data.attrib['f']), float(data.attrib['m'])]
dataTmp = [float(data.attrib['t']), float(
data.attrib['f']), float(data.attrib['m'])]
if dataTmp[0] > 0:
thrustDiff = dataTmp[1] - lPoint[1]
massDiff = dataTmp[2] - lPoint[2]
Expand Down Expand Up @@ -371,4 +389,4 @@ def update(self, time: float) -> tuple[float, float]:
else:
return 0.0, self._data[-1][1]*0.001
else:
return 0.0, self._data[0][1]*0.001
return 0.0, self._data[0][1]*0.001
Loading

0 comments on commit 5f40290

Please sign in to comment.