code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
def calculate_lateral_gains(sim, state, vehicle, desired_poles, target_speed): """Update the state lateral gains""" # Only calculate gains if the target_speed is updated. # TODO: Replace this w/ an isclose(...) check if state.target_speed == target_speed: return state.target_speed = target_speed # Vehicle params half_vehicle_len = vehicle.length / 2 vehicle_mass, vehicle_inertia_z = vehicle.chassis.mass_and_inertia road_stiffness = sim.road_stiffness # Linearization of lateral dynamics if target_speed > 0: state_matrix = np.array( [ [0, target_speed, 0, target_speed], [0, 0, 1, 0], [ 0, 0, -(2 * road_stiffness * (half_vehicle_len**2)) / (target_speed * vehicle_inertia_z), 0, ], [ 0, 0, -1, -2 * road_stiffness / (vehicle_mass * target_speed), ], ] ) input_matrix = np.array( [ [0], [0], [half_vehicle_len * road_stiffness / vehicle_inertia_z], [road_stiffness / (vehicle_mass * target_speed)], ] ) K = LaneFollowingController.place_poles( state_matrix, input_matrix, desired_poles ) # These constants are the min/max gains for the lateral error controller # and the heading controller, respectively. This is done to ensure that # the linearization error will not affect the stability of the controller. state.lateral_error_gain = np.clip(K[0], 3.4, 4.1) state.heading_error_gain = np.clip(K[1], 0.02, 0.04) else: # 0.01 and 0.36 are initial values for heading and lateral gains # This is only done to ensure that the vehicle starts to move for # the first time step where speed=0 state.heading_error_gain = 0.01 state.lateral_error_gain = 0.36
Update the state lateral gains
calculate_lateral_gains
python
huawei-noah/SMARTS
smarts/core/controllers/lane_following_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/lane_following_controller.py
MIT
def perform_action(cls, vehicle, action, state, dt_sec): """Perform throttle, break, and steering, keeping the previous steering angle as the start for the next steering angle. """ throttle, brake, steering_change = action # The following is the normalized steering change # under the assumption that the steering angles at # wheels can reach to their maximum values in one # second. clipped_steering_change = np.clip( steering_change, -1, 1, ) p = 0.001 # XXX: Theorized to improve stability, this has yet to be seen. steering = np.clip( (1 - p) * state.last_steering_angle + clipped_steering_change * dt_sec, -1, 1, ) vehicle.control( throttle=np.clip(throttle, 0.0, 1.0), brake=np.clip(brake, 0.0, 1.0), steering=steering, ) state.last_steering_angle = steering
Perform throttle, break, and steering, keeping the previous steering angle as the start for the next steering angle.
perform_action
python
huawei-noah/SMARTS
smarts/core/controllers/actuator_dynamic_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/actuator_dynamic_controller.py
MIT
def perform_trajectory_tracking_MPC( trajectory: Tuple[ Sequence[float], Sequence[float], Sequence[float], Sequence[float] ], vehicle, state, dt_sec: float, prediction_horizon: int = 5, ): """Attempts model predictive control for the given vehicle given an expected trajectory.""" half_vehicle_len = vehicle.length / 2 vehicle_mass, vehicle_inertia_z = vehicle.chassis.mass_and_inertia ( heading_error, lateral_error, ) = TrajectoryTrackingController.calculate_heading_lateral_error( vehicle=vehicle, trajectory=trajectory, initial_look_ahead_distant=3, speed_reduction_activation=True, ) raw_throttle = TrajectoryTrackingController.calculate_raw_throttle_feedback( vehicle=vehicle, state=state, trajectory=trajectory, velocity_gain=1, velocity_integral_gain=0, integral_velocity_error=0, velocity_damping_gain=0, windup_gain=0, traction_gain=8, speed_reduction_activation=True, throttle_filter_constant=10, dt_sec=dt_sec, )[0] if raw_throttle > 0: brake_norm, throttle_norm = 0, np.clip(raw_throttle, 0, 1) else: brake_norm, throttle_norm = np.clip(-raw_throttle, 0, 1), 0 longitudinal_velocity = vehicle.chassis.longitudinal_lateral_speed[0] # If longitudinal speed is less than 0.1 (m/s) then use 0.1 (m/s) as # the speed for state and input matrix calculations. longitudinal_velocity = max(0.1, longitudinal_velocity) state_matrix = np.array( [ [0, 1, 0, 0], [ 0, -( vehicle.chassis.front_rear_stiffness[0] + vehicle.chassis.front_rear_stiffness[1] ) / (vehicle_mass * longitudinal_velocity), ( vehicle.chassis.front_rear_stiffness[0] + vehicle.chassis.front_rear_stiffness[1] ) / vehicle_mass, half_vehicle_len * ( vehicle.chassis.front_rear_stiffness[0] + vehicle.chassis.front_rear_stiffness[1] ) / (vehicle_mass * longitudinal_velocity), ], [0, 0, 0, 1], [ 0, half_vehicle_len * ( -vehicle.chassis.front_rear_stiffness[0] + vehicle.chassis.front_rear_stiffness[1] ) / (vehicle_mass * longitudinal_velocity), half_vehicle_len * ( vehicle.chassis.front_rear_stiffness[0] - vehicle.chassis.front_rear_stiffness[1] ) / vehicle_mass, (half_vehicle_len**2) * ( vehicle.chassis.front_rear_stiffness[0] - vehicle.chassis.front_rear_stiffness[1] ) / (vehicle_mass * longitudinal_velocity), ], ] ) input_matrix = np.array( [ [0], [vehicle.chassis.front_rear_stiffness[0] / vehicle_mass], [0], [vehicle.chassis.front_rear_stiffness[1] / vehicle_inertia_z], ] ) drift_matrix = TrajectoryTrackingController.mpc_drift_matrix( vehicle, trajectory, prediction_horizon ) steering_norm = -TrajectoryTrackingController.MPC( trajectory, heading_error, lateral_error, dt_sec, state_matrix, input_matrix, drift_matrix, prediction_horizon, ) vehicle.control( throttle=throttle_norm, brake=brake_norm, steering=steering_norm, )
Attempts model predictive control for the given vehicle given an expected trajectory.
perform_trajectory_tracking_MPC
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_tracking_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_tracking_controller.py
MIT
def perform_trajectory_tracking_PD( trajectory, vehicle, state, dt_sec, ): """Attempts proportional derivative control for the vehicle given an expected trajectory. """ # Controller parameters for trajectory tracking. params = vehicle.chassis.controller_parameters final_heading_gain = params["final_heading_gain"] final_lateral_gain = params["final_lateral_gain"] final_steering_filter_constant = params["final_steering_filter_constant"] throttle_filter_constant = params["throttle_filter_constant"] velocity_gain = params["velocity_gain"] velocity_integral_gain = params["velocity_integral_gain"] traction_gain = params["traction_gain"] final_lateral_error_derivative_gain = params[ "final_lateral_error_derivative_gain" ] final_heading_error_derivative_gain = params[ "final_heading_error_derivative_gain" ] initial_look_ahead_distant = params["initial_look_ahead_distant"] derivative_activation = params["derivative_activation"] speed_reduction_activation = params["speed_reduction_activation"] velocity_damping_gain = params["velocity_damping_gain"] windup_gain = params["windup_gain"] # XXX: note that these values may be further adjusted below based on speed and curvature # XXX: we might want to combine the computation of these into a single fn lateral_gain = 0.61 heading_gain = 0.01 lateral_error_derivative_gain = 0.15 heading_error_derivative_gain = 0.5 # The gains can vary according to the desired velocity along # the trajectory. To achieve this, the desired speed is normalized # between 20 (km/hr) to 80 (km/hr) and the respective gains are # calculated using interpolation. 3, 0.03, 1.5, 0.2 are the # controller gains for lateral error, heading error and their # derivatives at the desired speed 20 (km/hr). normalized_speed = np.clip( (METER_PER_SECOND_TO_KM_PER_HR * trajectory[3][0] - 20) / (80 - 20), 0, 1 ) adjust_gains_for_normalized_speed = False # XXX: not using model config here if adjust_gains_for_normalized_speed: lateral_gain = lerp(3, final_lateral_gain, normalized_speed) lateral_error_derivative_gain = lerp( 0.2, final_lateral_error_derivative_gain, normalized_speed ) heading_gain = lerp(0.03, final_heading_gain, normalized_speed) heading_error_derivative_gain = lerp( 1.5, final_heading_error_derivative_gain, normalized_speed ) steering_filter_constant = lerp( 12, final_steering_filter_constant, normalized_speed ) elif vehicle.speed > 70 / METER_PER_SECOND_TO_KM_PER_HR: lateral_gain = 1.51 heading_error_derivative_gain = 0.1 # XXX: This should be handled like the other gains above... steering_filter_constant = lerp( 12, final_steering_filter_constant, normalized_speed ) if abs(min_angles_difference_signed(trajectory[2][-1], trajectory[2][0])) > 2: throttle_filter_constant = 2.5 if ( abs( TrajectoryTrackingController.curvature_calculation( trajectory, 0, num_points=3 ) ) < 150 ): heading_gain = 0.05 lateral_error_derivative_gain = 0.015 heading_error_derivative_gain = 0.05 ( heading_error, lateral_error, ) = TrajectoryTrackingController.calculate_heading_lateral_error( vehicle, trajectory, initial_look_ahead_distant, speed_reduction_activation ) curvature_radius = TrajectoryTrackingController.curvature_calculation( trajectory ) # Derivative terms of the controller (use with caution for large time steps>=0.1). # Increasing the values will increase the convergence time and reduces the oscillation. z_yaw = vehicle.chassis.velocity_vectors[1][2] derivative_term = ( +heading_error_derivative_gain * z_yaw + lateral_error_derivative_gain * (lateral_error - state.lateral_error) / dt_sec ) # Raw steering controller, default values 0.11 and 0.65 are used for heading and # lateral control gains. # TODO: The lateral and heading gains of the steering controller should be # calculated based on the current velocity. The coefficient value for the # feed forward term is 0.1 and it depends on the cornering stiffness and # vehicle inertia properties. steering_feed_forward_term = 0.1 * (1 / curvature_radius) * (vehicle.speed) ** 2 steering_raw = np.clip( derivative_activation * derivative_term + math.degrees(heading_gain * (heading_error)) + 1 * lateral_gain * lateral_error - steering_feed_forward_term, -1, 1, ) # The steering linear low pass filter. state.steering_state = low_pass_filter( steering_raw, state.steering_state, steering_filter_constant, dt_sec ) ( raw_throttle, desired_speed, ) = TrajectoryTrackingController.calculate_raw_throttle_feedback( vehicle, state, trajectory, velocity_gain, velocity_integral_gain, state.integral_velocity_error, velocity_damping_gain, windup_gain, traction_gain, speed_reduction_activation, throttle_filter_constant, dt_sec, ) if raw_throttle > 0: brake_norm, throttle_norm = 0, np.clip(raw_throttle, 0, 1) else: brake_norm, throttle_norm = np.clip(-raw_throttle, 0, 1), 0 state.heading_error = heading_error state.lateral_error = lateral_error state.integral_velocity_error += (vehicle.speed - desired_speed) * dt_sec vehicle.control( throttle=throttle_norm, brake=brake_norm, steering=state.steering_state, )
Attempts proportional derivative control for the vehicle given an expected trajectory.
perform_trajectory_tracking_PD
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_tracking_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_tracking_controller.py
MIT
def calculate_raw_throttle_feedback( vehicle, state, trajectory, velocity_gain, velocity_integral_gain, integral_velocity_error, velocity_damping_gain, windup_gain, traction_gain, speed_reduction_activation, throttle_filter_constant, dt_sec, ): """Applies filters to the throttle for stability.""" desired_speed = trajectory[3][-1] # If the vehicle is on the curvy portion of the road, then the desired speed # will be reduced to 80 percent of the desired speed of the trajectory. # Value 4 is the number of ahead trajectory points for starting the calculation # of the radius of curvature. Value 100 is the threshold for reducing the # desired speed profile. This value can be approximated using the # formula v^2/R=mu*g. In addition, we used additional threshold 30 for very # sharp turn in which the desired speed of the vehicle is set to 80 # percent of the original values with the upperbound of 29.8 m/s(30 km/hr). absolute_ahead_curvature = abs( TrajectoryTrackingController.curvature_calculation(trajectory, 4) ) if absolute_ahead_curvature < 30 and speed_reduction_activation: desired_speed = np.clip(0.8 * desired_speed, 0, 8.3) elif absolute_ahead_curvature < 100 and speed_reduction_activation: desired_speed *= 0.8 # Main velocity profile tracking controller, the default gain value is 0.1. # Default value 3 for the traction controller term involving lateral velocity is # chosen for better performance on curvy portion of the road. Note that # it should be at least one order of magnitude above the velocity # tracking term to ensure stability. velocity_error = vehicle.speed - desired_speed velocity_error_damping_term = (velocity_error - state.velocity_error) / dt_sec raw_throttle = METER_PER_SECOND_TO_KM_PER_HR * ( -0.5 * velocity_gain * velocity_error - velocity_integral_gain * (integral_velocity_error + windup_gain * state.integral_windup_error) - velocity_damping_gain * velocity_error_damping_term ) state.velocity_error = velocity_error # The anti-windup term inspired by: # https://ocw.mit.edu/courses/aeronautics-and-astronautics/16-30-feedback-control-systems-fall-2010/lecture-notes/MIT16_30F10_lec23.pdf state.integral_windup_error = np.clip(raw_throttle, -1, 1) - raw_throttle # The low pass filter for throttle. The traction control term is # applied after filter is applied to the velocity feedback. state.throttle_state = low_pass_filter( raw_throttle, state.throttle_state, throttle_filter_constant, dt_sec, raw_value=-traction_gain * abs(vehicle.chassis.longitudinal_lateral_speed[1]), ) return (state.throttle_state, desired_speed)
Applies filters to the throttle for stability.
calculate_raw_throttle_feedback
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_tracking_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_tracking_controller.py
MIT
def calculate_heading_lateral_error( vehicle, trajectory, initial_look_ahead_distant, speed_reduction_activation ): """Determine vehicle heading error and lateral error in regards to the given trajectory.""" heading_error = min_angles_difference_signed( (vehicle.heading % (2 * math.pi)), trajectory[2][0] ) # Number of look ahead points to calculate the # look ahead error. # TODO: Find the number of points using the # distance between trajectory points. look_ahead_points = initial_look_ahead_distant # If we are on the curvy portion of the road # we need to decrease the values for look ahead calculation # The value 30 for road curviness is obtained empirically # for bullet model. if ( abs(TrajectoryTrackingController.curvature_calculation(trajectory, 4)) < 30 and speed_reduction_activation ): initial_look_ahead_distant = 1 look_ahead_points = 1 path_vector = radians_to_vec( trajectory[2][min([look_ahead_points, len(trajectory[2]) - 1])] ) vehicle_look_ahead_pt = [ vehicle.position[0] - initial_look_ahead_distant * math.sin(vehicle.heading), vehicle.position[1] + initial_look_ahead_distant * math.cos(vehicle.heading), ] lateral_error = signed_dist_to_line( vehicle_look_ahead_pt, [ trajectory[0][min([look_ahead_points, len(trajectory[0]) - 1])], trajectory[1][min([look_ahead_points, len(trajectory[1]) - 1])], ], path_vector, ) return (heading_error, lateral_error)
Determine vehicle heading error and lateral error in regards to the given trajectory.
calculate_heading_lateral_error
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_tracking_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_tracking_controller.py
MIT
def curvature_calculation(trajectory, offset=0, num_points=5): """Attempts to approximate the curvature radius of a trajectory""" number_ahead_points = num_points relative_heading_sum, relative_distant_sum = 0, 0 if len(trajectory[2]) <= number_ahead_points + offset: return 1e20 for i in range(number_ahead_points): relative_heading_temp = min_angles_difference_signed( trajectory[2][i + 1 + offset], trajectory[2][i + offset] ) relative_heading_sum += relative_heading_temp relative_distant_sum += abs( math.sqrt( (trajectory[0][i + offset] - trajectory[0][i + offset + 1]) ** 2 + (trajectory[1][i + offset] - trajectory[1][i + offset + 1]) ** 2 ) ) # If relative_heading_sum is zero, then the local radius # of curvature is infinite, i.e. the local trajectory is # similar to a straight line. if relative_heading_sum == 0: return 1e20 else: curvature_radius = relative_distant_sum / relative_heading_sum if curvature_radius == 0: curvature_radius == 1e-2 return curvature_radius
Attempts to approximate the curvature radius of a trajectory
curvature_calculation
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_tracking_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_tracking_controller.py
MIT
def mpc_drift_matrix(vehicle, trajectory, prediction_horizon=1): """TODO: Clarify""" half_vehicle_len = vehicle.length / 2 vehicle_mass, vehicle_inertia_z = vehicle.chassis.mass_and_inertia factor_matrix = np.array( [ [0], [ ( half_vehicle_len * vehicle.chassis.front_rear_stiffness[0] + half_vehicle_len * vehicle.chassis.front_rear_stiffness[1] ) / vehicle_mass - (vehicle.chassis.longitudinal_lateral_speed[0]) ** 2 ], [0], [ ( (half_vehicle_len**2) * vehicle.chassis.front_rear_stiffness[0] - (half_vehicle_len**2) * vehicle.chassis.front_rear_stiffness[1] ) / vehicle_inertia_z ], ] ) matrix_drift = ( TrajectoryTrackingController.curvature_calculation(trajectory) ** -1 ) * factor_matrix for i in range(prediction_horizon - 1): matrix_drift = np.concatenate( ( matrix_drift, ( TrajectoryTrackingController.curvature_calculation( trajectory, i ) ** -1 ) * factor_matrix, ), axis=1, ) return matrix_drift
TODO: Clarify
mpc_drift_matrix
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_tracking_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_tracking_controller.py
MIT
def MPC( trajectory, heading_error, lateral_error, dt, state_matrix, input_matrix, drift_matrix, prediction_horizon=5, ): """Implementation of MPC, please see the following ref: Convex Optimization – Boyd and Vandenberghe https://github.com/markcannon/markcannon.github.io/blob/c3344814c9c79d5f0d5f3cf8fc2e7ef14cb4fad3/assets/downloads/teaching/C21_Model_Predictive_Control/mpc_notes.pdf https://markcannon.github.io/teaching/ """ matrix_A = np.eye(state_matrix.shape[0]) + dt * state_matrix matrix_B = dt * input_matrix matrix_B0 = dt * drift_matrix matrix_M = matrix_A matrix_C = np.concatenate( ( matrix_B, np.zeros( [matrix_B.shape[0], (prediction_horizon - 1) * matrix_B.shape[1]] ), ), axis=1, ) matrix_T_tilde = matrix_B0[:, 0] for i in range(prediction_horizon - 1): matrix_M = np.concatenate((matrix_M, matrix_power(matrix_A, i + 2)), axis=0) matrix_T_tilde = np.concatenate( ( matrix_T_tilde, np.matmul( matrix_A, matrix_T_tilde[ matrix_T_tilde.shape[0] - matrix_B0.shape[0] : matrix_T_tilde.shape[0] ], matrix_B0[:, i + 1], ), ), axis=0, ) temp = np.matmul(matrix_power(matrix_A, i + 1), matrix_B) for j in range(i + 1, 0, -1): temp = np.concatenate( (temp, np.matmul(matrix_power(matrix_A, j - 1), matrix_B)), axis=1 ) temp = np.concatenate( ( temp, np.zeros( [ matrix_B.shape[0], (prediction_horizon - i - 2) * matrix_B.shape[1], ] ), ), axis=1, ) matrix_C = np.concatenate((matrix_C, temp), axis=0) # Q_tilde contains the MPC state cost weights. The ordering of # gains are as [lateral_error,lateral_velocity,heading_error,yaw_rate]. # Increasing the lateral_error weight can cause oscillations which can # be damped out by increasing yaw_rate weight. Q_tilde = np.kron(np.eye(prediction_horizon), 0.1 * np.diag([354, 0, 14, 250])) # R_tilde contain the steering input weight. R_tilde = np.kron(np.eye(prediction_horizon), np.eye(1)) matrix_H = (np.transpose(matrix_C)).dot(Q_tilde).dot(matrix_C) + R_tilde matrix_F = (np.transpose(matrix_C)).dot(Q_tilde).dot(matrix_M) matrix_F1 = (np.transpose(matrix_C)).dot(Q_tilde).dot(matrix_T_tilde) # This is the solution to the unconstrained optimization problem # for the MPC. unconstrained_optimal_solution = np.matmul( np.linalg.inv(2 * matrix_H), np.matmul(matrix_F, np.array([[lateral_error], [0], [heading_error], [0]])) + np.reshape(matrix_F1, (-1, 1)), )[0][0] return np.clip(-unconstrained_optimal_solution, -1, 1)
Implementation of MPC, please see the following ref: Convex Optimization – Boyd and Vandenberghe https://github.com/markcannon/markcannon.github.io/blob/c3344814c9c79d5f0d5f3cf8fc2e7ef14cb4fad3/assets/downloads/teaching/C21_Model_Predictive_Control/mpc_notes.pdf https://markcannon.github.io/teaching/
MPC
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_tracking_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_tracking_controller.py
MIT
def get_next_state( self, cur_pose: Pose, cur_speed: float, dt: float, target_pose_at_t: Optional[np.ndarray], ) -> Tuple[Pose, float]: """Computes a cubic bezier curve to the target_pose_at_t.""" cur_state = np.array( [*cur_pose.position[:2], float(cur_pose.heading), cur_speed] ).astype(float) if target_pose_at_t is None: # if agent failed to produce a target pose, just use the previous pose target_pose_at_t = cur_state new_traj_pt = self._motion_planner.trajectory( cur_state, target_pose_at_t, 1, dt ).reshape(4) new_pose = Pose.from_center(new_traj_pt[:2], Heading(new_traj_pt[2])) return new_pose, new_traj_pt[3]
Computes a cubic bezier curve to the target_pose_at_t.
get_next_state
python
huawei-noah/SMARTS
smarts/core/controllers/motion_planner_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/motion_planner_controller.py
MIT
def perform_action( cls, controller_state: MotionPlannerControllerState, dt: float, vehicle, action: Optional[np.ndarray], ): """Performs an action adapting to the underlying chassis. Args: controller_state (MotionPlannerControllerState): The previous controller state from this controller. dt (float): Amount of time that has passed since the last action. vehicle (Vehicle): Vehicle to control. action: Pose denoted by [x_coordinate, y_coordinate, heading, t_s], at t_s seconds into future. """ assert isinstance(vehicle.chassis, BoxChassis) assert len(action) >= 4, f"{action}" pose, speed = controller_state.get_next_state( vehicle.pose, vehicle.speed, dt, action ) vehicle.control(pose, speed, dt)
Performs an action adapting to the underlying chassis. Args: controller_state (MotionPlannerControllerState): The previous controller state from this controller. dt (float): Amount of time that has passed since the last action. vehicle (Vehicle): Vehicle to control. action: Pose denoted by [x_coordinate, y_coordinate, heading, t_s], at t_s seconds into future.
perform_action
python
huawei-noah/SMARTS
smarts/core/controllers/motion_planner_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/motion_planner_controller.py
MIT
def perform_action( cls, dt: float, vehicle, action: Union[float, Tuple[float, float]], ): """Performs an action adapting to the underlying chassis. Args: dt (float): A delta time value. vehicle (Vehicle): The vehicle to control. action (Union[float, Tuple[float, float]]): (speed) XOR (acceleration, angular_velocity) """ chassis = vehicle.chassis if isinstance(action, (int, float)): # special case: setting the initial speed if isinstance(chassis, BoxChassis): vehicle.control(vehicle.pose, action, dt) elif isinstance(chassis, AckermannChassis): chassis.speed = action # hack that calls control internally return assert isinstance(action, (list, tuple)) and len(action) == 2 # acceleration is scalar in m/s^2, angular_velocity is scalar in rad/s # acceleration is in the direction of the heading only. acceleration, angular_velocity = action # Note: we only use angular_velocity (not angular_acceleration) to determine # the new heading and position in this action space. This sacrifices # some realism/control, but helps simplify the imitation learning model. target_heading = (vehicle.heading + angular_velocity * dt) % (2 * math.pi) if isinstance(chassis, BoxChassis): # Since BoxChassis does not use pybullet for force-to-motion computations (only collision detection), # we have to update the position and other state here (instead of pybullet.stepSimulation()). heading_vec = radians_to_vec(vehicle.heading) dpos = heading_vec * vehicle.speed * dt new_pose = Pose( position=vehicle.position + np.append(dpos, 0.0), orientation=fast_quaternion_from_angle(target_heading), ) target_speed = vehicle.speed + acceleration * dt vehicle.control(new_pose, target_speed, dt) elif isinstance(chassis, AckermannChassis): mass = chassis.mass_and_inertia[0] # in kg wheel_radius = chassis.wheel_radius # XXX: should also take wheel inertia into account here # XXX: ... or else we should apply this force directly to the main link point of the chassis. if acceleration >= 0: # necessary torque is N*m = kg*m*acceleration torque_ratio = mass / (4 * wheel_radius * chassis.max_torque) throttle = np.clip(acceleration * torque_ratio, 0, 1) brake = 0 else: throttle = 0 # necessary torque is N*m = kg*m*acceleration torque_ratio = mass / (4 * wheel_radius * chassis.max_btorque) brake = np.clip(acceleration * torque_ratio, 0, 1) steering = np.clip(dt * -angular_velocity * chassis.steering_ratio, -1, 1) vehicle.control(throttle=throttle, brake=brake, steering=steering) else: raise Exception("unsupported chassis type")
Performs an action adapting to the underlying chassis. Args: dt (float): A delta time value. vehicle (Vehicle): The vehicle to control. action (Union[float, Tuple[float, float]]): (speed) XOR (acceleration, angular_velocity)
perform_action
python
huawei-noah/SMARTS
smarts/core/controllers/direct_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/direct_controller.py
MIT
def perform_action( sim, agent_id, vehicle, action, controller_state, sensor_state, action_space, ): """Calls control for the given vehicle based on a given action space and action. Args: sim: A simulation instance. agent_id: An agent within the simulation that is associated with a vehicle. vehicle: A vehicle within the simulation that is associated with an agent. action: The action for the controller to perform. controller_state: The last vehicle controller state as relates to its action space. sensor_state: The state of a vehicle sensor as relates to vehicle sensors. action_space: The action space of the provided action. """ if action is None: return if action_space == ActionSpaceType.Continuous: vehicle.control( throttle=np.clip(action[0], 0.0, 1.0), brake=np.clip(action[1], 0.0, 1.0), steering=np.clip(action[2], -1, 1), ) elif action_space == ActionSpaceType.ActuatorDynamic: ActuatorDynamicController.perform_action( vehicle, action, controller_state, dt_sec=sim.last_dt ) elif action_space == ActionSpaceType.Trajectory: TrajectoryTrackingController.perform_trajectory_tracking_PD( action, vehicle, controller_state, dt_sec=sim.last_dt, ) elif action_space == ActionSpaceType.MPC: TrajectoryTrackingController.perform_trajectory_tracking_MPC( action, vehicle, controller_state, sim.last_dt ) elif action_space == ActionSpaceType.LaneWithContinuousSpeed: LaneFollowingController.perform_lane_following( sim, agent_id, vehicle, controller_state, sensor_state, action[0], action[1], ) elif action_space == ActionSpaceType.Lane: perform_lane_following = partial( LaneFollowingController.perform_lane_following, sim=sim, agent_id=agent_id, vehicle=vehicle, controller_state=controller_state, sensor_state=sensor_state, ) action = LaneAction(value=action) # 12.5 m/s (45 km/h) is used as the nominal speed for lane change. # For keep_lane, the nominal speed is set to 15 m/s (54 km/h). if action == LaneAction.keep_lane: perform_lane_following(target_speed=15, lane_change=0) elif action == LaneAction.slow_down: perform_lane_following(target_speed=0, lane_change=0) elif action == LaneAction.change_lane_left: perform_lane_following(target_speed=12.5, lane_change=1) elif action == LaneAction.change_lane_right: perform_lane_following(target_speed=12.5, lane_change=-1) elif action_space == ActionSpaceType.Direct: DirectController.perform_action(sim.last_dt, vehicle, action) elif action_space in ( ActionSpaceType.TargetPose, ActionSpaceType.MultiTargetPose, ActionSpaceType.RelativeTargetPose, ): motion_action = action if action_space is ActionSpaceType.RelativeTargetPose: position, heading = vehicle.pose.position, vehicle.pose.heading motion_action = [ action[0] + position[0], action[1] + position[1], action[2] + heading, 0.1, ] MotionPlannerController.perform_action( controller_state, sim.last_dt, vehicle, motion_action ) elif action_space == ActionSpaceType.TrajectoryWithTime: TrajectoryInterpolationController.perform_action( sim.last_dt, vehicle, action ) else: raise ValueError( f"perform_action({action_space=}, ...) has failed " "inside controller" )
Calls control for the given vehicle based on a given action space and action. Args: sim: A simulation instance. agent_id: An agent within the simulation that is associated with a vehicle. vehicle: A vehicle within the simulation that is associated with an agent. action: The action for the controller to perform. controller_state: The last vehicle controller state as relates to its action space. sensor_state: The state of a vehicle sensor as relates to vehicle sensors. action_space: The action space of the provided action.
perform_action
python
huawei-noah/SMARTS
smarts/core/controllers/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/__init__.py
MIT
def get_action_shape(action_space: ActionSpaceType): """Describes the shape of actions that are used for standard controllers. Args: action_space (ActionSpaceType): The action space to describe. Raises: NotImplementedError: The action space requested does is not yet implemented. Returns: Tuple[Any, str]: The action space and the descriptive attribute. """ # TODO MTA: test the action shapes against dummy agents. if action_space == ActionSpaceType.Empty: return Union[type(None), Literal[False], Tuple], "null" if action_space == ActionSpaceType.Lane: return ( Literal[ LaneAction.keep_lane, LaneAction.slow_down, LaneAction.change_lane_left, LaneAction.change_lane_right, ], "lane_action", ) if action_space in ( ActionSpaceType.ActuatorDynamic, ActionSpaceType.Continuous, ): return Tuple[float, float, float], ("throttle", "break", "steering") if action_space == ActionSpaceType.LaneWithContinuousSpeed: return Tuple[float, int], ("lane_speed", "lane_change_delta") if action_space in (ActionSpaceType.MPC, ActionSpaceType.Trajectory): return Tuple[ Sequence[float], Sequence[float], Sequence[float], Sequence[float] ], ("x_coords", "y_coords", "headings", "speeds") if action_space == ActionSpaceType.Direct: return Union[float, Tuple[float, float]], [ "speed", ("linear_acceleration", "angular_velocity"), ] if action_space == ActionSpaceType.TrajectoryWithTime: return Tuple[ Sequence[float], Sequence[float], Sequence[float], Sequence[float], Sequence[float], ], ("times", "x_coords", "y_coords", "headings", "speeds") TargetPoseSpace = Tuple[float, float, float, float] TargetPoseAttributes = ("x_coord", "y_coord", "heading", "time_delta") if action_space == ActionSpaceType.TargetPose: return TargetPoseSpace, TargetPoseAttributes if action_space == ActionSpaceType.MultiTargetPose: return Dict[str, TargetPoseSpace], {"agent_id": TargetPoseAttributes} if action_space == ActionSpaceType.RelativeTargetPose: return Tuple[float, float, float], ("delta_x", "delta_y", "delta_heading") raise NotImplementedError(f"Type {action_space} is not implemented")
Describes the shape of actions that are used for standard controllers. Args: action_space (ActionSpaceType): The action space to describe. Raises: NotImplementedError: The action space requested does is not yet implemented. Returns: Tuple[Any, str]: The action space and the descriptive attribute.
get_action_shape
python
huawei-noah/SMARTS
smarts/core/controllers/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/__init__.py
MIT
def from_action_space(action_space, vehicle_pose, sim): """Generate the appropriate controller state given an action space.""" if action_space in ( ActionSpaceType.Lane, ActionSpaceType.LaneWithContinuousSpeed, ): target_lane = sim.road_map.nearest_lane(vehicle_pose.point) if not target_lane: # This likely means this is a traffic history vehicle that is out-of-lane. # If not, maybe increase radius in nearest_lane call? raise ControllerOutOfLaneException( "Controller has failed because actor is too far from lane for lane-following." ) return LaneFollowingControllerState(target_lane.lane_id) if action_space == ActionSpaceType.ActuatorDynamic: return ActuatorDynamicControllerState() if action_space == ActionSpaceType.Trajectory: return TrajectoryTrackingControllerState() if action_space == ActionSpaceType.MPC: return TrajectoryTrackingControllerState() if action_space in ( ActionSpaceType.TargetPose, ActionSpaceType.MultiTargetPose, ActionSpaceType.RelativeTargetPose, ): return MotionPlannerControllerState() # Other action spaces do not need a controller state object return None
Generate the appropriate controller state given an action space.
from_action_space
python
huawei-noah/SMARTS
smarts/core/controllers/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/__init__.py
MIT
def assert_is_legal_trajectory(cls, trajectory: np.ndarray): """Test if the trajectory is correctly formed.""" assert ( len(trajectory[TrajectoryField.TIME_INDEX]) >= 2 ), f"length of trajectory is {len(trajectory[TrajectoryField.TIME_INDEX])}" assert np.isfinite( trajectory ).all(), "trajectory has nan, positive inf or negative inf" assert ( np.diff(trajectory[TrajectoryField.TIME_INDEX]) > 0 ).all(), "trajectory times are not strictly increasing!"
Test if the trajectory is correctly formed.
assert_is_legal_trajectory
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_interpolation_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_interpolation_controller.py
MIT
def _interpolate(cls, ms0: np.ndarray, ms1: np.ndarray, time: float) -> np.ndarray: """Linearly interpolate between two vehicle motion states. Returns: np.ndarray: New vehicle state between vehicle motion state ms0 and ms1 """ start_time = ms0[TrajectoryField.TIME_INDEX] end_time = ms1[TrajectoryField.TIME_INDEX] assert ( end_time >= start_time and time >= start_time ), f"{start_time} <= {time} <= {end_time} ?" ratio = math.fabs((time - start_time) / (end_time - start_time)) left_over = 1.0 - ratio np_motion_state = left_over * ms0 + ratio * ms1 CS = left_over * math.cos(ms0[TrajectoryField.THETA_INDEX]) + ratio * math.cos( ms1[TrajectoryField.THETA_INDEX] ) SN = left_over * math.sin(ms0[TrajectoryField.THETA_INDEX]) + ratio * math.sin( ms1[TrajectoryField.THETA_INDEX] ) np_motion_state[TrajectoryField.THETA_INDEX] = math.atan2(SN, CS) return np_motion_state
Linearly interpolate between two vehicle motion states. Returns: np.ndarray: New vehicle state between vehicle motion state ms0 and ms1
_interpolate
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_interpolation_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_interpolation_controller.py
MIT
def _locate_motion_state( cls, trajectory: np.ndarray, time: float ) -> Tuple[np.ndarray, np.ndarray]: """Find the first pair of motion states within the given trajectory where the second is later than given time.""" for i, t in enumerate(trajectory[TrajectoryField.TIME_INDEX]): if t > time: return trajectory[:, i - 1], trajectory[:, i] assert ( False ), f"could not locate points within the trajectory that span {time} secs from now" return trajectory[:, 0], trajectory[:, 1]
Find the first pair of motion states within the given trajectory where the second is later than given time.
_locate_motion_state
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_interpolation_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_interpolation_controller.py
MIT
def perform_action(cls, dt: float, vehicle, trajectory: np.ndarray): """Move vehicle by trajectory interpolation. If you want vehicle stop at a specific pose, trajectory[:attr:`TrajectoryField.TIME_INDEX`][0] should be set as `numpy.inf`. Args: dt (float): the amount of time that is expected to pass between actions vehicle (Vehicle) : vehicle to be controlled trajectory (np.ndarray) : trajectory with 5 dimensions - TIME, X, Y, THETA and VEL """ assert isinstance(vehicle.chassis, BoxChassis) cls.assert_is_legal_trajectory(trajectory) ms0, ms1 = cls._locate_motion_state(trajectory, dt) if math.isinf(ms0[TrajectoryField.TIME_INDEX]) or math.isinf( ms1[TrajectoryField.TIME_INDEX] ): ms = ms0 speed = 0.0 else: ms = cls._interpolate(ms0, ms1, dt) speed = ms[TrajectoryField.VEL_INDEX] center_position = ms[TrajectoryField.X_INDEX : TrajectoryField.Y_INDEX + 1] center_heading = Heading(ms[TrajectoryField.THETA_INDEX]) pose = Pose.from_center(center_position, center_heading) vehicle.control(pose, speed, dt)
Move vehicle by trajectory interpolation. If you want vehicle stop at a specific pose, trajectory[:attr:`TrajectoryField.TIME_INDEX`][0] should be set as `numpy.inf`. Args: dt (float): the amount of time that is expected to pass between actions vehicle (Vehicle) : vehicle to be controlled trajectory (np.ndarray) : trajectory with 5 dimensions - TIME, X, Y, THETA and VEL
perform_action
python
huawei-noah/SMARTS
smarts/core/controllers/trajectory_interpolation_controller.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/controllers/trajectory_interpolation_controller.py
MIT
def observe( self, sim_frame: SimulationFrame, sim_local_constants: SimulationLocalConstants, agent_ids: Set[str], renderer: RendererBase, bullet_client: bc.BulletClient, ) -> Tuple[Dict[str, Observation], Dict[str, bool], Dict[str, Dict[str, Sensor]]]: """Runs observations in parallel where possible. Args: sim_frame (SimulationFrame): The current state from the simulation. sim_local_constants (SimulationLocalConstants): The values that should stay the same for a simulation over a reset. agent_ids ({str, ...}): The agent ids to process. renderer (Optional[Renderer]): The renderer (if any) that should be used. bullet_client: The physics client. """ observations, dones, updated_sensors = {}, {}, defaultdict(dict) num_spare_cpus = max(0, psutil.cpu_count(logical=False) - 1) used_processes = ( min( config()("core", "observation_workers", default=8, cast=int), num_spare_cpus, ) if self._process_count_override == None else max(1, self._process_count_override) ) used_workers = self._gen_workers_for_serializable_sensors( sim_frame, sim_local_constants, agent_ids, used_processes ) phys_observations = self._gen_phys_observations( sim_frame, sim_local_constants, agent_ids, bullet_client, updated_sensors ) # Collect futures with timeit("waiting for observations", logger.debug): if used_workers: while agent_ids != set(observations): assert all( w.running for w in used_workers ), "A process worker crashed." for result in mp.connection.wait( [worker.connection for worker in used_workers], timeout=5 ): # pytype: disable=attribute-error obs, ds, u_sens = result.recv() # pytype: enable=attribute-error observations.update(obs) dones.update(ds) for v_id, values in u_sens.items(): updated_sensors[v_id].update(values) # Merge physics sensor information for agent_id, p_obs in phys_observations.items(): observations[agent_id] = replace(observations[agent_id], **p_obs) self._sync_custom_camera_sensors(sim_frame, renderer, observations) if renderer: renderer.render() rendering_observations = self._gen_rendered_observations( sim_frame, sim_local_constants, agent_ids, renderer, updated_sensors ) # Merge sensor information for agent_id, r_obs in rendering_observations.items(): observations[agent_id] = replace(observations[agent_id], **r_obs) return observations, dones, updated_sensors
Runs observations in parallel where possible. Args: sim_frame (SimulationFrame): The current state from the simulation. sim_local_constants (SimulationLocalConstants): The values that should stay the same for a simulation over a reset. agent_ids ({str, ...}): The agent ids to process. renderer (Optional[Renderer]): The renderer (if any) that should be used. bullet_client: The physics client.
observe
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def stop_all_workers(self): """Stop all current workers and clear reference to them.""" for worker in self._workers: worker.stop() self._workers = []
Stop all current workers and clear reference to them.
stop_all_workers
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def _validate_configuration(self, local_constants: SimulationLocalConstants): """Check that constants have not changed which might indicate that the workers need to be updated.""" return local_constants == self._sim_local_constants
Check that constants have not changed which might indicate that the workers need to be updated.
_validate_configuration
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def generate_workers( self, count: int, workers_list: List[SensorsWorker], worker_kwargs: WorkerKwargs ): """Generate the given number of workers requested.""" while len(workers_list) < count: new_worker = SensorsWorker() workers_list.append(new_worker) new_worker.run() new_worker.send( request=SensorsWorker.Request( SensorsWorkerRequestId.SIMULATION_LOCAL_CONSTANTS, worker_kwargs ) )
Generate the given number of workers requested.
generate_workers
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def get_workers( self, count: int, sim_local_constants: SimulationLocalConstants, **kwargs ) -> List["SensorsWorker"]: """Get the give number of workers.""" if not self._validate_configuration(sim_local_constants): self.stop_all_workers() self._sim_local_constants = sim_local_constants if len(self._workers) < count: worker_kwargs = WorkerKwargs( **kwargs, sim_local_constants=sim_local_constants ) self.generate_workers(count, self._workers, worker_kwargs) return self._workers[:count]
Get the give number of workers.
get_workers
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def step(self, sim_frame: SimulationFrame, sensor_states: Iterable[SensorState]): """Step the sensor state.""" for sensor_state in sensor_states: sensor_state.step()
Step the sensor state.
step
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def process_count_override(self) -> Optional[int]: """The number of processes this implementation should run. Returns: int: Number of processes. """ return self._process_count_override
The number of processes this implementation should run. Returns: int: Number of processes.
process_count_override
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def merged(self, o_worker_kwargs: "WorkerKwargs") -> "WorkerKwargs": """Merge two worker arguments and return a new copy.""" new = type(self)() new.kwargs = {**self.kwargs, **o_worker_kwargs.kwargs} return new
Merge two worker arguments and return a new copy.
merged
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def deserialize(self): """Deserialize all objects in the arguments and return a dictionary copy.""" return { k: serializer.loads(a) if a is not None else a for k, a in self.kwargs.items() }
Deserialize all objects in the arguments and return a dictionary copy.
deserialize
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def _on_request(cls, state: Dict, request: Request) -> bool: """ Args: state: The persistent state on the worker request: A request made to the worker. Returns: bool: If the worker method `_do_work` should be called. """ raise NotImplementedError()
Args: state: The persistent state on the worker request: A request made to the worker. Returns: bool: If the worker method `_do_work` should be called.
_on_request
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def run(self): """Start the worker seeded with the given data.""" kwargs = dict(serialize_results=self._serialize_results) # pytype: disable=wrong-arg-types self._proc = mp.Process( target=self._run, args=(self._child_connection,), kwargs=kwargs, daemon=True, ) # pytype: enable=wrong-arg-types self._proc.start() return self._parent_connection
Start the worker seeded with the given data.
run
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def send(self, request: Request): """Sends a request to the worker.""" assert isinstance(request, self.Request) self._parent_connection.send(request)
Sends a request to the worker.
send
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def result(self, timeout=None): """The most recent result from the worker.""" with timeit("main thread blocked", logger.debug): conn = mp.connection.wait([self._parent_connection], timeout=timeout).pop() # pytype: disable=attribute-error result = conn.recv() # pytype: enable=attribute-error with timeit("deserialize for main thread", logger.debug): if self._serialize_results: result = serializer.loads(result) return result
The most recent result from the worker.
result
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def stop(self): """Sends a stop signal to the worker.""" try: self._parent_connection.send(self.WorkerDone()) except ImportError: # Python is shutting down. if not self._parent_connection.closed: self._parent_connection.close()
Sends a stop signal to the worker.
stop
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def running(self) -> bool: """If this current worker is still running.""" return self._proc is not None and self._proc.exitcode is None
If this current worker is still running.
running
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def connection(self): """The underlying connection to send data to the worker.""" return self._parent_connection
The underlying connection to send data to the worker.
connection
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def local(state: Dict): """The work method on the local thread.""" sim_local_constants = state["sim_local_constants"] sim_frame = state["sim_frame"] agent_ids = state["agent_ids"] return Sensors.observe_serializable_sensor_batch( sim_frame, sim_local_constants, agent_ids )
The work method on the local thread.
local
python
huawei-noah/SMARTS
smarts/core/sensors/parallel_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/parallel_sensor_resolver.py
MIT
def step(self, sim_frame: SimulationFrame, sensor_states: Iterable[SensorState]): """Step the sensor state.""" for sensor_state in sensor_states: sensor_state.step()
Step the sensor state.
step
python
huawei-noah/SMARTS
smarts/core/sensors/local_sensor_resolver.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/local_sensor_resolver.py
MIT
def step(self): """Update internal state.""" self._step += 1
Update internal state.
step
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def seen_alive_actors(self) -> bool: """If an agents alive actor has been spotted before.""" return self._seen_alive_actors
If an agents alive actor has been spotted before.
seen_alive_actors
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def seen_interest_actors(self) -> bool: """If an interest actor has been spotted before.""" return self._seen_interest_actors
If an interest actor has been spotted before.
seen_interest_actors
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def reached_max_episode_steps(self) -> bool: """Inbuilt sensor information that describes if episode step limit has been reached.""" if self._max_episode_steps is None: return False return self._step >= self._max_episode_steps
Inbuilt sensor information that describes if episode step limit has been reached.
reached_max_episode_steps
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def get_plan(self, road_map: RoadMap): """Get the current plan for the actor.""" return Plan.from_frame(self._plan_frame, road_map)
Get the current plan for the actor.
get_plan
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def steps_completed(self) -> int: """Get the number of steps where this sensor has been updated.""" return self._step
Get the number of steps where this sensor has been updated.
steps_completed
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def invalid(cls: Type[SensorState]) -> SensorState: """Generate a invalid default frame.""" return cls(None, PlanFrame.empty())
Generate a invalid default frame.
invalid
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def observe( self, sim_frame: SimulationFrame, sim_local_constants: SimulationLocalConstants, agent_ids: Set[str], renderer: RendererBase, bullet_client: bc.BulletClient, ) -> Tuple[Dict[str, Observation], Dict[str, bool], Dict[str, Dict[str, Sensor]]]: """Generate observations Args: sim_frame (SimulationFrame): The simulation frame. sim_local_constants (SimulationLocalConstants): Constraints defined by the local simulator. agent_ids (Set[str]): The agents to run. renderer (RendererBase): The renderer to use. bullet_client (Any): The bullet client. This parameter is likely to be removed. """ raise NotImplementedError()
Generate observations Args: sim_frame (SimulationFrame): The simulation frame. sim_local_constants (SimulationLocalConstants): Constraints defined by the local simulator. agent_ids (Set[str]): The agents to run. renderer (RendererBase): The renderer to use. bullet_client (Any): The bullet client. This parameter is likely to be removed.
observe
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def step(self, sim_frame: SimulationFrame, sensor_states: Iterable[SensorState]): """Step the sensor state.""" raise NotImplementedError()
Step the sensor state.
step
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def observe_serializable_sensor_batch( cls, sim_frame: SimulationFrame, sim_local_constants: SimulationLocalConstants, agent_ids_for_group: Iterable[str], ) -> Tuple[Dict[str, Observation], Dict[str, bool], Dict[str, Dict[str, Sensor]]]: """Run the serializable sensors in a batch.""" observations, dones, updated_sensors = {}, {}, {} for agent_id in agent_ids_for_group: vehicle_ids = sim_frame.vehicles_for_agents.get(agent_id) interface = sim_frame.agent_interfaces.get(agent_id) if not vehicle_ids: continue for vehicle_id in vehicle_ids: ( observations[agent_id], dones[agent_id], updated_sensors[vehicle_id], ) = cls.process_serialization_safe_sensors( sim_frame, sim_local_constants, interface, sim_frame.sensor_states[vehicle_id], vehicle_id, agent_id, ) return observations, dones, updated_sensors
Run the serializable sensors in a batch.
observe_serializable_sensor_batch
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def process_rendering_sensors( sim_frame: SimulationFrame, sim_local_constants: SimulationLocalConstants, interface: AgentInterface, sensor_state: SensorState, vehicle_id: str, renderer: RendererBase, ) -> Tuple[Dict[str, Any], Dict[str, Sensor]]: """Run observations that can only be done on the main thread.""" vehicle_sensors = sim_frame.vehicle_sensors[vehicle_id] def get_camera_sensor_result( sensors: Dict[str, Sensor], sensor_name: str, renderer: RendererBase ): if (sensor := sensors.get(sensor_name)) is not None: return sensor(renderer=renderer) return None updated_sensors = { sensor_name: sensor for sensor_name, sensor in vehicle_sensors.items() if isinstance(sensor, CameraSensor) } return ( dict( drivable_area_grid_map=get_camera_sensor_result( vehicle_sensors, "drivable_area_grid_map_sensor", renderer ), occupancy_grid_map=get_camera_sensor_result( vehicle_sensors, "ogm_sensor", renderer ), top_down_rgb=get_camera_sensor_result( vehicle_sensors, "rgb_sensor", renderer ), occlusion_map=get_camera_sensor_result( vehicle_sensors, "occlusion_map_sensor", renderer ), custom_renders=tuple( get_camera_sensor_result( vehicle_sensors, f"custom_render{i}_sensor", renderer ) for i, _ in enumerate(interface.custom_renders) ), ), updated_sensors, )
Run observations that can only be done on the main thread.
process_rendering_sensors
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def process_physics_sensors( sim_frame: SimulationFrame, sim_local_constants: SimulationLocalConstants, sensor_state: SensorState, vehicle_id: str, bullet_client: bc.BulletClient, ) -> Tuple[Dict[str, Any], Dict[str, Sensor]]: """Run observations that can only be done on the main thread.""" vehicle_sensors = sim_frame.vehicle_sensors[vehicle_id] vehicle_state = sim_frame.vehicle_states[vehicle_id] lidar = None updated_sensors = {} lidar_sensor = vehicle_sensors.get("lidar_sensor") if lidar_sensor: lidar_sensor.follow_vehicle(vehicle_state) lidar = lidar_sensor(bullet_client) updated_sensors["lidar_sensor"] = lidar_sensor return ( dict( lidar_point_cloud=lidar, ), updated_sensors, )
Run observations that can only be done on the main thread.
process_physics_sensors
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def process_serialization_unsafe_sensors( cls, sim_frame: SimulationFrame, sim_local_constants: SimulationLocalConstants, interface: AgentInterface, sensor_state: SensorState, vehicle_id: str, renderer: RendererBase, bullet_client: bc.BulletClient, ) -> Tuple[Dict[str, Any], Dict[str, Sensor]]: """Run observations that can only be done on the main thread.""" p_sensors, p_updated_sensors = cls.process_physics_sensors( sim_frame=sim_frame, sim_local_constants=sim_local_constants, sensor_state=sensor_state, vehicle_id=vehicle_id, bullet_client=bullet_client, ) r_sensors, r_updated_sensors = cls.process_rendering_sensors( sim_frame=sim_frame, sim_local_constants=sim_local_constants, interface=interface, sensor_state=sensor_state, vehicle_id=vehicle_id, renderer=renderer, ) return {**p_sensors, **r_sensors}, {**p_updated_sensors, **r_updated_sensors}
Run observations that can only be done on the main thread.
process_serialization_unsafe_sensors
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def process_serialization_safe_sensors( sim_frame: SimulationFrame, sim_local_constants: SimulationLocalConstants, interface: AgentInterface, sensor_state: SensorState, vehicle_id: str, agent_id: Optional[str] = None, ) -> Tuple[Observation, bool, Dict[str, Sensor]]: """Observations that can be done on any thread.""" vehicle_sensors = sim_frame.vehicle_sensors[vehicle_id] vehicle_state = sim_frame.vehicle_states[vehicle_id] plan = sensor_state.get_plan(sim_local_constants.road_map) neighborhood_vehicle_states = None neighborhood_vehicle_states_sensor = vehicle_sensors.get( "neighborhood_vehicle_states_sensor" ) if neighborhood_vehicle_states_sensor: neighborhood_vehicle_states = [] interest_pattern = ( interface.done_criteria.interest.actors_pattern if interface is not None and interface.done_criteria.interest is not None else None ) for nv in neighborhood_vehicle_states_sensor( vehicle_state, sim_frame.vehicle_states.values() ): veh_obs = _make_vehicle_observation( sim_local_constants.road_map, nv, sim_frame, interest_pattern ) lane_position_sensor = vehicle_sensors.get("lane_position_sensor") nv_lane_pos = None if veh_obs.lane_id is not LANE_ID_CONSTANT and lane_position_sensor: nv_lane_pos = lane_position_sensor( sim_local_constants.road_map.lane_by_id(veh_obs.lane_id), nv ) neighborhood_vehicle_states.append( veh_obs._replace(lane_position=nv_lane_pos) ) waypoints_sensor = vehicle_sensors.get("waypoints_sensor") if waypoints_sensor: waypoint_paths = waypoints_sensor( vehicle_state, plan, sim_local_constants.road_map ) else: waypoint_paths = sim_local_constants.road_map.waypoint_paths( vehicle_state.pose, lookahead=1, within_radius=vehicle_state.dimensions.length, ) closest_lane = sim_local_constants.road_map.nearest_lane( vehicle_state.pose.point ) ego_lane_pos = None if closest_lane: ego_lane_id = closest_lane.lane_id ego_lane_index = closest_lane.index ego_road_id = closest_lane.road.road_id lane_position_sensor = vehicle_sensors.get("lane_position_sensor") if lane_position_sensor: ego_lane_pos = lane_position_sensor(closest_lane, vehicle_state) else: ego_lane_id = LANE_ID_CONSTANT ego_lane_index = LANE_INDEX_CONSTANT ego_road_id = ROAD_ID_CONSTANT acceleration_params = { "linear_acceleration": None, "angular_acceleration": None, "linear_jerk": None, "angular_jerk": None, } accelerometer_sensor = vehicle_sensors.get("accelerometer_sensor") if accelerometer_sensor: acceleration_values = accelerometer_sensor( vehicle_state.linear_velocity, vehicle_state.angular_velocity, sim_frame.last_dt, ) acceleration_params.update( dict( zip( [ "linear_acceleration", "angular_acceleration", "linear_jerk", "angular_jerk", ], ( (None if av is None else tuple(float(f) for f in av)) for av in acceleration_values ), ) ) ) ego_vehicle = EgoVehicleObservation( id=vehicle_state.actor_id, position=vehicle_state.pose.position_tuple, bounding_box=vehicle_state.dimensions, heading=vehicle_state.pose.heading, speed=vehicle_state.speed, steering=vehicle_state.steering, yaw_rate=vehicle_state.yaw_rate, road_id=ego_road_id, lane_id=ego_lane_id, lane_index=ego_lane_index, mission=plan.mission, linear_velocity=vehicle_state.linear_velocity_tuple(), angular_velocity=vehicle_state.angular_velocity_tuple(), lane_position=ego_lane_pos, **acceleration_params, ) road_waypoints_sensor = vehicle_sensors.get("road_waypoints_sensor") road_waypoints = ( road_waypoints_sensor(vehicle_state, plan, sim_local_constants.road_map) if road_waypoints_sensor else None ) near_via_points = () via_sensor = vehicle_sensors.get("via_sensor") if via_sensor: near_via_points = via_sensor( vehicle_state, plan, sim_local_constants.road_map ) via_data = Vias( near_via_points=near_via_points, ) distance_travelled = 0 trip_meter_sensor: Optional[TripMeterSensor] = vehicle_sensors.get( "trip_meter_sensor" ) if trip_meter_sensor: if waypoint_paths: trip_meter_sensor.update_distance_wps_record( waypoint_paths, vehicle_state, plan, sim_local_constants.road_map ) distance_travelled = trip_meter_sensor(increment=True) driven_path_sensor = vehicle_sensors.get("driven_path_sensor") if driven_path_sensor: driven_path_sensor.track_latest_driven_path( sim_frame.elapsed_sim_time, vehicle_state ) if not waypoints_sensor: waypoint_paths = None done, events = Sensors._is_done_with_events( sim_frame, sim_local_constants, interface, vehicle_state, sensor_state, plan, ) if done and sensor_state.steps_completed == 1: logger.warning("Vehicle with ID: %s is done on the first step", vehicle_id) signals = None signals_sensor = vehicle_sensors.get("signals_sensor") if signals_sensor: provider_state = sim_frame.last_provider_state signals = signals_sensor( closest_lane, ego_lane_pos, vehicle_state, plan, provider_state, ) agent_controls = ( agent_id is not None and agent_id == sim_frame.agent_vehicle_controls.get(vehicle_state.actor_id) ) updated_sensors = { sensor_name: sensor for sensor_name, sensor in vehicle_sensors.items() if sensor.mutable and sensor.serializable } return ( Observation( dt=sim_frame.last_dt, step_count=sim_frame.step_count, steps_completed=sensor_state.steps_completed, elapsed_sim_time=sim_frame.elapsed_sim_time, events=events, ego_vehicle_state=ego_vehicle, under_this_agent_control=agent_controls, neighborhood_vehicle_states=neighborhood_vehicle_states or (), waypoint_paths=waypoint_paths, distance_travelled=distance_travelled, road_waypoints=road_waypoints, via_data=via_data, signals=signals, ), done, updated_sensors, )
Observations that can be done on any thread.
process_serialization_safe_sensors
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def observe_vehicle( cls, sim_frame: SimulationFrame, sim_local_constants: SimulationLocalConstants, interface: AgentInterface, sensor_state: SensorState, vehicle: Vehicle, renderer: RendererBase, bullet_client: bc.BulletClient, ) -> Tuple[Observation, bool, Dict[str, Sensor]]: """Generate observations for the given agent around the given vehicle.""" args = [sim_frame, sim_local_constants, interface, sensor_state, vehicle.id] safe_obs, dones, updated_safe_sensors = cls.process_serialization_safe_sensors( *args ) unsafe_obs, updated_unsafe_sensors = cls.process_serialization_unsafe_sensors( *args, renderer, bullet_client ) complete_obs = safe_obs._replace( **unsafe_obs, ) return (complete_obs, dones, {**updated_safe_sensors, **updated_unsafe_sensors})
Generate observations for the given agent around the given vehicle.
observe_vehicle
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def _vehicle_is_off_route_and_wrong_way( cls, sim_frame: SimulationFrame, sim_local_constants: SimulationLocalConstants, vehicle_state: VehicleState, plan: Plan, nearest_lanes: Optional[Sequence[Tuple[RoadMap.Lane, float]]] = None, ): """Determines if the agent is on route and on the correct side of the road. Args: sim_frame: An instance of the simulator. sim_local_constants: The current frozen state of the simulation for last reset. vehicle_state: The current state of the vehicle to check. plan: The current plan for the vehicle. nearest_lanes: Cached result of nearest lanes and distances for the vehicle position. Returns: A tuple (is_off_route, is_wrong_way) is_off_route: Actor's vehicle is not on its route or an oncoming traffic lane. is_wrong_way: Actor's vehicle is going against the lane travel direction. """ route_roads = plan.route.roads # No road nearby, so we're not on route! if not nearest_lanes: return (True, False) # Handle case where there are multiple nearest lanes the same dist away min_dist = nearest_lanes[0][1] tied_nearest = [ lane for (lane, d) in nearest_lanes if math.isclose(d, min_dist) ] nearest_on_route = [lane for lane in tied_nearest if lane.road in route_roads] nearest_lane = nearest_on_route[0] if nearest_on_route else nearest_lanes[0][0] # Check whether vehicle is in wrong-way is_wrong_way = cls._check_wrong_way_event(nearest_lane, vehicle_state) # Check whether vehicle has no-route or is on-route if ( not route_roads # Vehicle has no-route. E.g., endless mission with a random route or nearest_lane.road in route_roads # Vehicle is on-route or nearest_lane.in_junction ): return (False, is_wrong_way) vehicle_pos = vehicle_state.pose.point veh_offset = nearest_lane.offset_along_lane(vehicle_pos) # so we're obviously not on the route, but we might have just gone # over the center line into an oncoming lane... for on_lane in nearest_lane.oncoming_lanes_at_offset(veh_offset): if on_lane.road in route_roads: return (False, is_wrong_way) # Check for case if there was an early merge into another incoming lane. This means the # vehicle should still be following the lane direction to be valid as still on route. if not is_wrong_way: # See if the lane leads into the current route for lane in nearest_lane.outgoing_lanes: if lane.road in route_roads: return (False, is_wrong_way) # If outgoing lane is in a junction see if the junction lane leads into current route. if lane.in_junction: for out_lane in lane.outgoing_lanes: if out_lane.road in route_roads: return (False, is_wrong_way) # Vehicle is completely off-route return (True, is_wrong_way)
Determines if the agent is on route and on the correct side of the road. Args: sim_frame: An instance of the simulator. sim_local_constants: The current frozen state of the simulation for last reset. vehicle_state: The current state of the vehicle to check. plan: The current plan for the vehicle. nearest_lanes: Cached result of nearest lanes and distances for the vehicle position. Returns: A tuple (is_off_route, is_wrong_way) is_off_route: Actor's vehicle is not on its route or an oncoming traffic lane. is_wrong_way: Actor's vehicle is going against the lane travel direction.
_vehicle_is_off_route_and_wrong_way
python
huawei-noah/SMARTS
smarts/core/sensors/__init__.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/sensors/__init__.py
MIT
def dumps(__o): """Serializes the given object.""" import cloudpickle _lazy_init() r = __o type_ = type(__o) # TODO: Add a formatter parameter instead of handling proxies internal to serialization proxy_func = _proxies.get(type_) if proxy_func: r = proxy_func(__o) return cloudpickle.dumps(r)
Serializes the given object.
dumps
python
huawei-noah/SMARTS
smarts/core/serialization/default.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/serialization/default.py
MIT
def loads(__o): """Deserializes the given object.""" import cloudpickle r = cloudpickle.loads(__o) if hasattr(r, "deproxy"): r = r.deproxy() return r
Deserializes the given object.
loads
python
huawei-noah/SMARTS
smarts/core/serialization/default.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/serialization/default.py
MIT
def deproxy(self): """Convert the proxy back into the original object.""" raise NotImplementedError()
Convert the proxy back into the original object.
deproxy
python
huawei-noah/SMARTS
smarts/core/serialization/default.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/serialization/default.py
MIT
def required_to(cls, thing: str) -> "RendererException": """Generate a `RenderException` requiring a render to do `thing`.""" return cls( f"""A renderer is required to {thing}. You may not have installed the [camera-obs] dependencies required to render the camera sensor observations. Install them first using the command `pip install -e .[camera-obs]` at the source directory.""" )
Generate a `RenderException` requiring a render to do `thing`.
required_to
python
huawei-noah/SMARTS
smarts/core/utils/custom_exceptions.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/custom_exceptions.py
MIT
def required_to(cls, thing): """Generate a `RayException` requiring a render to do `thing`.""" return cls( f"""Ray Package is required to {thing}. You may not have installed the [rllib] or [train] dependencies required to run the ray dependent example. Install them first using the command `pip install -e .[train, rllib]` at the source directory to install the package ray[rllib]==1.0.1.post1""" )
Generate a `RayException` requiring a render to do `thing`.
required_to
python
huawei-noah/SMARTS
smarts/core/utils/custom_exceptions.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/custom_exceptions.py
MIT
def required_to(cls, thing): """Generate an instance of this exception that describes what can be done to remove the exception""" return cls( f"""OpenDRIVE Package is required to {thing}. You may not have installed the [opendrive] dependencies required to run the OpenDRIVE dependent example. Install them first using the command `pip install -e .[opendrive]` at the source directory to install the necessary packages""" )
Generate an instance of this exception that describes what can be done to remove the exception
required_to
python
huawei-noah/SMARTS
smarts/core/utils/custom_exceptions.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/custom_exceptions.py
MIT
def time_to_cover(dist: float, speed: float, acc: float = 0.0) -> float: """ Returns the time for a moving object traveling at speed and accelerating at acc to cover distance dist. Assumes that all units are consistent (for example, if distance is in meters, speed is in m/s). The returned value will be non-negative (but may be math.inf under some circumstances). """ if dist == 0: return 0 if abs(acc) < 1e-9: if speed == 0: return math.inf t = dist / speed return t if t >= 0 else math.inf discriminant = speed**2 + 2 * acc * dist if discriminant < 0: return math.inf rad = math.sqrt(discriminant) t1 = (rad - speed) / acc t2 = -(rad + speed) / acc mnt = min(t1, t2) if mnt >= 0: return mnt mxt = max(t1, t2) if mxt >= 0: return mxt return math.inf
Returns the time for a moving object traveling at speed and accelerating at acc to cover distance dist. Assumes that all units are consistent (for example, if distance is in meters, speed is in m/s). The returned value will be non-negative (but may be math.inf under some circumstances).
time_to_cover
python
huawei-noah/SMARTS
smarts/core/utils/kinematics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/kinematics.py
MIT
def distance_covered(time: float, speed: float, acc: float = 0.0) -> float: """ Returns the amount of distance covered by an object moving at speed and accelerating with acc. Assumes that all units are consistent (for example, if distance is in meters, speed is in m/s). """ return time * (speed + 0.5 * acc * time)
Returns the amount of distance covered by an object moving at speed and accelerating with acc. Assumes that all units are consistent (for example, if distance is in meters, speed is in m/s).
distance_covered
python
huawei-noah/SMARTS
smarts/core/utils/kinematics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/kinematics.py
MIT
def stopping_time(start_speed: float, deceleration: float) -> float: """ Returns the time it would take to stop from initial speed start_speed by decelerating at a constant rate of deceleration. Note that deceleration should be a non-negative value (not a negative acceleration). """ assert deceleration >= 0.0 if deceleration == 0.0: return math.inf return start_speed / deceleration
Returns the time it would take to stop from initial speed start_speed by decelerating at a constant rate of deceleration. Note that deceleration should be a non-negative value (not a negative acceleration).
stopping_time
python
huawei-noah/SMARTS
smarts/core/utils/kinematics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/kinematics.py
MIT
def stopping_distance(start_speed: float, deceleration: float) -> float: """ Returns the distance it would take to stop from initial speed start_speed by decelerating at a constant rate of deceleration. Note that deceleration should be a non-negative value (not a negative acceleration). """ assert deceleration >= 0.0 return 0.5 * start_speed * stopping_time(start_speed, deceleration)
Returns the distance it would take to stop from initial speed start_speed by decelerating at a constant rate of deceleration. Note that deceleration should be a non-negative value (not a negative acceleration).
stopping_distance
python
huawei-noah/SMARTS
smarts/core/utils/kinematics.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/kinematics.py
MIT
def truncate(str_, length, separator="..."): """Truncates a string to the given length by removing internal characters. :param str_: The string to truncate. :param length: The length to truncate the string to. :param separator: The intermediary characters that replaces removed characters. """ if len(str_) <= length: return str_ start = math.ceil((length - len(separator)) / 2) end = math.floor((length - len(separator)) / 2) return f"{str_[:start]}{separator}{str_[len(str_) - end:]}"
Truncates a string to the given length by removing internal characters. :param str_: The string to truncate. :param length: The length to truncate the string to. :param separator: The intermediary characters that replaces removed characters.
truncate
python
huawei-noah/SMARTS
smarts/core/utils/strings.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/strings.py
MIT
def duplicates(iterable, key: Optional[Callable] = None): """Finds all values that are duplicates.""" seen = set() matcher = iterable if key is not None: matcher = map(key, iterable) for v, m in zip(iterable, matcher): if m in seen: yield m, v else: seen.add(m)
Finds all values that are duplicates.
duplicates
python
huawei-noah/SMARTS
smarts/core/utils/iteration_tools.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/iteration_tools.py
MIT
def reset(self) -> "EpisodeLog": """Record an episode reset.""" e = self._current_episode if e: self._write_row() self._current_episode_num += 1 self._current_episode = EpisodeLog(self._current_episode_num) return self._current_episode
Record an episode reset.
reset
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def context(col_width): """Generate a formatted table context object.""" return tp.TableContext( [ "Episode", "Sim T / Wall T", "Total Steps", "Steps / Sec", "Scenario Map", "Scenario Routes", "Mission (Hash)", "Scores", ], width=col_width, style="round", )
Generate a formatted table context object.
context
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def wall_time(self): """Time elapsed since instantiation.""" return time.time() - self.start_time
Time elapsed since instantiation.
wall_time
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def sim_time(self): """An estimation of the total fixed-time-step simulation performed.""" return self.fixed_timestep_sec * self.steps
An estimation of the total fixed-time-step simulation performed.
sim_time
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def sim2wall_ratio(self): """The ration of sim time to wall time. Above 1 is hyper-real-time.""" return self.sim_time / self.wall_time
The ration of sim time to wall time. Above 1 is hyper-real-time.
sim2wall_ratio
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def steps_per_second(self): """The rate of steps performed since instantiation.""" return self.steps / self.wall_time
The rate of steps performed since instantiation.
steps_per_second
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def record_scenario(self, scenario_log): """Record a scenario end.""" self.fixed_timestep_sec = scenario_log["fixed_timestep_sec"] self.scenario_map = scenario_log["scenario_map"] self.scenario_traffic = scenario_log.get( "scenario_traffic", scenario_log.get("scenario_routes", "") ) self.mission_hash = scenario_log["mission_hash"]
Record a scenario end.
record_scenario
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def record_step(self, observations, rewards, terminateds, truncateds, infos): """Record a step end.""" self.steps += 1 if not isinstance(terminateds, dict): ( observations, rewards, terminateds, truncateds, infos, ) = self._convert_to_dict( observations, rewards, terminateds, truncateds, infos ) if terminateds.get("__all__", False) and infos is not None: for agent, score in infos.items(): self.scores[agent] = score["score"] else: for id in (_id for _id, t in terminateds.items() if t): self.scores[id] = infos[id]["score"]
Record a step end.
record_step
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def episodes(n): """An iteration method that provides numbered episodes. Acts similar to python's `range(n)` but yielding episode loggers. """ col_width = 18 with EpisodeLogs(col_width, n) as episode_logs: for _ in range(n): yield episode_logs.reset() episode_logs.reset()
An iteration method that provides numbered episodes. Acts similar to python's `range(n)` but yielding episode loggers.
episodes
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def continues(self, observation, reward, terminated, truncated, info) -> bool: """Determine if the current episode can continue.""" self._episodes.current_step += 1 if self._episodes.current_step >= self._episodes.max_steps: return False if isinstance(terminated, dict): return not terminated.get("__all__", all(terminated.values())) return not terminated
Determine if the current episode can continue.
continues
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def episode_range(max_steps): """An iteration method that provides a range of episodes that meets the given max steps.""" with Episodes(max_steps=max_steps) as episodes: while episodes.current_step < episodes.max_steps: yield Episode(episodes=episodes)
An iteration method that provides a range of episodes that meets the given max steps.
episode_range
python
huawei-noah/SMARTS
smarts/core/utils/episodes.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/episodes.py
MIT
def write_glb(self, output_path: Union[str, Path]): """Generate a geometry file.""" with open(output_path, "wb") as f: f.write(self._bytes)
Generate a geometry file.
write_glb
python
huawei-noah/SMARTS
smarts/core/utils/glb.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/glb.py
MIT
def _generate_meshes_from_polygons( polygons: List[Tuple[Polygon, Dict[str, Any]]] ) -> List[trimesh.Trimesh]: """Creates a mesh out of a list of polygons.""" meshes = [] # Trimesh's API require a list of vertices and a list of faces, where each # face contains three indexes into the vertices list. Ideally, the vertices # are all unique and the faces list references the same indexes as needed. # TODO: Batch the polygon processing. for poly, metadata in polygons: vertices, faces = [], [] point_dict = dict() current_point_index = 0 # Collect all the points on the shape to reduce checks by 3 times for x, y in poly.exterior.coords: p = (x, y, 0) if p not in point_dict: vertices.append(p) point_dict[p] = current_point_index current_point_index += 1 triangles = triangulate_polygon(poly) for triangle in triangles: face = np.array( [point_dict.get((x, y, 0), -1) for x, y in triangle.exterior.coords] ) # Add face if not invalid if -1 not in face: faces.append(face) if not vertices or not faces: continue mesh = trimesh.Trimesh(vertices=vertices, faces=faces, metadata=metadata) # Trimesh doesn't support a coordinate-system="z-up" configuration, so we # have to apply the transformation manually. mesh.apply_transform( trimesh.transformations.rotation_matrix(math.pi / 2, [-1, 0, 0]) ) meshes.append(mesh) return meshes
Creates a mesh out of a list of polygons.
_generate_meshes_from_polygons
python
huawei-noah/SMARTS
smarts/core/utils/glb.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/glb.py
MIT
def make_map_glb( polygons: List[Tuple[Polygon, Dict[str, Any]]], bbox: BoundingBox, lane_dividers, edge_dividers, ) -> GLBData: """Create a GLB file from a list of road polygons.""" # Attach additional information for rendering as metadata in the map glb metadata = { "bounding_box": ( bbox.min_pt.x, bbox.min_pt.y, bbox.max_pt.x, bbox.max_pt.y, ), "lane_dividers": lane_dividers, "edge_dividers": edge_dividers, } scene = trimesh.Scene(metadata=metadata) meshes = _generate_meshes_from_polygons(polygons) material = PBRMaterial("RoadDefault") for mesh in meshes: mesh.visual.material = material road_id = mesh.metadata["road_id"] lane_id = mesh.metadata.get("lane_id") name = str(road_id) if lane_id is not None: name += f"-{lane_id}" if OLD_TRIMESH: scene.add_geometry(mesh, name, extras=mesh.metadata) else: scene.add_geometry(mesh, name, geom_name=name, metadata=mesh.metadata) return GLBData(gltf.export_glb(scene, include_normals=True))
Create a GLB file from a list of road polygons.
make_map_glb
python
huawei-noah/SMARTS
smarts/core/utils/glb.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/glb.py
MIT
def make_road_line_glb(lines: List[List[Tuple[float, float]]]) -> GLBData: """Create a GLB file from a list of road/lane lines.""" scene = trimesh.Scene() material = trimesh.visual.material.PBRMaterial() for line_pts in lines: vertices = [(*pt, 0.1) for pt in line_pts] point_cloud = trimesh.PointCloud(vertices=vertices) point_cloud.apply_transform( trimesh.transformations.rotation_matrix(math.pi / 2, [-1, 0, 0]) ) scene.add_geometry(point_cloud) return GLBData(gltf.export_glb(scene))
Create a GLB file from a list of road/lane lines.
make_road_line_glb
python
huawei-noah/SMARTS
smarts/core/utils/glb.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/glb.py
MIT
def from_list(cls, coefficients: List[float]): """Generates CubicPolynomial. Args: coefficients: The list of coefficients [a, b, c, d] Returns: A new CubicPolynomial. """ return cls( a=coefficients[0], b=coefficients[1], c=coefficients[2], d=coefficients[3], )
Generates CubicPolynomial. Args: coefficients: The list of coefficients [a, b, c, d] Returns: A new CubicPolynomial.
from_list
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def eval(self, ds: float) -> float: """Evaluate a value along the polynomial.""" return self.a + self.b * ds + self.c * ds * ds + self.d * ds * ds * ds
Evaluate a value along the polynomial.
eval
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def constrain_angle(angle: float) -> float: """Constrain an angle within the inclusive range [-pi, pi]""" angle %= 2 * math.pi if angle > math.pi: angle -= 2 * math.pi return angle
Constrain an angle within the inclusive range [-pi, pi]
constrain_angle
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def batches(list_, n): """Split an indexable container into `n` batches. Args: list: The iterable to split into parts n: The number of batches """ for i in range(0, len(list_), n): yield list_[i : i + n]
Split an indexable container into `n` batches. Args: list: The iterable to split into parts n: The number of batches
batches
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def yaw_from_quaternion(quaternion) -> float: """Converts a quaternion to the yaw value. Args: quaternion (np.ndarray): np.array([x, y, z, w]) Returns: float: A angle in radians. """ assert len(quaternion) == 4, f"len({quaternion}) != 4" siny_cosp = 2 * (quaternion[0] * quaternion[1] + quaternion[3] * quaternion[2]) cosy_cosp = ( quaternion[3] ** 2 + quaternion[0] ** 2 - quaternion[1] ** 2 - quaternion[2] ** 2 ) yaw = np.arctan2(siny_cosp, cosy_cosp) return yaw
Converts a quaternion to the yaw value. Args: quaternion (np.ndarray): np.array([x, y, z, w]) Returns: float: A angle in radians.
yaw_from_quaternion
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def fast_quaternion_from_angle(angle: float) -> np.ndarray: """Converts a float to a quaternion. Args: angle: An angle in radians. Returns: (np.ndarray): np.array([x, y, z, w]) """ half_angle = angle * 0.5 return np.array([0, 0, math.sin(half_angle), math.cos(half_angle)])
Converts a float to a quaternion. Args: angle: An angle in radians. Returns: (np.ndarray): np.array([x, y, z, w])
fast_quaternion_from_angle
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def mult_quat(q1, q2): """Specialized quaternion multiplication as required by the unique attributes of quaternions. Returns: The product of the quaternions. """ q3 = np.copy(q1) q3[0] = q1[0] * q2[0] - q1[1] * q2[1] - q1[2] * q2[2] - q1[3] * q2[3] q3[1] = q1[0] * q2[1] + q1[1] * q2[0] + q1[2] * q2[3] - q1[3] * q2[2] q3[2] = q1[0] * q2[2] - q1[1] * q2[3] + q1[2] * q2[0] + q1[3] * q2[1] q3[3] = q1[0] * q2[3] + q1[1] * q2[2] - q1[2] * q2[1] + q1[3] * q2[0] return q3
Specialized quaternion multiplication as required by the unique attributes of quaternions. Returns: The product of the quaternions.
mult_quat
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def rotate_quat(quat, vect): """Rotate a vector with the rotation defined by a quaternion.""" # Transform a vector into an quaternion vect = np.append([0], vect) # Normalize it norm_vect = np.linalg.norm(vect) vect /= norm_vect # Computes the conjugate of quat quat_ = np.append(quat[0], -quat[1:]) # The result is given by: quat * vect * quat_ res = mult_quat(quat, mult_quat(vect, quat_)) * norm_vect return res[1:]
Rotate a vector with the rotation defined by a quaternion.
rotate_quat
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def clip(val, min_val, max_val): """Constrain a value between a min and max by clamping exterior values to the extremes.""" assert ( min_val <= max_val ), f"min_val({min_val}) must be less than max_val({max_val})" return min_val if val < min_val else max_val if val > max_val else val
Constrain a value between a min and max by clamping exterior values to the extremes.
clip
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def get_linear_segments_for_range( s_start: float, s_end: float, segment_size: float ) -> List[float]: """Given a range from s_start to s_end, give a linear segment of size segment_size.""" num_segments = int((s_end - s_start) / segment_size) + 1 return [s_start + seg * segment_size for seg in range(num_segments)]
Given a range from s_start to s_end, give a linear segment of size segment_size.
get_linear_segments_for_range
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def squared_dist(a, b) -> float: """Computes the squared distance between a and b. Args: a, b: same dimensions shaped `numpy` arrays. Returns: float: dist**2 """ delta = b - a return np.dot(delta, delta)
Computes the squared distance between a and b. Args: a, b: same dimensions shaped `numpy` arrays. Returns: float: dist**2
squared_dist
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def signed_dist_to_line(point, line_point, line_dir_vec) -> float: """Computes the signed distance to a directed line The signed of the distance is: - negative if point is on the right of the line - positive if point is on the left of the line ..code-block:: python >>> import numpy as np >>> signed_dist_to_line(np.array([2, 0]), np.array([0, 0]), np.array([0, 1.])) -2.0 >>> signed_dist_to_line(np.array([-1.5, 0]), np.array([0, 0]), np.array([0, 1.])) 1.5 """ p = vec_2d(point) p1 = line_point p2 = line_point + line_dir_vec u = abs( line_dir_vec[1] * p[0] - line_dir_vec[0] * p[1] + p2[0] * p1[1] - p2[1] * p1[0] ) d = u / np.linalg.norm(line_dir_vec) line_normal = np.array([-line_dir_vec[1], line_dir_vec[0]]) _sign = np.sign(np.dot(p - p1, line_normal)) return d * _sign
Computes the signed distance to a directed line The signed of the distance is: - negative if point is on the right of the line - positive if point is on the left of the line ..code-block:: python >>> import numpy as np >>> signed_dist_to_line(np.array([2, 0]), np.array([0, 0]), np.array([0, 1.])) -2.0 >>> signed_dist_to_line(np.array([-1.5, 0]), np.array([0, 0]), np.array([0, 1.])) 1.5
signed_dist_to_line
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def vec_2d(v) -> np.ndarray: """Converts a higher order vector to a 2D vector.""" assert len(v) >= 2 return np.array(v[:2])
Converts a higher order vector to a 2D vector.
vec_2d
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def sign(x) -> int: """Finds the sign of a numeric type. Args: x: A signed numeric type Returns: The sign [-1|1] of the input number """ return 1 - (x < 0) * 2
Finds the sign of a numeric type. Args: x: A signed numeric type Returns: The sign [-1|1] of the input number
sign
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def lerp(a, b, p): """Linear interpolation between a and b with p .. math:: a * (1.0 - p) + b * p Args: a, b: interpolated values p: [0..1] float describing the weight of a to b """ assert 0 <= p and p <= 1 return a * (1.0 - p) + b * p
Linear interpolation between a and b with p .. math:: a * (1.0 - p) + b * p Args: a, b: interpolated values p: [0..1] float describing the weight of a to b
lerp
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def safe_division(n: float, d: float, default=math.inf): """This method uses a short circuit form where `and` converts right side to true|false (as 1|0) .. note:: The cases are: 1) True and <value> == <value> 2) False and ``NaN`` == False """ if n == 0: return 0 return d and n / d or default
This method uses a short circuit form where `and` converts right side to true|false (as 1|0) .. note:: The cases are: 1) True and <value> == <value> 2) False and ``NaN`` == False
safe_division
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def low_pass_filter( input_value, previous_filter_state, filter_constant, time_step, lower_bound=-1, raw_value=0, ): """Filters out large value jumps by taking a filter state and returning a filter state. This is generally intended for filtering out high frequencies from raw signal values. Args: input_value: The raw signal value. previous_filter_state: The last generated value from the filter. filter_constant: The scale of the filter time_step: The length of time between the previously processed signal and the current signal. lower_bound: The lowest possible value allowed. raw_value: A scalar addition to the signal value. Returns: The processed raw signal value. """ previous_filter_state += ( time_step * filter_constant * (input_value - previous_filter_state) ) previous_filter_state = np.clip(previous_filter_state + raw_value, lower_bound, 1) return previous_filter_state
Filters out large value jumps by taking a filter state and returning a filter state. This is generally intended for filtering out high frequencies from raw signal values. Args: input_value: The raw signal value. previous_filter_state: The last generated value from the filter. filter_constant: The scale of the filter time_step: The length of time between the previously processed signal and the current signal. lower_bound: The lowest possible value allowed. raw_value: A scalar addition to the signal value. Returns: The processed raw signal value.
low_pass_filter
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def radians_to_vec(radians) -> np.ndarray: """Convert a radian value to a unit directional vector. 0 rad relates to [0x, 1y] with counter-clockwise rotation. """ # +y = 0 rad. angle = (radians + math.pi * 0.5) % (2 * math.pi) return np.array((math.cos(angle), math.sin(angle)))
Convert a radian value to a unit directional vector. 0 rad relates to [0x, 1y] with counter-clockwise rotation.
radians_to_vec
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def vec_to_radians(v) -> float: """Converts a vector to a radian value. [0x,+y] is 0 rad with counter-clockwise rotation.""" # See: https://stackoverflow.com/a/15130471 assert len(v) == 2, f"Vector must be 2D: {repr(v)}" x, y = v r = math.atan2(abs(y), abs(x)) # Adjust angle based on quadrant where +y = 0 rad. # Standard quadrants # +y # 2 | 1 # -x - - - +x # 3 | 4 # -y if x < 0: if y < 0: return (r + 0.5 * math.pi) % (2 * math.pi) # quad 3 return (0.5 * math.pi - r) % (2 * math.pi) # quad 2 elif y < 0: return (1.5 * math.pi - r) % (2 * math.pi) # quad 4 return (r - 0.5 * math.pi) % (2 * math.pi) # quad 1
Converts a vector to a radian value. [0x,+y] is 0 rad with counter-clockwise rotation.
vec_to_radians
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT
def circular_mean(vectors: Sequence[np.ndarray]) -> float: """Given a sequence of equal-length 2D vectors (e.g., unit vectors), returns their circular mean in radians, but with +y = 0 rad. See: https://en.wikipedia.org/wiki/Circular_mean""" return ( math.atan2(sum(v[1] for v in vectors), sum(v[0] for v in vectors)) - 0.5 * math.pi )
Given a sequence of equal-length 2D vectors (e.g., unit vectors), returns their circular mean in radians, but with +y = 0 rad. See: https://en.wikipedia.org/wiki/Circular_mean
circular_mean
python
huawei-noah/SMARTS
smarts/core/utils/core_math.py
https://github.com/huawei-noah/SMARTS/blob/master/smarts/core/utils/core_math.py
MIT