Skip to content
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ Attention: The newest changes should be on top -->
- ENH: Auto Populate Changelog [#919](https://github.com/RocketPy-Team/RocketPy/pull/919)
- ENH: Adaptive Monte Carlo via Convergence Criteria [#922](https://github.com/RocketPy-Team/RocketPy/pull/922)
- TST: Add acceptance tests for 3DOF flight simulation based on Bella Lui rocket [#914](https://github.com/RocketPy-Team/RocketPy/pull/914)
- ENH: adopt built-in Python logging instead of print() calls [#450](https://github.com/RocketPy-Team/RocketPy/issues/450)

### Changed

Expand Down
4 changes: 4 additions & 0 deletions rocketpy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,64 +1,68 @@
import logging

logging.getLogger(__name__).addHandler(logging.NullHandler())

from .control import _Controller

Check failure on line 5 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:5:1: E402 Module level import not at top of file
from .environment import Environment, EnvironmentAnalysis

Check failure on line 6 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:6:1: E402 Module level import not at top of file
from .mathutils import (
Function,
PiecewiseFunction,
funcify_method,
reset_funcified_methods,
)

Check failure on line 12 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:7:1: E402 Module level import not at top of file
from .motors import (
CylindricalTank,
EmptyMotor,
Fluid,
GenericMotor,
HybridMotor,
LevelBasedTank,
LiquidMotor,
MassBasedTank,
MassFlowRateBasedTank,
Motor,
PointMassMotor,
SolidMotor,
SphericalTank,
Tank,
TankGeometry,
UllageBasedTank,
)

Check failure on line 30 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:13:1: E402 Module level import not at top of file
from .plots.compare import Compare, CompareFlights

Check failure on line 31 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:31:1: E402 Module level import not at top of file
from .rocket import (
AeroSurface,
AirBrakes,
Components,
EllipticalFin,
EllipticalFins,
Fin,
Fins,
FreeFormFin,
FreeFormFins,
GenericSurface,
LinearGenericSurface,
NoseCone,
Parachute,
PointMassRocket,
RailButtons,
Rocket,
Tail,
TrapezoidalFin,
TrapezoidalFins,
)

Check failure on line 52 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:32:1: E402 Module level import not at top of file
from .sensitivity import SensitivityModel

Check failure on line 53 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:53:1: E402 Module level import not at top of file
from .sensors import Accelerometer, Barometer, GnssReceiver, Gyroscope

Check failure on line 54 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:54:1: E402 Module level import not at top of file
from .simulation import Flight, MonteCarlo, MultivariateRejectionSampler

Check failure on line 55 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:55:1: E402 Module level import not at top of file
from .stochastic import (
CustomSampler,
StochasticAirBrakes,
StochasticEllipticalFins,
StochasticEnvironment,
StochasticFlight,
StochasticNoseCone,
StochasticParachute,
StochasticRocket,
StochasticSolidMotor,
StochasticTail,
StochasticTrapezoidalFins,
)

Check failure on line 68 in rocketpy/__init__.py

View workflow job for this annotation

GitHub Actions / lint (3.10)

ruff (E402)

rocketpy/__init__.py:56:1: E402 Module level import not at top of file
31 changes: 17 additions & 14 deletions rocketpy/environment/environment.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# pylint: disable=too-many-public-methods, too-many-instance-attributes
import bisect
import json
import logging
import re
import warnings

logger = logging.getLogger(__name__)
from collections import namedtuple
from datetime import datetime

Expand Down Expand Up @@ -977,7 +980,7 @@ def set_elevation(self, elevation="Open-Elevation"):
self.elevation = elevation
else:
self.elevation = fetch_open_elevation(self.latitude, self.longitude)
print(f"Elevation received: {self.elevation} m")
logger.info("Elevation received: %.2f m", self.elevation)

def set_topographic_profile( # pylint: disable=redefined-builtin, unused-argument
self, type, file, dictionary="netCDF4", crs=None
Expand Down Expand Up @@ -1016,14 +1019,13 @@ def set_topographic_profile( # pylint: disable=redefined-builtin, unused-argume
# crsArray = nasa_dem.variables['crs'][:].tolist().
self.topographic_profile_activated = True

print("Region covered by the Topographical file: ")
print(
f"Latitude from {self.elev_lat_array[-1]:.6f}° to "
f"{self.elev_lat_array[0]:.6f}°"
)
print(
f"Longitude from {self.elev_lon_array[0]:.6f}° to "
f"{self.elev_lon_array[-1]:.6f}°"
logger.debug(
"Topographical file coverage: lat [%.6f°, %.6f°], "
"lon [%.6f°, %.6f°]",
self.elev_lat_array[-1],
self.elev_lat_array[0],
self.elev_lon_array[0],
self.elev_lon_array[-1],
)

def get_elevation_from_topographic_profile(self, lat, lon):
Expand Down Expand Up @@ -2738,9 +2740,10 @@ def export_environment(self, filename="environment"):

with open(filename + ".json", "w") as f:
json.dump(export_env_dictionary, f, sort_keys=False, indent=4, default=str)
print(
f"Your Environment file was saved at '{filename}.json'. You can use "
"it in the future by using the custom_atmosphere atmospheric model."
logger.info(
"Your Environment file was saved at '%s.json'. "
"You can use it in the future by using the custom_atmosphere atmospheric model.",
filename,
)

def set_earth_geometry(self, datum):
Expand Down Expand Up @@ -2973,6 +2976,6 @@ def from_dict(cls, data): # pylint: disable=too-many-statements

results = doctest.testmod()
if results.failed < 1:
print(f"All the {results.attempted} tests passed!")
logger.info("All the %d tests passed!", results.attempted)
Comment thread
YuriCastroDev marked this conversation as resolved.
Outdated
else:
print(f"{results.failed} out of {results.attempted} tests failed.")
logger.warning("%d out of %d tests failed.", results.failed, results.attempted)
Comment thread
YuriCastroDev marked this conversation as resolved.
Outdated
27 changes: 17 additions & 10 deletions rocketpy/environment/environment_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
import copy
import datetime
import json
import logging
import warnings

logger = logging.getLogger(__name__)
from collections import defaultdict
from functools import cached_property

Expand Down Expand Up @@ -236,13 +239,15 @@ def __check_requirements(self):
check_requirement_version(module_name, version)
except (ValueError, ImportError) as e:
has_error = True
print(
f"The following error occurred while importing {module_name}: {e}"
logger.error(
"The following error occurred while importing %s: %s",
module_name,
e,
)
if has_error:
print(
logger.error(
"Given the above errors, some methods may not work. Please run "
+ "'pip install rocketpy[env_analysis]' to install extra requirements."
"'pip install rocketpy[env_analysis]' to install extra requirements."
)

def __init_surface_dictionary(self):
Expand Down Expand Up @@ -508,8 +513,9 @@ def __init_unit_system(self):
}
else:
# Default to SI
print(
f"Defaulting to SI unit system, the {self.unit_system_string} was not found."
logger.warning(
"Defaulting to SI unit system, the '%s' unit system was not found.",
self.unit_system_string,
)
self.unit_system = {
"length": "m",
Expand Down Expand Up @@ -2843,9 +2849,10 @@ def export_mean_profiles(self, filename="export_env_analysis"):
self.export_dictionary, sort_keys=False, indent=4, default=str
)
)
print(
f"Your Environment Analysis file was saved, check it out: {filename}.json\n"
"You can use it to set a `customAtmosphere` atmospheric model"
logger.info(
"Your Environment Analysis file was saved: %s.json. "
"You can use it to set a customAtmosphere atmospheric model.",
filename,
)

@classmethod
Expand Down Expand Up @@ -2884,7 +2891,7 @@ def save(self, filename="env_analysis_dict"):
file = open(filename, "w") # pylint: disable=consider-using-with
file.write(encoded_class)
file.close()
print("Your Environment Analysis file was saved, check it out: " + filename)
logger.info("Your Environment Analysis file was saved: %s", filename)

def create_environment_object(
self, gravity=None, date=None, datum="SIRGAS2000", max_expected_height=80000.0
Expand Down
5 changes: 4 additions & 1 deletion rocketpy/environment/fetchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
functions may be changed without notice in future feature releases.
"""

import logging
import re
import time
from datetime import datetime, timedelta, timezone

logger = logging.getLogger(__name__)

import netCDF4
import requests

Expand Down Expand Up @@ -37,7 +40,7 @@ def fetch_open_elevation(lat, lon):
RuntimeError
If there is a problem reaching the Open-Elevation API servers.
"""
print(f"Fetching elevation from open-elevation.com for lat={lat}, lon={lon}...")
logger.debug("Fetching elevation from open-elevation.com for lat=%s, lon=%s", lat, lon)
request_url = f"https://api.open-elevation.com/api/v1/lookup?locations={lat},{lon}"
try:
response = requests.get(request_url)
Expand Down
7 changes: 5 additions & 2 deletions rocketpy/environment/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
future to improve their performance and usability.
"""

import logging
import math

logger = logging.getLogger(__name__)
import warnings

import netCDF4
Expand Down Expand Up @@ -850,6 +853,6 @@ def utm_to_geodesic( # pylint: disable=too-many-locals,too-many-statements

results = doctest.testmod()
if results.failed < 1:
print(f"All the {results.attempted} tests passed!")
logger.info("All the %d tests passed!", results.attempted)
else:
print(f"{results.failed} out of {results.attempted} tests failed.")
logger.warning("%d out of %d tests failed.", results.failed, results.attempted)
Comment thread
YuriCastroDev marked this conversation as resolved.
Outdated
9 changes: 6 additions & 3 deletions rocketpy/mathutils/function.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
carefully as it may impact all the rest of the project.
"""

import logging
import operator
import warnings

logger = logging.getLogger(__name__)
from bisect import bisect_left
from collections.abc import Iterable
from copy import deepcopy
Expand Down Expand Up @@ -2018,7 +2021,7 @@ def plot(self, *args, **kwargs):
elif self.__dom_dim__ == 2:
self.plot_2d(*args, **kwargs)
else:
print("Error: Only functions with 1D or 2D domains can be plotted.")
logger.error("Only functions with 1D or 2D domains can be plotted.")

@deprecated(
reason="The `Function.plot1D` method is set to be deprecated and fully "
Expand Down Expand Up @@ -4405,6 +4408,6 @@ def reset_funcified_methods(instance):

results = doctest.testmod()
if results.failed < 1:
print(f"All the {results.attempted} tests passed!")
logger.info("All the %d tests passed!", results.attempted)
else:
print(f"{results.failed} out of {results.attempted} tests failed.")
logger.warning("%d out of %d tests failed.", results.failed, results.attempted)
Comment thread
YuriCastroDev marked this conversation as resolved.
Outdated
7 changes: 5 additions & 2 deletions rocketpy/mathutils/vector_matrix.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import logging
from cmath import isclose
from functools import cached_property
from itertools import product

logger = logging.getLogger(__name__)

from rocketpy.tools import euler313_to_quaternions, normalize_quaternions


Expand Down Expand Up @@ -1108,6 +1111,6 @@ def from_dict(cls, data):

results = doctest.testmod()
if results.failed < 1:
print(f"All the {results.attempted} tests passed!")
logger.info("All the %d tests passed!", results.attempted)
else:
print(f"{results.failed} out of {results.attempted} tests failed.")
logger.warning("%d out of %d tests failed.", results.failed, results.attempted)
Comment thread
YuriCastroDev marked this conversation as resolved.
Outdated
14 changes: 9 additions & 5 deletions rocketpy/motors/tank_geometry.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import logging
import warnings
from functools import cached_property

logger = logging.getLogger(__name__)

import numpy as np

from ..mathutils.function import Function, funcify_method
Expand Down Expand Up @@ -458,11 +461,12 @@ def add_spherical_caps(self):
part. The height is not modified, meaning that the total volume of
the tank will decrease.
"""
print(
"Warning: Adding spherical caps to the tank will not modify the "
+ f"total height of the tank {self.height} m. "
+ "Its cylindrical portion height will be reduced to "
+ f"{self.height - 2 * self.radius_function} m."
logger.warning(
"Adding spherical caps to the tank will not modify the total height "
"of the tank (%.4f m). Its cylindrical portion height will be "
"reduced to %s m.",
self.height,
self.height - 2 * self.radius_function,
)

if not self.has_caps:
Expand Down
15 changes: 9 additions & 6 deletions rocketpy/plots/aero_surface_plots.py

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you agree that these message will stop making sense here?

The prints existed to separated each plot from the next one.
If we turn these into info logs, the user may not seeing them (unless they implement a handler).

On the other hand, if a user consumes the log without seeing the plot, it doesn't really make sense at all (i.e. reading "airfoil lift curve" doesn't make as much sense as reading "plotting airfoil lift curve")

In other words, we need to rethink what we really want to display in each message within the plots module.

Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
# pylint: disable=too-many-statements

import logging
from abc import ABC, abstractmethod

import matplotlib.pyplot as plt

logger = logging.getLogger(__name__)
import numpy as np
from matplotlib.patches import Ellipse

Expand Down Expand Up @@ -157,7 +160,7 @@ def airfoil(self, *, filename=None):
"""

if self.aero_surface.airfoil:
print("Airfoil lift curve:")
logger.info("Airfoil lift curve:")
self.aero_surface.airfoil_cl.plot_1d(force_data=True, filename=filename)

def roll(self, *, filename=None):
Expand All @@ -173,7 +176,7 @@ def roll(self, *, filename=None):
-------
None
"""
print("Roll parameters:")
logger.info("Roll parameters:")
self.aero_surface.roll_parameters[0](filename=filename)
self.aero_surface.roll_parameters[1](filename=filename)

Expand All @@ -194,7 +197,7 @@ class for more information on how this plot is made. Also, this method
-------
None
"""
print("Lift coefficient:")
logger.info("Lift coefficient:")
self.aero_surface.cl(filename=filename)
self.aero_surface.clalpha_single_fin(filename=filename)
self.aero_surface.clalpha_multiple_fins(filename=filename)
Expand Down Expand Up @@ -238,7 +241,7 @@ def airfoil(self, *, filename=None):
"""

if self.aero_surface.airfoil:
print("Airfoil lift curve:")
logger.info("Airfoil lift curve:")
self.aero_surface.airfoil_cl.plot_1d(force_data=True, filename=filename)

def roll(self, *, filename=None):
Expand All @@ -254,7 +257,7 @@ def roll(self, *, filename=None):
-------
None
"""
print("Roll parameters:")
logger.info("Roll parameters:")
self.aero_surface.roll_parameters[0](filename=filename)
self.aero_surface.roll_parameters[1](filename=filename)

Expand All @@ -275,7 +278,7 @@ class for more information on how this plot is made. Also, this method
-------
None
"""
print("Lift coefficient:")
logger.info("Lift coefficient:")
self.aero_surface.cl(filename=filename)
self.aero_surface.clalpha_single_fin(filename=filename)

Expand Down
10 changes: 7 additions & 3 deletions rocketpy/plots/compare/compare_flights.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
# TODO: remove this disable once the code is refactored
# pylint: disable=nested-min-max
import logging

import matplotlib.pyplot as plt
import numpy as np

logger = logging.getLogger(__name__)

from ..plot_helpers import show_or_save_fig, show_or_save_plot
from .compare import Compare

Expand Down Expand Up @@ -94,7 +98,7 @@ def __process_savefig(self, filename, fig):
"""
show_or_save_fig(fig, filename)
if filename:
print("Plot saved to file: " + filename)
logger.info("Plot saved to file: %s", filename)
else:
plt.show()

Expand Down Expand Up @@ -1084,7 +1088,7 @@ def stability_margin(
None
"""

print("This method is not implemented yet")
logger.warning("This method is not implemented yet.")

def attitude_frequency(
self,
Expand Down Expand Up @@ -1123,7 +1127,7 @@ def attitude_frequency(
None
"""

print("This method is not implemented yet")
logger.warning("This method is not implemented yet.")

@staticmethod
def compare_trajectories_3d( # pylint: disable=too-many-statements
Expand Down
Loading
Loading