Skip to content

Commit

Permalink
Formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Tim Smit committed Feb 26, 2024
1 parent 1b5d536 commit 2082b42
Show file tree
Hide file tree
Showing 24 changed files with 108 additions and 264 deletions.
4 changes: 1 addition & 3 deletions examples/Learning_example/simple_neural_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,7 @@ def __len__(self):
elif self.node_id == 2:
train_mask = X_train[:, 0] > -0

X_train = np.ma.compress_rows(
np.ma.masked_array(X_train, mask=np.transpose(np.tile(train_mask, (2, 1))))
)
X_train = np.ma.compress_rows(np.ma.masked_array(X_train, mask=np.transpose(np.tile(train_mask, (2, 1)))))
y_train = np.ma.masked_array(y_train, mask=train_mask).compressed()

# Create dataloaders
Expand Down
12 changes: 3 additions & 9 deletions examples/MPI_example/mpi_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@
t0 = pk.epoch_from_string("2023-Jan-04 20:00:00") # the starting date of our simulation

# Compute the orbit of each rank
planet_list, sats_pos_and_v, _ = get_constellation(
altitude, inclination, nSats, nPlanes, t0, verbose=False
)
planet_list, sats_pos_and_v, _ = get_constellation(altitude, inclination, nSats, nPlanes, t0, verbose=False)
print(f"Rank {rank} set up its orbit with altitude={altitude}m and inclination={inclination}deg")

############ PASEOS INIT #############
Expand All @@ -69,9 +67,7 @@
pos, v = sats_pos_and_v[0] # get our position and velocity

# Create the local actor, name will be the rank
local_actor = ActorBuilder.get_actor_scaffold(
name="Sat_" + str(rank), actor_type=SpacecraftActor, epoch=t0
)
local_actor = ActorBuilder.get_actor_scaffold(name="Sat_" + str(rank), actor_type=SpacecraftActor, epoch=t0)
ActorBuilder.set_orbit(actor=local_actor, position=pos, velocity=v, epoch=t0, central_body=earth)

paseos_instance = paseos.init_sim(local_actor=local_actor)
Expand Down Expand Up @@ -131,9 +127,7 @@ def constraint_func(verbose=SHOW_ALL_WINDOWS):
# Advance the simulation state of this rank
# Note how we pass the "constraint_func" to tell paseos
# to track windows
paseos_instance.advance_time(
timestep, current_power_consumption_in_W=0, constraint_function=constraint_func
)
paseos_instance.advance_time(timestep, current_power_consumption_in_W=0, constraint_function=constraint_func)
t += timestep

sys.stdout.flush() # update prints to better see parallelism
Expand Down
8 changes: 2 additions & 6 deletions examples/MPI_example/mpi_utility_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@ def _parse_actor_data(actor_data):
Returns:
actor: Created actor
"""
actor = ActorBuilder.get_actor_scaffold(
name=actor_data[0], actor_type=SpacecraftActor, epoch=actor_data[1]
)
actor = ActorBuilder.get_actor_scaffold(name=actor_data[0], actor_type=SpacecraftActor, epoch=actor_data[1])
ActorBuilder.set_orbit(
actor=actor,
position=actor_data[2],
Expand Down Expand Up @@ -84,6 +82,4 @@ def exchange_actors(comm, paseos_instance, local_actor, other_ranks, rank, verbo
send_request.wait()

if verbose:
print(
f"Rank {rank} completed actor exchange. Knows {paseos_instance.known_actor_names} now."
)
print(f"Rank {rank} completed actor exchange. Knows {paseos_instance.known_actor_names} now.")
16 changes: 4 additions & 12 deletions examples/Orekit_example/orekit_propagator.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,13 @@ def __init__(self, orbital_elements: list, epoch: AbsoluteDate, satellite_mass:
)

# Set up the numerical propagator tolerance
tolerances = NumericalPropagator.tolerances(
self.positionTolerance, initialOrbit, initialOrbit.getType()
)
tolerances = NumericalPropagator.tolerances(self.positionTolerance, initialOrbit, initialOrbit.getType())

# Set up the numerical integrator
integrator = DormandPrince853Integrator(
self.minStep,
self.maxstep,
JArray_double.cast_(
tolerances[0]
), # Double array of doubles needs to be casted in Python
JArray_double.cast_(tolerances[0]), # Double array of doubles needs to be casted in Python
JArray_double.cast_(tolerances[1]),
)
integrator.setInitialStepSize(self.initStep)
Expand All @@ -87,9 +83,7 @@ def __init__(self, orbital_elements: list, epoch: AbsoluteDate, satellite_mass:
# Add the force models
gravityProvider = GravityFieldFactory.getNormalizedProvider(10, 10)
self.propagator_num.addForceModel(
HolmesFeatherstoneAttractionModel(
FramesFactory.getITRF(IERSConventions.IERS_2010, True), gravityProvider
)
HolmesFeatherstoneAttractionModel(FramesFactory.getITRF(IERSConventions.IERS_2010, True), gravityProvider)
)

def eph(self, time_since_epoch_in_seconds: float):
Expand All @@ -101,8 +95,6 @@ def eph(self, time_since_epoch_in_seconds: float):
Returns:
orekit SpacecraftState: The position and velocity of the satellite.
"""
state = self.propagator_num.propagate(
self.initialDate, self.initialDate.shiftedBy(time_since_epoch_in_seconds)
)
state = self.propagator_num.propagate(self.initialDate, self.initialDate.shiftedBy(time_since_epoch_in_seconds))

return state
8 changes: 2 additions & 6 deletions examples/Sentinel_2_example_notebook/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,7 @@ def acquire_data(file_name):
lats = np.array(xs)
coords_dict = {"lat": lats, "lon": lons}

sentinel_img = (
sentinel_img.transpose(1, 2, 0) / 10000 + 1e-13
) # Diving for the default quantification value
sentinel_img = sentinel_img.transpose(1, 2, 0) / 10000 + 1e-13 # Diving for the default quantification value

return sentinel_img, coords_dict

Expand Down Expand Up @@ -228,9 +226,7 @@ def s2pix_detector(
list: [list of bounding boxes objects, list of bounding boxes coordinates]
"""

alert_matrix, _, _, _, _ = get_alert_matrix_and_thresholds(
sentinel_img, alpha_thr, beta_thr, S_thr, gamma_thr
)
alert_matrix, _, _, _, _ = get_alert_matrix_and_thresholds(sentinel_img, alpha_thr, beta_thr, S_thr, gamma_thr)
filtered_alert_matrix = cluster_9px(alert_matrix)
filtered_alert_matrix[filtered_alert_matrix < 9] = 0
filtered_alert_matrix[filtered_alert_matrix == 9] = 1
Expand Down
13 changes: 3 additions & 10 deletions paseos/activities/activity_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,7 @@ def register_activity(

if name in self._activities.keys():
raise ValueError(
"Trying to add already existing activity with name: "
+ name
+ ". Already have "
+ str(self._activities[name])
"Trying to add already existing activity with name: " + name + ". Already have " + str(self._activities[name])
)

self._activities[name] = DotMap(
Expand Down Expand Up @@ -104,15 +101,11 @@ def perform_activity(
constraint_func_args (list, optional): Arguments for the constraint function. Defaults to None.
"""
# Check if activity exists and if it already had consumption specified
assert (
name in self._activities.keys()
), f"Activity not found. Declared activities are {self._activities.keys()}"
assert name in self._activities.keys(), f"Activity not found. Declared activities are {self._activities.keys()}"
activity = self._activities[name]
logger.debug(f"Performing activity {activity}")

assert (
activity.power_consumption_in_watt >= 0
), "Power consumption has to be positive but was specified as " + str(
assert activity.power_consumption_in_watt >= 0, "Power consumption has to be positive but was specified as " + str(
activity.power_consumption_in_watt
)

Expand Down
14 changes: 3 additions & 11 deletions paseos/activities/activity_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,7 @@ def __init__(
"""
logger.trace("Initalized ActivityProcessor.")
assert update_interval > 0, "Update update_interval has to be positive."
assert (
power_consumption_in_watt >= 0
), "Power consumption has to be positive but was specified as " + str(
assert power_consumption_in_watt >= 0, "Power consumption has to be positive but was specified as " + str(
power_consumption_in_watt
)

Expand Down Expand Up @@ -64,10 +62,7 @@ async def stop(self):
# Calculate elapsed time since last update
elapsed_time = timer() - self.start_time
# Perform final update if not interrupted before (otherwise already upto date)
if (
not self._paseos_instance.local_actor.was_interrupted
and not self._paseos_instance.local_actor.is_dead
):
if not self._paseos_instance.local_actor.was_interrupted and not self._paseos_instance.local_actor.is_dead:
await self._update(elapsed_time)
# Reset interrupt (to prepare for potential next interrupt)
self._paseos_instance.local_actor._was_interrupted = False
Expand Down Expand Up @@ -113,10 +108,7 @@ async def _run(self):
# otherwise stop it and then the processor

# Radiation interruption leads to stop
if (
self._paseos_instance.local_actor.was_interrupted
or self._paseos_instance.local_actor.is_dead
):
if self._paseos_instance.local_actor.was_interrupted or self._paseos_instance.local_actor.is_dead:
await self.stop()
await self._activity_runner.stop()

Expand Down
16 changes: 4 additions & 12 deletions paseos/activities/activity_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,7 @@ async def stop(self):
try:
await self._termination_func(self._termination_args)
except Exception as e:
logger.error(
f"An exception occurred running the terminating the activity {self.name}."
)
logger.error(f"An exception occurred running the terminating the activity {self.name}.")
logger.error(str(e))
self.is_started = False
# Stop task and await it stopped:
Expand All @@ -106,20 +104,14 @@ async def check_constraint(self):
+ " The constraint function failed to return True or False."
)
except Exception as e:
logger.error(
f"An exception occurred running the checking the activity {self.name} constraint."
)
logger.error(f"An exception occurred running the checking the activity {self.name} constraint.")
logger.error(str(e))
return False
if not is_satisfied:
logger.debug(
f"Constraint of activity {self.name} is no longer satisfied, cancelling."
)
logger.debug(f"Constraint of activity {self.name} is no longer satisfied, cancelling.")
if not self._was_stopped:
await self.stop()
return False
else:
logger.warning(
f"Checking activity {self.name} constraints even though activity has no constraints."
)
logger.warning(f"Checking activity {self.name} constraints even though activity has no constraints.")
return True
1 change: 1 addition & 0 deletions paseos/actors/ground_station_actor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from loguru import logger
import pykep as pk
from skyfield.api import load

from .base_actor import BaseActor


Expand Down
10 changes: 4 additions & 6 deletions paseos/actors/spacecraft_actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ class SpacecraftActor(BaseActor):
_is_dead = False

def __init__(
self,
name: str,
epoch: pk.epoch,
self,
name: str,
epoch: pk.epoch,
) -> None:
"""Constructor for a spacecraft actor
Expand Down Expand Up @@ -158,9 +158,7 @@ def charge(self, duration_in_s: float):
duration_in_s (float): How long the activity is performed in seconds
"""
logger.debug(f"Charging actor {self} for {duration_in_s}s.")
assert (
duration_in_s > 0
), "Charging interval has to be positive but t1 was less or equal t0."
assert duration_in_s > 0, "Charging interval has to be positive but t1 was less or equal t0."

self = charge_model.charge(self, duration_in_s)

Expand Down
14 changes: 3 additions & 11 deletions paseos/central_body/central_body.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,9 @@ def __init__(
self._mesh = mesh
if encompassing_sphere_radius is not None:
self._encompassing_sphere = Sphere([0, 0, 0], encompassing_sphere_radius)
if (
rotation_declination is not None
and rotation_right_ascension is not None
and rotation_period is not None
):
if rotation_declination is not None and rotation_right_ascension is not None and rotation_period is not None:
if mesh is None or encompassing_sphere_radius is not None:
logger.warning(
"You provided rotation parameters but no mesh. This will result in a non-rotating body."
)
logger.warning("You provided rotation parameters but no mesh. This will result in a non-rotating body.")

# Convert to rad
rotation_declination = radians(rotation_declination)
Expand Down Expand Up @@ -110,9 +104,7 @@ def blocks_sun(self, actor, t: pk.epoch, plot=False) -> bool:
r_sat_heliocentric = r_central_body_heliocentric + r_sat_central_body_frame
logger.trace("r_sat_heliocentric is" + str(r_sat_heliocentric))

return self.is_between_points(
[0, 0, 0], r_sat_heliocentric, t, ReferenceFrame.Heliocentric, plot
)
return self.is_between_points([0, 0, 0], r_sat_heliocentric, t, ReferenceFrame.Heliocentric, plot)

def is_between_actors(self, actor_1, actor_2, t: pk.epoch, plot=False) -> bool:
"""Checks whether the central body is between the two actors.
Expand Down
Loading

0 comments on commit 2082b42

Please sign in to comment.