### Install Dependencies Source: https://github.com/commalab/foam/blob/master/_autodocs/errors.md Resolve ImportErrors by installing missing optional dependencies using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Spherize Single Mesh Example Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt Demonstrates how to spherize a single mesh using the main entry point function. This is a common starting point for using the FOAM library. ```python from foam import spherize_mesh mesh_file = "path/to/your/mesh.stl" sphere_output = "path/to/output/sphere.json" spherize_mesh(mesh_file, sphere_output) ``` -------------------------------- ### Install Foam with Pixi Source: https://github.com/commalab/foam/blob/master/README.md Use this command to install Foam using the pixi package manager. Ensure pixi is installed on your system. ```bash pixi run build ``` -------------------------------- ### Quick Reference and Examples Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt This document provides concise examples and common patterns for using FOAM, covering typical workflows from single mesh spherization to CLI usage. ```APIDOC ## Spherize Single Mesh ### Description Example of spherizing a single mesh file and saving the results. ### Code Example ```python from foam import spherize_mesh result = spherize_mesh(input_mesh='path/to/your/mesh.stl', output_format='json') with open('output_spheres.json', 'w') as f: f.write(result.json()) ``` ## Spherize URDF Robot ### Description Example of using `SpherizationHelper` to spherize meshes associated with a URDF robot. ### Code Example ```python from foam import SpherizationHelper h = SpherizationHelper() robot_spheres = h.spherize_robot(urdf_path='path/to/your/robot.urdf') # Process or save robot_spheres ``` ## Parallel Processing ### Description Demonstrates how to leverage the `ParallelSpherizer` for concurrent operations. ### Code Example (Example showing instantiation and use of `ParallelSpherizer` to manage multiple spherization tasks.) ## Parameter Tuning ### Description Illustrates how to pass specific algorithm or preprocessing parameters. ### Code Example ```python result = spherize_mesh( input_mesh='mesh.stl', algorithm_params={'medial': {'resolution': 50}}, preprocessing_params={'smooth_iterations': 10} ) ``` ## Data Extraction ### Description Example of extracting sphere data from a URDF using a script. ### CLI Example `python scripts/spheres_from_urdf.py --input_urdf robot.urdf --output_file extracted_spheres.json` ## Mesh Repair ### Description Shows how to use utility functions for mesh fixing and smoothing. ### Code Example ```python from foam.utility import load_mesh_file, fix_mesh, smooth_mesh mesh = load_mesh_file('bad_mesh.stl') fixed_mesh = fix_mesh(mesh) smoothed_mesh = smooth_mesh(fixed_mesh, smoothing_params={'iterations': 5}) ``` ## Batch Processing ### Description Conceptual example for processing multiple meshes in a batch. ### Code Example (Looping through a list of mesh files and calling `spherize_mesh` for each.) ## CLI Usage ### Description Basic examples of using the command-line tools. ### Examples - `python scripts/generate_spheres.py --input_mesh model.obj --output_file model.json` - `python scripts/visualize_spheres.py --sphere_data model.json` ``` -------------------------------- ### Sphere Offset Method Example Source: https://github.com/commalab/foam/blob/master/_autodocs/api-reference-core.md Shows how to use the offset method to translate a sphere and prints the updated origin. ```python from foam.model import Sphere import numpy as np sphere = Sphere(1.0, 2.0, 3.0, 0.5) print(sphere.origin) # [1. 2. 3.] sphere.offset(np.array([1.0, 0.0, 0.0])) print(sphere.origin) # [2. 2. 3.] ``` -------------------------------- ### Example Usage of generate_sphere_urdf.py Source: https://github.com/commalab/foam/blob/master/_autodocs/configuration.md A comprehensive example showcasing common command-line arguments for spherizing a URDF file, including output, database, depth, threads, and volume heuristic settings. ```bash python scripts/generate_sphere_urdf.py robot.urdf \ --output spherized_robot.urdf \ --database robot_cache.json \ --depth 2 \ --threads 8 \ --use_volume_heuristic \ --volume_heuristic_ratio 0.7 \ --method medial ``` -------------------------------- ### Parallel Spherization Example Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt Illustrates how to perform spherization in parallel using the ParallelSpherizer class. This is beneficial for large meshes or multiple spherization tasks. ```python from foam import ParallelSpherizer # Initialize the spherizer with desired number of threads spherizer = ParallelSpherizer(num_threads=4) mesh_files = ["mesh1.stl", "mesh2.stl", "mesh3.stl"] sphere_outputs = ["sphere1.json", "sphere2.json", "sphere3.json"] spherizer.spherize_meshes(mesh_files, sphere_outputs) ``` -------------------------------- ### Spherization Offset Method Example Source: https://github.com/commalab/foam/blob/master/_autodocs/api-reference-core.md Illustrates translating all spheres in a spherization by a specified offset. ```python import numpy as np spherization.offset(np.array([2.0, 0.0, 0.0])) # All sphere.origin values are shifted by [2, 0, 0] ``` -------------------------------- ### Start and Stop Docker Container Source: https://github.com/commalab/foam/blob/master/DOCKER_QUICKSTART.md Commands to start and stop a Docker container named 'foam'. ```docker docker start foam ``` ```docker docker stop foam ``` -------------------------------- ### Per-Link Branch Multipliers Example Source: https://github.com/commalab/foam/blob/master/_autodocs/configuration.md Demonstrates how to override the global 'branch' parameter for specific links by providing link names followed by multiplier values. ```bash python generate_sphere_urdf.py robot.urdf \ --branch 8 \ link1=2.0 \ link2=0.5 ``` -------------------------------- ### Foam Preprocess Module - Add Thickness Example Source: https://github.com/commalab/foam/blob/master/_autodocs/module-structure.md Demonstrates how to add thickness to a planar mesh using the `add_thickness` function. This utility is not part of the main API. ```python def add_thickness(mesh, thickness): # Add thickness to planar mesh (extrusion) # Example usage code (not exported) original_mesh = trimesh.load('../assets/meshes/link_aruco_left_base.STL') thickened_mesh = add_thickness(original_mesh, thickness=0.01) thickened_mesh.export('New_thickened_mesh.stl') ``` -------------------------------- ### Setting URDF Spheres Example Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt Shows how to set sphere approximations for URDF links using the set_urdf_spheres function. This is often a precursor to spherization or analysis. ```python from foam.utility import set_urdf_spheres urdf_file = "path/to/your/robot.urdf" sphere_data_file = "path/to/sphere.json" output_urdf = "path/to/output/robot_with_spheres.urdf" set_urdf_spheres(urdf_file, sphere_data_file, output_urdf) ``` -------------------------------- ### Spherization Length Method Example Source: https://github.com/commalab/foam/blob/master/_autodocs/api-reference-core.md Demonstrates how to get the number of spheres within a Spherization object using the len() function. ```python spherization = Spherization( spheres=[Sphere(0, 0, 0, 1), Sphere(1, 1, 1, 0.5)], mean_error=0.05, best_error=0.01, worst_error=0.10 ) print(len(spherization)) # 2 ``` -------------------------------- ### Foam Standard Import Pattern Source: https://github.com/commalab/foam/blob/master/_autodocs/module-structure.md Illustrates the standard way to import and use Foam functionalities, including loading URDFs, getting meshes, and using the SpherizationHelper. ```python import foam from pathlib import Path # Load URDF urdf = foam.load_urdf(Path("robot.urdf")) # Get meshes meshes = foam.get_urdf_meshes(urdf) # Spherize using helper helper = foam.SpherizationHelper(Path("cache.json"), threads=8) for mesh in meshes: helper.spherize_mesh(mesh.name, mesh.mesh, mesh.scale, mesh.xyz) helper.get_spherization("mesh_name", depth=1) ``` -------------------------------- ### URDF Mesh Loading Example Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt Shows how to load mesh files associated with a URDF model using the get_urdf_meshes function. This is useful for analyzing or processing robot geometry. ```python from foam.utility import get_urdf_meshes urdf_file = "path/to/your/robot.urdf" mesh_data = get_urdf_meshes(urdf_file) # mesh_data is a dictionary mapping link names to mesh file paths ``` -------------------------------- ### Handle Generic File Loading Errors Source: https://github.com/commalab/foam/blob/master/_autodocs/errors.md This example shows how to catch generic exceptions that may occur during mesh file loading due to unsupported formats, corruption, or trimesh internal errors. It prints the exception type and details for debugging. ```python from foam.utility import load_mesh_file from pathlib import Path try: mesh = load_mesh_file(Path("unknown.xyz")) except Exception as e: print(f"Type: {type(e).__name__}") print(f"Details: {e}") ``` -------------------------------- ### Spherize URDF Robot Example Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt Shows how to spherize an entire URDF robot model. This is useful for generating spherical representations of articulated robots. ```python from foam import spherize_mesh urdf_file = "path/to/your/robot.urdf" sphere_output = "path/to/output/robot_spheres.json" spherize_mesh(urdf_file, sphere_output) ``` -------------------------------- ### URDF Structure Example Source: https://github.com/commalab/foam/blob/master/_autodocs/types.md Illustrates the expected nested dictionary structure for a parsed URDF file, including the 'robot' key and its sub-elements like 'link'. ```python { 'robot': { '@path': Path, 'link': [ { '@name': str, 'collision': Union[dict, list[dict]], }, ], } } ``` -------------------------------- ### Copyright Notice Template Source: https://github.com/commalab/foam/blob/master/python_third_party_licenses.txt A template for copyright notices to be included at the start of source files. It specifies the year, author, and a pointer to the full license. ```text Copyright (C) ``` -------------------------------- ### URDF Primitive Extraction Example Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt Demonstrates extracting primitive shapes (like boxes, spheres, cylinders) from a URDF model using get_urdf_primitives. This can be used for simplified robot representations. ```python from foam.utility import get_urdf_primitives urdf_file = "path/to/your/robot.urdf" primitives = get_urdf_primitives(urdf_file) # primitives is a list of URDFPrimitive objects ``` -------------------------------- ### SpherizationHelper.__init__ Source: https://github.com/commalab/foam/blob/master/_autodocs/api-reference-core.md Initializes the SpherizationHelper, a high-level orchestrator combining parallel processing with database caching. ```APIDOC ## SpherizationHelper.__init__ ### Description Initializes the SpherizationHelper, a high-level orchestrator combining parallel processing with database caching, designed for URDF processing workflows. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **database** (Path) - Required - Path to SQLite/JSON database for caching results. - **threads** (int) - Optional - Default: 8 - Number of worker threads for parallel spherization. ``` -------------------------------- ### Get URDF Meshes Utility Source: https://github.com/commalab/foam/blob/master/_autodocs/module-structure.md Extracts mesh information from a URDF dictionary, with an optional shrinkage factor. ```python def get_urdf_meshes(urdf: URDFDict, shrinkage: float = 1.0) -> list[URDFMesh] ``` -------------------------------- ### foam/utility/__init__.py - Public Exports Source: https://github.com/commalab/foam/blob/master/_autodocs/module-structure.md Provides utilities for mesh processing, URDF parsing, and file I/O. ```APIDOC ## Module: `foam.utility` **Location:** `foam/utility/__init__.py` **Purpose:** Mesh processing, URDF parsing, file I/O utilities. **Public Exports:** ```python # Mesh processing def load_mesh_file(mesh_filepath: Path) -> Trimesh def fix_mesh(mesh: Trimesh) -> None def smooth_mesh(mesh: Trimesh) -> None def as_mesh(scene_or_mesh: Trimesh | Scene) -> Trimesh | None # Context manager @contextmanager def tempmesh() -> Iterator[tuple[IO, Path]] # URDF processing def load_urdf(urdf_path: Path) -> URDFDict def get_urdf_meshes(urdf: URDFDict, shrinkage: float = 1.0) -> list[URDFMesh] def get_urdf_primitives(urdf: URDFDict, shrinkage: float = 1.0) -> list[URDFPrimitive] def get_urdf_spheres(urdf: URDFDict) -> Iterator[tuple[float, float, float, float]] def set_urdf_spheres(urdf: URDFDict, spheres: dict) -> None def save_urdf(urdf: URDFDict, filename: Path) -> None # Data classes @dataclass class URDFMesh @dataclass class URDFPrimitive # Type aliases URDFDict = dict[str, Any] ``` ``` -------------------------------- ### Get URDF Spheres Utility Source: https://github.com/commalab/foam/blob/master/_autodocs/module-structure.md Iterates through a URDF dictionary to extract sphere approximations, returning origin and radius for each. ```python def get_urdf_spheres(urdf: URDFDict) -> Iterator[tuple[float, float, float, float]] ``` -------------------------------- ### Get URDF Primitives Utility Source: https://github.com/commalab/foam/blob/master/_autodocs/module-structure.md Extracts primitive geometry information from a URDF dictionary, with an optional shrinkage factor. ```python def get_urdf_primitives(urdf: URDFDict, shrinkage: float = 1.0) -> list[URDFPrimitive] ``` -------------------------------- ### Extract Sphere Data and Export Source: https://github.com/commalab/foam/blob/master/_autodocs/quick-reference.md Get sphere center and radius from a mesh. Supports iteration, export as tuples, or as a NumPy array. ```python from foam import spherize_mesh spherizations = spherize_mesh("link", "link.stl") spherization = spherizations[0] # Iterate over spheres for sphere in spherization.spheres: x, y, z = sphere.origin r = sphere.radius print(f"Sphere: center=({x:.3f}, {y:.3f}, {z:.3f}), radius={r:.3f}") # Export as list of tuples sphere_tuples = [ (sphere.origin[0], sphere.origin[1], sphere.origin[2], sphere.radius) for sphere in spherization.spheres ] print(sphere_tuples) # Export as numpy array import numpy as np sphere_array = np.array([ [*sphere.origin, sphere.radius] for sphere in spherization.spheres ]) ``` -------------------------------- ### Tune Sphere Generation Parameters Source: https://github.com/commalab/foam/blob/master/_autodocs/scripts-reference.md Demonstrates how to tune parameters like --branch, --depth, --initSpheres, and --erFact to balance speed and accuracy when generating sphere approximations for URDF files. ```bash # Fast (few spheres, quick) python scripts/generate_sphere_urdf.py panda.urdf \ --branch 4 --depth 0 \ --initSpheres 500 --minSpheres 50 \ --output panda_fast.urdf # Balanced python scripts/generate_sphere_urdf.py panda.urdf \ --branch 8 --depth 1 \ --output panda_balanced.urdf # Accurate (many spheres, slow) python scripts/generate_sphere_urdf.py panda.urdf \ --branch 16 --depth 2 \ --initSpheres 2000 --erFact 1 \ --output panda_accurate.urdf ``` -------------------------------- ### Foam Component-Level Usage Source: https://github.com/commalab/foam/blob/master/_autodocs/module-structure.md Demonstrates importing specific classes and functions from different Foam modules like `model`, `utility`, and `external`. ```python from foam.model import Sphere, Spherization from foam.utility import load_urdf, get_urdf_meshes from foam.external import compute_spheres ``` -------------------------------- ### Extract Spheres from URDF Source: https://github.com/commalab/foam/blob/master/_autodocs/quick-reference.md Get sphere coordinates from an already-spherized URDF file using load_urdf and get_urdf_spheres. Supports conversion to a NumPy array. ```python from foam import load_urdf, get_urdf_spheres urdf = load_urdf("panda_spheres.urdf") print("Spheres in URDF:") for x, y, z, r in get_urdf_spheres(urdf): print(f" ({x:.3f}, {y:.3f}, {z:.3f}, r={r:.3f})") # Convert to numpy array import numpy as np spheres = np.array(list(get_urdf_spheres(urdf))) ``` -------------------------------- ### Path Object Creation and Usage Source: https://github.com/commalab/foam/blob/master/_autodocs/types.md Illustrates creating a `pathlib.Path` object for a mesh file, checking its existence, and obtaining its parent directory. ```python from pathlib import Path # Create path mesh_path = Path("data/robot_link.stl") # Check existence if mesh_path.exists(): mesh = load_mesh_file(mesh_path) # Get directory urdf_dir = Path("robot.urdf").parent ``` -------------------------------- ### Project Structure Overview Source: https://github.com/commalab/foam/blob/master/_autodocs/README.md Illustrates the directory layout of the Foam project, highlighting key modules and their purposes. ```text foam/ ├── __init__.py # High-level API ├── model/ # Data structures ├── utility/ # URDF & mesh utils ├── external/ # Binary wrappers ├── preprocess.py # Preprocessing └── external/ (dir) # Compiled binaries ``` -------------------------------- ### CLI Usage: Visualize Spheres Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt Example of using the visualize_spheres.py script to visualize sphere data in 3D. This script helps in verifying the results of spherization. ```bash python -m foam.scripts.visualize_spheres --spheres path/to/spheres.json --output visualization.html ``` -------------------------------- ### foam/__init__.py - Public Exports Source: https://github.com/commalab/foam/blob/master/_autodocs/module-structure.md Provides access to core classes, functions, and constants for mesh spherization and processing. ```APIDOC ## Module: `foam` (main) **Entry Point:** `foam/__init__.py` **Public Exports:** All of the following are available from `import foam`: ```python # Classes from .model import Sphere, Spherization from .model import SphereEncoder, SphereDecoder # Functions from .utility import ( load_mesh_file, fix_mesh, smooth_mesh, load_urdf, get_urdf_meshes, get_urdf_primitives, get_urdf_spheres, set_urdf_spheres, save_urdf ) from .external import ( compute_spheres, check_valid_for_spherization, simplify, simplify_manifold, manifold, manifold_plus ) # Module-level functions spherize_mesh # High-level mesh spherization smooth_manifold # Manifold + simplification # Classes ParallelSpherizer # Thread pool for parallel processing SpherizationDatabase # Cache storage SpherizationHelper # Orchestrator for URDF processing ``` **Key Constants:** ```python # Transformation matrices (from trimesh.transformations) compose_matrix # Combine rotation, translation, scale euler_matrix # Euler angles to rotation matrix translation_matrix # Translation vector to homogeneous matrix quaternion_matrix # Quaternion to rotation matrix ``` ``` -------------------------------- ### Path Object for Combining Paths Source: https://github.com/commalab/foam/blob/master/_autodocs/types.md Demonstrates using the `/` operator with `pathlib.Path` objects to construct a full file path by joining directory and file components. ```python # Combine paths full_path = urdf_dir / "meshes" / "link.obj" ``` -------------------------------- ### Generate Sphere URDF: Reset Cache Source: https://github.com/commalab/foam/blob/master/_autodocs/scripts-reference.md Shows how to delete the cache database file to start the spherization process fresh, discarding any previously cached results. ```bash rm sphere_database.json python scripts/generate_sphere_urdf.py panda.urdf ``` -------------------------------- ### Build Docker Image Source: https://github.com/commalab/foam/blob/master/DOCKER_QUICKSTART.md Builds a Docker image tagged as 'foam-image' from the current directory's Dockerfile. ```docker docker build -t foam-image . ``` -------------------------------- ### Configuration Options Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt This document lists all configuration options and parameters available for customizing the spherization process, mesh preprocessing, and script execution. ```APIDOC ## Core Spherization Parameters (This section would detail parameters that apply globally to the spherization process, such as accuracy, density, or output format settings.) ## Algorithm-Specific Parameters ### Medial Axis Parameters (Parameters specific to the medial axis algorithm, e.g., `medial_resolution`, `medial_threshold`.) ### Grid-Based Parameters (Parameters for grid-based spherization, e.g., `grid_size`, `grid_depth`.) ### Spawn-Based Parameters (Parameters for spawn-based spherization, e.g., `spawn_density`, `spawn_radius`.) ### Octree Parameters (Parameters for octree decomposition, e.g., `octree_depth`, `octree_leaf_size`.) ### Hubbard's Method Parameters (Parameters specific to Hubbard's method.) ## Mesh Preprocessing Parameters (Parameters controlling mesh cleaning, smoothing, decimation, etc., e.g., `fix_normals`, `smoothing_iterations`, `target_face_count`.) ## Transform Parameters (Parameters related to coordinate transformations, scaling, or alignment.) ## Script CLI Arguments (This section would detail command-line arguments for scripts like `generate_spheres.py`, `generate_sphere_urdf.py`, etc. For example: - `--input_mesh` (string): Path to the input mesh file. - `--output_file` (string): Path for the output file. - `--algorithm` (string): Spherization algorithm to use (e.g., 'medial', 'grid'). - `--parameter_file` (string): Path to a configuration file.) ## Output File Formats (Details on supported output formats for spherization results, e.g., JSON, PLY, URDF.) ## Tuning Guidance (Recommendations and best practices for tuning parameters to achieve desired results for different use cases.) ``` -------------------------------- ### Command-Line Tools Reference Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt This document provides a reference for the command-line interface (CLI) tools included with FOAM, detailing their usage, arguments, and common workflows. ```APIDOC ## generate_spheres.py ### Description Generates spheres for a single input mesh. ### Usage `python scripts/generate_spheres.py --input_mesh --output_file [options]` ### CLI Arguments - `--input_mesh` (string): Path to the input mesh file (e.g., .stl, .obj). - `--output_file` (string): Path to save the generated sphere data (e.g., .json). - `--algorithm` (string): Spherization algorithm to use (e.g., 'medial', 'grid'). - `--config` (string): Path to a configuration file for advanced parameters. ## generate_sphere_urdf.py ### Description Generates spheres and creates a new URDF file representing a robot with these spheres. ### Usage `python scripts/generate_sphere_urdf.py --input_urdf --output_urdf [options]` ### CLI Arguments - `--input_urdf` (string): Path to the original URDF file. - `--output_urdf` (string): Path to save the modified URDF file with spheres. - `--link_name` (string): Optional. Specific link in the URDF to attach spheres to. ## spheres_from_urdf.py ### Description Extracts sphere representations from an existing URDF file. ### Usage `python scripts/spheres_from_urdf.py --input_urdf --output_file ` ### CLI Arguments - `--input_urdf` (string): Path to the input URDF file. - `--output_file` (string): Path to save the extracted sphere data. ## visualize_spheres.py ### Description Provides 3D visualization of generated sphere data. ### Usage `python scripts/visualize_spheres.py --sphere_data [options]` ### CLI Arguments - `--sphere_data` (string): Path to the sphere data file (e.g., .json). - `--output_image` (string): Optional. Path to save a screenshot of the visualization. ## visualize_urdf.py ### Description Visualizes a URDF robot model, potentially with spheres, using PyBullet. ### Usage `python scripts/visualize_urdf.py --urdf_path [options]` ### CLI Arguments - `--urdf_path` (string): Path to the URDF file. - `--use_spheres` (boolean): Flag to visualize spheres if present in the URDF. ## Common Workflows (This section would provide step-by-step examples for common tasks, such as: - Spherizing a single mesh and saving the results. - Modifying a URDF to include spheres for collision checking. - Extracting sphere data from a robot model.) ``` -------------------------------- ### CLI Usage: Generate Spheres from Single Mesh Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt Example of using the generate_spheres.py command-line script to create spheres from a single mesh file. This is a common workflow for basic spherization. ```bash python -m foam.scripts.generate_spheres --mesh path/to/input.stl --output spheres.json ``` -------------------------------- ### Build Foam Dependencies Source: https://github.com/commalab/foam/blob/master/README.md Clone the Foam repository and build its dependencies using CMake and pip. This process requires Git, CMake, Ninja, and Python 3.11. ```bash git clone --recursive https://github.com/CoMMALab/foam.git cd foam cmake -Bbuild -GNinja . cmake --build build/ pip install -r requirements.txt ``` -------------------------------- ### Generate and Visualize Spheres Source: https://github.com/commalab/foam/blob/master/_autodocs/scripts-reference.md This workflow first generates sphere approximations for a given STL file and then visualizes these spheres. Ensure you are in the Foam project directory before running. ```bash cd /path/to/foam # Generate spheres python scripts/generate_spheres.py robot_link.stl \ --depth 1 \ --branch 8 \ --output link_spheres.json # Visualize python scripts/visualize_spheres.py robot_link.stl link_spheres.json ``` -------------------------------- ### Extract URDF Primitive Geometries Source: https://github.com/commalab/foam/blob/master/_autodocs/api-reference-utility.md Get primitive collision geometries (boxes, spheres, cylinders) from a URDF. This allows you to access and analyze basic shapes defined in the robot model. ```python from foam.utility import get_urdf_primitives, load_urdf from pathlib import Path urdf = load_urdf(Path("robot.urdf")) primitives = get_urdf_primitives(urdf) for prim in primitives: print(f"Primitive: {prim.name}") print(f"Type: {type(prim.mesh).__name__}") ``` -------------------------------- ### URDF Collision Geometry Structure Source: https://github.com/commalab/foam/blob/master/_autodocs/types.md Details the structure for collision geometry within a URDF dictionary, showing examples for mesh, box, sphere, and cylinder shapes, along with origin transformations. ```python { 'geometry': { 'mesh': { '@filename': str, '@scale': str (optional) } # OR 'box': { '@size': str } # OR 'sphere': { '@radius': str } # OR 'cylinder': { '@radius': str, '@length': str } }, 'origin': { '@xyz': str, '@rpy': str } } ``` -------------------------------- ### Sphere Constructor and Attributes Source: https://github.com/commalab/foam/blob/master/_autodocs/api-reference-core.md Demonstrates the initialization of a Sphere object and accessing its origin and radius attributes. ```python def __init__( self, x: float, y: float, z: float, r: float, offset: NDArray | None = None ) -> None: pass ``` -------------------------------- ### Handle Non-existent File Path Error Source: https://github.com/commalab/foam/blob/master/_autodocs/errors.md This example demonstrates catching a RuntimeError when a specified URDF file path does not exist. It's useful for validating file paths before or during script execution. ```bash python scripts/generate_spheres.py nonexistent_mesh.stl # RuntimeError: Path nonexistent_mesh.stl does not exist! ``` -------------------------------- ### SpherizationDatabase.__init__ Source: https://github.com/commalab/foam/blob/master/_autodocs/api-reference-core.md Initializes a persistent JSON-based cache for spherization results. ```APIDOC ## SpherizationDatabase.__init__ ### Description Initializes a persistent JSON-based cache for spherization results, keyed by mesh name, branch factor, and depth. ### Method `__init__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **path** (Path) - Required - Path to JSON file for storing cached spherizations. **Note:** The database is written to disk when the object is destroyed (in `__del__`). ``` -------------------------------- ### Run Docker Container Source: https://github.com/commalab/foam/blob/master/DOCKER_QUICKSTART.md Runs a Docker container named 'foam' from the 'foam-image', mounting the current directory to '/foam' inside the container. ```docker docker run -it -v "$(pwd)/:/foam" --name=foam foam-image ``` -------------------------------- ### Generate Sphere URDF: Variable Arguments Example Source: https://github.com/commalab/foam/blob/master/_autodocs/scripts-reference.md Illustrates how to use variable arguments to override the default branch (sphere count) for specific links. The effective branch is calculated based on the base branch and the link-specific multiplier. ```bash python scripts/generate_sphere_urdf.py robot.urdf \ --branch 8 \ link1=2.0 \ link2=0.5 ``` -------------------------------- ### Create Custom Targets and Copy Binaries Source: https://github.com/commalab/foam/blob/master/CMakeLists.txt Generates fake targets for all existing targets and copies their built files to a specified directory after the build. ```cmake get_all_targets(all_targets) foreach(target ${all_targets}) add_custom_target(${target}_fake ALL) add_dependencies(${target}_fake ${target}) add_custom_command(TARGET ${target}_fake POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy $ ${FOAM_PROGRAMS_DIR}) endforeach() ``` -------------------------------- ### Configure Include Directories for 'simplify_old' Source: https://github.com/commalab/foam/blob/master/external/CMakeLists.txt Specifies private include directories for the 'simplify_old' target, including paths for Eigen, libigl, and old manifold third-party libraries. ```cmake target_include_directories(simplify_old PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/manifold/3rd_party/eigen/) ``` ```cmake target_include_directories(simplify_old PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/manifold/3rd_party/libigl/include) ``` ```cmake target_include_directories(simplify_old PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/manifold_old/3rd) ``` -------------------------------- ### Make External Binaries Executable Source: https://github.com/commalab/foam/blob/master/_autodocs/errors.md Ensure that external binary files have execute permissions. ```bash chmod +x foam/external/* ``` -------------------------------- ### Foam Parallel Processing with ParallelSpherizer Source: https://github.com/commalab/foam/blob/master/_autodocs/module-structure.md Illustrates how to use the `ParallelSpherizer` for concurrent mesh spherization, including waiting for completion and retrieving results. ```python from foam import ParallelSpherizer from pathlib import Path spherizer = ParallelSpherizer(threads=4) futures = [ spherizer.spherize_mesh(f"mesh{i}", Path(f"mesh{i}.stl")) for i in range(10) ] spherizer.wait() results = [spherizer.get(f"mesh{i}") for i in range(10)] ``` -------------------------------- ### Core API Documentation Source: https://github.com/commalab/foam/blob/master/_autodocs/README.md The primary entry point for most users. Covers main functions for mesh spherization, preprocessing utilities, concurrent processing, result caching, URDF workflows, and data classes. ```APIDOC ## Core API ### Description Provides the main high-level API for using the Foam library, including functions for mesh spherization and related utilities. ### Functions - `spherize_mesh()`: Main function for single-mesh spherization. - `smooth_manifold()`: Mesh preprocessing utility. ### Classes - `ParallelSpherizer`: Thread pool for concurrent processing. - `SpherizationDatabase`: JSON-based result caching. - `SpherizationHelper`: Orchestrator for URDF workflows. ### Data Classes - `Sphere`: Represents a single sphere. - `Spherization`: Represents a complete approximation at one refinement level. ### Serialization - `SphereEncoder`: JSON encoder for Sphere objects. - `SphereDecoder`: JSON decoder for Sphere objects. ### Recommended Usage Start here for using Foam in your code. ``` -------------------------------- ### Scripts Reference Source: https://github.com/commalab/foam/blob/master/_autodocs/README.md A complete reference for all command-line interface (CLI) scripts provided with the Foam library, including their parameters, behavior, and use cases. ```APIDOC ## Scripts Reference ### Description Provides a complete reference for all command-line tools included with the Foam library, detailing their functionality, parameters, and usage examples. ### Core Scripts - `generate_spheres.py`: Spherizes a single mesh. - `generate_sphere_urdf.py`: Spherizes all geometries within a URDF file. - `spheres_from_urdf.py`: Extracts sphere approximations from a URDF file. ### Visualization Scripts - `visualize_spheres.py`: Provides a 3D visualization of a mesh and its sphere approximation. - `visualize_urdf.py`: Loads and visualizes a URDF file using the PyBullet simulator. ### Script Details Each script entry includes: - Full parameter list. - Behavior description. - Usage examples. - Common use cases. ### Recommended Usage When using Foam from the command line. ``` -------------------------------- ### Configuration Reference Source: https://github.com/commalab/foam/blob/master/_autodocs/README.md A complete catalog of all configuration options and parameters available in the Foam library, detailing their effects on spherization and mesh processing. ```APIDOC ## Configuration Reference ### Description Provides a comprehensive catalog of all spherization parameters and their effects, including core, algorithm-specific, preprocessing, and transform parameters. ### Core Parameters (All Methods) - `depth`: Controls the recursion depth for spherization. - `branch`: Controls branching factor in spherization. - `method`: Specifies the spherization algorithm to use. - `verify`: Enables verification of the spherization results. ### Algorithm-Specific Parameters - **Medial**: `initSpheres`, `minSpheres`, `erFact`, `expand`, `merge`, `burst`, `maxOptLevel`, `balExcess`. - **Grid/Spawn**: `testerLevels`, `numCover`, `minCover`. - **Hubbard**: `num_samples`, `min_samples`. ### Mesh Preprocessing Parameters - `manifold_leaves`: Parameter for manifold processing. - `simplification_ratio`: Ratio for mesh simplification. ### Transform Parameters - `scale`: Scaling factor for transformations. - `position`: Positional offset for transformations. - `orientation`: Rotational offset for transformations. ### Script CLI Arguments Parameters for command-line scripts like `generate_spheres.py` and `generate_sphere_urdf.py`. ### Output and Cache Details on output file formats and the structure of the cache database. ### Recommended Usage When tuning parameters or understanding what options do. ``` -------------------------------- ### External Binary: Mesh Simplification Source: https://github.com/commalab/foam/blob/master/_autodocs/CONTENTS.txt Demonstrates using the external binary's mesh simplification function. This is useful for reducing mesh complexity before further processing. ```python from foam.external import simplify input_mesh = "path/to/mesh.stl" output_mesh = "path/to/simplified_mesh.stl" simplify(input_mesh, output_mesh, target_reduction=0.5) ```