### Install PyOctoMap via pip Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Use this command to install the pre-built wheel for the recommended setup. ```bash # Install pre-built wheel (recommended) pip install pyoctomap ``` -------------------------------- ### Install core and build dependencies Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Install necessary packages to resolve ImportError or build-from-source failures. ```bash # Install core dependencies pip install numpy cython # For building from source pip install setuptools wheel # For library bundling (Linux) pip install auditwheel ``` -------------------------------- ### Prepare build environment Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/build_system.md Installs required Python build dependencies. ```bash pip install -U pip setuptools wheel numpy cython auditwheel ``` -------------------------------- ### Start Local Development Environment Source: https://github.com/spinkoo/pyoctomap/blob/main/docker/README.md Use Docker Compose to spin up the local development environment. ```bash cd docker docker-compose up ``` -------------------------------- ### Install and verify PyOctoMap Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/build_system.md Installs the generated wheel and performs a basic import test. ```bash pip install dist/*.whl python -c "import pyoctomap; tree = pyoctomap.OcTree(0.1)" ``` -------------------------------- ### Install PyOctoMap via pip Source: https://github.com/spinkoo/pyoctomap/blob/main/README_pypi_preview.md Standard installation command for the PyOctoMap package. ```bash pip install pyoctomap ``` -------------------------------- ### Build OctoMap from source Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Manually build and install OctoMap libraries if they are not found by the installer. ```bash # Clone and build OctoMap cd src/octomap mkdir build && cd build cmake .. make -j4 sudo make install # Update library path sudo ldconfig ``` -------------------------------- ### Build wheels locally with cibuildwheel Source: https://github.com/spinkoo/pyoctomap/blob/main/README_pypi_preview.md Commands to install the build tool and initiate the wheel creation process. ```bash pip install cibuildwheel cibuildwheel --platform linux # or macos / windows ``` -------------------------------- ### Verify bundled libraries Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Check the installation path and list the contents of the bundled libraries directory. ```bash # Check if libraries are bundled python -c "import octomap; print(octomap.__file__)" ls -la $(python -c "import octomap; print(octomap.__file__)")/../libs/ ``` -------------------------------- ### Install pyoctomap in WSL Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Use pip to install the package within a WSL2 environment. ```bash # In WSL pip install pyoctomap ``` -------------------------------- ### Configure WSL2 for PyOctoMap Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Verify WSL version and install Python environment within the WSL instance. ```bash # Check WSL version wsl --list --verbose # Update to WSL2 if needed wsl --set-version Ubuntu 2 # Install Python in WSL sudo apt update sudo apt install python3 python3-pip ``` -------------------------------- ### Markdown URL transformation examples Source: https://github.com/spinkoo/pyoctomap/blob/main/github2pypi/README.md Demonstrates the transformation of a relative image path to an absolute GitHub URL. ```markdown ![Example](examples/octree_visualization.png) ``` ```markdown ![Example](https://github.com/Spinkoo/pyoctomap/blob/main/examples/octree_visualization.png?raw=true) ``` -------------------------------- ### Build in headless or Colab environments Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/build_system.md Installs necessary build tools and executes the build script in a non-interactive environment. ```bash !apt-get update -qq && apt-get install -y -qq cmake build-essential !git clone --recursive https://github.com/Spinkoo/pyoctomap.git !cd pyoctomap && chmod +x build.sh && ./build.sh ``` -------------------------------- ### Force PyOctoMap wheel installation Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Use these commands to bypass source builds and force the installation of pre-built manylinux wheels. ```bash # Force wheel installation (recommended) pip install pyoctomap --only-binary=all # If that fails, try with no cache pip install pyoctomap --only-binary=all --no-cache-dir ``` -------------------------------- ### Verify OctoMap Installation Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Use this script to check the Python path and verify if the octomap module is correctly installed and importable. ```python # Check if module is installed import sys print(sys.path) # Try importing try: import octomap print("OctoMap imported successfully") except ImportError as e: print(f"Import error: {e}") ``` -------------------------------- ### Versioned Symlink Structure Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Example of the symlink hierarchy used for bundled shared libraries. ```text liboctomap.so -> liboctomap.so.1.10 liboctomap.so.1.10 -> liboctomap.so.1.10.0 liboctomap.so.1.10.0 (actual library) ``` -------------------------------- ### Reset Python Environment Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Create a clean virtual environment to isolate dependencies and ensure a fresh installation of the package. ```bash # Create fresh virtual environment python3 -m venv fresh_env source fresh_env/bin/activate pip install pyoctomap ``` -------------------------------- ### Execute standard Linux build script Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/build_system.md Runs the primary build script to compile OctoMap, generate wheels, and verify the installation. ```bash chmod +x build.sh ./build.sh ``` -------------------------------- ### Verify and update Python version Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Check the current Python version and install a compatible version (3.8+) if necessary. ```bash # Check Python version python3 --version # If version is too old, install Python 3.8+ sudo apt update sudo apt install python3.8 python3.8-pip ``` -------------------------------- ### Update compiler toolchain for Cython Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Install build-essential and update GCC versions to resolve Cython compilation errors. ```bash # Install build essentials sudo apt install build-essential # Update gcc sudo apt install gcc-9 g++-9 sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-9 90 sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-9 90 ``` -------------------------------- ### Clone repository with submodules Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/build_system.md Initializes the repository and all required submodules. ```bash git clone --recursive https://github.com/Spinkoo/pyoctomap.git cd pyoctomap ``` -------------------------------- ### Perform local development and testing Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Use these commands to set up the environment in editable mode and run the test suite. ```bash # Install in development mode pip install -e . # Test with bundled libraries python -m pytest tests/ ``` -------------------------------- ### Basic Occupancy Mapping with pyoctomap Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Demonstrates initializing an OcTree, updating node occupancy, and saving the map to a binary file. ```python # Create an octree with 0.1m resolution import pyoctomap import numpy as np tree = pyoctomap.OcTree(0.1) # Add occupied points tree.updateNode([1.0, 2.0, 3.0], True) tree.updateNode([1.1, 2.1, 3.1], True) # Add free space tree.updateNode([0.5, 0.5, 0.5], False) # Check occupancy node = tree.search([1.0, 2.0, 3.0]) if node and tree.isNodeOccupied(node): print("Point is occupied!") # Save to file tree.write("my_map.bt") ``` -------------------------------- ### Initialize OcTreeKey Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Demonstrates instantiation of an OcTreeKey and access to its integer coordinate components. ```python from pyoctomap import OcTreeKey key = OcTreeKey() key[0], key[1], key[2] # integer coordinates ``` -------------------------------- ### Initialize and Query an OcTree Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Demonstrates creating an OcTree with a specific resolution, updating voxel occupancy, and checking the status of a node. ```python import numpy as np import pyoctomap # Create a tree with 0.1 m resolution tree = pyoctomap.OcTree(0.1) # Update occupancy at coordinates tree.updateNode([1.0, 2.0, 3.0], True) # occupied tree.updateNode([1.0, 2.0, 3.0], False) # free # Query node = tree.search([1.0, 2.0, 3.0]) if node and tree.isNodeOccupied(node): print("Occupied voxel") ``` -------------------------------- ### Initialize and manipulate a standard OcTree Source: https://github.com/spinkoo/pyoctomap/blob/main/README_pypi_preview.md Demonstrates creating an OcTree, updating node occupancy, checking node status, and saving the map to a file. ```python import pyoctomap import numpy as np # Create an octree with 0.1m resolution tree = pyoctomap.OcTree(0.1) # Add occupied points tree.updateNode([1.0, 2.0, 3.0], True) tree.updateNode([1.1, 2.1, 3.1], True) # Add free space tree.updateNode([0.5, 0.5, 0.5], False) # Check occupancy node = tree.search([1.0, 2.0, 3.0]) if node and tree.isNodeOccupied(node): print("Point is occupied!") # Save to file tree.write("my_map.bt") ``` -------------------------------- ### Initialize ColorOcTree Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Instantiate a ColorOcTree with a specified resolution. ```python from pyoctomap import ColorOcTree tree = ColorOcTree(0.1) ``` -------------------------------- ### Build PyOctoMap from Source Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Follow these steps to clone the repository, build the underlying OctoMap C++ library, and run the automated build script. ```bash # Clone with submodules git clone --recursive https://github.com/Spinkoo/pyoctomap.git cd pyoctomap # Build and install OctoMap C++ library cd src/octomap mkdir build && cd build cmake .. && make && sudo make install # Return to main project and run automated build script cd ../../.. chmod +x build.sh ./build.sh ``` -------------------------------- ### Configure CI/CD for wheel building Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Automate the build and repair process using GitHub Actions. ```yaml # GitHub Actions example - name: Build wheel run: | pip install build auditwheel python -m build auditwheel repair dist/*.whl ``` -------------------------------- ### Perform manual wheel builds Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Commands for development-focused builds or manual packaging of Cython extensions and library bundling. ```bash # For development/testing only python setup.py bdist_wheel auditwheel repair dist/*.whl # Linux only ``` ```bash # 1. Build Cython extensions python setup.py build_ext --inplace # 2. Create wheel python setup.py bdist_wheel # 3. Bundle libraries auditwheel repair dist/pyoctomap-*.whl # 4. Install bundled wheel pip install dist/pyoctomap-*_linux_x86_64.whl ``` -------------------------------- ### Initialize OcTreeStamped Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Create a new time-stamped occupancy tree from a resolution or an existing file. ```python from pyoctomap import OcTreeStamped tree = OcTreeStamped(0.1) tree_from_file = OcTreeStamped("stamped.ot") ``` -------------------------------- ### Use ColorOcTree for RGB occupancy mapping Source: https://github.com/spinkoo/pyoctomap/blob/main/README_pypi_preview.md Shows how to initialize a ColorOcTree and assign RGB color values to specific voxel coordinates. ```python import pyoctomap import numpy as np tree = pyoctomap.ColorOcTree(0.1) coord = [1.0, 1.0, 1.0] tree.updateNode(coord, True) tree.setNodeColor(coord, 255, 0, 0) # R, G, B (0-255) ``` -------------------------------- ### Perform Room Mapping with Ray Casting Source: https://github.com/spinkoo/pyoctomap/blob/main/README_pypi_preview.md Demonstrates creating an OcTree and using batch insertion for efficient point cloud processing. ```python import pyoctomap import numpy as np # Create octree tree = pyoctomap.OcTree(0.05) # 5cm resolution sensor_origin = np.array([2.0, 2.0, 1.5]) # Add walls with ray casting wall_points = [] for x in np.arange(0, 4.0, 0.05): for y in np.arange(0, 4.0, 0.05): wall_points.append([x, y, 0]) # Floor wall_points.append([x, y, 3.0]) # Ceiling # Use batch insertion for better performance wall_points = np.array(wall_points) tree.insertPointCloud(wall_points, sensor_origin, lazy_eval=True) tree.updateInnerOccupancy() print(f"Tree size: {tree.size()} nodes") ``` -------------------------------- ### Batch Insertion Patterns Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/performance_guide.md Demonstrates the performance difference between per-point updates and batch point cloud insertion. ```python for p in points: # slow tree.updateNode(p, True) ``` ```python tree.insertPointCloud(points, sensor_origin, max_range=50.0, lazy_eval=True) tree.updateInnerOccupancy() # once per batch ``` -------------------------------- ### Execute Manual Build Script Source: https://github.com/spinkoo/pyoctomap/blob/main/docker/README.md Run the provided shell script to build and test the project using Docker. ```bash cd docker ./build-docker.sh ``` -------------------------------- ### Save and Load Binary Tree (.bt) Files Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Use the .bt format for efficient, occupancy-only tree storage compatible with standard OctoMap tools. ```python # Save tree tree.write("my_map.bt") # Load tree loaded_tree = tree.read("my_map.bt") ``` -------------------------------- ### Save and Load ColorOcTree (.ot) Files Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md The .ot format supports additional node data such as color information. ```python # Save ColorOcTree color_tree.write("colored_map.ot") # Load ColorOcTree loaded_tree = pyoctomap.ColorOcTree("colored_map.ot") ``` -------------------------------- ### Color Occupancy Mapping with ColorOcTree Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Shows how to manage colored nodes in an octree, including setting, retrieving, and averaging node colors. ```python import pyoctomap import numpy as np # Create a ColorOcTree with 0.1m resolution tree = pyoctomap.ColorOcTree(0.1) # Add a colored node (Red) coord = [1.0, 1.0, 1.0] tree.updateNode(coord, True) tree.setNodeColor(coord, 255, 0, 0) # R, G, B (0-255) # Search and retrieve color node = tree.search(coord) if node: color = node.getColor() print(f"Node color: {color}") # (255, 0, 0) # Average color (mixing multiple observations) tree.averageNodeColor(coord, 0, 255, 0) # Mix with Green print(f"New color: ``` -------------------------------- ### Build and bundle PyOctoMap Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/build_system.md Generates the Python wheel and repairs it for distribution. ```bash python -m build # or python setup.py bdist_wheel auditwheel repair dist/*.whl ``` -------------------------------- ### Automate Map Backups Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Create a timestamped backup of existing map files before overwriting them to prevent data loss. ```python import shutil from datetime import datetime def save_with_backup(tree, filename): # Create backup if file exists if os.path.exists(filename): backup_name = f"{filename}.backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}" shutil.copy2(filename, backup_name) # Save new file tree.write(filename) print(f"Map saved: {filename}") # Usage save_with_backup(tree, "my_map.bt") ``` -------------------------------- ### Clone the PyOctoMap repository Source: https://github.com/spinkoo/pyoctomap/blob/main/README_pypi_preview.md Initial step for building from source, ensuring submodules are included. ```bash # Clone the repository with submodules git clone --recursive https://github.com/Spinkoo/pyoctomap.git cd pyoctomap ``` -------------------------------- ### Reinstall and Rebuild pyoctomap Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Use these commands to perform a clean reinstall, remove stale bytecode files, and rebuild the extension modules from source. ```bash # Reinstall package pip uninstall pyoctomap pip install pyoctomap # Clear Python cache find . -name "*.pyc" -delete find . -name "__pycache__" -type d -exec rm -rf {} + # Rebuild from source python setup.py clean python setup.py build_ext --inplace ``` -------------------------------- ### Initialize CountingOcTree Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Create a new tree instance with a specified resolution or load an existing tree from a file. ```python from pyoctomap import CountingOcTree tree = CountingOcTree(0.1) # resolution in meters tree_from_file = CountingOcTree("counts.bt") ``` -------------------------------- ### Compare library dependencies Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Use ldd to compare system-installed libraries against the bundled versions. ```bash # Check system libraries ldd /usr/lib/x86_64-linux-gnu/liboctomap.so # Check bundled libraries ldd octomap/libs/liboctomap.so.1.10.0 ``` -------------------------------- ### Convert file formats using OctoMap tools Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Use command-line utilities to convert .bt files to VRML or point cloud formats. ```bash # Convert to other formats using OctoMap tools bt2vrml my_map.bt my_map.wrl octree2pointcloud my_map.bt my_map.pcd ``` -------------------------------- ### Room Mapping with Ray Casting Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Initializes an OctoMap and populates it with wall points using ray casting techniques. ```python # Create octree tree = pyoctomap.OcTree(0.05) # 5cm resolution sensor_origin = np.array([2.0, 2.0, 1.5]) # Add walls with ray casting wall_points = [] for x in np.arange(0, 4.0, 0.05): for y in np.arange(0, 4.0, 0.05): wall_points.append([x, y, 0]) ``` -------------------------------- ### Dynamic Environment Mapping Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Uses decayAndInsertPointCloud to manage moving sensors and prevent ghosting in dynamic environments. ```python # For moving sensors in dynamic environments, use decayAndInsertPointCloud # to handle occluded-ghost problems tree = pyoctomap.OcTree(0.1) # 10cm resolution # Simulate sequential scans from a moving sensor for scan_num in range( ``` -------------------------------- ### Batch Point Cloud Insertion Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Demonstrates inserting point cloud data into an OcTree using batch processing for improved performance. ```python # Floor wall_points.append([x, y, 0.0]) # Ceiling # Use batch insertion for better performance wall_points = np.array(wall_points) tree.insertPointCloud(wall_points, sensor_origin, lazy_eval=True) tree.updateInnerOccupancy() print(f"Tree size: {tree.size()} nodes") ``` -------------------------------- ### Implement Path Planning with Ray Casting Source: https://github.com/spinkoo/pyoctomap/blob/main/README_pypi_preview.md Shows how to check for obstacles between two points using the castRay method and how to validate paths through multiple waypoints. ```python import pyoctomap import numpy as np # Create an octree for path planning tree = pyoctomap.OcTree(0.1) # 10cm resolution # Add some obstacles to the map obstacles = [ [1.0, 1.0, 0.5], # Wall at (1,1) [1.5, 1.5, 0.5], # Another obstacle [2.0, 1.0, 0.5], # Wall at (2,1) ] for obstacle in obstacles: tree.updateNode(obstacle, True) def is_path_clear(start, end, tree): """Efficient ray casting for path planning using OctoMap's built-in castRay""" start = np.array(start, dtype=np.float64) end = np.array(end, dtype=np.float64) # Calculate direction vector direction = end - start ray_length = np.linalg.norm(direction) if ray_length == 0: return True, None # Normalize direction direction = direction / ray_length # Use OctoMap's efficient castRay method end_point = np.zeros(3, dtype=np.float64) hit = tree.castRay(start, direction, end_point, ignoreUnknownCells=True, maxRange=ray_length) if hit: # Ray hit an obstacle - path is blocked return False, end_point else: # No obstacle found - path is clear return True, None # Check if path is clear start = [0.5, 2.0, 0.5] end = [2.0, 2.0, 0.5] clear, obstacle = is_path_clear(start, end, tree) if clear: print("✅ Path is clear!") else: print(f"❌ Path blocked at: {obstacle}") # Advanced path planning with multiple waypoints def plan_path(waypoints, tree): """Plan a path through multiple waypoints using ray casting""" path_clear = True obstacles = [] for i in range(len(waypoints) - 1): start = waypoints[i] end = waypoints[i + 1] clear, obstacle = is_path_clear(start, end, tree) if not clear: path_clear = False obstacles.append((i, i+1, obstacle)) return path_clear, obstacles # Example: Plan path through multiple waypoints waypoints = [ [0.0, 0.0, 0.5], [1.0, 1.0, 0.5], [2.0, 2.0, 0.5], [3.0, 3.0, 0.5] ] path_clear, obstacles = plan_path(waypoints, tree) if path_clear: print("✅ Complete path is clear!") else: print(f"❌ Path blocked at segments: {obstacles}") ``` -------------------------------- ### Build wheels using Docker Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Automates the build process across multiple Python versions using a containerized environment. ```bash #!/bin/bash # build-wheel.sh - Docker-based build for multiple Python versions # 1. Build wheels using Docker docker build -f docker/Dockerfile.wheel -t pyoctomap-wheel . # 2. Extract wheels from container docker run --name temp-container pyoctomap-wheel docker cp temp-container:/wheels/ ./dist/ docker rm temp-container # 3. Test the wheels pip install dist/*.whl python -c "import pyoctomap; print('Success!')" ``` -------------------------------- ### Counting Observations with CountingOcTree Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/counting_octree_explanation.md Demonstrates initializing the tree, updating node counts, and retrieving voxel centers based on hit thresholds. ```python tree = CountingOcTree(0.1) # 0.1m resolution # Observe location [1.0, 2.0, 3.0] three times tree.updateNode([1.0, 2.0, 3.0]) # Count = 1 tree.updateNode([1.0, 2.0, 3.0]) # Count = 2 tree.updateNode([1.0, 2.0, 3.0]) # Count = 3 # Query the count node = tree.search([1.0, 2.0, 3.0]) print(node.getCount()) # Output: 3 # Find frequently observed locations (count >= 2) frequent = tree.getCentersMinHits(2) # Returns: [[1.05, 2.05, 3.05]] (voxel center coordinates) ``` -------------------------------- ### Build using Docker Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/build_system.md Uses the provided Docker script for reproducible builds in isolated containers. ```bash chmod +x docker/build-docker.sh ./docker/build-docker.sh ``` -------------------------------- ### OcTree Construction Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Initialize a new OcTree instance with a specified resolution. ```APIDOC ## OcTree(resolution) ### Description Initializes a new occupancy tree with a specific voxel resolution. ### Parameters - **resolution** (float) - Required - Voxel size in meters. ``` -------------------------------- ### Initialize Root Node Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/counting_octree_explanation.md Creates the root node if it does not already exist in the tree. ```cpp if (root == NULL) { root = new CountingOcTreeNode(); tree_size++; } ``` -------------------------------- ### Check library versions Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Inspect the shared object dependencies for the bundled libraries. ```bash # Check library versions ldd $(python -c "import octomap; print(octomap.__file__)")/../libs/*.so ``` -------------------------------- ### Perform File I/O operations Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Save and load occupancy maps using standard .bt files or binary serialization. ```python tree.write("map.bt") # Save to standard OctoMap .bt file loaded = tree.read("map.bt") blob = tree.writeBinary() # Serialize to bytes tree.readBinary("map.bt") # Read from file path ``` -------------------------------- ### Upload wheels to PyPI Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Distribute built wheels to public or private repositories using twine. ```bash # Upload to PyPI twine upload dist/*.whl ``` ```bash # Upload to private PyPI twine upload --repository-url https://your-pypi.com/simple/ dist/*.whl ``` -------------------------------- ### Update System and Python Packages Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Keep the host system and Python build tools up to date to prevent compatibility issues. ```bash # Update system packages sudo apt update && sudo apt upgrade # Update Python packages pip install --upgrade pip setuptools wheel ``` -------------------------------- ### Manage Voxel Color Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Demonstrates updating node occupancy and setting its RGB color, followed by retrieving the color value. ```python from pyoctomap import ColorOcTree import numpy as np tree = ColorOcTree(0.1) coord = [1.0, 1.0, 1.0] tree.updateNode(coord, True) tree.setNodeColor(coord, 255, 0, 0) node = tree.search(coord) if node: print("Color:", node.getColor()) # (255, 0, 0) ``` -------------------------------- ### System Diagnostic Commands Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Use these commands to gather environment information when reporting issues. ```bash python3 --version ``` ```bash uname -a ``` -------------------------------- ### Generate wheels for all supported Python versions Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/build_system.md Iterates through supported interpreters in the Docker environment to produce distributable wheels. ```bash ./build-wheel.sh ``` -------------------------------- ### Define File Naming Conventions Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Use descriptive filenames including metadata like date, resolution, or version to maintain organized map storage. ```python # Good naming conventions tree.write("map_2024_01_15_10cm.bt") tree.write("office_floor1_v2.bt") tree.write("scan_room_001.bt") ``` -------------------------------- ### Inspect wheel directory layout Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Visual representation of the internal structure of the generated wheel file. ```text pyoctomap-1.1.0-cp312-cp312-linux_x86_64.whl ├── octomap/ │ ├── __init__.py │ ├── octomap.pyx │ ├── octomap_defs.pxd │ └── dynamicEDT3D_defs.pxd ├── octomap.libs/ │ ├── liboctomap.so.1.10.0 │ ├── libdynamicedt3D.so.1.0.0 │ ├── liboctomath.so.1.10.0 │ └── [versioned symlinks] └── METADATA ``` -------------------------------- ### CountingOcTree Construction Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Initialize a new CountingOcTree with a specific resolution or load one from a file. ```APIDOC ## CountingOcTree Constructor ### Description Initializes a new CountingOcTree instance. ### Signature `CountingOcTree(resolution_or_path)` ### Parameters - **resolution_or_path** (float or str) - Required - The resolution in meters (float) or the path to a .bt file (str). ``` -------------------------------- ### Perform batch point cloud insertion with colors Source: https://github.com/spinkoo/pyoctomap/blob/main/README.md Uses insertPointCloud to add multiple points and their corresponding colors to a ColorOcTree in one operation. ```python # Insert point cloud with colors in a single operation points = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=np.float64) colors = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=np.float64) # RGB in [0, 1] range sensor_origin = np.array([0.0, 0.0, 0.0]) # Optional: for proper ray casting tree.insertPointCloud(points, sensor_origin=sensor_origin, colors=colors) ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Configure the logging module to output debug-level information. ```python import logging logging.basicConfig(level=logging.DEBUG) # Your octomap code here ``` -------------------------------- ### Troubleshoot file existence Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Check for file presence before attempting operations to avoid FileNotFoundError. ```python import os if not os.path.exists("my_map.bt"): print("File does not exist") ``` -------------------------------- ### Profile Performance Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Measure execution time and profile code blocks using time and cProfile. ```python import time import cProfile # Time operations start = time.time() tree.addPointsBatch(points) end = time.time() print(f"Batch operation took: {end - start:.3f} seconds") # Profile code cProfile.run('tree.addPointsBatch(points)') ``` -------------------------------- ### Build OctoMap C++ library Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/build_system.md Compiles the upstream OctoMap library from source. ```bash cd src/octomap mkdir -p build && cd build cmake .. -DCMAKE_BUILD_TYPE=Release make -j"$(nproc)" sudo make install && sudo ldconfig cd ../../.. ``` -------------------------------- ### Verify File I/O Permissions Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Check read/write permissions and ensure absolute paths are used for file operations. ```python import os # Check file permissions filename = "my_map.bt" if os.path.exists(filename): if not os.access(filename, os.W_OK): print("No write permission") if not os.access(filename, os.R_OK): print("No read permission") # Use absolute paths abs_path = os.path.abspath(filename) tree.write(abs_path) ``` -------------------------------- ### Construct an OcTree Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Initialize an OcTree instance with a specified voxel resolution in meters. ```python from pyoctomap import OcTree tree = OcTree(resolution=0.1) # 10 cm voxels ``` -------------------------------- ### Implement Error Handling for File I/O Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Wrap read and write operations in try-except blocks to manage potential filesystem errors gracefully. ```python try: tree.write("my_map.bt") print("Map saved successfully") except Exception as e: print(f"Failed to save map: {e}") try: loaded_tree = tree.read("my_map.bt") if loaded_tree: print("Map loaded successfully") else: print("Failed to load map") except Exception as e: print(f"Error loading map: {e}") ``` -------------------------------- ### Debug Library Loading Errors Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Check for missing shared object files and verify library dependencies when encountering OSError. ```bash # Check if libraries are bundled python -c "import octomap; print(octomap.__file__)" ls -la $(python -c "import octomap; print(octomap.__file__)")/../libs/ # Check library dependencies ldd $(python -c "import octomap; print(octomap.__file__)")/../libs/*.so ``` -------------------------------- ### Inspect Tree State Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Print diagnostic information about the current tree configuration and size. ```python # Verify tree is properly initialized print(f"Tree resolution: {tree.getResolution()}") print(f"Tree size: {tree.size()}") print(f"Tree depth: {tree.getTreeDepth()}") print(f"Leaf nodes: {tree.getNumLeafNodes()}") ``` -------------------------------- ### OcTreeStamped Constructor Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Initializes a new time-stamped occupancy tree. ```APIDOC ## Constructor ### Description Creates an instance of OcTreeStamped, either empty with a specified resolution or loaded from a file. ### Signature - `OcTreeStamped(resolution: float)` - `OcTreeStamped(filename: str)` ``` -------------------------------- ### Manage wheel compatibility Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Use auditwheel to inspect and repair wheel files for Linux distribution compatibility. ```bash # Check wheel compatibility auditwheel show dist/*.whl # Repair wheel auditwheel repair dist/*.whl --plat linux_x86_64 ``` -------------------------------- ### Batch Operations Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Performs fast batch insertion of point clouds using standard or parallel ray methods. ```python # Fast C++ batch insertion (full rays, optional discretization and lazy evaluation) points = np.random.uniform(-5, 5, (1000, 3)) origin = np.array([0., 0., 0.], dtype=np.float64) tree.insertPointCloud(points, origin, discretize=False, lazy_eval=True) tree.updateInnerOccupancy() # Manual after lazy # Ultra-fast version using parallel rays (no deduplication) tree.insertPointCloudRaysFast(points, origin, max_range=50.0, lazy_eval=True) tree.updateInnerOccupancy() ``` -------------------------------- ### Manage files in cloud storage Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Upload and download octree files to AWS S3 using boto3. ```python import boto3 def upload_to_s3(tree, bucket, key): """Upload octree to S3""" tree.write("/tmp/temp_map.bt") s3 = boto3.client('s3') s3.upload_file("/tmp/temp_map.bt", bucket, key) os.remove("/tmp/temp_map.bt") def download_from_s3(bucket, key, local_path): """Download octree from S3""" s3 = boto3.client('s3') s3.download_file(bucket, key, local_path) return octomap.OcTree(0.1).read(local_path) ``` -------------------------------- ### Insert Point Cloud with Temporal Decay Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Uses decayAndInsertPointCloud to handle dynamic environments by applying temporal decay to occupied voxels before insertion. Adjust logodd_decay_value to control the rate at which ghost objects fade. ```python for scan_num in range(100): # Generate new scan (e.g., from LiDAR) point_cloud = np.random.rand(500, 3) * 10 # Simulated point cloud sensor_origin = np.array([scan_num * 0.1, 0.0, 1.5]) # Moving sensor # Recommended: Decay and insert # This solves the occluded-ghost problem by: # 1. Applying temporal decay to occupied voxels in scan's bounding box # 2. Inserting the new point cloud tree.decayAndInsertPointCloud( point_cloud, sensor_origin, logodd_decay_value=-0.2, # Default: ~20 scans for ghost to fade max_range=50.0, update_inner_occupancy=True ) ``` -------------------------------- ### Batch Insertion Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md High-performance batch insertion of point clouds into the tree. ```APIDOC ## insertPointCloud(point_cloud, sensor_origin, max_range=-1.0, lazy_eval=False, discretize=False, method="default") ### Description Performs batch insertion of a point cloud into the tree, optimized for performance. ``` -------------------------------- ### Validate .bt files Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Verify file existence, size, and integrity by attempting to load the tree before processing. ```python def validate_bt_file(filename): """Validate a .bt file before loading""" if not os.path.exists(filename): return False, "File does not exist" if os.path.getsize(filename) == 0: return False, "File is empty" try: test_tree = octomap.OcTree(0.1) loaded_tree = test_tree.read(filename) if loaded_tree and loaded_tree.size() > 0: return True, "File is valid" else: return False, "File appears to be empty or corrupted" except Exception as e: return False, f"Error reading file: {e}" # Usage is_valid, message = validate_bt_file("my_map.bt") print(f"File validation: {message}") ``` -------------------------------- ### Iterate over leaf nodes Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Demonstrates traversing leaf nodes in an occupancy tree and checking their occupancy status. ```python for leaf in tree.begin_leafs(): coord = leaf.getCoordinate() if tree.isNodeOccupied(leaf): print("Occupied at", coord) ``` -------------------------------- ### Perform Direct Binary Serialization Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Serialize octree data directly to binary format without requiring intermediate file I/O. ```python # Save to binary data binary_data = tree.writeBinary() # Load from binary data tree.readBinary("my_map.bt") ``` -------------------------------- ### Debug import errors Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/wheel_technology.md Print the current system path and verify the octomap module location to diagnose import failures. ```python # Debug import import sys print(sys.path) import octomap print(octomap.__file__) ``` -------------------------------- ### Path Planning with Ray Casting Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Implements path checking using the castRay method to detect obstacles between two points. ```python # Create an octree for path planning tree = pyoctomap.OcTree(0.1) # 10cm resolution # Add some obstacles to the map obstacles = [ [1.0, 1.0, 0.5], # Wall at (1,1) [1.5, 1.5, 0.5], # Another obstacle [2.0, 1.0, 0.5], # Wall at (2,1) ] for obstacle in obstacles: tree.updateNode(obstacle, True) def is_path_clear(start, end, tree): """Efficient ray casting for path planning using OctoMap's built-in castRay""" start = np.array(start, dtype=np.float64) end = np.array(end, dtype=np.float64) # Calculate direction vector direction = end - start ray_length = np.linalg.norm(direction) if ray_length == 0: return True, None # Normalize direction direction = direction / ray_length # Use OctoMap's efficient castRay method end_point = np.zeros(3, dtype=np.float64) hit = tree.castRay(start, direction, end_point, ignoreUnknownCells=True, maxRange=ray_length) if hit: return False, end_point else: return True, None # Check if path is clear start = [0.5, 2.0, 0.5] end = [2.0, 2.0, 0.5] clear, obstacle = is_path_clear(start, end, tree) if clear: print("✅ Path is clear!") else: print(f"❌ Path blocked at: {obstacle}") ``` -------------------------------- ### ColorOcTree Methods Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Methods for manipulating voxel colors and inserting point cloud data into the ColorOcTree. ```APIDOC ## setNodeColor(point, r, g, b) ### Description Sets the RGB color for a voxel at the specified point. ### Parameters - **point** (list/array) - Required - Voxel coordinates. - **r** (int) - Required - Red component (0-255). - **g** (int) - Required - Green component (0-255). - **b** (int) - Required - Blue component (0-255). ## averageNodeColor(point, r, g, b) ### Description Averages a new RGB measurement into the existing voxel color. ## integrateNodeColor(point, r, g, b) ### Description Integrates color weighted by occupancy updates. ## insertPointCloud(points, sensor_origin=None, max_range=-1.0, lazy_eval=True, colors=None) ### Description Inserts a point cloud and sets colors for all points in a single operation. ### Parameters - **points** (numpy.ndarray) - Required - N×3 array of point coordinates. - **sensor_origin** (list, optional) - Optional - Sensor origin [x, y, z]. - **max_range** (float, optional) - Optional - Maximum range for ray casting. - **lazy_eval** (bool, optional) - Optional - Whether to use lazy evaluation. - **colors** (numpy.ndarray, optional) - Optional - N×3 array of color values in [0, 1] range. ### Returns - **int** - Number of points processed. ## extractPointCloud() ### Description Extracts coordinates and RGB colors from the tree. ### Returns - **tuple** - (occupied_points, empty_points, colors) where colors is an N×3 np.uint8 array. ``` -------------------------------- ### Dynamic Mapping and Point Cloud Insertion Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Inserts scans from a moving sensor while applying temporal decay to mitigate ghosting artifacts. ```python # Recommended function for inserting scans from a moving sensor # Solves the occluded-ghost problem by applying temporal decay before insertion point_cloud = np.random.rand(1000, 3) * 10 sensor_origin = np.array([0.0, 0.0, 1.5]) # Tuning the decay value: # Scans_to_Forget = 4.0 / abs(logodd_decay_value) # # Moderate (default: -0.2): ~20 scans for ghost to fade # Aggressive (-1.0 to -3.0): 2-4 scans (highly dynamic environments) # Weak (-0.05 to -0.1): 40-80 scans (mostly static maps) tree.decayAndInsertPointCloud( point_cloud, sensor_origin, logodd_decay_value=-0.2, # Must be negative max_range=50.0 ) ``` -------------------------------- ### Integrate with ROS Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/file_format.md Save maps for ROS compatibility and extract data from ROS bags. ```python # Save in ROS-compatible format tree.write("/tmp/ros_map.bt") # Load from ROS bag import rosbag bag = rosbag.Bag('map.bag') for topic, msg, t in bag.read_messages(topics=['/octomap']): # Process ROS message pass ``` -------------------------------- ### Incremental Batching for Streaming Data Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/performance_guide.md Buffers incoming points and performs batch updates to minimize Python overhead during high-frequency data ingestion. ```python buffer = [] def add_scan(points): buffer.extend(points) if len(buffer) >= 10_000: arr = np.asarray(buffer, dtype=np.float64).reshape(-1, 3) tree.insertPointCloud(arr, sensor_origin, lazy_eval=True) buffer.clear() tree.updateInnerOccupancy() ``` -------------------------------- ### Convert README URLs using GitHub2PyPI Source: https://github.com/spinkoo/pyoctomap/blob/main/github2pypi/README.md Use the replace_url function to process README content by providing the repository slug and the file content. ```python import github2pypi def get_long_description(): with open("README.md", encoding="utf-8") as f: content = f.read() return github2pypi.replace_url( slug="Spinkoo/pyoctomap", content=content ) ``` -------------------------------- ### Recursive Traversal for getCentersMinHits in C++ Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/counting_octree_explanation.md Traverses the octree to identify leaf nodes meeting the minimum observation threshold. Requires a valid node structure and depth tracking. ```cpp void getCentersMinHitsRecurs(...) { if (depth < max_depth && nodeHasChildren(node)) { // Not a leaf - recurse into children for (unsigned int i=0; i<8; ++i) { if (nodeChildExists(node, i)) { getCentersMinHitsRecurs(...); // Recursive call } } } else { // Leaf node reached if (node->getCount() >= min_hits) { node_centers.push_back(keyToCoord(parent_key, depth)); } } } ``` -------------------------------- ### Timing Critical Sections Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/performance_guide.md Measures execution time for point cloud insertion and inner occupancy updates to evaluate performance changes. ```python import time start = time.time() tree.insertPointCloud(points, sensor_origin, lazy_eval=True) tree.updateInnerOccupancy() elapsed = time.time() - start print(f"Update took {elapsed:.3f} s") ``` -------------------------------- ### Resolve build memory issues Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Reduce parallel build jobs or increase system swap space to prevent out-of-memory errors. ```bash # Reduce parallel jobs make -j2 # Or increase swap sudo fallocate -l 2G /swapfile sudo chmod 600 /swapfile sudo mkswap /swapfile sudo swapon /swapfile ``` -------------------------------- ### insertPointCloud Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/api_reference.md Inserts a batch of points into the tree with optional timestamping. ```APIDOC ## insertPointCloud ### Description Inserts a point cloud into the tree. Optionally sets a uniform timestamp for all affected nodes. ### Parameters - **points** (numpy.ndarray) - Required - N×3 array of point coordinates. - **sensor_origin** (list) - Optional - [x, y, z] origin for ray casting. - **max_range** (float) - Optional - Maximum range for ray casting. - **lazy_eval** (bool) - Optional - Whether to use lazy evaluation. - **discretize** (bool) - Optional - Whether to discretize points. - **timestamps** (int) - Optional - Unsigned integer timestamp for all inserted nodes. ### Returns - (int) Number of points processed if timestamps are provided. ``` -------------------------------- ### Manage Memory Usage Source: https://github.com/spinkoo/pyoctomap/blob/main/docs/troubleshooting.md Optimize memory consumption by adjusting tree resolution and deferring inner occupancy updates. ```python # Use appropriate resolution tree = octomap.OcTree(0.1) # 10cm resolution # Update inner occupancy less frequently tree.addPointsBatch(points, update_inner_occupancy=False) tree.updateInnerOccupancy() # Call once after batch ``` -------------------------------- ### decayAndInsertPointCloud Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Updates the octree with a new point cloud while applying temporal decay to handle dynamic environments and occluded-ghost problems. ```APIDOC ## decayAndInsertPointCloud ### Description Updates the octree by applying temporal decay to occupied voxels within the scan's bounding box and inserting the new point cloud data. ### Parameters - **point_cloud** (numpy.ndarray) - Required - The point cloud data to insert. - **sensor_origin** (numpy.ndarray) - Required - The origin coordinates of the sensor. - **logodd_decay_value** (float) - Optional - The decay value applied to voxels. Default is -0.2. - **max_range** (float) - Optional - The maximum range for the sensor. Default is 50.0. - **update_inner_occupancy** (bool) - Optional - Whether to update inner node occupancy. Default is True. ``` -------------------------------- ### Integrate Color and Save Map Source: https://github.com/spinkoo/pyoctomap/blob/main/index.html Integrates color into an OctoMap node and saves the resulting structure to a file. ```python {tree.search(coord).getColor()}") # Integrate color (weighted by occupancy) tree.integrateNodeColor(coord, 0, 0, 255) # Add Blue # Save to file (.ot format preserves colors) tree.write("colored_map.ot") ```