From 994921814103a7de14382696ad2cd7754e9a3fb7 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 9 Dec 2025 14:57:10 +0000 Subject: [PATCH 1/4] Initial plan From 69d085b85fd0854a744e1e42747569e9a4d624af Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 9 Dec 2025 15:04:46 +0000 Subject: [PATCH 2/4] Add complete SVDD monitoring package with training and monitoring nodes Co-authored-by: jondave <6209386+jondave@users.noreply.github.com> --- .github/workflows/ros-ci.yml | 2 +- .gitignore | 7 + LICENSE | 222 ++--------------- README.md | 228 +++++++++++++----- requirements.txt | 2 + src/ros2_svdd_monitor/package.xml | 23 ++ .../resource/ros2_svdd_monitor | 0 .../ros2_svdd_monitor/__init__.py | 1 + .../ros2_svdd_monitor/config.py | 32 +++ .../ros2_svdd_monitor/features.py | 91 +++++++ .../ros2_svdd_monitor/monitor_node.py | 141 +++++++++++ .../ros2_svdd_monitor/svdd_model.py | 129 ++++++++++ .../ros2_svdd_monitor/train_node.py | 141 +++++++++++ src/ros2_svdd_monitor/setup.cfg | 4 + src/ros2_svdd_monitor/setup.py | 27 +++ src/ros2_svdd_monitor/test/__init__.py | 1 + src/ros2_svdd_monitor/test/test_config.py | 41 ++++ src/ros2_svdd_monitor/test/test_features.py | 133 ++++++++++ src/ros2_svdd_monitor/test/test_svdd_model.py | 145 +++++++++++ 19 files changed, 1113 insertions(+), 257 deletions(-) create mode 100644 requirements.txt create mode 100644 src/ros2_svdd_monitor/package.xml create mode 100644 src/ros2_svdd_monitor/resource/ros2_svdd_monitor create mode 100644 src/ros2_svdd_monitor/ros2_svdd_monitor/__init__.py create mode 100644 src/ros2_svdd_monitor/ros2_svdd_monitor/config.py create mode 100644 src/ros2_svdd_monitor/ros2_svdd_monitor/features.py create mode 100644 src/ros2_svdd_monitor/ros2_svdd_monitor/monitor_node.py create mode 100644 src/ros2_svdd_monitor/ros2_svdd_monitor/svdd_model.py create mode 100644 src/ros2_svdd_monitor/ros2_svdd_monitor/train_node.py create mode 100644 src/ros2_svdd_monitor/setup.cfg create mode 100644 src/ros2_svdd_monitor/setup.py create mode 100644 src/ros2_svdd_monitor/test/__init__.py create mode 100644 src/ros2_svdd_monitor/test/test_config.py create mode 100644 src/ros2_svdd_monitor/test/test_features.py create mode 100644 src/ros2_svdd_monitor/test/test_svdd_model.py diff --git a/.github/workflows/ros-ci.yml b/.github/workflows/ros-ci.yml index ca82656..312b09d 100644 --- a/.github/workflows/ros-ci.yml +++ b/.github/workflows/ros-ci.yml @@ -67,4 +67,4 @@ jobs: with: import-token: ${{ github.token }} target-ros2-distro: ${{ matrix.ros_distribution }} - skip-tests: true + skip-tests: false diff --git a/.gitignore b/.gitignore index 1bfa387..908d255 100644 --- a/.gitignore +++ b/.gitignore @@ -51,3 +51,10 @@ qtcreator-* # Catkin custom files CATKIN_IGNORE .DS_Store + +# SVDD model files +*.pkl + +# ROS bag files +*.bag +*.db3 diff --git a/LICENSE b/LICENSE index 261eeb9..bfd1b75 100644 --- a/LICENSE +++ b/LICENSE @@ -1,201 +1,21 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. +MIT License + +Copyright (c) 2024 L-CAS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index c028888..ed61cc8 100644 --- a/README.md +++ b/README.md @@ -1,82 +1,200 @@ -## ROS2 Package Template +# ROS2 SVDD Monitor -This repository serves as a template for creating ROS2 packages, equipped with a comprehensive CI workflow and devcontainer configuration. +A ROS2 Humble package for real-time anomaly detection using Support Vector Data Description (SVDD). This package monitors robot behavior by analyzing IMU and velocity command data to detect anomalous patterns. -### Development Environment Setup +## Overview -To begin development in a containerized environment: +The `ros2_svdd_monitor` package implements anomaly detection using One-Class SVM (Support Vector Data Description). It subscribes to `/imu` and `/cmd_vel` topics, extracts features from the sensor data, and uses a trained SVDD model to detect anomalies in robot behavior. -1. **Use this repo as a template:** - The best way to work with this repo is to use it as a template for your ROS package development, to do so, in the top right corner select `Use this template`: - - ![2024-04-24](https://github.com/LCAS/ros2_pkg_template/assets/47870260/2aba3511-7a3f-4e88-a3c1-26ba2be48b45) +## Features - Then in the next step specify the owner and the package name as shown below: - - ![template](https://github.com/LCAS/ros2_pkg_template/assets/47870260/b564c9d7-81d4-4dc1-baba-9355b59d09c1) - +- **Real-time anomaly detection** using SVDD/One-Class SVM +- **Feature extraction** from IMU and cmd_vel data +- **Two-phase operation**: training and monitoring +- **Configurable parameters** for model training and detection +- **ROS2 integration** with standard message types +- **Comprehensive testing** with pytest -3. **Open in Visual Studio Code:** - Open the cloned repository in VSCode. VSCode will prompt you to "Reopen in Container." Alternatively, you can use the command palette (`Ctrl+Shift+P`) and search for the "reopen in container" command. +## Installation - ![Reopen in Container](https://github.com/LCAS/ros2_pkg_template/assets/47870260/52b26ae9-ffe9-4e7c-afb9-88cee88f870f) +### Prerequisites - Then this will promote you with the following two options: - ![image](https://github.com/user-attachments/assets/d0885c75-59de-4b5d-a8b7-c38bf02444d4) +- ROS2 Humble +- Python 3.8+ +- pip - You may select the base image according to your targeted application. For instance, if the nodes do not require GPU processing tasks, it is preferable to use the default devcontainer as it is more lightweight. +### Dependencies -5. **Container Setup:** - Once reopened in the container, VSCode will initiate the building process and pull all necessary dependencies. You can monitor the building log within VSCode. +Install Python dependencies: - ![Devcontainer Log](https://github.com/LCAS/ros2_pkg_template/assets/47870260/4a01e140-972e-4f10-b866-acaabf6b4cfd) +```bash +pip install -r requirements.txt +``` -6. **Verify Container Environment:** - After the build completes, VSCode will connect to the container. You can verify that you are within the container environment. +### Build - ![In Container](https://github.com/LCAS/ros2_pkg_template/assets/47870260/9efec878-5d83-4aed-a9d0-8a1cf6bbf655) +```bash +cd /path/to/workspace +colcon build --packages-select ros2_svdd_monitor +source install/setup.bash +``` -### Devcontainer Features +## Usage -The devcontainer includes a light desktop interface. To utilize this feature: +### Training Phase -1. **Configuration:** - Add the following features to the devcontainer configuration: +First, collect normal operation data and train the SVDD model: - ```json - "features": { - "ghcr.io/LCAS/devcontainer-features/desktop-lite:1": {} - }, - "forwardPorts": [6080, 5801], - "portsAttributes": { - "6080": { - "label": "desktop" - }, - "5801": { - "label": "desktop opengl" - } - } - ``` +```bash +ros2 run ros2_svdd_monitor train +``` -2. **Accessing the Desktop Interface:** - Open the user interface by navigating to the PORTS tab in VSCode, selecting port `6080` (or port `5801` for the CUDA-OpenGL version), and opening it in the browser. +The training node will: +1. Subscribe to `/imu` and `/cmd_vel` topics +2. Collect data for 60 seconds (configurable) +3. Extract features from the sensor data +4. Train the SVDD model +5. Save the trained model to `~/svdd_model.pkl` - ![Open in Browser](https://github.com/LCAS/ros2_pkg_template/assets/47870260/b61f4c95-453b-4c92-ad66-5133c91abb05) +**Important**: Ensure your robot is operating normally during the training phase, as the model will learn what "normal" behavior looks like. -3. **Connecting to the Interface:** - Click on "Connect" and use the password `vscode` to access the desktop interface. +### Monitoring Phase - ![NoVNC](https://github.com/LCAS/ros2_pkg_template/assets/47870260/71246a4c-fd02-4196-b390-b18804f9cd4e) +After training, run the monitoring node to detect anomalies: -### Enjoy Development! +```bash +ros2 run ros2_svdd_monitor monitor +``` -By leveraging this setup, you can develop on a remote machine with a lightweight desktop interface. Magic! Furthermore, this template package provides very nice ROS2 functionality like syntax highlight and template code generation. +The monitoring node will: +1. Load the trained model +2. Subscribe to `/imu` and `/cmd_vel` topics +3. Continuously extract features and detect anomalies +4. Publish anomaly detection results to: + - `/anomaly_detected` (std_msgs/Bool): True if anomaly detected + - `/anomaly_score` (std_msgs/Float32): Anomaly score (negative = anomaly) -**All ROS2 packages should go into the `src/` folder. Create them with `ros2 pkg create...`.** +## Topics -**The devcontainer tries to install all dependencies of the workspace automatically as much as possible, and also tries to build the workspace when it is created, to speed up later colcon builds.** +### Subscribed Topics -### References +- `/imu` (sensor_msgs/Imu): IMU sensor data +- `/cmd_vel` (geometry_msgs/Twist): Velocity commands -1. [ros2-teaching-ws](https://github.com/LCAS/ros2-teaching-ws) -2. [Get Started with Dev Containers in VS Code](https://youtu.be/b1RavPr_878?si=ADepc_VocOHTXP55) +### Published Topics (Monitor Node) + +- `/anomaly_detected` (std_msgs/Bool): Boolean indicating if anomaly is detected +- `/anomaly_score` (std_msgs/Float32): Anomaly score from the SVDD model + +## Configuration + +Configuration parameters are defined in `ros2_svdd_monitor/config.py`: + +### Model Parameters +- `nu`: Upper bound on fraction of outliers (default: 0.1) +- `kernel`: Kernel type for SVM (default: 'rbf') +- `gamma`: Kernel coefficient (default: 'auto') + +### Feature Parameters +- `window_size`: Number of samples for feature computation (default: 10) +- `feature_buffer_size`: Buffer size for streaming features (default: 100) + +### Training Parameters +- `training_duration`: Duration in seconds for training data collection (default: 60.0) + +### Monitoring Parameters +- `anomaly_threshold`: Decision threshold (default: 0.0) +- `publish_rate`: Rate for publishing results in Hz (default: 1.0) + +## Architecture + +### Modules + +1. **config.py**: Configuration parameters for the SVDD system +2. **features.py**: Feature extraction from IMU and cmd_vel data +3. **svdd_model.py**: SVDD model implementation using scikit-learn's OneClassSVM +4. **train_node.py**: ROS2 node for training the SVDD model +5. **monitor_node.py**: ROS2 node for real-time anomaly detection + +### Feature Extraction + +The feature extractor computes statistical features from windowed sensor data: +- **IMU features**: mean, std, min, max of linear acceleration (x, y, z) and angular velocity (x, y, z) +- **cmd_vel features**: mean, std, min, max of linear velocity (x, y, z) and angular velocity (x, y, z) + +Total: 48 features (6 dimensions × 4 statistics × 2 data sources) + +## Testing + +Run tests using pytest: + +```bash +cd src/ros2_svdd_monitor +pytest +``` + +Or using colcon: + +```bash +colcon test --packages-select ros2_svdd_monitor +colcon test-result --verbose +``` + +## Development + +### Development Environment + +This package includes a devcontainer configuration for development with VSCode. See the devcontainer documentation in `.devcontainer/` for setup instructions. + +### Code Style + +This package follows ROS2 Python style guidelines. Run linters: + +```bash +ament_flake8 ros2_svdd_monitor +ament_pep257 ros2_svdd_monitor +``` + +## License + +This project is licensed under the MIT License - see the LICENSE file for details. + +## Acknowledgments + +- Based on the LCAS ros2_pkg_template +- Uses scikit-learn for One-Class SVM implementation + +## Troubleshooting + +### No features collected during training + +**Problem**: Training completes but reports "No features collected during training period!" + +**Solution**: +- Ensure `/imu` and `/cmd_vel` topics are actively publishing data +- Check topic names match your robot's configuration +- Verify data is being published at a reasonable rate (> 1 Hz) + +### Model file not found + +**Problem**: Monitor node reports "Model file not found" + +**Solution**: +- Run the training node first: `ros2 run ros2_svdd_monitor train` +- Check that the model was saved successfully +- Verify the model path in config.py matches your system + +### Import errors + +**Problem**: "ModuleNotFoundError" for numpy or sklearn + +**Solution**: +- Install dependencies: `pip install -r requirements.txt` +- Ensure your ROS2 workspace is properly sourced + +## Contributing + +Contributions are welcome! Please ensure: +- Code passes all tests +- New features include corresponding tests +- Code follows ROS2 Python style guidelines diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3ca9bf1 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +numpy>=1.21.0 +scikit-learn>=1.0.0 diff --git a/src/ros2_svdd_monitor/package.xml b/src/ros2_svdd_monitor/package.xml new file mode 100644 index 0000000..7b90fa6 --- /dev/null +++ b/src/ros2_svdd_monitor/package.xml @@ -0,0 +1,23 @@ + + + + ros2_svdd_monitor + 0.1.0 + ROS2 package for anomaly detection using Support Vector Data Description (SVDD) + L-CAS + MIT + + rclpy + sensor_msgs + geometry_msgs + std_msgs + + ament_copyright + ament_flake8 + ament_pep257 + python3-pytest + + + ament_python + + diff --git a/src/ros2_svdd_monitor/resource/ros2_svdd_monitor b/src/ros2_svdd_monitor/resource/ros2_svdd_monitor new file mode 100644 index 0000000..e69de29 diff --git a/src/ros2_svdd_monitor/ros2_svdd_monitor/__init__.py b/src/ros2_svdd_monitor/ros2_svdd_monitor/__init__.py new file mode 100644 index 0000000..84d1253 --- /dev/null +++ b/src/ros2_svdd_monitor/ros2_svdd_monitor/__init__.py @@ -0,0 +1 @@ +"""ROS2 SVDD Monitor package for anomaly detection.""" diff --git a/src/ros2_svdd_monitor/ros2_svdd_monitor/config.py b/src/ros2_svdd_monitor/ros2_svdd_monitor/config.py new file mode 100644 index 0000000..70ad4c8 --- /dev/null +++ b/src/ros2_svdd_monitor/ros2_svdd_monitor/config.py @@ -0,0 +1,32 @@ +"""Configuration module for SVDD monitor.""" + +import os + + +class SVDDConfig: + """Configuration for SVDD anomaly detection.""" + + def __init__(self): + """Initialize SVDD configuration.""" + # Topics + self.imu_topic = '/imu' + self.cmd_vel_topic = '/cmd_vel' + + # Model parameters + self.nu = 0.1 # Outlier fraction for OneClassSVM + self.kernel = 'rbf' + self.gamma = 'auto' + + # Feature extraction parameters + self.window_size = 10 # Number of samples for feature computation + self.feature_buffer_size = 100 # Buffer size for streaming features + + # Model path + self.model_path = os.path.expanduser('~/svdd_model.pkl') + + # Training parameters + self.training_duration = 60.0 # Duration in seconds for training data collection + + # Monitoring parameters + self.anomaly_threshold = 0.0 # Decision threshold (positive = anomaly) + self.publish_rate = 1.0 # Rate for publishing anomaly detection results (Hz) diff --git a/src/ros2_svdd_monitor/ros2_svdd_monitor/features.py b/src/ros2_svdd_monitor/ros2_svdd_monitor/features.py new file mode 100644 index 0000000..c1ac189 --- /dev/null +++ b/src/ros2_svdd_monitor/ros2_svdd_monitor/features.py @@ -0,0 +1,91 @@ +"""Feature extraction module for IMU and cmd_vel data.""" + +import numpy as np +from collections import deque + + +class FeatureExtractor: + """Extract features from IMU and cmd_vel messages for SVDD.""" + + def __init__(self, window_size=10): + """ + Initialize feature extractor. + + Args: + window_size: Number of samples for feature computation + """ + self.window_size = window_size + self.imu_buffer = deque(maxlen=window_size) + self.cmd_vel_buffer = deque(maxlen=window_size) + + def add_imu_data(self, imu_msg): + """ + Add IMU data to buffer. + + Args: + imu_msg: sensor_msgs/Imu message + """ + # Extract linear acceleration and angular velocity + imu_data = np.array([ + imu_msg.linear_acceleration.x, + imu_msg.linear_acceleration.y, + imu_msg.linear_acceleration.z, + imu_msg.angular_velocity.x, + imu_msg.angular_velocity.y, + imu_msg.angular_velocity.z + ]) + self.imu_buffer.append(imu_data) + + def add_cmd_vel_data(self, cmd_vel_msg): + """ + Add cmd_vel data to buffer. + + Args: + cmd_vel_msg: geometry_msgs/Twist message + """ + # Extract linear and angular velocity commands + cmd_vel_data = np.array([ + cmd_vel_msg.linear.x, + cmd_vel_msg.linear.y, + cmd_vel_msg.linear.z, + cmd_vel_msg.angular.x, + cmd_vel_msg.angular.y, + cmd_vel_msg.angular.z + ]) + self.cmd_vel_buffer.append(cmd_vel_data) + + def extract_features(self): + """ + Extract features from buffered data. + + Returns: + np.ndarray: Feature vector, or None if insufficient data + """ + if len(self.imu_buffer) < self.window_size or len(self.cmd_vel_buffer) < self.window_size: + return None + + # Convert buffers to numpy arrays + imu_array = np.array(self.imu_buffer) + cmd_vel_array = np.array(self.cmd_vel_buffer) + + # Extract statistical features + features = [] + + # IMU features (mean, std, min, max for each dimension) + features.extend(np.mean(imu_array, axis=0)) + features.extend(np.std(imu_array, axis=0)) + features.extend(np.min(imu_array, axis=0)) + features.extend(np.max(imu_array, axis=0)) + + # cmd_vel features (mean, std, min, max for each dimension) + features.extend(np.mean(cmd_vel_array, axis=0)) + features.extend(np.std(cmd_vel_array, axis=0)) + features.extend(np.min(cmd_vel_array, axis=0)) + features.extend(np.max(cmd_vel_array, axis=0)) + + return np.array(features) + + def reset(self): + """Reset the feature buffers.""" + self.imu_buffer.clear() + self.cmd_vel_buffer.clear() diff --git a/src/ros2_svdd_monitor/ros2_svdd_monitor/monitor_node.py b/src/ros2_svdd_monitor/ros2_svdd_monitor/monitor_node.py new file mode 100644 index 0000000..b0962fb --- /dev/null +++ b/src/ros2_svdd_monitor/ros2_svdd_monitor/monitor_node.py @@ -0,0 +1,141 @@ +"""Monitoring node for SVDD anomaly detection.""" + +import rclpy +from rclpy.node import Node +from sensor_msgs.msg import Imu +from geometry_msgs.msg import Twist +from std_msgs.msg import Bool, Float32 +import os + +from ros2_svdd_monitor.config import SVDDConfig +from ros2_svdd_monitor.features import FeatureExtractor +from ros2_svdd_monitor.svdd_model import SVDDModel + + +class MonitorNode(Node): + """ROS2 node for SVDD-based anomaly detection.""" + + def __init__(self): + """Initialize monitoring node.""" + super().__init__('svdd_monitor') + + # Configuration + self.config = SVDDConfig() + + # Feature extractor + self.feature_extractor = FeatureExtractor(window_size=self.config.window_size) + + # SVDD model + self.model = SVDDModel( + nu=self.config.nu, + kernel=self.config.kernel, + gamma=self.config.gamma + ) + + # Load trained model + if not os.path.exists(self.config.model_path): + self.get_logger().error(f'Model file not found at {self.config.model_path}!') + self.get_logger().error('Please run the training node first.') + raise RuntimeError('Model file not found') + + if not self.model.load(self.config.model_path): + self.get_logger().error('Failed to load model!') + raise RuntimeError('Failed to load model') + + self.get_logger().info(f'Model loaded successfully from {self.config.model_path}') + + # Subscribers + self.imu_sub = self.create_subscription( + Imu, + self.config.imu_topic, + self.imu_callback, + 10 + ) + + self.cmd_vel_sub = self.create_subscription( + Twist, + self.config.cmd_vel_topic, + self.cmd_vel_callback, + 10 + ) + + # Publishers + self.anomaly_pub = self.create_publisher(Bool, '/anomaly_detected', 10) + self.score_pub = self.create_publisher(Float32, '/anomaly_score', 10) + + # Timer for periodic anomaly checking + self.check_timer = self.create_timer( + 1.0 / self.config.publish_rate, + self.check_anomaly + ) + + self.get_logger().info('Monitoring started. Waiting for sensor data...') + + def imu_callback(self, msg): + """ + Handle IMU messages. + + Args: + msg: sensor_msgs/Imu message + """ + self.feature_extractor.add_imu_data(msg) + + def cmd_vel_callback(self, msg): + """ + Handle cmd_vel messages. + + Args: + msg: geometry_msgs/Twist message + """ + self.feature_extractor.add_cmd_vel_data(msg) + + def check_anomaly(self): + """Check for anomalies in buffered data.""" + # Extract features + features = self.feature_extractor.extract_features() + + if features is None: + return + + try: + # Predict anomaly + predictions, scores = self.model.predict(features) + + # predictions: 1 for inliers, -1 for outliers + # scores: negative values indicate outliers + is_anomaly = predictions[0] == -1 + anomaly_score = float(scores[0]) + + # Publish results + anomaly_msg = Bool() + anomaly_msg.data = is_anomaly + self.anomaly_pub.publish(anomaly_msg) + + score_msg = Float32() + score_msg.data = anomaly_score + self.score_pub.publish(score_msg) + + if is_anomaly: + self.get_logger().warn(f'Anomaly detected! Score: {anomaly_score:.4f}') + + except Exception as e: + self.get_logger().error(f'Error during anomaly detection: {e}') + + +def main(args=None): + """Main entry point for monitoring node.""" + rclpy.init(args=args) + + try: + node = MonitorNode() + rclpy.spin(node) + except KeyboardInterrupt: + pass + except Exception as e: + print(f'Error: {e}') + finally: + rclpy.shutdown() + + +if __name__ == '__main__': + main() diff --git a/src/ros2_svdd_monitor/ros2_svdd_monitor/svdd_model.py b/src/ros2_svdd_monitor/ros2_svdd_monitor/svdd_model.py new file mode 100644 index 0000000..cdcc641 --- /dev/null +++ b/src/ros2_svdd_monitor/ros2_svdd_monitor/svdd_model.py @@ -0,0 +1,129 @@ +"""SVDD model using scikit-learn's OneClassSVM.""" + +import pickle +import numpy as np +from sklearn.svm import OneClassSVM +from sklearn.preprocessing import StandardScaler + + +class SVDDModel: + """Support Vector Data Description model for anomaly detection.""" + + def __init__(self, nu=0.1, kernel='rbf', gamma='auto'): + """ + Initialize SVDD model. + + Args: + nu: Upper bound on fraction of outliers (0 < nu <= 1) + kernel: Kernel type for SVM + gamma: Kernel coefficient + """ + self.nu = nu + self.kernel = kernel + self.gamma = gamma + self.model = OneClassSVM(nu=nu, kernel=kernel, gamma=gamma) + self.scaler = StandardScaler() + self.is_trained = False + + def train(self, features): + """ + Train the SVDD model. + + Args: + features: numpy array of shape (n_samples, n_features) + + Returns: + bool: True if training successful, False otherwise + """ + if features is None or len(features) == 0: + return False + + try: + # Normalize features + features_scaled = self.scaler.fit_transform(features) + + # Train the model + self.model.fit(features_scaled) + self.is_trained = True + return True + except Exception as e: + print(f"Error training SVDD model: {e}") + return False + + def predict(self, features): + """ + Predict if features are anomalous. + + Args: + features: numpy array of shape (n_samples, n_features) or (n_features,) + + Returns: + tuple: (predictions, decision_scores) + predictions: 1 for inliers, -1 for outliers + decision_scores: signed distance to boundary (negative = outlier) + """ + if not self.is_trained: + raise RuntimeError("Model must be trained before prediction") + + # Ensure features is 2D + if features.ndim == 1: + features = features.reshape(1, -1) + + # Normalize features + features_scaled = self.scaler.transform(features) + + # Predict + predictions = self.model.predict(features_scaled) + decision_scores = self.model.decision_function(features_scaled) + + return predictions, decision_scores + + def save(self, filepath): + """ + Save model to file. + + Args: + filepath: Path to save the model + + Returns: + bool: True if save successful, False otherwise + """ + try: + model_data = { + 'model': self.model, + 'scaler': self.scaler, + 'is_trained': self.is_trained, + 'nu': self.nu, + 'kernel': self.kernel, + 'gamma': self.gamma + } + with open(filepath, 'wb') as f: + pickle.dump(model_data, f) + return True + except Exception as e: + print(f"Error saving model: {e}") + return False + + def load(self, filepath): + """ + Load model from file. + + Args: + filepath: Path to load the model from + + Returns: + bool: True if load successful, False otherwise + """ + try: + with open(filepath, 'rb') as f: + model_data = pickle.load(f) + self.model = model_data['model'] + self.scaler = model_data['scaler'] + self.is_trained = model_data['is_trained'] + self.nu = model_data['nu'] + self.kernel = model_data['kernel'] + self.gamma = model_data['gamma'] + return True + except Exception as e: + print(f"Error loading model: {e}") + return False diff --git a/src/ros2_svdd_monitor/ros2_svdd_monitor/train_node.py b/src/ros2_svdd_monitor/ros2_svdd_monitor/train_node.py new file mode 100644 index 0000000..f47d80d --- /dev/null +++ b/src/ros2_svdd_monitor/ros2_svdd_monitor/train_node.py @@ -0,0 +1,141 @@ +"""Training node for SVDD model.""" + +import rclpy +from rclpy.node import Node +from sensor_msgs.msg import Imu +from geometry_msgs.msg import Twist +import numpy as np + +from ros2_svdd_monitor.config import SVDDConfig +from ros2_svdd_monitor.features import FeatureExtractor +from ros2_svdd_monitor.svdd_model import SVDDModel + + +class TrainNode(Node): + """ROS2 node for training SVDD model.""" + + def __init__(self): + """Initialize training node.""" + super().__init__('svdd_train') + + # Configuration + self.config = SVDDConfig() + + # Feature extractor + self.feature_extractor = FeatureExtractor(window_size=self.config.window_size) + + # SVDD model + self.model = SVDDModel( + nu=self.config.nu, + kernel=self.config.kernel, + gamma=self.config.gamma + ) + + # Data storage + self.features_list = [] + + # Flags + self.training_active = True + + # Subscribers + self.imu_sub = self.create_subscription( + Imu, + self.config.imu_topic, + self.imu_callback, + 10 + ) + + self.cmd_vel_sub = self.create_subscription( + Twist, + self.config.cmd_vel_topic, + self.cmd_vel_callback, + 10 + ) + + # Timer for training completion + self.training_timer = self.create_timer( + self.config.training_duration, + self.complete_training + ) + + self.get_logger().info(f'Training started. Collecting data for {self.config.training_duration} seconds...') + + def imu_callback(self, msg): + """ + Handle IMU messages. + + Args: + msg: sensor_msgs/Imu message + """ + if not self.training_active: + return + + self.feature_extractor.add_imu_data(msg) + self.try_extract_features() + + def cmd_vel_callback(self, msg): + """ + Handle cmd_vel messages. + + Args: + msg: geometry_msgs/Twist message + """ + if not self.training_active: + return + + self.feature_extractor.add_cmd_vel_data(msg) + + def try_extract_features(self): + """Try to extract features from buffered data.""" + features = self.feature_extractor.extract_features() + if features is not None: + self.features_list.append(features) + + def complete_training(self): + """Complete training and save model.""" + self.training_active = False + self.training_timer.cancel() + + if len(self.features_list) == 0: + self.get_logger().error('No features collected during training period!') + self.get_logger().info('Please ensure /imu and /cmd_vel topics are publishing data.') + return + + self.get_logger().info(f'Training completed. Collected {len(self.features_list)} feature samples.') + + # Convert features to numpy array + features_array = np.array(self.features_list) + + # Train the model + self.get_logger().info('Training SVDD model...') + success = self.model.train(features_array) + + if success: + # Save the model + self.get_logger().info(f'Saving model to {self.config.model_path}...') + save_success = self.model.save(self.config.model_path) + + if save_success: + self.get_logger().info('Model saved successfully!') + else: + self.get_logger().error('Failed to save model!') + else: + self.get_logger().error('Failed to train model!') + + +def main(args=None): + """Main entry point for training node.""" + rclpy.init(args=args) + node = TrainNode() + + try: + rclpy.spin(node) + except KeyboardInterrupt: + pass + finally: + node.destroy_node() + rclpy.shutdown() + + +if __name__ == '__main__': + main() diff --git a/src/ros2_svdd_monitor/setup.cfg b/src/ros2_svdd_monitor/setup.cfg new file mode 100644 index 0000000..473ba4c --- /dev/null +++ b/src/ros2_svdd_monitor/setup.cfg @@ -0,0 +1,4 @@ +[develop] +script_dir=$base/lib/ros2_svdd_monitor +[install] +install_scripts=$base/lib/ros2_svdd_monitor diff --git a/src/ros2_svdd_monitor/setup.py b/src/ros2_svdd_monitor/setup.py new file mode 100644 index 0000000..10ca682 --- /dev/null +++ b/src/ros2_svdd_monitor/setup.py @@ -0,0 +1,27 @@ +from setuptools import find_packages, setup + +package_name = 'ros2_svdd_monitor' + +setup( + name=package_name, + version='0.1.0', + packages=find_packages(exclude=['test']), + data_files=[ + ('share/ament_index/resource_index/packages', + ['resource/' + package_name]), + ('share/' + package_name, ['package.xml']), + ], + install_requires=['setuptools'], + zip_safe=True, + maintainer='L-CAS', + maintainer_email='lcas@lincoln.ac.uk', + description='ROS2 package for anomaly detection using Support Vector Data Description (SVDD)', + license='MIT', + tests_require=['pytest'], + entry_points={ + 'console_scripts': [ + 'train = ros2_svdd_monitor.train_node:main', + 'monitor = ros2_svdd_monitor.monitor_node:main', + ], + }, +) diff --git a/src/ros2_svdd_monitor/test/__init__.py b/src/ros2_svdd_monitor/test/__init__.py new file mode 100644 index 0000000..c3236fe --- /dev/null +++ b/src/ros2_svdd_monitor/test/__init__.py @@ -0,0 +1 @@ +"""Test module for ros2_svdd_monitor.""" diff --git a/src/ros2_svdd_monitor/test/test_config.py b/src/ros2_svdd_monitor/test/test_config.py new file mode 100644 index 0000000..c7a704e --- /dev/null +++ b/src/ros2_svdd_monitor/test/test_config.py @@ -0,0 +1,41 @@ +"""Tests for configuration module.""" + +import pytest +from ros2_svdd_monitor.config import SVDDConfig + + +def test_config_initialization(): + """Test configuration initialization.""" + config = SVDDConfig() + + # Test topic names + assert config.imu_topic == '/imu' + assert config.cmd_vel_topic == '/cmd_vel' + + # Test model parameters + assert config.nu == 0.1 + assert config.kernel == 'rbf' + assert config.gamma == 'auto' + + # Test feature parameters + assert config.window_size == 10 + assert config.feature_buffer_size == 100 + + # Test paths + assert config.model_path is not None + assert 'svdd_model.pkl' in config.model_path + + # Test training parameters + assert config.training_duration == 60.0 + + # Test monitoring parameters + assert config.anomaly_threshold == 0.0 + assert config.publish_rate == 1.0 + + +def test_config_model_path(): + """Test that model path is properly expanded.""" + config = SVDDConfig() + + # Path should be expanded (no ~ in path) + assert '~' not in config.model_path diff --git a/src/ros2_svdd_monitor/test/test_features.py b/src/ros2_svdd_monitor/test/test_features.py new file mode 100644 index 0000000..c6cb208 --- /dev/null +++ b/src/ros2_svdd_monitor/test/test_features.py @@ -0,0 +1,133 @@ +"""Tests for feature extraction module.""" + +import pytest +import numpy as np +from sensor_msgs.msg import Imu +from geometry_msgs.msg import Twist, Vector3 +from ros2_svdd_monitor.features import FeatureExtractor + + +def create_imu_msg(linear_acc, angular_vel): + """Create an IMU message.""" + msg = Imu() + msg.linear_acceleration.x = linear_acc[0] + msg.linear_acceleration.y = linear_acc[1] + msg.linear_acceleration.z = linear_acc[2] + msg.angular_velocity.x = angular_vel[0] + msg.angular_velocity.y = angular_vel[1] + msg.angular_velocity.z = angular_vel[2] + return msg + + +def create_twist_msg(linear, angular): + """Create a Twist message.""" + msg = Twist() + msg.linear.x = linear[0] + msg.linear.y = linear[1] + msg.linear.z = linear[2] + msg.angular.x = angular[0] + msg.angular.y = angular[1] + msg.angular.z = angular[2] + return msg + + +def test_feature_extractor_initialization(): + """Test feature extractor initialization.""" + extractor = FeatureExtractor(window_size=5) + assert extractor.window_size == 5 + assert len(extractor.imu_buffer) == 0 + assert len(extractor.cmd_vel_buffer) == 0 + + +def test_add_imu_data(): + """Test adding IMU data to buffer.""" + extractor = FeatureExtractor(window_size=3) + + for i in range(5): + imu_msg = create_imu_msg([i, i+1, i+2], [i+3, i+4, i+5]) + extractor.add_imu_data(imu_msg) + + # Buffer should have max 3 elements + assert len(extractor.imu_buffer) == 3 + + +def test_add_cmd_vel_data(): + """Test adding cmd_vel data to buffer.""" + extractor = FeatureExtractor(window_size=3) + + for i in range(5): + cmd_vel_msg = create_twist_msg([i, i+1, i+2], [i+3, i+4, i+5]) + extractor.add_cmd_vel_data(cmd_vel_msg) + + # Buffer should have max 3 elements + assert len(extractor.cmd_vel_buffer) == 3 + + +def test_extract_features_insufficient_data(): + """Test feature extraction with insufficient data.""" + extractor = FeatureExtractor(window_size=5) + + # Add only 3 samples + for i in range(3): + imu_msg = create_imu_msg([i, i+1, i+2], [i+3, i+4, i+5]) + cmd_vel_msg = create_twist_msg([i, i+1, i+2], [i+3, i+4, i+5]) + extractor.add_imu_data(imu_msg) + extractor.add_cmd_vel_data(cmd_vel_msg) + + features = extractor.extract_features() + assert features is None + + +def test_extract_features_sufficient_data(): + """Test feature extraction with sufficient data.""" + extractor = FeatureExtractor(window_size=5) + + # Add 5 samples + for i in range(5): + imu_msg = create_imu_msg([i, i+1, i+2], [i+3, i+4, i+5]) + cmd_vel_msg = create_twist_msg([i, i+1, i+2], [i+3, i+4, i+5]) + extractor.add_imu_data(imu_msg) + extractor.add_cmd_vel_data(cmd_vel_msg) + + features = extractor.extract_features() + assert features is not None + assert isinstance(features, np.ndarray) + # 6 IMU dimensions * 4 stats + 6 cmd_vel dimensions * 4 stats = 48 features + assert len(features) == 48 + + +def test_reset(): + """Test resetting the feature extractor.""" + extractor = FeatureExtractor(window_size=3) + + for i in range(3): + imu_msg = create_imu_msg([i, i+1, i+2], [i+3, i+4, i+5]) + cmd_vel_msg = create_twist_msg([i, i+1, i+2], [i+3, i+4, i+5]) + extractor.add_imu_data(imu_msg) + extractor.add_cmd_vel_data(cmd_vel_msg) + + assert len(extractor.imu_buffer) == 3 + assert len(extractor.cmd_vel_buffer) == 3 + + extractor.reset() + + assert len(extractor.imu_buffer) == 0 + assert len(extractor.cmd_vel_buffer) == 0 + + +def test_feature_statistics(): + """Test that feature statistics are computed correctly.""" + extractor = FeatureExtractor(window_size=3) + + # Add 3 samples with known values + for i in range(3): + imu_msg = create_imu_msg([1.0, 2.0, 3.0], [4.0, 5.0, 6.0]) + cmd_vel_msg = create_twist_msg([0.5, 0.0, 0.0], [0.0, 0.0, 1.0]) + extractor.add_imu_data(imu_msg) + extractor.add_cmd_vel_data(cmd_vel_msg) + + features = extractor.extract_features() + assert features is not None + + # Check that features have correct shape + assert len(features) == 48 diff --git a/src/ros2_svdd_monitor/test/test_svdd_model.py b/src/ros2_svdd_monitor/test/test_svdd_model.py new file mode 100644 index 0000000..2404e1f --- /dev/null +++ b/src/ros2_svdd_monitor/test/test_svdd_model.py @@ -0,0 +1,145 @@ +"""Tests for SVDD model module.""" + +import pytest +import numpy as np +import tempfile +import os +from ros2_svdd_monitor.svdd_model import SVDDModel + + +def test_svdd_model_initialization(): + """Test SVDD model initialization.""" + model = SVDDModel(nu=0.1, kernel='rbf', gamma='auto') + assert model.nu == 0.1 + assert model.kernel == 'rbf' + assert model.gamma == 'auto' + assert not model.is_trained + + +def test_train_with_valid_data(): + """Test training with valid data.""" + model = SVDDModel() + + # Generate some training data + np.random.seed(42) + features = np.random.randn(100, 10) + + success = model.train(features) + assert success + assert model.is_trained + + +def test_train_with_empty_data(): + """Test training with empty data.""" + model = SVDDModel() + + features = np.array([]) + success = model.train(features) + assert not success + assert not model.is_trained + + +def test_train_with_none(): + """Test training with None data.""" + model = SVDDModel() + + success = model.train(None) + assert not success + assert not model.is_trained + + +def test_predict_before_training(): + """Test prediction before training raises error.""" + model = SVDDModel() + + features = np.random.randn(1, 10) + + with pytest.raises(RuntimeError): + model.predict(features) + + +def test_predict_after_training(): + """Test prediction after training.""" + model = SVDDModel() + + # Train the model + np.random.seed(42) + train_features = np.random.randn(100, 10) + model.train(train_features) + + # Test prediction with single sample + test_features = np.random.randn(10) + predictions, scores = model.predict(test_features) + + assert len(predictions) == 1 + assert len(scores) == 1 + assert predictions[0] in [-1, 1] + + # Test prediction with multiple samples + test_features_multi = np.random.randn(5, 10) + predictions, scores = model.predict(test_features_multi) + + assert len(predictions) == 5 + assert len(scores) == 5 + + +def test_save_and_load_model(): + """Test saving and loading model.""" + model = SVDDModel() + + # Train the model + np.random.seed(42) + train_features = np.random.randn(100, 10) + model.train(train_features) + + # Save the model + with tempfile.NamedTemporaryFile(delete=False, suffix='.pkl') as tmp: + tmp_path = tmp.name + + try: + success = model.save(tmp_path) + assert success + assert os.path.exists(tmp_path) + + # Load the model + new_model = SVDDModel() + success = new_model.load(tmp_path) + assert success + assert new_model.is_trained + assert new_model.nu == model.nu + assert new_model.kernel == model.kernel + + # Test prediction with loaded model + test_features = np.random.randn(10) + predictions, scores = new_model.predict(test_features) + assert len(predictions) == 1 + + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + + +def test_load_nonexistent_file(): + """Test loading from nonexistent file.""" + model = SVDDModel() + success = model.load('/nonexistent/path/model.pkl') + assert not success + assert not model.is_trained + + +def test_model_consistency(): + """Test that model produces consistent results.""" + model = SVDDModel() + + # Train the model + np.random.seed(42) + train_features = np.random.randn(100, 10) + model.train(train_features) + + # Test prediction consistency + test_features = np.random.randn(10) + predictions1, scores1 = model.predict(test_features) + predictions2, scores2 = model.predict(test_features) + + assert np.array_equal(predictions1, predictions2) + assert np.array_equal(scores1, scores2) From 6bc3d9fbade6f167f695ac2c44019691cc953ba1 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 9 Dec 2025 15:12:32 +0000 Subject: [PATCH 3/4] Fix code review issues: add dependencies to setup.py and use proper logging Co-authored-by: jondave <6209386+jondave@users.noreply.github.com> --- src/ros2_svdd_monitor/ros2_svdd_monitor/svdd_model.py | 9 ++++++--- src/ros2_svdd_monitor/setup.py | 6 +++++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/ros2_svdd_monitor/ros2_svdd_monitor/svdd_model.py b/src/ros2_svdd_monitor/ros2_svdd_monitor/svdd_model.py index cdcc641..13184cb 100644 --- a/src/ros2_svdd_monitor/ros2_svdd_monitor/svdd_model.py +++ b/src/ros2_svdd_monitor/ros2_svdd_monitor/svdd_model.py @@ -2,9 +2,12 @@ import pickle import numpy as np +import logging from sklearn.svm import OneClassSVM from sklearn.preprocessing import StandardScaler +logger = logging.getLogger(__name__) + class SVDDModel: """Support Vector Data Description model for anomaly detection.""" @@ -47,7 +50,7 @@ def train(self, features): self.is_trained = True return True except Exception as e: - print(f"Error training SVDD model: {e}") + logger.error(f"Error training SVDD model: {e}") return False def predict(self, features): @@ -101,7 +104,7 @@ def save(self, filepath): pickle.dump(model_data, f) return True except Exception as e: - print(f"Error saving model: {e}") + logger.error(f"Error saving model: {e}") return False def load(self, filepath): @@ -125,5 +128,5 @@ def load(self, filepath): self.gamma = model_data['gamma'] return True except Exception as e: - print(f"Error loading model: {e}") + logger.error(f"Error loading model: {e}") return False diff --git a/src/ros2_svdd_monitor/setup.py b/src/ros2_svdd_monitor/setup.py index 10ca682..d57818b 100644 --- a/src/ros2_svdd_monitor/setup.py +++ b/src/ros2_svdd_monitor/setup.py @@ -11,7 +11,11 @@ ['resource/' + package_name]), ('share/' + package_name, ['package.xml']), ], - install_requires=['setuptools'], + install_requires=[ + 'setuptools', + 'numpy>=1.21.0', + 'scikit-learn>=1.0.0', + ], zip_safe=True, maintainer='L-CAS', maintainer_email='lcas@lincoln.ac.uk', From 75a5ebc2594c8c878da7f77f8f7a3dfa7e7793c4 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Tue, 9 Dec 2025 15:15:51 +0000 Subject: [PATCH 4/4] Fix remaining print statement in monitor_node.py to use proper logging Co-authored-by: jondave <6209386+jondave@users.noreply.github.com> --- src/ros2_svdd_monitor/ros2_svdd_monitor/monitor_node.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/ros2_svdd_monitor/ros2_svdd_monitor/monitor_node.py b/src/ros2_svdd_monitor/ros2_svdd_monitor/monitor_node.py index b0962fb..12d2856 100644 --- a/src/ros2_svdd_monitor/ros2_svdd_monitor/monitor_node.py +++ b/src/ros2_svdd_monitor/ros2_svdd_monitor/monitor_node.py @@ -124,6 +124,9 @@ def check_anomaly(self): def main(args=None): """Main entry point for monitoring node.""" + import logging + logger = logging.getLogger(__name__) + rclpy.init(args=args) try: @@ -132,7 +135,7 @@ def main(args=None): except KeyboardInterrupt: pass except Exception as e: - print(f'Error: {e}') + logger.error(f'Error: {e}') finally: rclpy.shutdown()