Skip to content

Commit

Permalink
wipe business logic from controller
Browse files Browse the repository at this point in the history
  • Loading branch information
GabrielBarberini committed Aug 24, 2024
1 parent d4439f1 commit b9a1b75
Show file tree
Hide file tree
Showing 19 changed files with 848 additions and 5,177 deletions.
2 changes: 1 addition & 1 deletion lib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
def parse_error(error):
exc_type = type(error).__name__
exc_obj = f"{error}".replace("\n", " ").replace(" ", " ")
return f"{exc_type} exception: {exc_obj}"
return f"{exc_type}: {exc_obj}"


from lib.api import app
335 changes: 15 additions & 320 deletions lib/controllers/flight.py

Large diffs are not rendered by default.

113 changes: 10 additions & 103 deletions lib/controllers/motor.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
from typing import Union
from fastapi import HTTPException, status
from pymongo.errors import PyMongoError
from rocketpy.motors.solid_motor import SolidMotor
from rocketpy.motors.liquid_motor import LiquidMotor
from rocketpy.motors.hybrid_motor import HybridMotor
import jsonpickle

from lib import logger, parse_error
from lib.models.motor import Motor, MotorKinds
from lib.services.motor import MotorService
from lib.repositories.motor import MotorRepository
from lib.views.motor import (
MotorSummary,
MotorData,
MotorCreated,
MotorUpdated,
MotorDeleted,
Expand All @@ -30,10 +27,9 @@ class MotorController:
- Create a rocketpy.Motor object from a Motor model object.
"""

def __init__(self, *, motor: Motor, motor_kind: MotorKinds):
self.guard(motor, motor_kind)
def __init__(self, motor: Motor):
self.guard(motor)
self._motor = motor
self._motor_kind = motor_kind

@property
def motor(self) -> Motor:
Expand All @@ -43,67 +39,8 @@ def motor(self) -> Motor:
def motor(self, motor: Motor):
self._motor = motor

@property
def motor_kind(self) -> MotorKinds:
return self._motor_kind

@staticmethod
def get_rocketpy_motor(
motor: Motor,
) -> Union[LiquidMotor, HybridMotor, SolidMotor]:
"""
Get the rocketpy motor object.
Returns:
Union[LiquidMotor, HybridMotor, SolidMotor]
"""

motor_core = {
"thrust_source": f"lib/data/engines/{motor.thrust_source.value}.eng",
"burn_time": motor.burn_time,
"nozzle_radius": motor.nozzle_radius,
"dry_mass": motor.dry_mass,
"dry_inertia": motor.dry_inertia,
"center_of_dry_mass_position": motor.center_of_dry_mass_position,
}

match motor.motor_kind:
case MotorKinds.LIQUID:
rocketpy_motor = LiquidMotor(**motor_core)
case MotorKinds.HYBRID:
rocketpy_motor = HybridMotor(
**motor_core,
throat_radius=motor.throat_radius,
grain_number=motor.grain_number,
grain_density=motor.grain_density,
grain_outer_radius=motor.grain_outer_radius,
grain_initial_inner_radius=motor.grain_initial_inner_radius,
grain_initial_height=motor.grain_initial_height,
grain_separation=motor.grain_separation,
grains_center_of_mass_position=motor.grains_center_of_mass_position,
)
case _:
rocketpy_motor = SolidMotor(
**motor_core,
grain_number=motor.grain_number,
grain_density=motor.grain_density,
grain_outer_radius=motor.grain_outer_radius,
grain_initial_inner_radius=motor.grain_initial_inner_radius,
grain_initial_height=motor.grain_initial_height,
grains_center_of_mass_position=motor.grains_center_of_mass_position,
grain_separation=motor.grain_separation,
throat_radius=motor.throat_radius,
interpolation_method=motor.interpolation_method,
)

if motor.motor_kind != MotorKinds.SOLID:
for tank in motor.tanks:
rocketpy_motor.add_tank(tank.tank, tank.position)

return rocketpy_motor

def guard(self, motor: Motor, motor_kind):
if motor_kind != MotorKinds.SOLID and motor.tanks is None:
def guard(self, motor: Motor):
if motor.motor_kind != MotorKinds.SOLID and motor.tanks is None:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Tanks must be provided for liquid and hybrid motors.",
Expand All @@ -119,7 +56,7 @@ async def create_motor(self) -> Union[MotorCreated, HTTPException]:
try:
async with MotorRepository() as motor_repo:
motor_repo.fetch_motor(self.motor)
await motor_repo.create_motor(motor_kind=self.motor_kind)
await motor_repo.create_motor()
except PyMongoError as e:
logger.error(f"controllers.motor.create_motor: PyMongoError {e}")
raise HTTPException(
Expand Down Expand Up @@ -208,7 +145,7 @@ async def get_rocketpy_motor_as_jsonpickle(
"""
try:
read_motor = await cls.get_motor_by_id(motor_id)
rocketpy_motor = cls.get_rocketpy_motor(read_motor)
rocketpy_motor = MotorService.from_motor_model(read_motor)
except HTTPException as e:
raise e from e
except Exception as e:
Expand Down Expand Up @@ -247,7 +184,7 @@ async def update_motor_by_id(
try:
async with MotorRepository() as motor_repo:
motor_repo.fetch_motor(self.motor)
await motor_repo.create_motor(motor_kind=self.motor_kind)
await motor_repo.create_motor()
await motor_repo.delete_motor_by_id(motor_id)
except PyMongoError as e:
logger.error(f"controllers.motor.update_motor: PyMongoError {e}")
Expand Down Expand Up @@ -330,38 +267,8 @@ async def simulate_motor(
"""
try:
read_motor = await cls.get_motor_by_id(motor_id)
motor = cls.get_rocketpy_motor(read_motor)

motor_simulation_numbers = MotorData(
total_burning_time="Total Burning Time: "
+ str(motor.burn_out_time)
+ " s",
total_propellant_mass="Total Propellant Mass: "
+ "{:.3f}".format(motor.propellant_initial_mass)
+ " kg",
average_propellant_exhaust_velocity="Average Propellant Exhaust Velocity: "
+ "{:.3f}".format(
motor.exhaust_velocity.average(*motor.burn_time)
)
+ " m/s",
average_thrust="Average Thrust: "
+ "{:.3f}".format(motor.average_thrust)
+ " N",
maximum_thrust="Maximum Thrust: "
+ str(motor.max_thrust)
+ " N at "
+ str(motor.max_thrust_time)
+ " s after ignition.",
total_impulse="Total Impulse: "
+ "{:.3f}".format(motor.total_impulse)
+ " Ns\n",
)
# motor_simulation_plots = MotorPlots(
# motor.thrust.plot(lower=lower_limit, upper=upper_limit)
# )
motor_summary = MotorSummary(
motor_data=motor_simulation_numbers
) # , plots=motor_simulation_plots )
rocketpy_motor = MotorService.from_motor_model(read_motor)
motor_summary = rocketpy_motor.get_motor_summary()
except HTTPException as e:
raise e from e
except Exception as e:
Expand Down
Loading

0 comments on commit b9a1b75

Please sign in to comment.