Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

532 feature remodel acc first iteration #603

Merged
merged 31 commits into from
Jan 13, 2025

Conversation

Vroni27
Copy link
Collaborator

@Vroni27 Vroni27 commented Jan 12, 2025

Description

In this PR, the ACC was improved using the new radar data provided by #579. Apart from that, the old structure was kept up.

Fixes # 532

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)

Does this PR introduce a breaking change?

No

Most important changes

Which files functionalities are most important in this PR. On which part should the reviewer be focussed on?
ACC.py

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works (might be obsolete with CI later on)
  • New and existing unit tests pass locally with my changes (might be obsolete with CI later on)

Summary by CodeRabbit

  • New Features

    • Enhanced Adaptive Cruise Control (ACC) with new radar data integration
    • Added ability to track lead vehicle's distance and velocity
    • Improved speed control logic based on lead vehicle information
  • Documentation

    • Updated ACC module documentation with new subscribed topic details
  • Bug Fixes

    • Refined speed calculation method for more accurate vehicle control

Merge branch '532-feature-remodel-acc-first-iteration' of https://github.com/una-auxme/paf into 532-feature-remodel-acc-first-iteration
@Vroni27 Vroni27 linked an issue Jan 12, 2025 that may be closed by this pull request
Copy link
Contributor

coderabbitai bot commented Jan 12, 2025

Walkthrough

This pull request enhances the Adaptive Cruise Control (ACC) system by integrating radar data for more precise lead vehicle tracking. The changes introduce a new subscriber to receive radar information about the lead vehicle's distance and velocity. The ACC module now uses these radar-derived measurements to calculate safe speeds, replacing the previous obstacle-based approach. The motion planning component has also been updated to track and publish the source of target velocity.

Changes

File Change Summary
code/planning/src/local_planner/ACC.py Added radar data subscription, new methods for processing lead vehicle data, updated speed calculation logic
code/planning/src/local_planner/motion_planning.py Added target_velocity_selector attribute and publisher to track speed source
doc/planning/ACC.md Updated documentation to include new radar topic subscription

Sequence Diagram

sequenceDiagram
    participant Radar
    participant ACC
    participant MotionPlanning
    
    Radar->>ACC: Publish lead vehicle data
    ACC->>ACC: Process radar data
    ACC->>ACC: Calculate safe speed
    ACC->>MotionPlanning: Send target speed
    MotionPlanning->>MotionPlanning: Update velocity selector
    MotionPlanning->>ROS: Publish velocity selector
Loading

Possibly related issues

Possibly related PRs

Suggested labels

planning

Suggested reviewers

  • vinzenzm

Poem

🚗 Radar whispers, speed adjusts with grace,
A robotic dance at a cautious pace.
Lead vehicle near? No need to fear!
ACC now sees with vision clear.
Smooth sailing on the digital highway,
Where rabbit-coded logic saves the day! 🐰

Finishing Touches

  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (4)
code/planning/src/local_planner/ACC_old.py (1)

215-219: Add validation for obstacle data before calculations

In the control loop, there is no check to ensure that self.obstacle_distance and self.obstacle_speed are valid numerical values (not NaN or infinite). To enhance robustness, validate these variables before using them in calculations.

Apply this diff to add validation:

 if (
     self.obstacle_distance is not None
     and self.obstacle_speed is not None
     and self.__current_velocity is not None
+    and not np.isnan(self.obstacle_distance)
+    and not np.isnan(self.obstacle_speed)
+    and not np.isinf(self.obstacle_distance)
+    and not np.isinf(self.obstacle_speed)
 ):
code/planning/src/local_planner/ACC.py (1)

115-118: Consider removing obsolete obstacle variables

With the integration of radar data, self.obstacle_speed and self.obstacle_distance appear to be unused. Removing these variables can clean up the code and reduce confusion.

Apply this diff to remove unused variables:

-# Distance and speed from possible collision object
-self.obstacle_speed: float = 10
-self.obstacle_distance: float = 50
code/planning/src/local_planner/motion_planning.py (1)

492-498: Consider using a dictionary for speed-to-selector mapping.

The current if-elif chain could be replaced with a more maintainable mapping solution.

-            if self.target_speed == acc_speed:
-                self.target_velocity_selector = "acc_speed"
-                # be speed is sometimes equals acc speed (in case of cruise behaviour)
-            elif self.target_speed == be_speed:
-                self.target_velocity_selector = "be_speed"
-            elif self.target_speed == corner_speed:
-                self.target_velocity_selector = "corner_speed"
+            speed_to_selector = {
+                acc_speed: "acc_speed",
+                be_speed: "be_speed",
+                corner_speed: "corner_speed"
+            }
+            self.target_velocity_selector = speed_to_selector.get(self.target_speed, "not selected")
doc/planning/ACC.md (1)

31-31: Enhance documentation clarity.

  1. Add a period at the end of the line for consistency.
  2. Consider adding more details about the data format and units for the range and velocity values.
-/paf/hero/Radar/lead_vehicle/range_velocity_array`: Distance to the vehicle in front, relative speed of the vehicle in front
+/paf/hero/Radar/lead_vehicle/range_velocity_array`: Distance to the vehicle in front (meters) and relative speed of the vehicle in front (m/s).
🧰 Tools
🪛 LanguageTool

[uncategorized] ~31-~31: Loose punctuation mark.
Context: ...Radar/lead_vehicle/range_velocity_array`: Distance to the vehicle in front, relat...

(UNLIKELY_OPENING_PUNCTUATION)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 20558eb and 25e110c.

📒 Files selected for processing (6)
  • .vscode/launch.json (1 hunks)
  • code/planning/launch/planning.launch (1 hunks)
  • code/planning/src/local_planner/ACC.py (3 hunks)
  • code/planning/src/local_planner/ACC_old.py (1 hunks)
  • code/planning/src/local_planner/motion_planning.py (4 hunks)
  • doc/planning/ACC.md (2 hunks)
🧰 Additional context used
🪛 LanguageTool
doc/planning/ACC.md

[uncategorized] ~31-~31: Loose punctuation mark.
Context: ...Radar/lead_vehicle/range_velocity_array`: Distance to the vehicle in front, relat...

(UNLIKELY_OPENING_PUNCTUATION)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build and push image
🔇 Additional comments (7)
code/planning/src/local_planner/ACC_old.py (1)

103-104: ⚠️ Potential issue

Correct the type annotation for self.obstacle_speed

The variable self.obstacle_speed is annotated as tuple, but it is assigned a single float value in the __collision_callback method. Update the type annotation to float for consistency and to prevent potential type errors.

Apply this diff to correct the type:

-self.obstacle_speed: tuple = None
+self.obstacle_speed: float = None

Likely invalid or redundant comment.

code/planning/src/local_planner/ACC.py (2)

246-249: Verify the handling of negative leading_vehicle_speed

Setting acc_speed to 0.0 when self.leading_vehicle_speed < 0.0 may not be appropriate. A negative leading_vehicle_speed might indicate that the lead vehicle is moving towards the ego vehicle. Ensure that this logic correctly reflects the intended behavior of the ACC system.


260-261: Review the calculation of safe_speed

The formula for safe_speed uses the ratio of leading_vehicle_distance to safety_distance. Confirm that this calculation aligns with the desired ACC behavior and considers edge cases, such as when safety_distance is zero.

code/planning/src/local_planner/motion_planning.py (2)

44-44: LGTM! Clean initialization of new velocity selector components.

The initialization of the target_velocity_selector attribute and its corresponding publisher follows ROS conventions and best practices.

Also applies to: 166-169


720-720: LGTM! Good error handling in control loop.

Publishing a default value when conditions aren't met ensures the selector state is always communicated.

.vscode/launch.json (1)

22-35: LGTM! Well-structured debug configuration.

The new debug configuration for port 53001 follows VS Code conventions and maintains consistency with the existing configuration.

doc/planning/ACC.md (1)

5-8: LGTM! Improved documentation structure.

The reorganized section headers enhance readability and navigation.

Copy link
Collaborator

@Johannes1098 Johannes1098 left a comment

Choose a reason for hiding this comment

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

Overall code looks good, some things were noted to look again.
No test of functioning code was accomplished by me as it's still weekend.
@THDThieleT will go to the lab tomorrow morning and do a function check and also maybe furthermore review.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (3)
code/planning/src/local_planner/motion_planning.py (1)

44-44: Consider using an enumeration for velocity selector values.

Using string literals for velocity selector values could lead to maintenance issues and typos. Consider defining an enumeration to represent these values.

Example implementation:

from enum import Enum, auto

class VelocitySelector(Enum):
    NOT_SELECTED = "not selected"
    ACC_SPEED = "acc_speed"
    BE_SPEED = "be_speed"
    CORNER_SPEED = "corner_speed"
    UNKNOWN = "unknown"

Then use it like:

self.target_velocity_selector = VelocitySelector.NOT_SELECTED.value  # For initialization
# In update_target_speed:
if self.target_speed == acc_speed:
    self.target_velocity_selector = VelocitySelector.ACC_SPEED.value

Also applies to: 492-498

code/planning/src/local_planner/ACC.py (2)

110-110: Consider using Optional[float] for clarity.

Since these variables can be None, using Optional[float] would more accurately represent their type.

-        self.obstacle_speed: float = None
-        self.obstacle_distance: float = None
+        self.obstacle_speed: Optional[float] = None
+        self.obstacle_distance: Optional[float] = None

Don't forget to add from typing import Optional at the top of the file.

Also applies to: 112-112


238-249: Simplify condition checks and handle edge cases.

The comment suggests timing issues with None checks. Consider restructuring to handle edge cases more gracefully:

  1. Move safety distance calculation outside the if block
  2. Add early returns for invalid states
+            # Calculate safety distance once
+            safety_distance = calculate_rule_of_thumb(
+                False, self.__current_velocity
+            ) if self.__current_velocity is not None else None
+
+            # Early return for invalid states
+            if self.__current_velocity is None:
+                self.velocity_pub.publish(0)
+                return
+
             if (
-                # often none
                 self.leading_vehicle_distance is not None
-                # often none -> often does elif even if if-case is necessary
                 and self.leading_vehicle_speed is not None
-                and self.__current_velocity is not None
             ):
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 25e110c and eec46e3.

📒 Files selected for processing (3)
  • .vscode/launch.json (1 hunks)
  • code/planning/src/local_planner/ACC.py (3 hunks)
  • code/planning/src/local_planner/motion_planning.py (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .vscode/launch.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build and push image
🔇 Additional comments (6)
code/planning/src/local_planner/motion_planning.py (3)

44-44: LGTM! Good initialization value.

The target_velocity_selector is correctly initialized with a descriptive default value "not selected".


166-169: LGTM! Publisher initialization follows ROS conventions.

The publisher is correctly initialized with appropriate topic name and QoS profile.


720-720: Consider using the initial value for consistency.

The control loop publishes "0" when behavior, ACC speed, or corners are not set, but this differs from the initial value "not selected" set in line 44.

-                self.velocity_selector_pub.publish("0")
+                self.velocity_selector_pub.publish("not selected")
code/planning/src/local_planner/ACC.py (3)

76-82: LGTM! Well-structured addition of radar data handling.

The new subscriber and attributes are properly initialized and follow the existing patterns in the code.

Also applies to: 115-118


122-135: 🛠️ Refactor suggestion

Enhance radar data validation.

While the length check is good, consider adding these additional validations:

  1. Check for NaN/infinite values in radar data
  2. Validate self.__current_velocity before calculating leading_vehicle_speed
     def __update_radar_data(self, data: Float32MultiArray):
-        if not data.data or len(data.data) < 2:
+        if (not data.data or len(data.data) < 2 or
+            np.isinf(data.data[0]) or np.isnan(data.data[0]) or
+            np.isinf(data.data[1]) or np.isnan(data.data[1])):
             # no distance and speed data of the leading vehicle is transferred
             # (leading vehicle is very far away)
             self.leading_vehicle_distance = None
             self.leading_vehicle_relative_speed = None
             self.leading_vehicle_speed = None
         else:
             self.leading_vehicle_distance = data.data[0]
             self.leading_vehicle_relative_speed = data.data[1]
+            if self.__current_velocity is not None:
                 self.leading_vehicle_speed = (
                     self.__current_velocity + self.leading_vehicle_relative_speed
                 )
+            else:
+                self.leading_vehicle_speed = None

Likely invalid or redundant comment.


252-261: 🛠️ Refactor suggestion

Consider adding bounds checking for safety calculations.

The safety distance and speed calculations should include bounds checking to prevent potential issues:

  1. Ensure safety_distance is positive
  2. Add minimum threshold for leading_vehicle_distance
-                safety_distance: float
-                safety_distance = calculate_rule_of_thumb(
-                    False, self.__current_velocity
-                )
+                if safety_distance <= 0:
+                    self.velocity_pub.publish(0)
+                    return
+
+                # Ensure minimum safety distance
+                if self.leading_vehicle_distance < 0.5:  # minimum 0.5m
+                    self.velocity_pub.publish(0)
+                    return
+
                 if self.leading_vehicle_distance < safety_distance:

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
code/planning/src/local_planner/motion_planning.py (1)

492-498: ⚠️ Potential issue

Add a default case for target velocity selector.

The current implementation doesn't handle the case where target_speed doesn't match any of the compared speeds. This could lead to inconsistent selector values.

Apply this diff to handle all cases:

     if self.target_speed == acc_speed:
         self.target_velocity_selector = "acc_speed"
-        # be speed is sometimes equals acc speed (in case of cruise behaviour)
     elif self.target_speed == be_speed:
         self.target_velocity_selector = "be_speed"
     elif self.target_speed == corner_speed:
         self.target_velocity_selector = "corner_speed"
+    else:
+        self.target_velocity_selector = "unknown"  # Handle unexpected cases
🧹 Nitpick comments (1)
code/planning/src/local_planner/motion_planning.py (1)

Line range hint 492-720: Consider using an Enum for selector values.

The current implementation uses string literals for selector values, which could lead to typos and maintenance issues. Consider using an Enum to enforce type safety and maintainability.

Example implementation:

from enum import Enum, auto

class VelocitySelector(Enum):
    NOT_SELECTED = "not selected"
    ACC_SPEED = "acc_speed"
    BE_SPEED = "be_speed"
    CORNER_SPEED = "corner_speed"
    UNKNOWN = "unknown"

Then update the usage:

-self.target_velocity_selector = "not selected"
+self.target_velocity_selector = VelocitySelector.NOT_SELECTED.value

-if self.target_speed == acc_speed:
-    self.target_velocity_selector = "acc_speed"
+if self.target_speed == acc_speed:
+    self.target_velocity_selector = VelocitySelector.ACC_SPEED.value
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between eec46e3 and 6544fc1.

📒 Files selected for processing (1)
  • code/planning/src/local_planner/motion_planning.py (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Build and push image
🔇 Additional comments (4)
code/planning/src/local_planner/motion_planning.py (4)

44-44: LGTM: Good initialization of the selector.

The initial value "not selected" is appropriate and consistent with the usage throughout the code.


166-169: LGTM: Publisher initialization follows ROS conventions.

The publisher is correctly initialized with appropriate topic name and QoS profile.


501-501: LGTM: Consistent publishing of the selector value.

The selector value is published alongside the target speed, maintaining synchronization.


720-720: LGTM: Appropriate default selector value.

When required conditions are not met, the selector is correctly set to "not selected".

@Vroni27 Vroni27 requested a review from THDThieleT January 13, 2025 12:36
Copy link
Collaborator

@THDThieleT THDThieleT left a comment

Choose a reason for hiding this comment

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

changes are made and are now ready for the main branch

@Vroni27 Vroni27 merged commit 10515e5 into main Jan 13, 2025
4 checks passed
@Vroni27 Vroni27 deleted the 532-feature-remodel-acc-first-iteration branch January 13, 2025 13:19
@asamluka asamluka restored the 532-feature-remodel-acc-first-iteration branch January 29, 2025 15:58
@asamluka asamluka deleted the 532-feature-remodel-acc-first-iteration branch February 10, 2025 16:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature]: Remodel ACC (first iteration)
3 participants