### Development Setup Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/installation.md Set up a development environment by cloning the repository and installing dependencies in development mode using uv. Requires uv and rustup. ```bash git clone https://github.com/Davidham3/traj-dist-rs.git cd traj-dist-rs uv sync --dev --all-extras ``` -------------------------------- ### Python Quick Start Examples Source: https://github.com/davidham3/traj-dist-rs/blob/main/README.md Demonstrates how to calculate various trajectory distances (SSPD, DTW, Hausdorff) and perform batch computations using the traj-dist-rs Python library. Ensure trajectories are defined as lists of coordinates or NumPy arrays. ```python import numpy as np import traj_dist_rs # Define trajectories as list of [x, y] coordinates or numpy arrays traj1 = [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]] traj2 = [[0.1, 0.1], [1.1, 1.1], [2.1, 2.1]] # Calculate SSPD distance distance = traj_dist_rs.sspd(traj1, traj2, dist_type="euclidean") print(f"SSPD distance: {distance}") # Calculate DTW distance (returns DpResult with distance and optional matrix) result = traj_dist_rs.dtw(traj1, traj2, dist_type="euclidean", use_full_matrix=False) print(f"DTW distance: {result.distance}") # Calculate Hausdorff distance distance = traj_dist_rs.hausdorff(traj1, traj2, dist_type="spherical") print(f"Hausdorff distance: {distance}") # Batch computation with pdist (pairwise distances) trajectories = [np.array([[0.0, 0.0], [1.0, 1.0]]) for _ in range(10)] metric = traj_dist_rs.Metric.sspd(type_d="euclidean") distances = traj_dist_rs.pdist(trajectories, metric=metric, parallel=True) print(f"Computed {len(distances)} pairwise distances") # With progress bar (rendered to stderr) distances = traj_dist_rs.pdist(trajectories, metric=metric, parallel=True, show_progress=True) # Cross-distance computation with cdist dist_matrix = traj_dist_rs.cdist(trajectories[:5], trajectories[5:], metric=metric) print(f"Distance matrix shape: {dist_matrix.shape}") ``` -------------------------------- ### Rust Quick Start Examples Source: https://github.com/davidham3/traj-dist-rs/blob/main/README.md Illustrates calculating SSPD and DTW distances, and performing batch pairwise distance computations using the traj-dist-rs Rust library. Requires importing necessary modules and defining trajectories as vectors of coordinate pairs. ```rust use traj_dist_rs::distance::sspd::sspd; use traj_dist_rs::distance::dtw::dtw; use traj_dist_rs::distance::base::TrajectoryCalculator; use traj_dist_rs::distance::distance_type::DistanceType; use traj_dist_rs::distance::batch::{pdist, Metric, DistanceAlgorithm}; fn main() { let traj1 = vec![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]; let traj2 = vec![[0.1, 0.1], [1.1, 1.1], [2.1, 2.1]]; // Calculate SSPD distance let dist = sspd(&traj1, &traj2, DistanceType::Euclidean); println!("SSPD distance: {}", dist); // Calculate DTW distance let calculator = TrajectoryCalculator::new(&traj1, &traj2, DistanceType::Euclidean); let result = dtw(&calculator, false); println!("DTW distance: {}", result.distance); // Batch computation with pdist let trajectories = vec![ vec![[0.0, 0.0], [1.0, 1.0]], vec![[0.0, 1.0], [1.0, 0.0]], vec![[0.5, 0.5], [1.5, 1.5]], ]; let metric = Metric::new(DistanceAlgorithm::SSPD, DistanceType::Euclidean); let distances = pdist(&trajectories, &metric, true, true).unwrap(); println!("Computed {} pairwise distances", distances.len()); } ``` -------------------------------- ### Install from Source Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/installation.md Clone the repository and install the package from source using uv. Requires uv and rustup. ```bash git clone https://github.com/Davidham3/traj-dist-rs.git cd traj-dist-rs uv pip install . ``` -------------------------------- ### Usage Examples Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/_COMPLETION_REPORT.txt Production-ready code examples in Python and Rust, with explanations, demonstrating various usage patterns. ```APIDOC ## Usage Examples ### Description This section provides practical, production-ready code examples in both Python and Rust to illustrate common usage patterns and demonstrate the library's capabilities. ### Source File Location usage-examples.md ### Key Information - **Languages**: Python, Rust - **Examples**: 8 Python + 7 Rust examples. - **Content**: Code patterns with explanations. - **Format**: Markdown with code blocks. ``` -------------------------------- ### Install from PyPI Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/installation.md Use pip to install the traj-dist-rs package from the Python Package Index. ```bash pip install traj-dist-rs ``` -------------------------------- ### Install uv Package Manager (Linux/macOS) Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Installs the uv Python package manager using a script. Ensure you have curl installed. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Configuration Options Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/_COMPLETION_REPORT.txt Guide to configuration parameters and options, including decision guides, use cases, and performance tuning advice. ```APIDOC ## Configuration Options ### Description This section details the configuration parameters and options available for the library, offering decision guides, use case examples, and performance tuning tips. ### Source File Location configuration.md ### Key Information - **Content**: Parameters, options, use cases, performance tuning. - **Format**: Markdown with parameter reference tables. ``` -------------------------------- ### Install traj-dist-rs Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/usage_for_python.ipynb Install the traj-dist-rs package using pip. Uncomment the line to install. ```python # Uncomment to install # !pip install traj-dist-rs ``` -------------------------------- ### Install uv Package Manager (Windows) Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Installs the uv Python package manager using a PowerShell script. ```powershell powershell -c "irm https://astral.sh/uv/install.ps1 | iex" ``` -------------------------------- ### Verify traj-dist-rs Installation Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Activates the virtual environment and verifies the traj-dist-rs installation by importing it in Python. ```bash source .venv/bin/activate python -c "import traj_dist_rs; print('traj-dist-rs installed successfully')" ``` -------------------------------- ### Install traj-dist Environment Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Sets up the Python environment for traj-dist, including dependencies and building the package. Assumes you are in the traj-dist directory. ```bash cd traj-dist bash scripts/setup_traj_dist_env.sh ``` -------------------------------- ### Full DP Matrix Storage Example Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/types.md Illustrates the row-major layout of a full DP matrix for algorithms like DTW. The example shows a 4x3 matrix and the formula for accessing elements using `matrix[i * cols + j]`. ```plaintext # DP matrix dimensions: (3+1) × (2+1) = 4 × 3 # Flattened array length: 12 elements # Row-major layout: # [0][0] [0][1] [0][2] # [1][0] [1][1] [1][2] # [2][0] [2][1] [2][2] # [3][0] [3][1] [3][2] # Access: `matrix[i * (cols) + j]` = `matrix[i * 3 + j]` ``` -------------------------------- ### Import and Print Version Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/usage_for_python.ipynb Import the traj-dist-rs library and print its version. This is a basic setup step. ```python import traj_dist_rs import numpy as np print(f"traj_dist_rs version: {traj_dist_rs.__version__}") ``` -------------------------------- ### Install traj-dist-rs from source using uv Source: https://github.com/davidham3/traj-dist-rs/blob/main/README.md Builds and installs the traj-dist-rs library from its source code using uv. This method requires Rust 1.85 or later and assumes you have cloned the repository. ```bash # Clone the repository git clone https://github.com/Davidham3/traj-dist-rs.git cd traj-dist-rs # Compile and install via uv uv pip install . ``` -------------------------------- ### Verify traj-dist Installation Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Activates the virtual environment and verifies the traj-dist installation by importing it in Python. ```bash source .venv/bin/activate cd /tmp python -c "import traj_dist; print('traj-dist installed successfully')" ``` -------------------------------- ### Install traj-dist-rs Environment and Bindings Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Installs development dependencies for traj-dist-rs and builds its Python bindings in release mode for optimal performance. Assumes you are in the traj-dist-rs directory. ```bash cd traj-dist-rs uv sync --dev --all-extras maturin develop --release ``` -------------------------------- ### Install traj-dist-rs with test dependencies Source: https://github.com/davidham3/traj-dist-rs/blob/main/README.md Installs the traj-dist-rs library from PyPI along with its test dependencies, suitable for development and testing purposes. ```bash pip install traj-dist-rs[test] ``` -------------------------------- ### Verify uv Installation Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Checks if the uv package manager is installed and accessible. ```bash uv --version ``` -------------------------------- ### DpResult Example Usage Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/types.md Demonstrates calling the dtw function with and without computing the full DP matrix, and accessing its properties. ```python import traj_dist_rs traj1 = [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]] traj2 = [[0.1, 0.1], [1.1, 1.1], [2.1, 2.1]] # Without matrix result = traj_dist_rs.dtw(traj1, traj2, "euclidean", use_full_matrix=False) print(result.distance) # 0.1414... print(result.matrix) # None # With matrix result = traj_dist_rs.dtw(traj1, traj2, "euclidean", use_full_matrix=True) print(result.distance) # 0.1414... print(result.matrix.shape) # (4, 4) - (3+1, 3+1) # Access matrix values matrix_2d = result.matrix.reshape((4, 4)) print(matrix_2d[3, 3]) # The final DP value (same as result.distance) ``` -------------------------------- ### Install Rust and Cargo Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Installs Rust and Cargo, the build system and package manager for Rust. This is required for traj-dist-rs. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env ``` -------------------------------- ### Python Progress Display for Large Datasets Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/MANIFEST.md Shows how to display progress for long-running computations on large datasets. This requires the `tqdm` library to be installed. ```python from traj_dist import TrajCollection, Levenshtein from tqdm import tqdm # Assume tc is a large TrajCollection # For demonstration, create a small one traj1 = [(0, 0), (1, 1)] traj2 = [(0, 0), (2, 2)] tc = TrajCollection([traj1, traj2]) # Use tqdm to wrap the pdist calculation pdist_result = Levenshtein.pdist(tc, progress_callback=tqdm.update) print("Progress display complete.") ``` -------------------------------- ### Python Trajectory Format Example Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/README.md Demonstrates the expected format for trajectories in Python, using lists or NumPy arrays. ```python trajectory = [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]] trajectory = np.array([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]) ``` -------------------------------- ### Verify Rust and Cargo Installation Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Checks if the Rust compiler (rustc) and Cargo are installed and accessible. ```bash rustc --version cargo --version ``` -------------------------------- ### Rust Trajectory Format Example Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/README.md Shows the expected format for trajectories in Rust, using a Vec of [f64; 2] or any type implementing CoordSequence. ```rust let trajectory: Vec<[f64; 2]> = vec![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]; ``` -------------------------------- ### Python Basic Distance Calculation Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/MANIFEST.md Demonstrates a basic distance calculation in Python. Ensure the library is installed and imported. ```python from traj_dist import TrajCollection, Levenshtein # Example trajectories (replace with your actual data) traj1 = [(0, 0), (1, 1), (2, 2)] traj2 = [(0, 0), (1, 0), (2, 2)] # Create a TrajCollection tc = TrajCollection([traj1, traj2]) # Calculate Levenshtein distance dist = Levenshtein.calc(tc) print(f"Levenshtein distance: {dist}") ``` -------------------------------- ### Rust Usage of Distance Types Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/configuration.md Shows how to instantiate metrics with supported distance types in Rust, including examples for fully supported and Euclidean-only algorithms. ```rust use traj_dist_rs::distance::distance_type::DistanceType; use traj_dist_rs::distance::batch::{Metric, DistanceAlgorithm}; // Full support let metric = Metric::new(DistanceAlgorithm::DTW, DistanceType::Spherical); // Euclidean only let metric = Metric::new(DistanceAlgorithm::EDwP, DistanceType::Euclidean); // Panics if Spherical is used // let metric = Metric::new(DistanceAlgorithm::Frechet, DistanceType::Spherical); // This will panic in the distance computation ``` -------------------------------- ### DpResult Python Usage Example Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/types.md Demonstrates accessing the distance and matrix properties of a DpResult object in Python. ```python result = traj_dist_rs.dtw(t1, t2, "euclidean", use_full_matrix=True) print(result.distance) # float: the distance value print(result.matrix) # numpy array or None ``` -------------------------------- ### Rust Memory-Efficient Processing Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/MANIFEST.md Demonstrates memory-efficient processing of trajectories in Rust. This example focuses on iterating through data without loading everything into memory at once. ```rust use traj_dist::trajectory::Trajectory; fn process_trajectory_chunk(chunk: &[Trajectory]) { // Process a chunk of trajectories efficiently for traj in chunk { // Perform operations on traj } } fn main() { // Assume trajectories are loaded or streamed in chunks let trajectories: Vec = vec![ vec![(0.0, 0.0)].into(), vec![(1.0, 1.0)].into() ]; // Process in chunks to save memory process_trajectory_chunk(&trajectories); println!("Memory-efficient processing simulated."); } ``` -------------------------------- ### Batch Computation API Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/_COMPLETION_REPORT.txt Documentation for batch processing functions (pdist/cdist) and metric configuration, including support matrices and examples. ```APIDOC ## Batch Computation API ### Description This section covers the API for batch computation, including functions like `pdist` and `cdist`, along with guidance on metric configuration and support matrices. ### Source File Location batch-computation.md ### Key Information - **Functions Documented**: 2 (pdist, cdist) - **Content**: Operation guides, support matrix, examples. - **Format**: Markdown with structured tables and code blocks. ``` -------------------------------- ### Rust Metric Construction Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/types.md Demonstrates how to construct a Metric object using the Metric::new constructor. Examples show creating a metric for SSPD with Euclidean distance and LCSS with Euclidean distance and a specified epsilon. ```rust use traj_dist_rs::distance::batch::{Metric, DistanceAlgorithm, DistanceType}; let metric = Metric::new( DistanceAlgorithm::SSPD, DistanceType::Euclidean ); let metric_lcss = Metric::new( DistanceAlgorithm::LCSS { eps: 5.0 }, DistanceType::Euclidean ); ``` -------------------------------- ### Display Progress for Large Datasets Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/usage-examples.md Monitor progress during batch computation of trajectory distances. This example shows how to enable progress display for large datasets, which is useful for user feedback. ```python import traj_dist_rs import numpy as np ``` -------------------------------- ### Python Example for Spherical Distance Optimization Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/configuration.md Illustrates the usage of Spherical distance in Python, highlighting that traj-dist-rs automatically applies optimizations for performance. ```python # Spherical distance with automatic optimization result = traj_dist_rs.dtw(traj1, traj2, "spherical") # Internally: TrajectoryCalculator creates SphericalTrajectoryCache # for both trajectories, eliminating trig recalculation overhead ``` -------------------------------- ### Distance Functions API Reference Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/_COMPLETION_REPORT.txt Provides detailed documentation for 9 distance algorithms, including their signatures, parameters, return types, and examples. ```APIDOC ## Distance Functions API Reference ### Description This section details the 9 distance algorithms available in the library. It includes function signatures with types, parameter tables, return type documentation, and code examples. ### Source File Location distance-functions.md ### Key Information - **Algorithms Documented**: 9 - **Content**: Signatures, parameters, return types, examples, complexity, error conditions. - **Format**: Markdown with structured tables and code blocks. ``` -------------------------------- ### Import traj_dist_rs in Rust Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/module-index.md Shows how to import specific items or entire modules from the traj_dist_rs library in Rust. Examples include importing specific functions and using full paths. ```rust // Import specific items use traj_dist_rs::distance::sspd::sspd; use traj_dist_rs::distance::batch::{pdist, Metric}; // Or import entire module use traj_dist_rs::distance; // Or use full paths let metric = traj_dist_rs::distance::batch::Metric::new(...); ``` -------------------------------- ### Define and Print Trajectories Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/usage_for_rust.ipynb Defines two sample trajectories as vectors of [x, y] coordinates and prints them to the console. This serves as a basic setup for distance calculations. ```rust // Define two trajectories as vectors of [x, y] coordinates let traj1: Vec<[f64; 2]> = vec![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]; let traj2: Vec<[f64; 2]> = vec![[0.1, 0.1], [1.1, 1.1], [2.1, 2.1]]; println!("Trajectory 1: {:?}", traj1); println!("Trajectory 2: {:?}", traj2); ``` -------------------------------- ### Rust Error Handling Patterns Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/MANIFEST.md Demonstrates common error handling patterns when working with trajectory distances in Rust. This example shows how to handle potential errors gracefully. ```rust use traj_dist::distance::levenshtein::Levenshtein; use traj_dist::trajectory::Trajectory; use traj_dist::errors::TrajDistError; fn calculate_distance(traj1: &Trajectory, traj2: &Trajectory) -> Result { // In a real scenario, this might return an error Ok(Levenshtein::calc(traj1, traj2)) } fn main() { let traj1: Trajectory = vec![(0.0, 0.0)].into(); let traj2: Trajectory = vec![(0.0, 0.0)].into(); match calculate_distance(&traj1, &traj2) { Ok(dist) => println!("Distance calculated: {}", dist), Err(e) => eprintln!("Error calculating distance: {}", e), } } ``` -------------------------------- ### Configure and Use Metrics with Different Algorithms Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/usage_for_rust.ipynb Demonstrates creating and using Metric objects for various distance algorithms, including those with specific parameters. Shows batch computation of distances between trajectories. ```python let traj1: Vec<[f64; 2]> = vec![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]; let traj2: Vec<[f64; 2]> = vec![[0.1, 0.1], [1.1, 1.1], [2.1, 2.1]]; // Create metrics for different algorithms let metric_sspd = Metric::new(DistanceAlgorithm::SSPD, DistanceType::Euclidean); let metric_dtw = Metric::new(DistanceAlgorithm::DTW, DistanceType::Euclidean); let metric_hausdorff = Metric::new(DistanceAlgorithm::Hausdorff, DistanceType::Euclidean); let metric_discret_frechet = Metric::new(DistanceAlgorithm::DiscretFrechet, DistanceType::Euclidean); // Algorithms with parameters let metric_lcss = Metric::new(DistanceAlgorithm::LCSS { eps: 0.5 }, DistanceType::Euclidean); let metric_edr = Metric::new(DistanceAlgorithm::EDR { eps: 0.5 }, DistanceType::Euclidean); let metric_erp = Metric::new(DistanceAlgorithm::ERP { g: [0.0, 0.0] }, DistanceType::Euclidean); // Use metrics with batch computation let trajectories = vec![traj1, traj2]; let distances_sspd = pdist(&trajectories, &metric_sspd, true, false).unwrap(); let distances_dtw = pdist(&trajectories, &metric_dtw, true, false).unwrap(); let distances_lcss = pdist(&trajectories, &metric_lcss, true, false).unwrap(); println!("SSPD distance: {:.4}", distances_sspd[0]); println!("DTW distance: {:.4}", distances_dtw[0]); println!("LCSS distance: {:.4}", distances_lcss[0]); ``` -------------------------------- ### Rust: Using Different Distance Algorithms Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/usage-examples.md Illustrates how to compute distances using various algorithms like SSPD, Hausdorff, and DTW. It shows the difference between simple algorithms and dynamic programming algorithms that require a `TrajectoryCalculator`. ```rust use traj_dist_rs::distance::{ sspd::sspd, dtw::dtw, hausdorff::hausdorff, base::TrajectoryCalculator, distance_type::DistanceType, }; fn main() { let traj1 = vec![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]; let traj2 = vec![[0.1, 0.1], [1.1, 1.1], [2.1, 2.1], [3.1, 3.1]]; let dist_type = DistanceType::Euclidean; // Simple algorithms (no calculator needed) let sspd_dist = sspd(&traj1, &traj2, dist_type); let hausdorff_dist = hausdorff(&traj1, &traj2, dist_type); println!("SSPD: {:.6}", sspd_dist); println!("Hausdorff: {:.6}", hausdorff_dist); // DP algorithms (require calculator) let calculator = TrajectoryCalculator::new(&traj1, &traj2, dist_type); let dtw_result = dtw(&calculator, false); println!("DTW: {:.6}", dtw_result.distance); // DTW with matrix let dtw_result_matrix = dtw(&calculator, true); if let Some(matrix) = &dtw_result_matrix.matrix { let n0 = traj1.len() + 1; let n1 = traj2.len() + 1; println!("DTW matrix shape: {}x{}", n0, n1); println!("Final DP value: {:.6}", matrix[matrix.len() - 1]); } } ``` -------------------------------- ### Run Benchmark with Quick Test Parameters Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Executes a quick benchmark test, suitable for debugging, with reduced numbers for trajectory pairs, warmup runs, and measurement runs. ```bash K=50 WARMUP_RUNS=3 NUM_RUNS=10 bash scripts/benchmark/run_benchmark.sh ``` -------------------------------- ### View Performance Report Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Use this command to display the generated performance comparison report after benchmark execution. ```bash cat traj-dist-rs/mk_docs/docs/performance.md ``` -------------------------------- ### Run Benchmark with Default Parameters Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/benchmark_guide.md Executes the benchmark script with specified parameters for trajectory pairs, warmup runs, and measurement runs. Assumes you are in the traj-dist-rs directory. ```bash cd traj-dist-rs K=1000 WARMUP_RUNS=10 NUM_RUNS=50 bash scripts/benchmark/run_benchmark.sh ``` -------------------------------- ### Python Usage of Algorithms Without Parameters Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/configuration.md Demonstrates calling algorithms like SSPD and DTW in Python when no additional parameters beyond trajectories and distance type are required. ```python # No additional parameters needed result = traj_dist_rs.sspd(traj1, traj2, "euclidean") metric = traj_dist_rs.Metric.dtw(type_d="euclidean") ``` -------------------------------- ### Run Integration Tests and Build Script Source: https://github.com/davidham3/traj-dist-rs/blob/main/README.md Execute the pre-build script to format code, run linters, execute all tests, and generate Python stub files. This script is essential for daily development and ensuring code quality. ```bash bash scripts/pre_build.sh ``` -------------------------------- ### Python Comparing Algorithms Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/MANIFEST.md Illustrates how to compare the results of different distance algorithms on the same trajectories. This helps in choosing the most suitable algorithm for a specific task. ```python from traj_dist import TrajCollection, Levenshtein, Frechet # Example trajectories traj1 = [(0, 0), (1, 1), (2, 2)] traj2 = [(0, 0), (1, 0), (2, 2)] tc = TrajCollection([traj1, traj2]) # Calculate distances using different algorithms lev_dist = Levenshtein.calc(tc) frechet_dist = Frechet.calc(tc) print(f"Levenshtein distance: {lev_dist}") print(f"Frechet distance: {frechet_dist}") ``` -------------------------------- ### Using PrecomputedDistanceCalculator for DTW Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/usage_for_rust.ipynb Demonstrates how to initialize and use PrecomputedDistanceCalculator with a predefined distance matrix for DTW calculations. Compares the result with on-the-fly Euclidean distance calculation. ```rust // TrajectoryCalculator, PrecomputedDistanceCalculator, DistanceType, dtw // are all already imported above. // Precomputed distance matrix in row-major order (index = row * ncols + col) let matrix = vec![ 0.0f64, 1.0, 2.0, // point 0 → traj2[0], traj2[1], traj2[2] 1.0, 0.0, 1.0, // point 1 → traj2[0], traj2[1], traj2[2] ]; // PrecomputedDistanceCalculator implements DistanceCalculator, // so it can be passed to any DP-based algorithm (dtw, lcss, edr, erp, discret_frechet) { let calc = PrecomputedDistanceCalculator::new(&matrix, 2, 3); println!("DTW (precomputed): {:.4}", dtw(&calc, false).distance); } // Compare with TrajectoryCalculator on the same distance values let traj1 = vec![[0.0, 0.0], [1.0, 0.0]]; let traj2 = vec![[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]; { let calc = TrajectoryCalculator::new(&traj1, &traj2, DistanceType::Euclidean); println!("DTW (trajectory): {:.4}", dtw(&calc, false).distance); } ``` -------------------------------- ### Python Performance Tips Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/quick-reference.md Provides recommendations for optimizing performance in Python, including using NumPy arrays, enabling parallelization, and avoiding unnecessary matrix computations for large datasets. ```python # ✓ Use numpy arrays trajectories = [np.array(t) for t in trajectories] # ✓ Enable parallelization pdist(trajectories, metric, parallel=True) # ✓ Avoid full matrix for large trajectories dtw(t1, t2, "euclidean", use_full_matrix=False) # ✓ Process large datasets in batches for batch in batches: pdist(batch, metric, parallel=True) # ✗ Don't use Python lists if you can use numpy # ✗ Don't compute full matrix unless needed # ✗ Don't process entire dataset at once for very large inputs ``` -------------------------------- ### Rust Basic Distance Calculation Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/MANIFEST.md A basic example of calculating distance between two trajectories in Rust. Ensure the `traj_dist` crate is added as a dependency. ```rust use traj_dist::distance::levenshtein::Levenshtein; use traj_dist::trajectory::Trajectory; fn main() { let traj1: Trajectory = vec![(0.0, 0.0), (1.0, 1.0), (2.0, 2.0)].into(); let traj2: Trajectory = vec![(0.0, 0.0), (1.0, 0.0), (2.0, 2.0)].into(); let distance = Levenshtein::calc(&traj1, &traj2); println!("Levenshtein distance: {}", distance); } ``` -------------------------------- ### Rust Performance Tips Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/quick-reference.md Offers performance advice for Rust users, emphasizing the use of `Vec<[f64; 2]>` or slices, enabling parallel processing, and reusing `TrajectoryCalculator` instances. ```rust # ✓ Use Vec<[f64; 2]> or slice &[[f64; 2]] let trajectory: Vec<[f64; 2]> = vec![[0.0, 0.0], [1.0, 1.0]]; # ✓ Enable parallel processing pdist(&trajectories, &metric, true, false)? # ✓ Reuse TrajectoryCalculator let calc = TrajectoryCalculator::new(&t1, &t2, DistanceType::Euclidean); let result1 = dtw(&calc, false); let result2 = lcss(&calc, 5.0, false); # ✗ Don't use shared mutable state in parallel code # ✗ Don't compute unnecessary matrices # ✗ Don't clone large trajectory data unnecessarily ``` -------------------------------- ### Metric API Configuration Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/usage_for_python.ipynb Shows how to configure different distance algorithms using the Metric API and use them with batch computation. Trajectories must be defined. ```python import traj_dist_rs import numpy as np traj1 = np.array([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]) traj2 = np.array([[0.1, 0.1], [1.1, 1.1], [2.1, 2.1]]) # Create metrics for different algorithms metric_sspd = traj_dist_rs.Metric.sspd(type_d="euclidean") metric_dtw = traj_dist_rs.Metric.dtw(type_d="euclidean") metric_hausdorff = traj_dist_rs.Metric.hausdorff(type_d="euclidean") metric_discret_frechet = traj_dist_rs.Metric.discret_frechet(type_d="euclidean") # Algorithms with parameters metric_lcss = traj_dist_rs.Metric.lcss(eps=0.5, type_d="euclidean") metric_edr = traj_dist_rs.Metric.edr(eps=0.5, type_d="euclidean") metric_erp = traj_dist_rs.Metric.erp(g=[0.0, 0.0], type_d="euclidean") # Use metrics with batch computation trajectories = [traj1, traj2] distances_sspd = traj_dist_rs.pdist(trajectories, metric=metric_sspd) distances_dtw = traj_dist_rs.pdist(trajectories, metric=metric_dtw) distances_lcss = traj_dist_rs.pdist(trajectories, metric=metric_lcss) print(f"SSPD distance: {distances_sspd[0]:.4f}") print(f"DTW distance: {distances_dtw[0]:.4f}") print(f"LCSS distance: {distances_lcss[0]:.4f}") ``` -------------------------------- ### Handling Rust InvalidParams Error in pdist Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/errors.md Example of how to match and handle the InvalidParams error variant when calling the Rust pdist function with insufficient trajectories. ```rust use traj_dist_rs::distance::batch::{pdist, Metric, DistanceAlgorithm, DistanceType}; let trajectories = vec![vec![[0.0, 0.0], [1.0, 1.0]]]; let metric = Metric::new(DistanceAlgorithm::SSPD, DistanceType::Euclidean); match pdist(&trajectories, &metric, true, false) { Ok(distances) => println!("Success: {} distances", distances.len()), Err(TrajDistError::InvalidParams(msg)) => { eprintln!("Invalid parameters: {}", msg); } Err(e) => eprintln!("Error: {}", e), } ``` -------------------------------- ### Python Type Validation Example Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/errors.md Demonstrates valid and invalid inputs for trajectory data types and epsilon values, catching TypeError or ValueError during processing. ```python import traj_dist_rs import numpy as np # Valid inputs t1_list = [[0.0, 0.0], [1.0, 1.0]] t1_array = np.array([[0.0, 0.0], [1.0, 1.0]]) result1 = traj_dist_rs.sspd(t1_list, t1_list, "euclidean") result2 = traj_dist_rs.sspd(t1_array, t1_array, "euclidean") # Invalid input (will raise TypeError) try: t1_invalid = [[0, "invalid"], [1, 2]] result = traj_dist_rs.sspd(t1_invalid, t1_list, "euclidean") except (TypeError, ValueError) as e: print(f"Type conversion failed: {e}") ``` -------------------------------- ### Visualizing Trajectories and Distances with Matplotlib Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/usage_for_python.ipynb Plot two trajectories and display calculated distances (SSPD, DTW, Hausdorff) on the plot title. Requires matplotlib to be installed. ```python import traj_dist_rs import matplotlib.pyplot as plt # Create trajectories for visualization traj1 = [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]] traj2 = [[0.0, 1.0], [1.0, 0.0], [2.0, 3.0], [3.0, 2.0]] # Calculate distances sspd_dist = traj_dist_rs.sspd(traj1, traj2, "euclidean") dtw_dist = traj_dist_rs.dtw(traj1, traj2, "euclidean") hausdorff_dist = traj_dist_rs.hausdorff(traj1, traj2, "euclidean") # Plot trajectories plt.figure(figsize=(10, 6)) traj1_x, traj1_y = zip(*traj1) traj2_x, traj2_y = zip(*traj2) plt.plot(traj1_x, traj1_y, 'b-o', label='Trajectory 1', linewidth=2, markersize=8) plt.plot(traj2_x, traj2_y, 'r-s', label='Trajectory 2', linewidth=2, markersize=8) plt.title(f'Trajectory Comparison\nSSPD: {sspd_dist:.3f}, DTW: {dtw_dist.distance:.3f}, Hausdorff: {hausdorff_dist:.3f}') plt.xlabel('X coordinate') plt.ylabel('Y coordinate') plt.legend() plt.grid(True, linestyle='--', alpha=0.6) plt.show() ``` -------------------------------- ### Wrong Trajectory Format Example Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/quick-reference.md Illustrates a common mistake where a single point is provided instead of a sequence of points for a trajectory. The correct format is a list of points. ```python # Wrong: single point instead of trajectory distance = traj_dist_rs.sspd([0, 0], [1, 1], "euclidean") # Right: trajectory is sequence of points distance = traj_dist_rs.sspd([[0, 0], [1, 1]], [[0, 1], [1, 0]], "euclidean") ``` -------------------------------- ### Get Full DP Matrix Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/quick-reference.md Calculate the DTW distance and retrieve the full DP matrix. The matrix can be reshaped for further analysis. This is useful for visualizing the alignment path. ```python result = traj_dist_rs.dtw(traj1, traj2, "euclidean", use_full_matrix=True) if result.matrix is not None: # Reshape to 2D matrix_2d = result.matrix.reshape((len(traj1) + 1, len(traj2) + 1)) print("Final DP value:", matrix_2d[-1, -1]) ``` -------------------------------- ### Import traj_dist_rs in Python Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/module-index.md Demonstrates how to import and use the traj_dist_rs library in Python. All functionality is available directly from the root namespace. ```python # Direct imports from main package import traj_dist_rs metric = traj_dist_rs.Metric.dtw() result = traj_dist_rs.dtw(t1, t2, "euclidean") # All functionality is in the root namespace # No submodules exposed in Python ``` -------------------------------- ### Using Spherical Metric with Euclidean-Only Algorithm Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/quick-reference.md Demonstrates an error that occurs when attempting to use the 'spherical' distance type with an algorithm that only supports 'euclidean'. Frechet is an example of such an algorithm. ```python # Wrong: Frechet doesn't support spherical metric = traj_dist_rs.Metric.frechet(type_d="spherical") # Error # Right: Frechet is Euclidean only metric = traj_dist_rs.Metric.frechet() # OK ``` -------------------------------- ### Python Metric Factory Methods Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/README.md Demonstrates how to instantiate various distance metrics using factory methods in the Python API. Specify distance types like 'euclidean' and parameters like 'eps' or 'g' where required. ```python traj_dist_rs.Metric.sspd(type_d="euclidean") traj_dist_rs.Metric.dtw(type_d="euclidean") traj_dist_rs.Metric.hausdorff(type_d="euclidean") traj_dist_rs.Metric.lcss(eps, type_d="euclidean") traj_dist_rs.Metric.edr(eps, type_d="euclidean") traj_dist_rs.Metric.erp(g, type_d="euclidean") traj_dist_rs.Metric.discret_frechet(type_d="euclidean") traj_dist_rs.Metric.edwp() traj_dist_rs.Metric.frechet() ``` -------------------------------- ### Rust Multiple Algorithms Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/MANIFEST.md Shows how to use multiple distance algorithms within a single Rust program. This allows for comparing results or choosing the best algorithm for a task. ```rust use traj_dist::distance::{levenshtein::Levenshtein, frechet::Frechet}; use traj_dist::trajectory::Trajectory; fn main() { let traj1: Trajectory = vec![(0.0, 0.0), (1.0, 1.0)].into(); let traj2: Trajectory = vec![(0.0, 0.0), (2.0, 2.0)].into(); let levenshtein_dist = Levenshtein::calc(&traj1, &traj2); let frechet_dist = Frechet::calc(&traj1, &traj2); println!("Levenshtein distance: {}", levenshtein_dist); println!("Frechet distance: {}", frechet_dist); } ``` -------------------------------- ### DTW Calculation (Rust) Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/distance-functions.md Performs Dynamic Time Warping using a pre-configured TrajectoryCalculator. This Rust example demonstrates the core DTW computation without returning the full matrix. ```rust use traj_dist_rs::distance::dtw::dtw; use traj_dist_rs::distance::base::TrajectoryCalculator; use traj_dist_rs::distance::distance_type::DistanceType; let traj1 = vec![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]; let traj2 = vec![[0.1, 0.1], [1.1, 1.1], [2.1, 2.1]]; let calculator = TrajectoryCalculator::new(&traj1, &traj2, DistanceType::Euclidean); let result = dtw(&calculator, false); println!("DTW distance: {}", result.distance); ``` -------------------------------- ### Python: Performance Tips for traj-dist-rs Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/usage-examples.md Provides performance optimization tips for using the traj-dist-rs library from Python. It covers using NumPy arrays, enabling parallelization, avoiding full DP matrices for DTW, and processing data in batches. ```python # Tip 1: Use numpy arrays instead of lists for zero-copy access import numpy as np trajectories = [np.array(t) for t in raw_trajectories] # Better # Tip 2: Enable parallelization for batch operations distances = traj_dist_rs.pdist(trajectories, metric, parallel=True) # Tip 3: Avoid storing full DP matrices for large trajectories result = traj_dist_rs.dtw(t1, t2, "euclidean", use_full_matrix=False) # Tip 4: Process large datasets in batches batch_size = 1000 for i in range(0, len(trajectories), batch_size): batch = trajectories[i:i + batch_size] distances = traj_dist_rs.pdist(batch, metric, parallel=True) ``` -------------------------------- ### Rust Metric Methods Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/types.md Shows how to use methods of the Metric object in Rust, including retrieving the algorithm and distance type, and computing the distance between two trajectories. ```rust // Get the algorithm metric.algorithm() // Get the distance type metric.distance_type() // Compute distance between two trajectories let dist = metric.distance(&traj1, &traj2); ``` -------------------------------- ### Python Error Handling Example Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/README.md Demonstrates how to handle potential errors, such as invalid parameters or serialization issues, when using the traj-dist-rs library in Python. Uses try-except blocks to catch ValueError and RuntimeError. ```python # ValueError: Invalid parameters try: result = traj_dist_rs.dtw(traj1, traj2, "invalid") except ValueError as e: print(f"Invalid: {e}") # RuntimeError: Serialization errors try: pickled = pickle.dumps(result) except RuntimeError as e: print(f"Serialization error: {e}") ``` -------------------------------- ### Pickle Serialization of DpResult Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/types.md Illustrates how to serialize and deserialize DpResult objects using Python's pickle module. ```python import pickle result = traj_dist_rs.dtw(t1, t2, "euclidean", use_full_matrix=True) serialized = pickle.dumps(result) deserialized = pickle.loads(serialized) ``` -------------------------------- ### Rust Error Handling Example Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/README.md Shows how to handle errors returned by Rust functions in traj-dist-rs, specifically using the Result type. Demonstrates matching on Ok and Err variants, including specific error types like TrajDistError::InvalidParams. ```rust // Return Result type match pdist(&trajectories, &metric, true, false) { Ok(distances) => { /* process */ }, Err(TrajDistError::InvalidParams(msg)) => { /* handle */ }, Err(e) => { /* handle */ }, } ``` -------------------------------- ### Basic Distance Calculation in Rust Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/usage-examples.md Demonstrates calculating SSPD and DTW distances between two trajectories in Rust. Shows how to use the TrajectoryCalculator for DTW and optionally compute the full DP matrix. ```rust use traj_dist_rs::distance::sspd::sspd; use traj_dist_rs::distance::dtw::dtw; use traj_dist_rs::distance::base::TrajectoryCalculator; use traj_dist_rs::distance::distance_type::DistanceType; fn main() { let traj1 = vec![[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]; let traj2 = vec![[0.1, 0.1], [1.1, 1.1], [2.1, 2.1]]; // SSPD - simple point-to-segment distance let dist = sspd(&traj1, &traj2, DistanceType::Euclidean); println!("SSPD: {:.6}", dist); // DTW - requires distance calculator let calculator = TrajectoryCalculator::new(&traj1, &traj2, DistanceType::Euclidean); let result = dtw(&calculator, false); // false = don't compute full matrix println!("DTW: {:.6}", result.distance); // With full DP matrix let result_with_matrix = dtw(&calculator, true); if let Some(matrix) = &result_with_matrix.matrix { println!("Matrix length: {}", matrix.len()); } } ``` -------------------------------- ### Define Trajectories for Parameterized Algorithms Source: https://github.com/davidham3/traj-dist-rs/blob/main/mk_docs/docs/usage_for_python.ipynb Define two sample trajectories as NumPy arrays for demonstrating algorithms that require additional parameters. Print the trajectories. ```python import traj_dist_rs import numpy as np traj1 = np.array([[0.0, 0.0], [1.0, 1.0], [2.0, 2.0], [3.0, 3.0]]) traj2 = np.array([[0.5, 0.5], [1.5, 1.5], [2.5, 2.5], [3.5, 3.5]]) print("Using trajectories with parameters:") print("Trajectory 1:", traj1) print("Trajectory 2:", traj2) ``` -------------------------------- ### DP Matrix Usage (Python) Source: https://github.com/davidham3/traj-dist-rs/blob/main/_autodocs/quick-reference.md This snippet is a placeholder and does not contain executable code. It indicates a section intended for demonstrating the usage of DP matrices in Python. ```python ```