Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Sensors #583

Merged
merged 83 commits into from
May 21, 2024
Merged
Show file tree
Hide file tree
Changes from 29 commits
Commits
Show all changes
83 commits
Select commit Hold shift + click to select a range
e403872
ENH: sensors class
MateusStano Apr 1, 2024
6cd3598
ENH: add accelerometer and gyroscope classes
MateusStano Apr 1, 2024
3b81777
ENH: euler to quaternions tool function
MateusStano Apr 1, 2024
4c8aa13
ENH: add sensors to other classes
MateusStano Apr 1, 2024
09e0d75
ENH: prints and sensors draw
MateusStano Apr 1, 2024
38866f4
ENH: add sensors to parachutes
MateusStano Apr 1, 2024
b386e38
TST: add sensors fixtures
MateusStano Apr 1, 2024
6ff2dde
TST: add sensors tests
MateusStano Apr 1, 2024
5ae01b9
DEV: sensors testing notebook
MateusStano Apr 1, 2024
1dd5781
ENH: add option to add noise to each axis seperatly
MateusStano Apr 2, 2024
943542a
MNT: run isort
MateusStano Apr 2, 2024
28ebc46
ENH: calculate u_dot only once for all sensors
MateusStano Apr 2, 2024
378bb54
MNT: change `measured_values` to `measured_data`
MateusStano Apr 2, 2024
d8440f2
TST: unite gyro and accel tests
MateusStano Apr 2, 2024
99f445f
Update rocketpy/plots/rocket_plots.py
MateusStano Apr 11, 2024
4db26f0
ENH: normalize quaternions for transform matrix
MateusStano Apr 12, 2024
4356af7
TST: lower tolerances
MateusStano Apr 12, 2024
5c37f06
BUG: handle zero norm differently due to numpy.float64
MateusStano Apr 15, 2024
8d64998
MNT: quantization typos
MateusStano Apr 15, 2024
28da8f3
DOCS: mention Hadamard product
MateusStano Apr 15, 2024
cef72a0
DOC: complete sensors class docstrings
MateusStano Apr 15, 2024
5f8f1f4
Squashed commit of the following:
MateusStano Apr 29, 2024
9a6b052
MNT: fix component repr for sensors
MateusStano Apr 30, 2024
7953cb0
ENH: add _attatched_rockets to sensors
MateusStano Apr 30, 2024
5a37553
ENH: add sensors saving methods
MateusStano Apr 30, 2024
09ea252
MNT: simplify sensors repr
MateusStano Apr 30, 2024
9851392
ENH: use _save_data in accel and gyro
MateusStano Apr 30, 2024
0f81bc3
ENH: improve accelerometer export
MateusStano Apr 30, 2024
a740fc2
ENH: imrpove gyroscope export
MateusStano Apr 30, 2024
cf6c26d
ENH: add sensor initialization
MateusStano Apr 30, 2024
2a14f1d
ENH: speed up measure call
MateusStano Apr 30, 2024
216523c
ENH: add final sensor cache
MateusStano Apr 30, 2024
09288d4
ENH: add export sensor data
MateusStano Apr 30, 2024
aa6fcdf
BUG: wrong initialization order
MateusStano Apr 30, 2024
bf6b083
TST: test for new measured_data and exports
MateusStano Apr 30, 2024
5f86223
ENH: abstract noise printings
MateusStano Apr 30, 2024
4dcc26b
MNT: run isort
MateusStano May 1, 2024
32898c5
Merge branch 'develop' into enh/sensors
MateusStano May 1, 2024
f7332d8
Merge branch 'develop' into enh/sensors
Gui-FernandesBR May 2, 2024
2131ee9
ENH: add noise variance
MateusStano May 2, 2024
b2da0c3
BUG: fix prints for noise variance
MateusStano May 2, 2024
123d033
TST: add variances
MateusStano May 2, 2024
7d0e6f3
Merge branch 'enh/sensors' of https://github.com/RocketPy-Team/Rocket…
MateusStano May 2, 2024
00f0f3a
Update rocketpy/rocket/rocket.py
MateusStano May 3, 2024
de2d8bd
MNT: remove .type attribute
MateusStano May 6, 2024
fec6725
DOC: fix units of transformation_euler_anges
MateusStano May 6, 2024
ce2a63d
DOC: add examples to transformation_euler_angles
MateusStano May 6, 2024
f2656c5
DOC: mention Euler parameters in docs
MateusStano May 6, 2024
41bf9e9
TST: test_euler_to_quaternions
MateusStano May 6, 2024
11873cd
TST: fix doc tests
MateusStano May 6, 2024
b795031
MNT: privatize components attributes and improve docs
MateusStano May 6, 2024
968f55a
TST: add index to var names
MateusStano May 6, 2024
d827b8e
MNT: return temp drift directly
MateusStano May 6, 2024
0b0f201
ENH: improve export methods
MateusStano May 6, 2024
bad3b07
DOC: typos
MateusStano May 6, 2024
0891c6c
MNT: improve flight init
MateusStano May 6, 2024
fa1b6a8
Fix code style issues with Black
lint-action May 6, 2024
b7439f4
Merge branch 'enh/sensors' of https://github.com/RocketPy-Team/Rocket…
MateusStano May 6, 2024
8c71432
TST: overall improvements on sensor testing
MateusStano May 6, 2024
5885992
ENH: change format of sensor_data dict
MateusStano May 6, 2024
02cad05
MNT: improve flight init
MateusStano May 6, 2024
69f17cd
TST: increase rel tolerances
MateusStano May 6, 2024
6894f58
Merge branch 'enh/sensors' of https://github.com/RocketPy-Team/Rocket…
MateusStano May 6, 2024
8d96e58
TST: fix export sensor data test
MateusStano May 6, 2024
ec4e25e
TST: fix doctests
MateusStano May 6, 2024
adb2dbb
TST: fix doctests
MateusStano May 6, 2024
e0812a2
ENH: change units in prints
MateusStano May 9, 2024
6ec4c0b
ENH: add .round to Matrix and remove broken doctests
MateusStano May 10, 2024
78e67f2
TST: test transfromation euler angles
MateusStano May 10, 2024
d49b5c4
TST: imrpove test_euler_to_quaternions
MateusStano May 10, 2024
57b41ab
DEV: update sensors_testing notebook
Gui-FernandesBR May 15, 2024
7a2e50a
MNT: minor fixes - typos and isort
Gui-FernandesBR May 15, 2024
a57308d
MNT: remove aft double underscore from __units
MateusStano May 16, 2024
11a8ab6
DOC: remove .type
MateusStano May 16, 2024
2984065
MNT: remove .units underscores
MateusStano May 16, 2024
82f79e7
MNT: remove repetition from sensors prints
MateusStano May 16, 2024
5016283
ENH: normalize_quaternions in tools.py
MateusStano May 16, 2024
6806912
BUG: remove Matrix circuklar import in tools
MateusStano May 16, 2024
b99b301
MNT: remove unused variable
MateusStano May 16, 2024
75f8d9e
ENH: explicit for loop variables
MateusStano May 16, 2024
c1864b2
Merge branch 'enh/sensors' of https://github.com/RocketPy-Team/Rocket…
MateusStano May 16, 2024
a20d31d
DOC: improve orientation docs
MateusStano May 16, 2024
ce1d179
ENH: x_position to x_offset
MateusStano May 16, 2024
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
448 changes: 121 additions & 327 deletions docs/notebooks/sensors_testing.ipynb

Large diffs are not rendered by default.

49 changes: 45 additions & 4 deletions rocketpy/mathutils/vector_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@
"""R3 vector with the same direction of self, but normalized."""
try:
return self / abs(self)
except ZeroDivisionError:
return self

Check warning on line 160 in rocketpy/mathutils/vector_matrix.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/mathutils/vector_matrix.py#L159-L160

Added lines #L159 - L160 were not covered by tests

@cached_property
def cross_matrix(self):
Expand Down Expand Up @@ -949,6 +949,47 @@
"""
return self.__matmul__(other)

def round(self, decimals=0):
"""Round all the values matrix to a given number of decimals.

phmbressan marked this conversation as resolved.
Show resolved Hide resolved
Parameters
----------
decimals : int, optional
Number of decimal places to round to. Defaults to 0.

Returns
-------
Matrix
The rounded matrix.

Examples
--------
>>> M = Matrix([[1.1234, 2.3456, 3.4567], [4.5678, 5.6789, 6.7890], [7.8901, 8.9012, 9.0123]])
>>> M.round(2)
Matrix([1.12, 2.35, 3.46],
[4.57, 5.68, 6.79],
[7.89, 8.9, 9.01])
"""
return Matrix(
[
[
round(self.xx, decimals),
round(self.xy, decimals),
round(self.xz, decimals),
],
[
round(self.yx, decimals),
round(self.yy, decimals),
round(self.yz, decimals),
],
[
round(self.zx, decimals),
round(self.zy, decimals),
round(self.zz, decimals),
],
]
)

def __str__(self):
return (
f"[{self.xx}, {self.xy}, {self.xz}]\n"
Expand Down Expand Up @@ -999,7 +1040,7 @@
q_x /= q_norm
q_y /= q_norm
q_z /= q_norm
# precompute common terms
# pre-compute common terms
q_x2 = q_x**2
q_y2 = q_y**2
q_z2 = q_z**2
Expand Down Expand Up @@ -1037,11 +1078,11 @@
Parameters
----------
roll : float
The roll angle in radians.
The roll angle in degrees.
pitch : float
The pitch angle in radians.
The pitch angle in degrees.
yaw : float
The yaw angle in radians.
The yaw angle in degrees.

Returns
-------
Expand Down
12 changes: 2 additions & 10 deletions rocketpy/prints/sensors_prints.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
from abc import ABC, abstractmethod

UNITS = {
"Gyroscope": "rad/s",
"Accelerometer": "m/s^2",
"Magnetometer": "T",
"PressureSensor": "Pa",
"TemperatureSensor": "K",
}


class _SensorsPrints(ABC):
def __init__(self, sensor):
self.sensor = sensor
self.units = UNITS[sensor.type]
self.units = sensor.__units__
phmbressan marked this conversation as resolved.
Show resolved Hide resolved

def _print_aligned(self, label, value):
Gui-FernandesBR marked this conversation as resolved.
Show resolved Hide resolved
"""Prints a label and a value aligned vertically."""
Expand All @@ -22,7 +14,7 @@
"""Prints the identity of the sensor."""
print("Identification of the Sensor:\n")
self._print_aligned("Name:", self.sensor.name)
self._print_aligned("Type:", self.sensor.type)
self._print_aligned("Type:", self.sensor.__class__.__name__)

def orientation(self):
"""Prints the orientation of the sensor."""
Expand All @@ -47,7 +39,7 @@
@abstractmethod
def noise(self):
"""Prints the noise of the sensor."""
pass

Check warning on line 42 in rocketpy/prints/sensors_prints.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/prints/sensors_prints.py#L42

Added line #L42 was not covered by tests

def _general_noise(self):
"""Prints the noise of the sensor."""
Expand Down
2 changes: 1 addition & 1 deletion rocketpy/rocket/aero_surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -1978,7 +1978,7 @@ def __init__(
Default is False.
deployment_level : float, optional
Initial deployment level, ranging from 0 to 1. Deployment level is
the fraction of the total airbrake area that is Deployment. Default
the fraction of the total airbrake area that is deployed. Default
is 0.
name : str, optional
Name of the air brakes. Default is "AirBrakes".
Expand Down
14 changes: 7 additions & 7 deletions rocketpy/rocket/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@

# List of components and their positions to avoid extra for loops in
# simulation time
self._component_list = []
self._position_list = []
self.__component_list = []
self.__position_list = []

def __repr__(self):
"""Return a string representation of the Components instance."""
Expand Down Expand Up @@ -66,8 +66,8 @@
-------
None
"""
self._component_list.append(component)
self._position_list.append(position)
self.__component_list.append(component)
self.__position_list.append(position)
self._components.append(self.component_tuple(component, position))

def get_by_type(self, component_type):
Expand Down Expand Up @@ -115,10 +115,10 @@

Returns
-------
list
list[Component]
A list of all the components in the list of components.
"""
return self._component_list
return self.__component_list

def get_positions(self):
"""Return a list of all the positions of the components in the list of
Expand All @@ -130,7 +130,7 @@
A list of all the positions of the components in the list of
components.
"""
return self._position_list
return self.__position_list

Check warning on line 133 in rocketpy/rocket/components.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/rocket/components.py#L133

Added line #L133 was not covered by tests

def remove(self, component):
"""Remove a component from the list of components. If more than one
Expand Down
6 changes: 3 additions & 3 deletions rocketpy/rocket/rocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -1181,10 +1181,10 @@
Position, in meters, of the sensor's coordinate system origin
relative to the user defined rocket coordinate system.
x_position : int, float, optional
Distance in meters by which the CM is to be translated in the x
Distance in meters by which the sensor is to be translated in the x
direction relative to geometrical center line. Default is 0.
y_position : int, float, optional
Distance in meters by which the CM is to be translated in the y
Distance in meters by which the sensor is to be translated in the y
direction relative to geometrical center line. Default is 0.

Returns
Expand All @@ -1194,7 +1194,7 @@
self.sensors.add(sensor, Vector([x_position, y_position, position]))
MateusStano marked this conversation as resolved.
Show resolved Hide resolved
try:
sensor._attached_rockets[self] += 1
except:
except KeyError:
sensor._attached_rockets[self] = 1

def add_air_brakes(
Expand Down Expand Up @@ -1486,7 +1486,7 @@
Plane in which the rocket will be drawn. Default is 'xz'. Other
options is 'yz'. Used only for sensors representation.
"""
self.plots.draw(vis_args, plane)

Check warning on line 1489 in rocketpy/rocket/rocket.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/rocket/rocket.py#L1489

Added line #L1489 was not covered by tests

def info(self):
"""Prints out a summary of the data and graphs available about
Expand Down
15 changes: 9 additions & 6 deletions rocketpy/sensors/accelerometer.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@
temperature drift.
"""

__units__ = "m/s^2"

def __init__(
self,
sampling_rate,
Expand Down Expand Up @@ -191,7 +193,6 @@
cross_axis_sensitivity=cross_axis_sensitivity,
name=name,
)
self.type = "Accelerometer"
self.consider_gravity = consider_gravity
self.prints = _AccelerometerPrints(self)

Expand Down Expand Up @@ -236,7 +237,7 @@
)
A = inertial_to_sensor @ A

# Apply noise + bias and quatize
# Apply noise + bias and quantize
A = self.apply_noise(A)
A = self.apply_temperature_drift(A)
A = self.quantize(A)
Expand All @@ -260,7 +261,9 @@
-------
None
"""
if format == "csv":
if format.lower() not in ["json", "csv"]:
raise ValueError("Invalid format")

Check warning on line 265 in rocketpy/sensors/accelerometer.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/accelerometer.py#L265

Added line #L265 was not covered by tests
if format.lower() == "csv":
# if sensor has been added multiple times to the simulated rocket
if isinstance(self.measured_data[0], list):
print("Data saved to", end=" ")
Expand All @@ -276,7 +279,8 @@
for t, ax, ay, az in self.measured_data:
f.write(f"{t},{ax},{ay},{az}\n")
print(f"Data saved to {filename}")
elif format == "json":
return
if format.lower() == "json":
if isinstance(self.measured_data[0], list):
print("Data saved to", end=" ")
for i, data in enumerate(self.measured_data):
Expand All @@ -299,5 +303,4 @@
with open(filename, "w") as f:
json.dump(dict, f)
print(f"Data saved to {filename}")
else:
raise ValueError("Invalid format")
return
13 changes: 8 additions & 5 deletions rocketpy/sensors/gyroscope.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@
temperature drift.
"""

__units__ = "rad/s"

def __init__(
self,
sampling_rate,
Expand Down Expand Up @@ -191,7 +193,6 @@
cross_axis_sensitivity=cross_axis_sensitivity,
name=name,
)
self.type = "Gyroscope"
self.acceleration_sensitivity = self._vectorize_input(
acceleration_sensitivity, "acceleration_sensitivity"
)
Expand Down Expand Up @@ -291,7 +292,9 @@
-------
None
"""
if format == "csv":
if format.lower() not in ["csv", "json"]:
raise ValueError("Invalid format")

Check warning on line 296 in rocketpy/sensors/gyroscope.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/gyroscope.py#L296

Added line #L296 was not covered by tests
if format.lower() == "csv":
# if sensor has been added multiple times to the simulated rocket
if isinstance(self.measured_data[0], list):
print("Data saved to", end=" ")
Expand All @@ -307,7 +310,8 @@
for t, wx, wy, wz in self.measured_data:
f.write(f"{t},{wx},{wy},{wz}\n")
print(f"Data saved to {filename}")
elif format == "json":
return
if format.lower() == "json":
if isinstance(self.measured_data[0], list):
print("Data saved to", end=" ")
for i, data in enumerate(self.measured_data):
Expand All @@ -330,5 +334,4 @@
with open(filename, "w") as f:
json.dump(dict, f)
print(f"Data saved to {filename}")
else:
raise ValueError("Invalid format")
return
10 changes: 6 additions & 4 deletions rocketpy/sensors/sensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@
standard rotation sequence is z-y-x (3-2-1) is used, meaning the
sensor is first rotated by ψ around the z axis, then by θ around
the new y axis and finally by φ around the new x axis.
TODO: x and y are not defined in the rocket class. User has no
way to know which axis is which.
- A list of lists (matrix) of shape 3x3, representing the rotation
matrix from the sensor frame to the rocket frame. The sensor frame
of reference is defined as to have z axis along the sensor's normal
Expand Down Expand Up @@ -194,21 +196,23 @@

# handle measurement range
if isinstance(measurement_range, (tuple, list)):
if len(measurement_range) != 2:
raise ValueError("Invalid measurement range format")
self.measurement_range = measurement_range

Check warning on line 201 in rocketpy/sensors/sensors.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/sensors.py#L199-L201

Added lines #L199 - L201 were not covered by tests
elif isinstance(measurement_range, (int, float)):
self.measurement_range = (-measurement_range, measurement_range)
else:
raise ValueError("Invalid measurement range format")

Check warning on line 205 in rocketpy/sensors/sensors.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/sensors.py#L205

Added line #L205 was not covered by tests

# rotation matrix and normal vector
if any(isinstance(row, (tuple, list)) for row in orientation): # matrix
self.rotation_matrix = Matrix(orientation)

Check warning on line 209 in rocketpy/sensors/sensors.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/sensors.py#L209

Added line #L209 was not covered by tests
elif len(orientation) == 3: # euler angles
self.rotation_matrix = Matrix.transformation_euler_angles(*orientation)
self.rotation_matrix = Matrix.transformation_euler_angles(
*orientation
).round(12)
else:
raise ValueError("Invalid orientation format")

Check warning on line 215 in rocketpy/sensors/sensors.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/sensors.py#L215

Added line #L215 was not covered by tests
self.normal_vector = Vector(
[
self.rotation_matrix[0][2],
Expand All @@ -233,10 +237,10 @@
self._attached_rockets = {}

def __repr__(self):
return f"{self.name}"

Check warning on line 240 in rocketpy/sensors/sensors.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/sensors.py#L240

Added line #L240 was not covered by tests

def __call__(self, *args, **kwargs):
return self.measure(*args, **kwargs)

Check warning on line 243 in rocketpy/sensors/sensors.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/sensors.py#L243

Added line #L243 was not covered by tests

def _vectorize_input(self, value, name):
if isinstance(value, (int, float)):
Expand All @@ -244,7 +248,7 @@
elif isinstance(value, (tuple, list)):
return Vector(value)
else:
raise ValueError(f"Invalid {name} format")

Check warning on line 251 in rocketpy/sensors/sensors.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/sensors.py#L251

Added line #L251 was not covered by tests

def _reset(self, simulated_rocket):
"""Reset the sensor data for a new simulation."""
Expand Down Expand Up @@ -274,11 +278,11 @@

@abstractmethod
def measure(self, *args, **kwargs):
pass

Check warning on line 281 in rocketpy/sensors/sensors.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/sensors.py#L281

Added line #L281 was not covered by tests

@abstractmethod
def export_measured_data(self):
pass

Check warning on line 285 in rocketpy/sensors/sensors.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/sensors/sensors.py#L285

Added line #L285 was not covered by tests

def quantize(self, value):
"""
Expand Down Expand Up @@ -366,6 +370,4 @@
Vector([1, 1, 1])
+ (self.operating_temperature - 25) / 100 * self.temperature_scale_factor
)
value = value & scale_factor

return value
return value & scale_factor
16 changes: 3 additions & 13 deletions rocketpy/simulation/flight.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,11 +606,8 @@
self.terminate_on_apogee = terminate_on_apogee
self.name = name
self.equations_of_motion = equations_of_motion

# Controller initialization
self.__init_controllers()

# Flight initialization
self.__init_controllers()
self.__init_post_process_variables()
self.__init_solution_monitors()
self.__init_equations_of_motion()
Expand Down Expand Up @@ -744,7 +741,7 @@
self.env.barometric_height(pressure + noise)
- self.env.elevation
)
if parachute.triggerfunc(

Check warning on line 744 in rocketpy/simulation/flight.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/simulation/flight.py#L744

Added line #L744 was not covered by tests
pressure + noise, hAGL, self.y_sol, self.sensors
):
# print('\nEVENT DETECTED')
Expand Down Expand Up @@ -778,7 +775,7 @@
)
# Prepare to leave loops and start new flight phase
phase.TimeNodes.flush_after(node_index)
phase.TimeNodes.add_node(self.t, [], [], [])

Check warning on line 778 in rocketpy/simulation/flight.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/simulation/flight.py#L778

Added line #L778 was not covered by tests
phase.solver.status = "finished"
# Save parachute event
self.parachute_events.append([self.t, parachute])
Expand Down Expand Up @@ -1250,7 +1247,7 @@
self.sensors = self.rocket.sensors.get_components()
if self._controllers or self.sensors:
if self.time_overshoot == True:
self.time_overshoot = False

Check warning on line 1250 in rocketpy/simulation/flight.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/simulation/flight.py#L1250

Added line #L1250 was not covered by tests
warnings.warn(
"time_overshoot has been set to False due to the presence "
"of controllers or sensors. "
Expand Down Expand Up @@ -1288,22 +1285,15 @@
]

def __cache_sensor_data(self):
"""Cache sensor data for simulations with sensors."""
sensor_data = {}
sensors = []
for sensor in self.sensors:
# skip sensors that are used more then once in the rocket
if sensor not in sensors:
sensors.append(sensor)
num_instances = sensor._attached_rockets[self.rocket]
# sensor added only once
if num_instances == 1:
sensor_data[sensor] = sensor.measured_data[:]
# sensor added more then once
if num_instances > 1:
sensor_data[sensor] = {}
# iterate through each of the same sensor instances
for index in range(num_instances):
sensor_data[sensor][index + 1] = sensor.measured_data[index][:]
sensor_data[sensor] = sensor.measured_data[:]
self.sensor_data = sensor_data

@cached_property
Expand Down Expand Up @@ -1712,12 +1702,12 @@

if post_processing:
# Accelerations
self.ax_list.append([t, ax])
self.ay_list.append([t, ay])
self.az_list.append([t, az])
self.alpha1_list.append([t, alpha1])
self.alpha2_list.append([t, alpha2])
self.alpha3_list.append([t, alpha3])

Check warning on line 1710 in rocketpy/simulation/flight.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/simulation/flight.py#L1705-L1710

Added lines #L1705 - L1710 were not covered by tests
# Dynamics variables
self.R1_list.append([t, R1])
self.R2_list.append([t, R2])
Expand Down Expand Up @@ -3415,8 +3405,8 @@
data_dict[key.name] = value
else:
# export data of only that sensor
data_dict = {}
data_dict[sensor.name] = self.sensor_data[sensor]

Check warning on line 3409 in rocketpy/simulation/flight.py

View check run for this annotation

Codecov / codecov/patch

rocketpy/simulation/flight.py#L3408-L3409

Added lines #L3408 - L3409 were not covered by tests
with open(file_name, "w") as file:
json.dump(data_dict, file)
print("Sensor data exported to", file_name)
Expand Down
32 changes: 17 additions & 15 deletions rocketpy/tools.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import functools
import importlib
import importlib.metadata
import math
import re
import time
from bisect import bisect_left
Expand Down Expand Up @@ -467,32 +468,33 @@ def quaternions_to_nutation(e1, e2):
return (180 / np.pi) * 2 * np.arcsin(-((e1**2 + e2**2) ** 0.5))


def euler_to_quaternions(roll, pitch, yaw):
"""Calculates the quaternions from the Euler angles in 3-2-1 sequence.
def euler_to_quaternions(yaw, pitch, roll):
"""Calculates the quaternions (Euler parameters) from the Euler angles in
yaw, pitch, and roll sequence (3-2-1).

Parameters
----------
roll : float
Euler angle due to roll (psi) in degrees
pitch : float
Euler angle due to pitch (theta) in degrees
yaw : float
Euler angle due to yaw (phi) in degrees
pitch : float
Euler angle due to pitch (theta) in degrees
roll : float
Euler angle due to roll (psi) in degrees

Returns
-------
tuple
Tuple containing the Euler parameters e0, e1, e2, e3
"""
psi = np.radians(roll)
theta = np.radians(pitch)
phi = np.radians(yaw)
cr = np.cos(phi / 2)
sr = np.sin(phi / 2)
cp = np.cos(theta / 2)
sp = np.sin(theta / 2)
cy = np.cos(psi / 2)
sy = np.sin(psi / 2)
phi = math.radians(yaw)
theta = math.radians(pitch)
psi = math.radians(roll)
cr = math.cos(phi / 2)
sr = math.sin(phi / 2)
cp = math.cos(theta / 2)
sp = math.sin(theta / 2)
cy = math.cos(psi / 2)
sy = math.sin(psi / 2)
e0 = cr * cp * cy + sr * sp * sy
e1 = sr * cp * cy - cr * sp * sy
e2 = cr * sp * cy + sr * cp * sy
Expand Down
Loading
Loading