Certainly! Below is the optimized and enhanced version of your MHPEPS simulator Python script. The improvements include:
- Realistic Parameters: Updated default values to reflect realistic parameters based on the provided technical documentation.
- Code Optimization: Refactored the code for better performance and readability.
- Child Window with Animated Rocket: Added a child window that visualizes the rocket as a triangle moving realistically based on simulation data.
- Hover Functionality: Implemented hover detection over the rocket to display its current parameters as a tooltip.
Enhanced Python Script
import math
import tkinter as tk
from tkinter import ttk, messagebox
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
# Constants
G0 = 9.80665 # Standard gravity, m/s²
class PowerUnit:
def __init__(self, power_density, efficiency, mass):
"""
Parameters:
power_density: Power density (W/kg)
efficiency: Conversion efficiency (0 < efficiency <= 1)
mass: Mass of the power unit (kg)
"""
self.power_density = power_density
self.efficiency = efficiency
self.mass = mass
self.power = self.power_density * self.mass * self.efficiency # Generated power (W)
def get_power(self):
return self.power
class PlasmaThruster:
def __init__(self, efficiency, V, mi, charge):
"""
Parameters:
efficiency: Thrust efficiency (0 < efficiency <= 1)
V: Acceleration voltage (V)
mi: Mass of ion (kg)
charge: Charge of ion (C)
"""
self.efficiency = efficiency
self.V = V
self.mi = mi
self.charge = charge
def calculate_exhaust_velocity(self):
"""
v_e = (q * V) / m_i
"""
ve = (self.charge * self.V) / self.mi
return ve
def calculate_thrust_energy_based(self, power):
"""
F = (2 * η * P) / v_e
"""
ve = self.calculate_exhaust_velocity()
if ve == 0:
return 0
F = (2 * self.efficiency * power) / ve
return F
def calculate_specific_impulse(self):
"""
I_sp = v_e / g0
"""
ve = self.calculate_exhaust_velocity()
I_sp = ve / G0
return I_sp
def calculate_power_consumption(self, thrust):
"""
P = (F * v_e) / (2 * η)
"""
ve = self.calculate_exhaust_velocity()
if self.efficiency == 0:
return float('inf')
P = (thrust * ve) / (2 * self.efficiency)
return P
class Rocket:
def __init__(self, mass_initial, power_unit, thruster, modules=1):
"""
Parameters:
mass_initial: Initial mass of the rocket (kg)
power_unit: Instance of PowerUnit
thruster: Instance of PlasmaThruster
modules: Number of thruster modules
"""
self.mass_initial = mass_initial
self.mass = mass_initial
self.power_unit = power_unit
self.thruster = thruster
self.modules = modules
self.total_power = self.power_unit.get_power() * self.modules
self.ve = self.thruster.calculate_exhaust_velocity()
self.I_sp = self.thruster.calculate_specific_impulse()
def step(self, delta_t):
"""
Perform one simulation step over delta_t seconds.
Returns:
thrust: Thrust (N)
dm: Mass of propellant consumed (kg)
"""
thrust = self.thruster.calculate_thrust_energy_based(self.total_power)
if self.ve == 0:
dm_dt = 0
else:
dm_dt = (2 * self.total_power) / (self.ve ** 2)
dm = dm_dt * delta_t
if self.mass - dm < 0:
dm = self.mass
self.mass = 0
else:
self.mass -= dm
return thrust, dm
def simulate(self, duration, delta_t):
"""
Simulate the rocket operation over 'duration' seconds with steps of 'delta_t'.
Returns:
times, speeds, masses, thrusts: Lists of simulation data
"""
times = []
speeds = []
masses = []
thrusts = []
velocity = 0.0
time_elapsed = 0.0
while time_elapsed <= duration and self.mass > 0:
thrust, dm = self.step(delta_t)
acceleration = thrust / self.mass if self.mass != 0 else 0
velocity += acceleration * delta_t
time_elapsed += delta_t
times.append(time_elapsed)
speeds.append(velocity)
masses.append(self.mass)
thrusts.append(thrust)
return times, speeds, masses, thrusts
class Tooltip:
"""
Tooltip class to display information when hovering over the rocket.
"""
def __init__(self, widget, text=''):
self.widget = widget
self.text = text
self.tooltip = None
widget.bind("<Enter>", self.show_tooltip)
widget.bind("<Leave>", self.hide_tooltip)
def show_tooltip(self, event=None):
if self.tooltip:
return
x = y = 0
x, y, cx, cy = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
self.tooltip = tk.Toplevel(self.widget)
self.tooltip.wm_overrideredirect(True)
self.tooltip.wm_geometry(f"+{x}+{y}")
label = ttk.Label(self.tooltip, text=self.text, background="yellow", relief='solid', borderwidth=1, justify='left')
label.pack(ipadx=1)
def hide_tooltip(self, event=None):
if self.tooltip:
self.tooltip.destroy()
self.tooltip = None
class MHPEPS_Simulator(tk.Tk):
def __init__(self):
super().__init__()
self.title("MHPEPS Simulator")
self.geometry("1200x700")
self.create_widgets()
def create_widgets(self):
# Frames for input parameters and output visualization
input_frame = ttk.Frame(self, padding="10")
input_frame.pack(side=tk.LEFT, fill=tk.Y)
output_frame = ttk.Frame(self, padding="10")
output_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
# Title
ttk.Label(input_frame, text="Simulation Settings", font=("Helvetica", 16, "bold")).pack(pady=10)
# PowerUnit Parameters
ttk.Label(input_frame, text="PowerUnit Parameters", font=("Helvetica", 12, "bold")).pack(pady=5)
self.pu_power_density = self.create_labeled_entry(input_frame, "Power Density (W/kg):", "3000")
self.pu_efficiency = self.create_labeled_entry(input_frame, "Energy Conversion Efficiency:", "0.95")
self.pu_mass = self.create_labeled_entry(input_frame, "PowerUnit Mass (kg):", "50")
# PlasmaThruster Parameters
ttk.Label(input_frame, text="PlasmaThruster Parameters", font=("Helvetica", 12, "bold")).pack(pady=5)
self.pt_efficiency = self.create_labeled_entry(input_frame, "Thrust Efficiency (η):", "0.85")
self.pt_voltage = self.create_labeled_entry(input_frame, "Acceleration Voltage (V):", "10000")
# Updated default mass of ion to 2.18e-22 kg based on user's note
self.pt_mi = self.create_labeled_entry(input_frame, "Ion Mass (kg):", "2.18e-22")
self.pt_charge = self.create_labeled_entry(input_frame, "Ion Charge (C):", "1.6e-19")
# Rocket Parameters
ttk.Label(input_frame, text="Rocket Parameters", font=("Helvetica", 12, "bold")).pack(pady=5)
self.rocket_mass_initial = self.create_labeled_entry(input_frame, "Initial Rocket Mass (kg):", "1500")
self.rocket_modules = self.create_labeled_entry(input_frame, "Number of Thruster Modules:", "4")
# Simulation Parameters
ttk.Label(input_frame, text="Simulation Parameters", font=("Helvetica", 12, "bold")).pack(pady=5)
self.sim_duration = self.create_labeled_entry(input_frame, "Duration (s):", "1000")
self.sim_delta_t = self.create_labeled_entry(input_frame, "Time Step (s):", "1")
# Run Simulation Button
ttk.Button(input_frame, text="Run Simulation", command=self.run_simulation).pack(pady=20)
# Plot Area
self.figure, self.axes = plt.subplots(3, 1, figsize=(8, 10))
self.canvas = FigureCanvasTkAgg(self.figure, master=output_frame)
self.canvas.draw()
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
# Rocket Animation Button
ttk.Button(output_frame, text="Show Rocket Animation", command=self.show_animation).pack(pady=10)
# Initialize simulation data
self.simulation_data = None
def create_labeled_entry(self, parent, label_text, default_value):
frame = ttk.Frame(parent)
frame.pack(fill=tk.X, pady=2)
label = ttk.Label(frame, text=label_text, width=30, anchor=tk.W)
label.pack(side=tk.LEFT)
entry = ttk.Entry(frame)
entry.insert(0, default_value)
entry.pack(side=tk.RIGHT, fill=tk.X, expand=True)
return entry
def run_simulation(self):
try:
# Retrieve and convert parameters
pu_power_density = float(self.pu_power_density.get())
pu_efficiency = float(self.pu_efficiency.get())
pu_mass = float(self.pu_mass.get())
pt_efficiency = float(self.pt_efficiency.get())
pt_voltage = float(self.pt_voltage.get())
pt_mi = float(self.pt_mi.get())
pt_charge = float(self.pt_charge.get())
rocket_mass_initial = float(self.rocket_mass_initial.get())
rocket_modules = int(float(self.rocket_modules.get()))
sim_duration = float(self.sim_duration.get())
sim_delta_t = float(self.sim_delta_t.get())
# Validate parameters
if any([
pu_power_density <= 0,
pu_efficiency <= 0 or pu_efficiency > 1,
pu_mass <= 0,
pt_efficiency <= 0 or pt_efficiency > 1,
pt_voltage <= 0,
pt_mi <= 0,
pt_charge == 0,
rocket_mass_initial <= 0,
rocket_modules <= 0,
sim_duration <= 0,
sim_delta_t <= 0
]):
raise ValueError("Please enter valid positive values.")
# Initialize subsystems
power_unit = PowerUnit(pu_power_density, pu_efficiency, pu_mass)
thruster = PlasmaThruster(pt_efficiency, pt_voltage, pt_mi, pt_charge)
rocket = Rocket(rocket_mass_initial, power_unit, thruster, rocket_modules)
# Run simulation
times, speeds, masses, thrusts = rocket.simulate(sim_duration, sim_delta_t)
self.simulation_data = (times, speeds, masses, thrusts)
if not times:
raise ValueError("Simulation could not be performed with the given parameters.")
# Clear previous plots
for ax in self.axes:
ax.clear()
# Plotting
ax1, ax2, ax3 = self.axes
ax1.plot(times, speeds, label="Speed (m/s)", color='blue')
ax1.set_title('Rocket Speed Over Time')
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Speed (m/s)')
ax1.grid(True)
ax1.legend()
ax2.plot(times, thrusts, label="Thrust (N)", color='green')
ax2.set_title('Thrust Over Time')
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Thrust (N)')
ax2.grid(True)
ax2.legend()
ax3.plot(times, masses, label="Mass (kg)", color='red')
ax3.set_title('Rocket Mass Over Time')
ax3.set_xlabel('Time (s)')
ax3.set_ylabel('Mass (kg)')
ax3.grid(True)
ax3.legend()
self.figure.tight_layout()
self.canvas.draw()
messagebox.showinfo("Simulation Complete", "The simulation has been successfully completed.")
except ValueError as ve:
messagebox.showerror("Input Error", f"Invalid input: {ve}")
except Exception as e:
messagebox.showerror("Error", f"An error occurred: {e}")
def show_animation(self):
if not self.simulation_data:
messagebox.showwarning("No Simulation Data", "Please run a simulation first.")
return
# Create child window
anim_window = tk.Toplevel(self)
anim_window.title("Rocket Animation")
anim_window.geometry("800x600")
# Canvas for animation
canvas = tk.Canvas(anim_window, width=800, height=600, bg="black")
canvas.pack(fill=tk.BOTH, expand=True)
times, speeds, masses, thrusts = self.simulation_data
delta_t = self.sim_delta_t.get()
total_time = times[-1]
max_distance = 700 # Maximum distance the rocket can travel on the canvas
rocket_size = 20 # Size of the rocket
# Calculate total displacement based on final velocity (simplistic approach)
total_displacement = speeds[-1] * total_time
if total_displacement == 0:
scale = 1
else:
scale = max_distance / total_displacement
# Initial position
current_x = 50
current_y = 300
# Create rocket as a triangle
point1 = (current_x, current_y - rocket_size)
point2 = (current_x, current_y + rocket_size)
point3 = (current_x + rocket_size * 1.5, current_y)
rocket_shape = canvas.create_polygon(point1, point2, point3, fill="white")
# Text displaying thrust and mass
info_text = canvas.create_text(current_x + rocket_size * 2, current_y,
text=f"Thrust: {thrusts[0]:.2f} N\nMass: {masses[0]:.2f} kg",
fill="white", font=("Helvetica", 10), anchor=tk.W)
# Tooltip setup
tooltip = Tooltip(canvas, "")
def update_tooltip(event):
# Get mouse position
x, y = event.x, event.y
# Get rocket's current position
coords = canvas.coords(rocket_shape)
# Simple collision detection
if (coords[0] <= x <= coords[4]) and (coords[1] <= y <= coords[3]):
tooltip.text = f"Thrust: {current_thrust:.2f} N\nMass: {current_mass:.2f} kg"
if not tooltip.tooltip:
tooltip.show_tooltip()
else:
tooltip.hide_tooltip()
canvas.bind("<Motion>", update_tooltip)
# Animation function
def animate(index=0):
nonlocal current_x
if index >= len(times):
return
current_thrust = thrusts[index]
current_mass = masses[index]
current_speed = speeds[index]
# Calculate displacement
displacement = current_speed * delta_t * scale
current_x += displacement
if current_x > 750:
current_x = 750 # Prevent moving out of canvas
# Move rocket
move_x = displacement
canvas.move(rocket_shape, move_x, 0)
canvas.move(info_text, move_x, 0)
# Update info text
canvas.itemconfig(info_text, text=f"Thrust: {current_thrust:.2f} N\nMass: {current_mass:.2f} kg")
# Schedule next frame
canvas.after(10, lambda: animate(index + 1))
# Start animation
animate()
def main():
app = MHPEPS_Simulator()
app.mainloop()
if __name__ == "__main__":
main()
Key Enhancements Explained
-
Realistic Parameters:
- Power Density: Set to
3000 W/kg reflecting advanced power units.
- Energy Conversion Efficiency: High efficiency of
0.95 for better power utilization.
- Thruster Efficiency: Increased to
0.85 to align with high-performance plasma thrusters.
- Acceleration Voltage: Set to
10000 V, achieving the high exhaust velocities desired.
- Ion Mass: Updated to
2.18e-22 kg as per your note.
- Ion Charge: Remains
1.6e-19 C, which is the fundamental charge of a proton.
-
Code Optimization:
- Refactored Classes: Improved readability and documentation within classes.
- Simulation Data Handling: Stored simulation data for reuse in animations.
- Error Handling: Enhanced error messages for better user feedback.
-
Child Window with Animated Rocket:
- Separate Animation Window: Added a button to open a new window displaying the rocket animation.
- Rocket Representation: The rocket is depicted as a white triangle moving horizontally based on simulation data.
- Dynamic Movement: The rocket's position updates in real-time, reflecting acceleration and velocity changes.
-
Hover Functionality:
- Tooltip Implementation: A
Tooltip class is created to show the current thrust and mass when the user hovers over the rocket.
- Collision Detection: The tooltip appears only when the mouse is over the rocket's area.
Usage Instructions
-
Running the Simulation:
- Launch the application.
- Adjust the simulation parameters as needed. The defaults are set to realistic values for MHPEPS.
- Click on the "Run Simulation" button to execute the simulation. The plots for speed, thrust, and mass over time will be displayed.
-
Viewing the Animation:
- After running the simulation, click on the "Show Rocket Animation" button.
- A new window will open, displaying the animated rocket.
- Move your mouse over the rocket to view its current thrust and mass in a tooltip.
Additional Enhancements (Optional)
-
Improved Collision Detection:
- Enhance the hover detection to accurately follow the rocket's shape rather than a simple bounding box.
- This can be achieved by calculating the distance from the mouse pointer to the rocket's triangular area.
-
Realistic Physics Integration:
- Incorporate more complex physics for realistic motion, such as considering gravitational forces or external factors.
- Use libraries like
pygame for more advanced animations if needed.
-
Interactive Controls in Animation Window:
- Add controls to pause, resume, or adjust the speed of the animation.
- Display additional information such as total distance traveled or remaining propellant.
-
Saving Simulation Data:
- Provide options to save simulation results and animations for later analysis or reporting.
Conclusion
This enhanced script provides a more realistic and interactive simulation environment for the Modular Hybrid Plasma-Electric Propulsion System (MHPEPS). The improvements ensure that users can visualize the rocket's behavior accurately and obtain insightful data through both graphical plots and real-time animations.
Feel free to further customize and expand the simulator based on your specific requirements and additional features you may want to incorporate.