### Build Project with Pip Source: https://github.com/commonroad/commonroad-clcs/blob/main/README_FOR_DEVELOPERS.md Installs the C++ code, Python shared library, and the package into your environment. Ensure build dependencies are installed first. ```bash pip install -v . ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/commonroad/commonroad-clcs/blob/main/README.md Build the project documentation locally using mkdocs. Ensure optional 'docs' are installed first. ```bash mkdocs build ``` -------------------------------- ### Editable Install with Auto Rebuilds Source: https://github.com/commonroad/commonroad-clcs/blob/main/README_FOR_DEVELOPERS.md Installs the package in editable mode with automatic rebuilds when source code changes. Requires C++ and Python build dependencies. Use `--no-build-isolation` to build in your local environment. ```bash pip install -r requirements_build.txt ``` ```bash pip install -v --no-build-isolation --config-settings=editable.rebuild=true -e . ``` -------------------------------- ### Debug Install with GDB Source: https://github.com/commonroad/commonroad-clcs/blob/main/README_FOR_DEVELOPERS.md Installs the package in editable mode with CMake Debug build type. Then, launch the Python interpreter with GDB for C++ debugging. ```bash pip install -v --no-build-isolation --config-settings=editable.rebuild=true --config-settings=cmake.build-type="Debug" -e . ``` ```bash gdb -ex r --args python compute_reachable_set.py ``` -------------------------------- ### Import Necessary Libraries Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/00_getting_started.ipynb Imports essential libraries for CommonRoad scenario loading, visualization, route planning, and CLCS functionalities. Ensure all dependencies are installed. ```python %matplotlib inline import os from matplotlib import pyplot as plt # commonroad-io from commonroad.common.file_reader import CommonRoadFileReader from commonroad.visualization.mp_renderer import MPRenderer # commonroad-route-planner from commonroad_route_planner.route_planner import RoutePlanner from commonroad_route_planner.reference_path_planner import ReferencePathPlanner # commonroad-clcs from commonroad_clcs.clcs import CurvilinearCoordinateSystem from commonroad_clcs.ref_path_processing.factory import ProcessorFactory from commonroad_clcs.helper.visualization import plot_scenario_and_clcs from commonroad_clcs.config import ( CLCSParams, ProcessingOption, ResamplingOption ) ``` -------------------------------- ### Install CommonRoad-CLCS Python Package Source: https://github.com/commonroad/commonroad-clcs/blob/main/README.md Install the CommonRoad-CLCS Python package using pip. This is the recommended installation method. ```bash pip install commonroad-clcs ``` -------------------------------- ### Build Python Bindings with CMake Source: https://github.com/commonroad/commonroad-clcs/blob/main/README_FOR_DEVELOPERS.md Enables Python bindings for CLCS and adds the Python site-packages directory to CMake's search path. Ensure pybind11 is installed. ```bash -DCR_CLCS_BUILD_PYTHON_BINDINGS=ON -DCMAKE_PREFIX_PATH=/path/to/site-packages ``` -------------------------------- ### Extend Reference Path Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/02_ref_path_processing.ipynb Extends the reference path forwards and backwards by a specified length to avoid planning issues near the start and end points. Extension is done by adding lanelet centerpoints or linear extrapolation. ```python from commonroad_clcs.util import extend_reference_path # extend reference path ref_path = extend_reference_path( reference_path=ref_path, resample_step=1.0, extend_front_length=10.0, extend_back_length=5.0, lanelet_network=scenario.lanelet_network ) ``` -------------------------------- ### Plan Initial Reference Path Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/01_advanced.ipynb Plans an initial reference path using RoutePlanner and ReferencePathPlanner from the scenario's lanelet network and planning problem. ```python from commonroad_route_planner.route_planner import RoutePlanner from commonroad_route_planner.reference_path_planner import ReferencePathPlanner # Plan initial reference path routes = RoutePlanner(scenario.lanelet_network, planning_problem).plan_routes() ref_path = ReferencePathPlanner( lanelet_network=scenario.lanelet_network, planning_problem=planning_problem, routes=routes ).plan_shortest_reference_path().reference_path ``` -------------------------------- ### Build CLCS with Python Wrapper and Pre-processing Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Demonstrates building the CurvilinearCoordinateSystem using the Python wrapper with pre-processing options like spline smoothing and resampling. ```python import numpy as np from commonroad_clcs.clcs import CurvilinearCoordinateSystem from commonroad_clcs.config import CLCSParams, ProcessingOption # Define a curved reference path (quarter-circle approximation) theta = np.linspace(0, np.pi / 2, 50) reference_path = np.column_stack((np.cos(theta) * 10, np.sin(theta) * 10)) # Configure: smooth with spline, then resample at 0.5 m intervals params = CLCSParams() params.processing_option = ProcessingOption.SPLINE_SMOOTHING params.resampling.fixed_step = 0.5 params.spline.smoothing_factor = 5.0 # Build CLCS clcs = CurvilinearCoordinateSystem(reference_path, params=params) # Inspect pre-computed reference path properties print("Ref path shape:", clcs.ref_path.shape) # (N, 2) print("Arc-length positions:", clcs.ref_pos[:5]) # [0.0, 0.5, 1.0, ...] print("Orientation (rad):", clcs.ref_theta[:3]) print("Curvature (1/m):", clcs.ref_curv[:3]) print("Curvature rate:", clcs.ref_curv_d[:3]) # Plot orientation, curvature, and curvature rate clcs.plot_reference_states() ``` -------------------------------- ### Plan Initial Reference Path Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/02_ref_path_processing.ipynb Plans the shortest reference path for a given scenario and planning problem using RoutePlanner and ReferencePathPlanner. A deep copy of the original reference path is stored for comparison. ```python from commonroad_route_planner.route_planner import RoutePlanner from commonroad_route_planner.reference_path_planner import ReferencePathPlanner from copy import deepcopy # Plan initial reference path routes = RoutePlanner(scenario.lanelet_network, planning_problem).plan_routes() ref_path = ReferencePathPlanner( lanelet_network=scenario.lanelet_network, planning_problem=planning_problem, routes=routes ).plan_shortest_reference_path().reference_path # store original reference path ref_path_original = deepcopy(ref_path) ``` -------------------------------- ### compute_pathlength_from_polyline Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Computes the cumulative arc-length for each vertex of a polyline, starting from zero at the first vertex. This is useful for parameterizing paths by distance. ```APIDOC ## compute_pathlength_from_polyline — Arc-length computation ### Description Returns cumulative arc-length values for each vertex of a polyline, starting at 0. ### Parameters - **polyline** (np.ndarray) - The input polyline. ### Request Example ```python import numpy as np # Assuming compute_pathlength_from_polyline is imported polyline = np.array([[0.0, 0.0], [3.0, 0.0], [3.0, 4.0], [6.0, 4.0]]) s = compute_pathlength_from_polyline(polyline) print("Arc-length positions:", s) # [0.0, 3.0, 7.0, 10.0] ``` ### Response - **s** (np.ndarray) - An array of cumulative arc-length values for each vertex. ``` -------------------------------- ### Configure and Pre-process Reference Path Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/00_getting_started.ipynb Sets processing options, such as spline smoothing and adaptive resampling, and then applies these to the initial reference path. This step ensures the path is suitable for CLCS construction. ```python # set options (see config.py for other possible parameters) params.processing_option = ProcessingOption.SPLINE_SMOOTHING params.resampling.option = ResamplingOption.ADAPTIVE # pre-process reference path ref_path_processor = ProcessorFactory.create_processor(params) ref_path = ref_path_processor(ref_path) ``` -------------------------------- ### Compute Arc-Length of a Polyline Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Calculates the cumulative arc-length for each vertex of a polyline, starting from 0 at the first vertex. Useful for parameterizing paths by distance. ```python import numpy as np from commonroad_clcs.util import compute_pathlength_from_polyline polyline = np.array([[0.0, 0.0], [3.0, 0.0], [3.0, 4.0], [6.0, 4.0]]) s = compute_pathlength_from_polyline(polyline) print("Arc-length positions:", s) # [0.0, 3.0, 7.0, 10.0] ``` -------------------------------- ### Build CLCS with Low-level C++ Backend Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Shows how to construct the C++ backend `pycrccosy.CurvilinearCoordinateSystem` directly for full control over parameters, without automatic pre-processing. ```python import numpy as np from commonroad_clcs.pycrccosy import CurvilinearCoordinateSystem # Straight reference path along X axis x_coords = np.linspace(0, 20, 41) y_coords = np.zeros(41) reference_path = np.column_stack((x_coords, y_coords)) # Build C++ CLCS directly ccosy = CurvilinearCoordinateSystem( reference_path, default_projection_domain_limit=30.0, # max lateral extent (m) eps=0.1, # tolerance for projection domain eps2=1e-2, # tolerance for path extension log_level="off", # logging: "off", "info", "debug" method=1 # projection method (1 or 2) ) print("Reference path (first 3 points):", np.asarray(ccosy.reference_path())[:3]) print("Projection domain vertices:", np.asarray(ccosy.projection_domain()).shape) ``` -------------------------------- ### Create Reference Path Processor Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/02_ref_path_processing.ipynb Instantiate a reference path processor using the ProcessorFactory with provided parameters. ```python ref_path_processor = ProcessorFactory.create_processor(params) ref_path_cs = ref_path_processor(ref_path) ``` -------------------------------- ### Create and Apply Elastic Band Processor Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Configure elastic band smoothing parameters and use ProcessorFactory to create a processor. Apply the processor to a reference path and observe the changes in point count. ```python import numpy as np import pickle from commonroad_clcs.config import CLCSParams, ProcessingOption from commonroad_clcs.ref_path_processing.factory import ProcessorFactory # Load a reference path (e.g., from a CommonRoad scenario) with open("tests/test_data/reference_path_b.pic", "rb") as f: data = pickle.load(f) reference_path = data["reference_path"] # Configure elastic band smoothing params = CLCSParams() params.processing_option = ProcessingOption.ELASTIC_BAND params.elastic_band.max_deviation = 0.2 params.elastic_band.weight_smooth = 1.0 params.elastic_band.weight_lat_error = 0.001 params.resampling.fixed_step = 1.0 # Create and apply processor processor = ProcessorFactory.create_processor(params) processed_path = processor(reference_path) print("Original path points:", reference_path.shape[0]) print("Processed path points:", processed_path.shape[0]) print("Original (input) path still accessible:", processor.ref_path_original.shape) ``` -------------------------------- ### Build Docker Image for CI Source: https://github.com/commonroad/commonroad-clcs/blob/main/ci/docker/README.md Builds the Docker image locally. Replace with the appropriate version tag used in the .gitlab-ci.yml file. ```bash docker build -t gitlab.lrz.de:5005/cps/commonroad/commonroad-clcs/deps: . ``` -------------------------------- ### Initialize CLCS Parameters Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/01_advanced.ipynb Initializes the CLCSParams object with default settings. ```python from commonroad_clcs.config import ( CLCSParams, ProcessingOption, ResamplingOption ) # initialize CLCS params params = CLCSParams() ``` -------------------------------- ### Login to GitLab Docker Registry Source: https://github.com/commonroad/commonroad-clcs/blob/main/ci/docker/README.md Authenticates with the GitLab Docker registry. Ensure you have the necessary credentials. ```bash docker login gitlab.lrz.de:5005 ``` -------------------------------- ### Push Docker Image to GitLab Registry Source: https://github.com/commonroad/commonroad-clcs/blob/main/ci/docker/README.md Pushes the newly built Docker image to the GitLab container registry. Ensure the matches the one used during the build. ```bash docker push gitlab.lrz.de:5005/cps/commonroad/commonroad-reachable-set/deps: ``` -------------------------------- ### Configure Adaptive Resampling Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/02_ref_path_processing.ipynb Sets up adaptive resampling parameters for the reference path. This method adjusts the sampling density based on curvature, increasing it in high-curvature areas and decreasing it in low-curvature areas. ```python # resampling settings params.resampling.option = ResamplingOption.ADAPTIVE params.resampling.min_step = 0.4 params.resampling.max_step = 2.0 ``` -------------------------------- ### Load Scenario and Planning Problem Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/01_advanced.ipynb Loads a CommonRoad scenario and extracts the first planning problem for use with CLCS. ```python import os from commonroad.common.file_reader import CommonRoadFileReader # Load scenario scenario_name = 'ZAM_Tjunction-1_42_T-1.xml' file_path = os.path.join(os.getcwd(), "../", scenario_name) scenario, planning_problem_set = CommonRoadFileReader(file_path).open() planning_problem = list(planning_problem_set.planning_problem_dict.values())[0] ``` -------------------------------- ### Configure CLCS Parameters and Save/Load YAML Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Set processing options, subdivision parameters, resampling settings, and backend tolerances. Configurations can be saved to and loaded from YAML files. ```python params.processing_option = ProcessingOption.CURVE_SUBDIVISION params.subdivision.degree = 2 # cubic B-spline limit curve params.subdivision.max_curvature = 0.1 # 1/m params.subdivision.max_deviation = 2.0 # m params.subdivision.max_iterations = 200 params.resampling.fixed_step = 0.5 # m # Or use adaptive resampling params.resampling.option = ResamplingOption.ADAPTIVE params.resampling.min_step = 0.3 params.resampling.max_step = 1.5 params.resampling.interpolation_type = "akima" # Backend tolerances params.default_proj_domain_limit = 25.0 params.eps = 0.1 params.eps2 = 1e-2 params.logging_level = "warn" # Save and reload from YAML params.save("my_clcs_config.yaml") params_loaded = CLCSParams.load("my_clcs_config.yaml") print("Loaded processing option:", params_loaded.processing_option) ``` -------------------------------- ### Load CommonRoad Scenario Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/00_getting_started.ipynb Loads a CommonRoad scenario and its associated planning problem from an XML file. This is the first step before planning any paths or creating coordinate systems. ```python # scenario name scenario_name = 'USA_US101-3_1_T-1.xml' # load scenario and planning problem file_path = os.path.join(os.getcwd(), "../", scenario_name) scenario, planning_problem_set = CommonRoadFileReader(file_path).open() planning_problem = list(planning_problem_set.planning_problem_dict.values())[0] ``` -------------------------------- ### Smooth Polyline using Elastic Band QP Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Smooths a polyline using an elastic band formulation with quadratic programming. The max_deviation parameter constrains the maximum lateral shift. ```python import numpy as np from commonroad_clcs.helper.smoothing import smooth_polyline_elastic_band # Noisy reference path x = np.linspace(0, 20, 100) y = 0.5 * np.sin(0.5 * x) + np.random.normal(0, 0.05, 100) polyline = np.column_stack((x, y)) smoothed = smooth_polyline_elastic_band( polyline, input_resampling=1.0, # coarse pre-resampling step (m) max_deviation=0.15, # max lateral shift constraint (m) weight_smooth=1.0, # smoothness weight weight_lat_error=0.001, # lateral error weight solver_max_iter=20000 ) print("Elastic band smoothed:", smoothed.shape) ``` -------------------------------- ### Pickle Support for CurvilinearCoordinateSystem Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Demonstrates serialization and deserialization of CurvilinearCoordinateSystem objects using pickle for caching. Requires numpy and CLCS configuration. ```python import pickle import numpy as np from commonroad_clcs.clcs import CurvilinearCoordinateSystem from commonroad_clcs.config import CLCSParams reference_path = np.column_stack((np.linspace(0, 20, 41), np.zeros(41))) clcs = CurvilinearCoordinateSystem(reference_path, params=CLCSParams()) # Serialize with open("clcs_cache.pkl", "wb") as f: pickle.dump(clcs, f) # Deserialize with open("clcs_cache.pkl", "rb") as f: clcs_loaded = pickle.load(f) # Verify round-trip s, d = clcs_loaded.convert_to_curvilinear_coords(5.0, 1.0) print(f"After reload — s={s:.3f}, d={d:.3f}") ``` -------------------------------- ### Compare Reference Path Lengths Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/02_ref_path_processing.ipynb Calculates and prints the lengths of the reference path before and after extension to quantify the effect of the extension operation. ```python from commonroad_clcs.util import compute_polyline_length # compare lengths before/after print(f"Length before extension: {compute_polyline_length(ref_path_original)}") print(f"Length after extension: {compute_polyline_length(ref_path)}") ``` -------------------------------- ### Plan Initial Reference Path Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/00_getting_started.ipynb Generates an initial reference path (a polyline) for the scenario using the commonroad-route-planner. This path serves as the basis for the curvilinear coordinate system. ```python # plan routes and reference path routes = RoutePlanner(scenario.lanelet_network, planning_problem).plan_routes() ref_path = ReferencePathPlanner( lanelet_network=scenario.lanelet_network, planning_problem=planning_problem, routes=routes ).plan_shortest_reference_path().reference_path ``` -------------------------------- ### Smooth and Resample Reference Path Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/02_ref_path_processing.ipynb Applies RDP polyline simplification to remove noisy points and resamples the path to a fixed step size. This is a preliminary step before further processing or extension. ```python from commonroad_clcs.helper.smoothing import smooth_polyline_rdp # first remove noisy points via RDP polyline simplification and resample the path ref_path = smooth_polyline_rdp( polyline = ref_path, resample_step = 1.0 ) ``` -------------------------------- ### pycrccosy.CurvilinearCoordinateSystem (C++ Backend) Source: https://context7.com/commonroad/commonroad-clcs/llms.txt The C++ backend class, directly usable when full control over construction parameters is needed. It accepts the reference path, a lateral projection domain limit, and two numerical tolerances. ```APIDOC ## pycrccosy.CurvilinearCoordinateSystem — Low-level C++ class ### Description The C++ backend class, directly usable when full control over construction parameters is needed (no automatic pre-processing). Accepts the reference path, a lateral projection domain limit, and two numerical tolerances. ### Usage ```python import numpy as np from commonroad_clcs.pycrccosy import CurvilinearCoordinateSystem # Straight reference path along X axis x_coords = np.linspace(0, 20, 41) y_coords = np.zeros(41) reference_path = np.column_stack((x_coords, y_coords)) # Build C++ CLCS directly ccosy = CurvilinearCoordinateSystem( reference_path, default_projection_domain_limit=30.0, # max lateral extent (m) eps=0.1, # tolerance for projection domain eps2=1e-2, # tolerance for path extension log_level="off", # logging: "off", "info", "debug" method=1 # projection method (1 or 2) ) print("Reference path (first 3 points):", np.asarray(ccosy.reference_path())[:3]) print("Projection domain vertices:", np.asarray(ccosy.projection_domain()).shape) ``` ``` -------------------------------- ### Configure Curve Subdivision for Smoothing and Curvature Limit Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/02_ref_path_processing.ipynb Sets up parameters for curve subdivision, an iterative process used to pre-process the reference path. This method allows for smoothing and limiting the maximum curvature. ```python # curve subdivision settings params.processing_option = ProcessingOption.CURVE_SUBDIVISION params.subdivision.degree = 2 params.subdivision.num_refinements = 3 params.subdivision.coarse_resampling_step = 2.0 params.subdivision.max_curvature = 0.12 ``` -------------------------------- ### Plot Scenario and CLCS Projection Domain Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Visualizes a CommonRoad scenario, CLCS reference path, and its projection domain using MPRenderer. Requires CommonRoad library and CLCS configuration. ```python import pickle import numpy as np from commonroad.common.file_reader import CommonRoadFileReader from commonroad_clcs.clcs import CurvilinearCoordinateSystem from commonroad_clcs.config import CLCSParams from commonroad_clcs.helper.visualization import plot_scenario_and_clcs # Load a CommonRoad scenario scenario, planning_problem_set = CommonRoadFileReader("my_scenario.xml").open() pp = list(planning_problem_set.planning_problem_dict.values())[0] # Build reference path from a lanelet's center vertices lanelet = scenario.lanelet_network.lanelets[0] reference_path = lanelet.center_vertices # Build CLCS params = CLCSParams() clcs = CurvilinearCoordinateSystem(reference_path, params=params) # Visualize scenario + CLCS projection domain plot_scenario_and_clcs( scenario=scenario, clcs=clcs.reference_path(), # pass pycrccosy object planning_problem=pp, proj_domain_plot="full", # "full", "left", or "right" plot_ref_path=True, show=True ) ``` -------------------------------- ### Create Curvilinear Coordinate System Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/01_advanced.ipynb Creates a CurvilinearCoordinateSystem instance with the pre-processed reference path and configured parameters. The logging level for the C++ backend can be set for debugging. ```python from commonroad_clcs.clcs import CurvilinearCoordinateSystem # log level params.logging_level = "info" # "debug" # proj domain computation method for visualization below params.method = 2 curvilinear_cosy = CurvilinearCoordinateSystem( reference_path=ref_path, params=params, preprocess_path=False ) ``` -------------------------------- ### Compare Reference Path Curvatures Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Computes curvature comparison metrics between original and modified reference paths. Requires numpy and specific helper functions for smoothing. ```python import numpy as np from commonroad_clcs.helper.evaluation import compare_ref_path_curvatures from commonroad_clcs.helper.smoothing import smooth_polyline_spline # Original noisy path x = np.linspace(0, 10, 50) original = np.column_stack((x, np.sin(x) + np.random.normal(0, 0.1, 50))) # Smoothed version smoothed = smooth_polyline_spline(original, smoothing_factor=10.0) metrics = compare_ref_path_curvatures(original, smoothed, verbose=True) # Output: # delta_kappa_avg: 0.0123 # delta_kappa_dot_avg: 0.0456 # delta_kappa_max: 0.0789 # delta_kappa_dot_max: 0.1234 print(metrics) ``` -------------------------------- ### Visualize Scenario and CLCS Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/00_getting_started.ipynb Visualizes the loaded scenario, the constructed curvilinear coordinate system, and the transformed points. This helps in understanding the spatial relationship between the Cartesian and curvilinear frames. ```python # plot scenario with CLCS rnd = MPRenderer(figsize=(7, 10), plot_limits=[0.0, 80.0, -80.0, 0.0]) plot_scenario_and_clcs( scenario, curvilinear_cosy, renderer=rnd, proj_domain_plot=None ) ``` -------------------------------- ### Smooth Reference Path via Spline Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/02_ref_path_processing.ipynb Applies spline smoothing to the reference path using B-splines to smooth jerky curvature profiles. This involves configuring spline parameters and creating a processor via ProcessorFactory. ```python from commonroad_clcs.ref_path_processing.factory import ProcessorFactory # spline smoothing settings params.processing_option = ProcessingOption.SPLINE_SMOOTHING params.spline.degree_spline = 3 params.spline.smoothing_factor = 2.0 # process reference path ref_path_processor = ProcessorFactory.create_processor(params) ref_path_spline = ref_path_processor(ref_path) ``` -------------------------------- ### CLCS Configuration Parameters Source: https://context7.com/commonroad/commonroad-clcs/llms.txt The `CLCSParams` dataclass provides a unified configuration for the CLCS, controlling reference path pre-processing, C++ backend tolerances, and method-specific sub-parameters. ```python from commonroad_clcs.config import ( CLCSParams, ProcessingOption, ResamplingOption, ) # Default configuration params = CLCSParams() ``` -------------------------------- ### Resample Polyline with Adaptive Step Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Resample a polyline with spacing that adapts to local curvature, using minimum and maximum step sizes. Supports 'cubic' interpolation. ```python import numpy as np from commonroad_clcs.util import resample_polyline_adaptive # Curved polyline (S-curve) theta = np.linspace(0, 2 * np.pi, 200) polyline = np.column_stack((theta, np.sin(theta))) resampled = resample_polyline_adaptive( polyline, min_ds=0.1, # minimum spacing (m) max_ds=0.5, # maximum spacing (m) interpolation_type="cubic" ) print("Adaptive resampled shape:", resampled.shape) # More points around peaks of the sine wave ``` -------------------------------- ### Pre-process Reference Path Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/01_advanced.ipynb Applies pre-processing to the reference path, including curve subdivision for smoothing and adaptive resampling. Ensure CLCSParams are configured with desired processing and resampling options. ```python from commonroad_clcs.ref_path_processing.factory import ProcessorFactory # set pre-processing options and call processor params.processing_option = ProcessingOption.CURVE_SUBDIVISION params.subdivision.max_curvature = 0.125 params.resampling.option = ResamplingOption.ADAPTIVE ref_path_processor = ProcessorFactory.create_processor(params) ref_path = ref_path_processor(ref_path) ``` -------------------------------- ### CurvilinearCoordinateSystem (Python Wrapper) Source: https://context7.com/commonroad/commonroad-clcs/llms.txt The high-level Python wrapper for the C++ pycrccosy.CurvilinearCoordinateSystem. It accepts a reference path and configuration parameters to build the curvilinear frame and provides access to pre-computed reference path properties. ```APIDOC ## CurvilinearCoordinateSystem — Python wrapper class ### Description The high-level Python wrapper for the C++ `pycrccosy.CurvilinearCoordinateSystem`. It accepts a reference path (numpy array of 2D points), pre-processes it according to the supplied `CLCSParams`, and constructs the curvilinear frame. Pre-computed properties (arc-length positions, orientation, curvature, curvature rate) are accessible as attributes. ### Usage ```python import numpy as np from commonroad_clcs.clcs import CurvilinearCoordinateSystem from commonroad_clcs.config import CLCSParams, ProcessingOption # Define a curved reference path (quarter-circle approximation) theta = np.linspace(0, np.pi / 2, 50) reference_path = np.column_stack((np.cos(theta) * 10, np.sin(theta) * 10)) # Configure: smooth with spline, then resample at 0.5 m intervals params = CLCSParams() params.processing_option = ProcessingOption.SPLINE_SMOOTHING params.resampling.fixed_step = 0.5 params.spline.smoothing_factor = 5.0 # Build CLCS clcs = CurvilinearCoordinateSystem(reference_path, params=params) # Inspect pre-computed reference path properties print("Ref path shape:", clcs.ref_path.shape) # (N, 2) print("Arc-length positions:", clcs.ref_pos[:5]) # [0.0, 0.5, 1.0, ...] print("Orientation (rad):", clcs.ref_theta[:3]) print("Curvature (1/m):", clcs.ref_curv[:3]) print("Curvature rate:", clcs.ref_curv_d[:3]) # Plot orientation, curvature, and curvature rate clcs.plot_reference_states() ``` ``` -------------------------------- ### Extend Reference Path Length Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Extends a reference path by a specified length at the front and back. Set lanelet_network to None for extension without lanelet awareness. ```python extended = extend_reference_path( reference_path, resample_step=0.5, extend_front_length=5.0, extend_back_length=3.0, lanelet_network=None # pass a CommonRoad LaneletNetwork for lanelet-aware extension ) print("Original length:", reference_path.shape[0]) print("Extended length:", extended.shape[0]) ``` -------------------------------- ### chaikins_corner_cutting Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Applies Chaikin's corner cutting algorithm to a polyline. Each refinement step replaces each point with two new points, resulting in a smoother curve that converges to a quadratic B-spline. ```APIDOC ## chaikins_corner_cutting — Chaikin's smoothing ### Description Applies Chaikin's corner cutting algorithm to a polyline. Each refinement step replaces each point with two new points at 1/4 and 3/4 along the adjacent edges. The limit curve is a quadratic B-spline. ### Parameters - **polyline** (np.ndarray) - The input polyline. - **refinements** (int) - The number of refinement steps to apply. ### Request Example ```python import numpy as np # Assuming chaikins_corner_cutting is imported polyline = np.array([ [0.0, 0.0], [1.0, 2.0], [3.0, 1.0], [4.0, 3.0], [6.0, 0.0] ]) smoothed = chaikins_corner_cutting(polyline, refinements=4) print("Original points:", len(polyline)) print("After Chaikin (4 refinements):", len(smoothed)) # 2^4 * (N-1) + 1 ``` ### Response - **smoothed** (np.ndarray) - The smoothed polyline after Chaikin's algorithm. ``` -------------------------------- ### Construct Curvilinear Coordinate System Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/00_getting_started.ipynb Constructs the CurvilinearCoordinateSystem object using the pre-processed reference path and CLCS parameters. `preprocess_path=False` is used because the path has already been processed. ```python # construct CLCS # (we set preprocess_path = False, since we have already done a pre-processing in the previous section) curvilinear_cosy = CurvilinearCoordinateSystem( reference_path=ref_path, params=params, preprocess_path=False ) ``` -------------------------------- ### Resample Polyline with Fixed Step Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Resample a polyline at uniform arc-length intervals using specified step size and interpolation method. Supports 'linear', 'cubic', and 'akima' interpolation. ```python import numpy as np from commonroad_clcs.util import resample_polyline # Irregular polyline polyline = np.array([ [0.0, 0.0], [0.5, 0.1], [1.5, 0.4], [3.0, 1.0], [5.0, 1.5], [7.0, 1.6], [10.0, 1.0] ]) # Resample at 1.0 m intervals using cubic interpolation resampled = resample_polyline(polyline, step=1.0, interpolation_type="cubic") print("Resampled shape:", resampled.shape) # (N, 2), uniform 1 m spacing print("First few points: ", resampled[:4]) ``` -------------------------------- ### Initialize CLCS Parameters Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/00_getting_started.ipynb Initializes the default parameters for the Curvilinear Coordinate System (CLCS). These parameters can be customized to control path processing and resampling behavior. ```python # initialize default CLCS parameter params = CLCSParams() ``` -------------------------------- ### Compare Reference Path Deviations Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Computes deviation metrics (path length, lateral, orientation) between original and modified reference paths. Requires numpy and specific helper functions for smoothing. ```python import numpy as np from commonroad_clcs.helper.evaluation import compare_ref_path_deviations from commonroad_clcs.helper.smoothing import smooth_polyline_subdivision import pickle with open("tests/test_data/reference_path_b.pic", "rb") as f: data = pickle.load(f) original = data["reference_path"] smoothed = smooth_polyline_subdivision(original, degree=2, max_curv=0.15) metrics = compare_ref_path_deviations(original, smoothed, verbose=True) # Output: # delta_s: 0.0034 # delta_d_avg: 0.1123 # delta_d_max: 0.4512 # delta_theta_avg: 0.0031 # delta_theta_max: 0.0210 print(metrics) ``` -------------------------------- ### Extend a Reference Path Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Extends a reference path forwards or backwards by a specified length. It prioritizes using lanelet information from a LaneletNetwork if available, otherwise uses linear extrapolation. ```python import numpy as np from commonroad_clcs.util import extend_reference_path # Short reference path reference_path = np.column_stack((np.linspace(0, 10, 21), np.zeros(21))) ``` -------------------------------- ### Compute Segment Intervals from Polyline Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/00_getting_started.ipynb Calculates segment intervals from a polyline using the compute_segment_intervals_from_polyline utility. Requires numpy for array operations. ```python from commonroad_clcs.util import compute_segment_intervals_from_polyline import numpy as np bla = compute_segment_intervals_from_polyline(ref_path) print(np.max(bla)) print(np.min(bla)) ``` -------------------------------- ### extend_reference_path Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Extends a given reference path either at the front, back, or both, by a specified length. It leverages successor/predecessor lanelet center-points from a CommonRoad `LaneletNetwork` if available, otherwise, it uses linear extrapolation. ```APIDOC ## extend_reference_path — Path extension ### Description Extends a reference path at the front and/or back by a given length. Uses successor/predecessor lanelet center-points from a CommonRoad `LaneletNetwork` when available; otherwise falls back to linear extrapolation. ### Parameters - **reference_path** (np.ndarray) - The initial reference path. - **lanelet_network** (LaneletNetwork, optional) - The LaneletNetwork to query for lanelet connections. Defaults to None. - **extend_front** (float, optional) - The length to extend the path at the front. Defaults to 0.0. - **extend_back** (float, optional) - The length to extend the path at the back. Defaults to 0.0. ### Request Example ```python import numpy as np # Assuming extend_reference_path is imported # Short reference path reference_path = np.column_stack((np.linspace(0, 10, 21), np.zeros(21))) # Example usage (assuming LaneletNetwork is defined and populated) # extended_path = extend_reference_path(reference_path, extend_front=5.0, extend_back=5.0) # print("Extended path shape:", extended_path.shape) ``` ### Response - **extended_path** (np.ndarray) - The extended reference path. ``` -------------------------------- ### convert_list_of_points_to_curvilinear_coords / convert_list_of_points_to_cartesian_coords Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Performs batch conversion of multiple Cartesian points to curvilinear coordinates or vice versa using multi-threading. The number of threads can be specified. ```APIDOC ## convert_list_of_points_to_curvilinear_coords / convert_list_of_points_to_cartesian_coords — Batch conversion ### Description Converts a list (or array) of Cartesian points to curvilinear coordinates (or vice versa) in one call, using multi-threading. The second argument specifies the number of threads. ### Method `convert_list_of_points_to_curvilinear_coords(points: np.ndarray, num_threads: int)` `convert_list_of_points_to_cartesian_coords(points: np.ndarray, num_threads: int)` ### Parameters #### Path Parameters - **points** (np.ndarray) - An array of points, where each point is represented as [x, y] or [s, d]. - **num_threads** (int) - The number of threads to use for the conversion. ### Request Example ```python import numpy as np from commonroad_clcs.pycrccosy import CurvilinearCoordinateSystem reference_path = np.column_stack((np.linspace(0, 20, 41), np.zeros(41))) ccosy = CurvilinearCoordinateSystem(reference_path, 30.0, 0.1, 0.1) # Points inside the projection domain cart_points = np.array([[2.0, 1.0], [5.0, -2.0], [10.0, 3.0], [15.0, 0.5]]) # Cartesian -> Curvilinear (4 threads) curv_points = np.array(ccosy.convert_list_of_points_to_curvilinear_coords(cart_points, 4)) print("Curvilinear points:", curv_points) # Curvilinear -> Cartesian (round-trip check) cart_points_back = np.array(ccosy.convert_list_of_points_to_cartesian_coords(curv_points, 4)) print("Round-trip error:", np.max(np.abs(cart_points_back - cart_points))) ``` ### Response #### Success Response (200) - **points** (np.ndarray) - An array of converted points. ``` -------------------------------- ### Apply Chaikin's Corner Cutting Smoothing Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Applies Chaikin's corner cutting algorithm for polyline smoothing. The number of refinements determines the smoothness; higher values result in more points and a smoother curve. ```python import numpy as np from commonroad_clcs.util import chaikins_corner_cutting polyline = np.array([ [0.0, 0.0], [1.0, 2.0], [3.0, 1.0], [4.0, 3.0], [6.0, 0.0] ]) smoothed = chaikins_corner_cutting(polyline, refinements=4) print("Original points:", len(polyline)) print("After Chaikin (4 refinements):", len(smoothed)) # 2^4 * (N-1) + 1 ``` -------------------------------- ### Plot Reference Path States Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/01_advanced.ipynb Plots the orientation, curvature, and curvature rate of the reference path. This helps in assessing the smoothness of the path and identifying any jerky segments. ```python curvilinear_cosy.plot_reference_states() ``` -------------------------------- ### smooth_polyline_elastic_band Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Smooths a polyline using an elastic band formulation with quadratic programming. It minimizes a combined smoothness and lateral error objective while respecting a maximum lateral deviation constraint. ```APIDOC ## smooth_polyline_elastic_band ### Description Smooths a polyline using a quadratic programming (OSQP) elastic band formulation, minimizing a combined smoothness and lateral error objective subject to a maximum lateral deviation constraint. ### Parameters - **polyline** (np.ndarray) - The input polyline to be smoothed. - **input_resampling** (float) - Coarse pre-resampling step in meters. - **max_deviation** (float) - Maximum lateral shift constraint in meters. - **weight_smooth** (float) - Weight for the smoothness objective. - **weight_lat_error** (float) - Weight for the lateral error objective. - **solver_max_iter** (int) - Maximum number of iterations for the solver. ### Request Example ```python import numpy as np # Assuming smooth_polyline_elastic_band is imported x = np.linspace(0, 20, 100) y = 0.5 * np.sin(0.5 * x) + np.random.normal(0, 0.05, 100) polyline = np.column_stack((x, y)) smoothed = smooth_polyline_elastic_band( polyline, input_resampling=1.0, # coarse pre-resampling step (m) max_deviation=0.15, # max lateral shift constraint (m) weight_smooth=1.0, # smoothness weight weight_lat_error=0.001, # lateral error weight solver_max_iter=20000 ) print("Elastic band smoothed:", smoothed.shape) ``` ### Response - **smoothed** (np.ndarray) - The smoothed polyline. ``` -------------------------------- ### Plot Reference Path Curvature Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/02_ref_path_processing.ipynb Visualize and compare the curvature of original, spline, and subdivision reference paths using matplotlib. Ensure matplotlib and the helper function are imported. ```python from matplotlib import pyplot as plt from commonroad_clcs.helper.evaluation import plot_ref_path_curvature # create fig fig, axs = plt.subplots(2) # plot curvatures plot_ref_path_curvature(ref_path_original, axs=axs, label="original", linestyle="dashed") plot_ref_path_curvature(ref_path_spline, axs=axs, label="spline") plot_ref_path_curvature(ref_path_cs, axs=axs, label="subdivision") ``` -------------------------------- ### Visualize Projection Domain Source: https://github.com/commonroad/commonroad-clcs/blob/main/tutorials/notebooks/01_advanced.ipynb Visualizes the projection domain of the CLCS, which represents the area where points can be uniquely transformed between Cartesian and curvilinear frames. This is useful for debugging potential issues in downstream tasks. ```python from commonroad.visualization.mp_renderer import MPRenderer from commonroad_clcs.helper.visualization import plot_scenario_and_clcs rnd = MPRenderer(figsize=(7, 10), plot_limits=[-6, 34.0, -10, 55]) plot_scenario_and_clcs( scenario, curvilinear_cosy, renderer=rnd, proj_domain_plot="full" ) ``` -------------------------------- ### Smooth Polyline using B-spline Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Fit an approximating B-spline to a polyline. Adjust the 'smoothing_factor' to balance fit accuracy and smoothness, where 0.0 results in an interpolating spline. ```python import numpy as np from commonroad_clcs.helper.smoothing import smooth_polyline_spline ``` -------------------------------- ### Detect Inflection Points in a Polyline Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Identifies inflection points in a polyline where the curvature changes sign. This is useful for segmenting paths into regions of consistent curvature. ```python import numpy as np from commonroad_clcs.util import get_inflection_points # S-curve polyline theta = np.linspace(0, 2 * np.pi, 200) polyline = np.column_stack((theta, np.sin(theta))) inflection_pts, inflection_idx = get_inflection_points(polyline, digits=4) print("Inflection point indices:", inflection_idx) print("Inflection point coordinates: ", inflection_pts) ``` -------------------------------- ### compute_curvature_from_polyline_python Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Computes the signed curvature at each vertex of a polyline. It uses numerical differentiation of the polyline's x and y coordinates with respect to arc-length. ```APIDOC ## compute_curvature_from_polyline_python — Curvature computation ### Description Computes the signed curvature at each vertex of a polyline using numerical differentiation of x and y with respect to arc-length. ### Parameters - **polyline** (np.ndarray) - The input polyline. ### Request Example ```python import numpy as np # Assuming compute_curvature_from_polyline_python is imported # Circle of radius 5 → curvature = 1/5 = 0.2 everywhere theta = np.linspace(0, 2 * np.pi, 200) polyline = np.column_stack((5 * np.cos(theta), 5 * np.sin(theta))) curv = compute_curvature_from_polyline_python(polyline) print("Mean curvature:", np.mean(curv)) # ≈ 0.2 print("Max curvature:", np.max(np.abs(curv))) ``` ### Response - **curv** (np.ndarray) - An array of signed curvature values for each vertex. ``` -------------------------------- ### Smooth Polyline using Subdivision Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Smooth a polyline using the Lane-Riesenfeld subdivision algorithm. The process continues until maximum curvature or deviation limits are met. Set 'verbose=True' to see iteration counts. ```python import numpy as np import pickle from commonroad_clcs.helper.smoothing import smooth_polyline_subdivision with open("tests/test_data/reference_path_b.pic", "rb") as f: data = pickle.load(f) reference_path = data["reference_path"] smoothed = smooth_polyline_subdivision( reference_path, degree=2, # cubic B-spline limit refinements=3, # subdivision steps per iteration coarse_resampling=2.0, # resampling step during iterations (m) max_curv=0.1, # target max curvature (1/m) max_dev=3.0, # max lateral deviation (m) max_iter=300, verbose=True # prints iteration count ) print("Smoothed path:", smoothed.shape) ``` -------------------------------- ### Smooth Polyline using Spline Interpolation Source: https://context7.com/commonroad/commonroad-clcs/llms.txt Smooths a polyline using a cubic B-spline. Adjust the smoothing_factor to control the trade-off between smoothness and faithfulness to the original data. ```python import numpy as np from commonroad_clcs.helper.smoothing import smooth_polyline_spline x = np.linspace(0, 10, 30) y = np.sin(x) + np.random.normal(0, 0.1, 30) polyline = np.column_stack((x, y)) smoothed = smooth_polyline_spline( polyline, degree=3, # cubic B-spline smoothing_factor=5.0 # larger = smoother, less faithful to data ) print("Spline-smoothed path:", smoothed.shape) ```