Skip to content

Commit 6b6195c

Browse files
DOC: better docstrings and type hints
1 parent fe15435 commit 6b6195c

File tree

11 files changed

+106
-145
lines changed

11 files changed

+106
-145
lines changed

rocketserializer/cli.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ def ork2json(
191191

192192
settings = ork_extractor(
193193
bs=bs,
194-
filepath=str(filepath),
194+
filepath=filepath,
195195
output_folder=output,
196196
ork=ork,
197197
eng=eng,
Lines changed: 42 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,30 @@
11
import logging
22
import os
33
from pathlib import Path
4+
from typing import Union
45

56
import numpy as np
67

78
logger = logging.getLogger(__name__)
89

910

10-
def save_drag_curve(datapoints, data_labels, output_folder):
11-
"""Extracts the drag curve from the data and saves it to a csv file.
12-
13-
Parameters
14-
----------
15-
datapoints : list
16-
The datapoints.
17-
data_labels : list of str
18-
The labels of the data.
19-
path : str
20-
Path to the folder where the drag curve should be saved. This needs to
21-
be a folder that already exists.
22-
23-
Returns
24-
-------
25-
path : str
26-
The path to the drag curve.
27-
"""
28-
# Remove the data after apogee
29-
altitude_vector = [
11+
def __collect_altitude_vector(
12+
datapoints: list[float], data_labels: list[str]
13+
) -> list[float]:
14+
return [
3015
float(datapoint.text.split(",")[data_labels.index("Altitude")])
3116
for datapoint in datapoints
3217
]
33-
logger.info("Collected altitude vector")
3418

19+
20+
def __remove_data_after_apogee(datapoints: list[float], altitude_vector: list[float]):
3521
apogee_index = np.argmax(altitude_vector)
36-
datapoints = datapoints[:apogee_index]
37-
logger.info("Removed data after apogee")
22+
return datapoints[:apogee_index]
3823

39-
# Extract the drag coefficient and Mach number
24+
25+
def __extract_drag_and_mach(
26+
datapoints: list[float], data_labels: list[str]
27+
) -> np.ndarray:
4028
cd = [
4129
float(datapoint.text.split(",")[data_labels.index("Axial drag coefficient")])
4230
for datapoint in datapoints
@@ -45,24 +33,41 @@ def save_drag_curve(datapoints, data_labels, output_folder):
4533
float(datapoint.text.split(",")[data_labels.index("Mach number")])
4634
for datapoint in datapoints
4735
]
48-
logger.info("Collected drag coefficient and Mach number")
36+
return np.array([mach, cd]).T
37+
38+
39+
def __process_drag_data(cd: np.ndarray) -> np.ndarray:
40+
cd = cd[~np.isnan(cd).any(axis=1), :] # Remove NaN values
41+
cd = cd[cd[:, 0].argsort()] # Sort by Mach number
42+
cd = np.unique(cd, axis=0) # Remove duplicate Mach numbers
43+
cd = cd[cd[:, 1] > 0, :] # Remove values when the drag is lower than 0
44+
return cd
4945

50-
# Convert to numpy array
51-
cd = np.array([mach, cd]).T
52-
# Remove NaN values to avoid errors
53-
cd = cd[~np.isnan(cd).any(axis=1), :]
54-
# Sort by Mach number
55-
cd = cd[cd[:, 0].argsort()]
56-
# Remove duplicate Mach numbers
57-
cd = np.unique(cd, axis=0)
58-
# Remove values when the drag is lower than 0
59-
cd = cd[cd[:, 1] > 0, :]
60-
logger.info("Successfully created the drag curve")
6146

62-
# Save to csv file
47+
def __save_to_csv(cd: np.ndarray, output_folder: Union[Path, str]) -> str:
6348
path = os.path.join(output_folder, "drag_curve.csv")
6449
np.savetxt(path, cd, delimiter=",", fmt="%.6f")
6550
logger.info(
6651
"Successfully saved the drag curve file to: '%s'", Path(path).as_posix()
6752
)
6853
return path
54+
55+
56+
def save_drag_curve(
57+
datapoints: list[float], data_labels: list[str], output_folder: Union[Path, str]
58+
) -> str:
59+
"""Extracts the drag curve from the data and saves it to a csv file."""
60+
61+
altitude_vector = __collect_altitude_vector(datapoints, data_labels)
62+
logger.info("Collected altitude vector")
63+
64+
datapoints = __remove_data_after_apogee(datapoints, altitude_vector)
65+
logger.info("Removed data after apogee")
66+
67+
cd = __extract_drag_and_mach(datapoints, data_labels)
68+
logger.info("Collected drag coefficient and Mach number")
69+
70+
cd = __process_drag_data(cd)
71+
logger.info("Successfully created the drag curve")
72+
73+
return __save_to_csv(cd, output_folder)

rocketserializer/components/flight.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,16 @@
11
import logging
22

3+
from bs4 import BeautifulSoup
4+
35
from .._helpers import _dict_to_string
46

57
logger = logging.getLogger(__name__)
68

79

8-
def search_launch_conditions(bs):
10+
def search_launch_conditions(bs: BeautifulSoup) -> dict:
911
"""Searches the launch conditions in the bs object. Returns a dict with the
1012
settings.
1113
12-
Parameters
13-
----------
14-
bs : BeautifulSoup
15-
The BeautifulSoup object of the open rocket file.
16-
1714
Returns
1815
-------
1916
settings : dict

rocketserializer/components/id.py

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,20 @@
11
import logging
22
from pathlib import Path
33

4+
from bs4 import BeautifulSoup
5+
46
from .._helpers import _dict_to_string
57

68
logger = logging.getLogger(__name__)
79

810

9-
def search_id_info(bs, filepath):
11+
def search_id_info(bs: BeautifulSoup, filepath: Path) -> dict:
1012
"""Searches for the identification of the .ork file
1113
12-
Parameters
13-
----------
14-
bs : BeautifulSoup
15-
BeautifulSoup object of the .ork file.
16-
filepath : str
17-
Path to the .ork file.
18-
1914
Returns
2015
-------
2116
dictionary
22-
Dictionary with the identification information of the .ork file. The
23-
keys are: "rocket_name", "comment", "designer", "ork_version" and
24-
"filepath".
17+
Dictionary with the identification information of the .ork file.
2518
"""
2619
settings = {}
2720
settings["rocket_name"] = bs.find("rocket").find("name").text

rocketserializer/components/motor.py

Lines changed: 16 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,28 @@
11
import logging
22
import os
33
from pathlib import Path
4+
from typing import Union
45

56
import numpy as np
7+
from bs4 import BeautifulSoup
68

79
from .._helpers import _dict_to_string
810

911
logger = logging.getLogger(__name__)
1012

1113

12-
def search_motor(bs, datapoints, data_labels):
14+
def search_motor(
15+
bs: BeautifulSoup, datapoints: list[float], data_labels: list[str]
16+
) -> dict:
1317
"""Search for the motor properties in the .ork file. The only property that
1418
is not included is the thrust curve, which is generated in the
1519
generate_thrust_curve function. Only rocketpy.SolidMotor class would be able
1620
to use the information from this function to create a motor object.
1721
18-
Parameters
19-
----------
20-
bs : bs4.BeautifulSoup
21-
The BeautifulSoup object of the .ork file.
22-
datapoints : list
23-
The datapoints from the .ork file.
24-
data_labels : list
25-
The labels of the datapoints.
26-
time_vector : list
27-
The time vector of the simulation.
28-
2922
Returns
3023
-------
3124
settings : dict
32-
Dictionary with the motor properties. The keys are: "burn_time",
33-
"grain_density", "grain_initial_inner_radius", "grain_outer_radius",
34-
"grain_initial_height", "nozzle_radius", "throat_radius", "dry_mass",
35-
"dry_inertia", "center_of_dry_mass", "grains_center_of_mass_position",
36-
"grain_number", "grain_separation", "nozzle_position" and
37-
"coordinate_system_orientation".
25+
Dictionary with the motor properties.
3826
"""
3927
settings = {}
4028

@@ -94,7 +82,12 @@ def search_motor(bs, datapoints, data_labels):
9482
return settings
9583

9684

97-
def generate_thrust_curve(folder_path, datapoints, data_labels, time_vector):
85+
def generate_thrust_curve(
86+
folder_path: Union[str, Path],
87+
datapoints: list[float],
88+
data_labels: list[str],
89+
time_vector: list[float],
90+
) -> str:
9891
"""Generate the thrust curve from the .ork file.
9992
10093
Parameters
@@ -145,15 +138,10 @@ def generate_thrust_curve(folder_path, datapoints, data_labels, time_vector):
145138
return source_name
146139

147140

148-
def __get_motor_mass(datapoints, data_labels):
149-
"""Get the motor mass from the .ork file.
150-
151-
Parameters
152-
----------
153-
datapoints : list
154-
List of datapoints from the .ork file.
155-
data_labels : list
156-
List of labels for the datapoints.
141+
def __get_motor_mass(
142+
datapoints: list[float], data_labels: list[str]
143+
) -> tuple[float, float, int]:
144+
"""Get the motor mass from the datapoints saved in the .ork file.
157145
158146
Returns
159147
-------

rocketserializer/components/parachute.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,20 @@
11
import logging
22

33
import numpy as np
4+
from bs4 import BeautifulSoup
45

56
from .._helpers import _dict_to_string
67

78
logger = logging.getLogger(__name__)
89

910

10-
def search_parachutes(bs):
11+
def search_parachutes(bs: BeautifulSoup) -> dict:
1112
"""Search for the parachutes in the bs and return the settings as a dict.
1213
13-
Parameters
14-
----------
15-
bs : bs4.BeautifulSoup
16-
The BeautifulSoup object of the .ork file.
17-
1814
Returns
1915
-------
2016
settings : dict
21-
A dict containing the settings for the parachutes. The keys are integers
22-
and the values are dicts containing the settings for each parachute.
23-
The keys of the parachute dicts are: "name", "cd", "cds", "area",
24-
"deploy_event", "deploy_delay", "deploy_altitude".
17+
A dict containing the settings for the parachutes.
2518
"""
2619
settings = {}
2720

rocketserializer/components/rail_buttons.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import logging
22

3+
from bs4 import BeautifulSoup
4+
35
logger = logging.getLogger(__name__)
46

57

6-
def search_rail_buttons(bs, elements: dict) -> dict:
8+
def search_rail_buttons(bs: BeautifulSoup, elements: dict) -> dict:
79

810
lugs_elements = []
911
for value in elements.values():

rocketserializer/components/stored_results.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,20 @@
11
import logging
22

3+
from bs4 import BeautifulSoup
4+
35
from .._helpers import _dict_to_string
46

57
logger = logging.getLogger(__name__)
68

79

8-
def search_stored_results(bs):
10+
def search_stored_results(bs: BeautifulSoup) -> dict:
911
"""Search for the stored simulation results in the bs and return the
1012
settings as a dict.
1113
12-
Parameters
13-
----------
14-
bs : BeautifulSoup
15-
BeautifulSoup object of the .ork file.
16-
1714
Returns
1815
-------
1916
settings : dict
20-
A dict containing the settings for the launch conditions. The keys are:
21-
"maxaltitude", "maxvelocity", "maxacceleration", "maxmach", "timetoapogee",
22-
"flighttime", "groundhitvelocity" and "launchrodvelocity".
17+
A dict containing the settings for the launch conditions.
2318
"""
2419
settings = {}
2520

rocketserializer/components/transition.py

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,23 @@
11
import logging
22

3+
from bs4 import BeautifulSoup
4+
35
from .._helpers import _dict_to_string
46

57
logger = logging.getLogger(__name__)
68

79

8-
def search_transitions(bs, elements, ork):
9-
"""Search for the transitions in the bs and return the settings as a dict.
10-
11-
Parameters
12-
----------
13-
bs : bs4.BeautifulSoup
14-
The BeautifulSoup object of the .ork file.
15-
elements : dict
16-
Dictionary with the elements of the rocket.
17-
ork : orhelper
18-
orhelper object of the open rocket file.
10+
def search_transitions(
11+
bs: BeautifulSoup,
12+
elements: dict,
13+
ork: "net.sr.openrocket.document.OpenRocketDocument",
14+
) -> dict:
15+
"""Search for the transitions in the bs and return the settings as a dict
1916
2017
Returns
2118
-------
2219
settings : dict
23-
Dictionary with the settings for the transitions. The keys are integers
24-
and the values are dicts containing the settings for each transition.
25-
The keys of the transition dicts are: "name", "top_radius",
26-
"bottom_radius", "length", "position".
20+
Dictionary with the settings for the transitions.
2721
"""
2822
settings = {}
2923
transitions = bs.findAll("transition")

rocketserializer/nb_builder.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import json
22
import logging
33
import os
4+
from pathlib import Path
45

56
import nbformat as nbf
67

@@ -12,7 +13,7 @@ class NotebookBuilder:
1213
using rocketpy simulation on it
1314
"""
1415

15-
def __init__(self, parameters_json: str) -> None:
16+
def __init__(self, parameters_json: Path) -> None:
1617
"""read the file and process the dictionary do not build anything yet"""
1718
self.parameters_json = parameters_json
1819
self.trapezoidal_fins_check = False

0 commit comments

Comments
 (0)