# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

#### **Serde Support for Core Types**

- **Added `Serialize` and `Deserialize` implementations for `Coords1D`**
  - Enables serialization/deserialization of coordinate collections
  - Preserves sorted invariant through serde bounds
  - Compatible with all common formats (JSON, TOML, MessagePack, etc.)

- **Added `Serialize` and `Deserialize` implementations for grid types**
  - `Grid1D`, `Grid1DUniform`, `Grid1DNonUniform` all serializable
  - Grid structure preserved through round-trip serialization
  - Useful for caching, checkpointing, and data exchange

- **New example file `examples/coords1d_serialization.rs`**
  - Demonstrates JSON serialization/deserialization patterns
  - Shows coordinate persistence and recovery workflows

#### **`NonNegativeRealScalar` Type**

- **Implemented `NonNegativeRealScalar<T>` in `scalars` module**
  - Type-safe wrapper ensuring `x ≥ 0` constraint
  - `try_new()` validates non-negative values
  - Useful for representing quantities like distances, lengths, or weights
  - Complements existing `PositiveRealScalar` (x > 0)

#### **Parallel Point Location**

- **Added `find_intervals_for_points_parallel()` to `IntervalPartition` trait**
  - Uses Rayon for parallel batch point location
  - Beneficial when locating ≥1,000 points at once
  - Complexity: O(n/p) for uniform grids, O((n/p) log m) for non-uniform
  - Requires `Self: Sync` and `Point: Send + Sync` bounds

- **New benchmarks for parallel point location**
  - Added `uniform_f64_batch_parallel` and `non_uniform_f64_batch_parallel` benchmarks
  - Performance comparison tables in documentation

- **Documentation for parallel vs sequential point location**
  - Added "When to Use Parallel Point Location" section in DECISION_GUIDE.md
  - Added "Parallel Batch Point Location" section in TUTORIAL.md
  - Performance guidance table showing speedup characteristics

#### **`From` Trait Implementations for Grid Types**

- **Implemented `From<Grid1DUniform>` for `Grid1D`**
  - Seamless conversion: `let grid: Grid1D<_> = uniform_grid.into()`
  - Enables generic functions accepting `Grid1D` to work with uniform grids

- **Implemented `From<Grid1DNonUniform>` for `Grid1D`**
  - Seamless conversion: `let grid: Grid1D<_> = non_uniform_grid.into()`
  - Allows storing different grid types in homogeneous collections

- **Added "Grid Type Conversions" section in TUTORIAL.md**
  - Examples using `From::from()` and `.into()` syntax
  - Use cases for generic functions and collections

- **Added tests for `From` trait conversions**
  - `test_from_grid1d_uniform_to_grid1d()`
  - `test_from_grid1d_non_uniform_to_grid1d()`
  - `test_from_grid1d_uniform_into_syntax()`
  - `test_from_grid1d_non_uniform_into_syntax()`

#### **Common Pitfalls Documentation**

- **Added "Common Pitfalls and How to Avoid Them" section in lib.rs**
  - **Pitfall 1**: Using boolean flags instead of type-safe intervals
  - **Pitfall 2**: Forgetting to import traits for interval construction
  - **Pitfall 3**: Using raw `usize` instead of type-safe wrappers
  - **Pitfall 4**: Assuming uniform spacing for generic grids
  - **Pitfall 5**: Pattern matching on `Interval` enum (with comprehensive examples)

#### **Generic Storage Support for `Coords1DInDomain`**

- **Generalized `Coords1DInDomain` struct with flexible storage types**
  - Added generic `CoordsStorage` parameter with `std::borrow::Borrow` constraint
  - Supports owned (`Coords1D<T>`), borrowed (`&Coords1D<T>`), and smart pointer storage
  - Maintains complete backward compatibility with existing code
  - Zero-cost abstraction with compile-time dispatch

- **Comprehensive smart pointer support**
  - **`Arc<Coords1D<T>>`**: Thread-safe shared ownership for concurrent access
  - **`Rc<Coords1D<T>>`**: Single-threaded shared ownership with reference counting
  - **`Box<Coords1D<T>>`**: Unique heap allocation for large coordinate sets
  - **`Cow<Coords1D<T>>`**: Clone-on-write semantics for flexible ownership

- **Ergonomic type aliases for common usage patterns**
  - `Coords1DInDomainOwned<T>`: Direct ownership (default behavior)
  - `Coords1DInDomainBorrowed<'a, T>`: Borrowed references with lifetime
  - `Coords1DInDomainArc<T>`: Thread-safe shared ownership
  - `Coords1DInDomainRc<T>`: Single-threaded shared ownership
  - `Coords1DInDomainBox<T>`: Unique heap allocation
  - `Coords1DInDomainCow<'a, T>`: Clone-on-write semantics

- **Memory-efficient coordinate operations**
  - `as_borrowed()`: Create zero-cost borrowed view from owned coordinates
  - `to_owned_coords()`: Create owned copy from borrowed coordinates
  - Efficient sharing of large coordinate datasets without unnecessary copying

- **Added 12 comprehensive tests** covering all storage types and conversion patterns
  - Smart pointer functionality verification (Arc, Rc, Box, Cow)
  - Type alias correctness validation
  - Shared ownership behavior testing
  - Memory efficiency and conversion method validation

- **Complete example demonstrating practical usage patterns**
  - Real-world usage with 1001-point coordinate sets
  - Memory efficiency comparison between storage types
  - Generic functions accepting any storage type
  - Thread-safe and single-threaded sharing scenarios

- **Comprehensive documentation enhancements**
  - Enhanced type parameter documentation explaining `CoordsStorage` generic parameter
  - New "Flexible Storage Types and Memory Management" documentation section
  - Practical examples for all 6 supported storage types with real-world use cases
  - Updated module-level and function documentation to reflect storage flexibility
  - All 857 doctests updated and passing with new generic examples

#### **Enhanced `TransformedPoints1D` Trait with Generic Storage Support**

- **Generalized `TransformedPoints1D` trait with flexible storage parameters**
  - Added generic `ParamStorage` and `PhysStorage` type parameters
  - Both parameters constrained by `std::borrow::Borrow<Coords1D<RealType>>`
  - Enables flexible storage for both parametric and physical domain coordinates
  - Maintains zero-cost abstraction with compile-time dispatch

- **Updated trait method signatures for generic storage**
  - `points_param_interval()` returns `&Coords1DInDomain<ParamDomainType, ParamStorage>`
  - `points_phys_interval()` returns `&Coords1DInDomain<PhysDomainType, PhysStorage>`
  - Full compatibility with all storage types (owned, borrowed, Arc, Rc, Box, Cow)

- **Ergonomic type aliases for transformed points**
  - `TransformedPoints1DOwned<ParamDomain, PhysDomain>`: Owned storage for both domains
  - `TransformedPoints1DBorrowed<'a, ParamDomain, PhysDomain>`: Borrowed storage with lifetime
  - `TransformedPoints1DArc<ParamDomain, PhysDomain>`: Thread-safe Arc storage
  - `TransformedPoints1DRc<ParamDomain, PhysDomain>`: Single-threaded Rc storage

- **Comprehensive documentation with practical examples**
  - Implementation examples for owned and borrowed storage patterns
  - Memory-efficient patterns for large coordinate transformations
  - Thread-safe sharing scenarios for concurrent numerical algorithms
  - Complete API documentation with real-world use cases

- **Added 4 comprehensive tests** validating all storage patterns
  - Owned storage implementation and functionality testing
  - Borrowed storage zero-copy behavior verification
  - Arc storage thread-safe sharing validation
  - Type alias compilation and correctness testing

- **Enhanced numerical algorithm support**
  - Enables efficient parametric ↔ physical domain transformations
  - Memory-efficient Chebyshev and other spectral method implementations
  - Thread-safe coordinate sharing for parallel numerical computations
  - Zero-copy coordinate access patterns for high-performance algorithms

### Changed

#### **Simplified Non-Uniform Grid Construction** ⚠️ BREAKING

- **Domain now inferred from coordinates in `Grid1D::try_from_sorted()`**
  - Old API: `Grid1D::try_from_sorted(coords, domain)` - required explicit domain
  - New API: `Grid1D::try_from_sorted(coords)` - domain inferred from first/last coordinates
  - Type annotation required: `Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords)`
  - Reduces boilerplate and eliminates domain/coordinates mismatch errors
  - Removed `LowerBoundMismatch` and `UpperBoundMismatch` error variants from `ErrorsGrid1D`

#### **Moved `new()` and `try_new()` to Trait**

- **Methods moved from inherent impl to `IntervalFinitePositiveLengthTrait`**
  - Previously: inherent impl on each interval type
  - Now: trait methods on `IntervalFinitePositiveLengthTrait`
  - Requires `use grid1d::intervals::*` to bring methods into scope
  - Enables more generic programming patterns
  - Documentation updated to reflect this change

#### **Renamed `HashableReal` to `HashableScalar`**

- **Consistent naming with scalar abstraction**
  - Reflects that the type works with any `RealScalar`, not just "real" numbers
  - Better alignment with `num-valid` terminology

#### **Moved Types to `num-valid` Crate**

- **The following types are now in `num-valid` instead of `grid1d`:**
  - `AbsoluteTolerance` → `num_valid::AbsoluteTolerance`
  - `RelativeTolerance` → `num_valid::RelativeTolerance`
  - `PositiveRealScalar` → `num_valid::scalars::PositiveRealScalar`
  - `NonNegativeRealScalar` → `num_valid::scalars::NonNegativeRealScalar`
  - Update imports from `grid1d::scalars::*` to `num_valid::*`

#### **Updated Dependencies**

- **`num-valid`**: 0.2.2 → 0.3.x
  - Uses `num_valid::core::errors::capture_backtrace()` instead of `Backtrace::force_capture()`
  - Updated version references throughout documentation

### Refactored

#### **Module Restructuring**

- **Extracted `coords` module from `lib.rs`**
  - New `src/coords.rs` containing `Coords1D` and `Coords1DInDomain` types
  - Tests moved to dedicated `coords` module
  - All coordinate-related types now in dedicated module
  - Import: `use grid1d::coords::*`

- **Extracted `traits` module from `lib.rs`**
  - New `src/traits.rs` containing core trait definitions
  - `HasDomain1D`, `HasCoords1D`, `BuildIntervalInPartition`, `IntervalPartition`, `TransformedPoints1D`
  - Better separation of concerns
  - Import: traits re-exported at crate root

- **Split `intervals` module into submodules**
  - `src/intervals/bounded.rs`: Bounded interval implementations
  - `src/intervals/unbounded.rs`: Unbounded interval implementations
  - `src/intervals/operations.rs`: Interval operations (intersection, union, hull, difference)
  - `src/intervals/conversions.rs`: Conversion traits and implementations
  - Public API unchanged; internal organization improved

- **Extracted `operations` submodule for intervals**
  - `IntervalOperations` trait and implementations in dedicated file
  - Cleaner separation of interval types from operations

### Fixed

- **Fixed broken rustdoc links in `coords` module**
  - Corrected intra-doc links after module extraction
  - All documentation links now resolve correctly

### Documentation

- **Updated Copilot instructions (`.github/copilot-instructions.md`)**
  - Comprehensive architectural guidance for AI assistants
  - Module structure, trait hierarchy, and coding conventions
  - Updated to reflect module restructuring

- **Updated TUTORIAL.md**
  - Fixed API errors in examples after domain inference change
  - Added "Grid Type Conversions" section
  - Added "Parallel Batch Point Location" section

- **Updated DECISION_GUIDE.md**
  - Added "When to Use Parallel Point Location" section
  - Performance guidance table for parallel vs sequential

- **Created technical analysis documents**
  - `ANALISI_TECNICA_COMPLETA.md`: Comprehensive technical analysis (Italian)
  - `ANALISI_TECNICA_DETTAGLIATA.md`: Detailed technical review

## [0.2.0] - 2025-10-17

### Added

#### **New `into_interval()` Method for Type-Safe Interval Conversions**

- **Added `into_interval(self) -> Interval<Self::RealType>`** method to `IntervalTrait`
  - Provides ergonomic, explicit conversion from any interval type to the general `Interval` enum
  - Zero-cost conversion that consumes `self` (follows Rust naming conventions)
  - Works with all interval types: bounded, unbounded, singleton, and enum variants
  - Particularly useful for heterogeneous collections and polymorphic return types
  
- **Comprehensive documentation for interval conversions**
  - New "Conversion to General Interval Type" section in `IntervalTrait` documentation
  - Lists all 13+ convertible interval types with examples
  - Clarifies that `Into<Interval>` is implemented for 4 specific bound type combinations, not as a blanket impl
  - Explains monomorphization behavior and usage patterns with generic type parameters
  
- **Added 20 tests** covering all interval type conversions (total: 890 unit tests, 849 doctests)

#### **Comprehensive Documentation and Tests for Boundary Predicates**

- **Enhanced documentation for `is_upper_bound_closed()` and `is_upper_bound_open()`**
  - Detailed boundary semantics with tables for all 7 interval types
  - Examples with closures, unbounded intervals, and generic programming
  - Documented complement relationship: `is_upper_bound_open() == !is_upper_bound_closed()`

- **Added 29 comprehensive tests** for boundary predicates and `clamp()` method
  - 14 tests for boundary predicates (closed/open, all variants, complement relationship)
  - 15 tests for `clamp()` (basic functionality, edge cases, mathematical properties, type safety)
  - Fixed floating point precision issue in test suite
  
- **Documentation improvements** across error types and traits
  - Inline documentation for struct fields in error types
  - Documentation for `BuildIntervalInPartition`, `Grid1DRefinement`, `TransformedPoints1D`
  - Enhanced API documentation with clear examples and cross-references

#### **Simplified Interval Hull Computation**

- **Reduced hull computation complexity by ~86%** (185 lines → 25 lines)
  - Introduced `min_lower_bound_maybe_unbounded()` and `max_upper_bound_maybe_unbounded()` helpers
  - Delegated interval type selection to `Interval::try_new()`
  - Eliminated 160+ lines of repetitive match logic
  
- **Added factory methods to `IntervalInfiniteLength`**
  - `new_lower_unbounded(upper: UpperBoundRuntime)`: Creates semi-bounded interval `(-∞, b]` or `(-∞, b)`
  - `new_upper_unbounded(lower: LowerBoundRuntime)`: Creates semi-bounded interval `[a, +∞)` or `(a, +∞)`
  
- **Added 32 comprehensive tests** for hull operations and unbounded intervals
  - 17 tests for factory methods, `Interval::try_new()`, and singleton detection
  - 15 tests for maybe_unbounded helpers with symmetry, associativity, and None propagation
  - Increased function coverage by 1.44% (94.95% → 96.39%)

#### **Generalized `IntervalHull` Trait**

- **Extended `IntervalHull` to support all interval types**
  - Previously limited to `IntervalFinitePositiveLength`
  - Now supports unbounded intervals, singleton intervals, and all enum variants
  - Maintains "closed wins over open" semantics at equal boundary values
  
- **Simplified hull implementations** across all interval types
  - Reduced code duplication by using shared helper functions
  - Improved maintainability with consistent bound selection logic

#### **Simplified `IntervalOperations::intersection()`**

- **Streamlined intersection logic** for unbounded intervals
  - Cleaner implementation using `Interval::try_new()` with runtime bounds
  - Removed redundant code paths
  - Maintains identical mathematical semantics

#### **New Bound Transformation Methods**

- **Runtime bound transformations for `IntervalBoundRuntime`:**
  - `flip_bound_type(self) -> Self`: Transforms Open ↔ Closed (e.g., `LowerOpen(0.0)` → `LowerClosed(0.0)`)
  - `flip_bound_side(self) -> IntervalBoundRuntime<T, Side::Opposite>`: Transforms Lower ↔ Upper
  - `flip_bound_side_and_type(self)`: Combines both transformations

- **Compile-time bound transformations for `IntervalBound`:**
  - `flip_bound_type(self) -> IntervalBound<T, Side, Type::Opposite>`: Zero-cost type-level transformation
  - `flip_bound_side(self) -> IntervalBound<T, Side::Opposite, Type>`: Type-safe side switching
  
- **Added `Opposite` associated type to `BoundSide` trait**
  - Enables compile-time type inference for bound transformations
  - Bidirectional constraint: `Side::Opposite::Opposite = Side`
  
- **Added 25 comprehensive tests** for bound transformation methods

#### **Implemented Interval Set Difference Operation**

- **Added `IntervalOperations::difference()`** method
  - Computes set difference `A \ B = { x : x ∈ A ∧ x ∉ B }`
  - Returns `IntervalDifference` enum with variants: `None`, `SingleConnected`, `TwoDisjoint`
  - Handles all combinations of bounded, unbounded, and singleton intervals
  
- **Added `IntervalDifference` enum** with comprehensive documentation
  - Mathematical foundation with set theory notation
  - Visual ASCII art examples for all 4 cases
  - Working usage examples demonstrating pattern matching
  - Cross-references to related operations

#### **Comprehensive Documentation for Interval Operations**

- **Enhanced documentation for `IntervalUnion` enum**
  - Mathematical foundation: `A ∪ B = { x : x ∈ A ∨ x ∈ B }`
  - Properties: Commutativity, Associativity, Identity, Idempotence
  - Visual ASCII art examples
  - Working usage examples with pattern matching

- **Added tutorial and decision guides**
  - Comprehensive user experience documentation
  - Decision trees for choosing appropriate interval types
  - Best practices and common patterns

### Changed

#### **Refactored Duplicate Code in Bound Conversion Traits**

- **Eliminated code duplication** in `BoundTypeConversion` and `BoundSideConversion`
  - Consolidated repeated implementations
  - Improved maintainability
  - No functional changes

#### **Migrated `refine()` to BTreeMap for Type-Safe Uniqueness** ⚠️ BREAKING

- **Changed return type** from `Vec` to `BTreeMap<IntervalId, _>`
  - Guarantees unique `IntervalId` keys at compile time
  - Prevents duplicate interval IDs in refinement results
  - More expressive API that encodes uniqueness constraint
  
- **Breaking change**: Users must update code that calls `refine()`
  - Old: `let refined_vec = grid.refine(...)`
  - New: `let refined_map = grid.refine(...); let refined_vec: Vec<_> = refined_map.into_values().collect()`

### Fixed

- **Fixed floating point precision issue** in `clamp()` test
  - Changed interval from `[5.0, 5.0 + f64::EPSILON]` to `[5.0, 5.001]`
  - Epsilon was too small relative to 5.0 to be representable

### Validated

- **Test Coverage**: 890 unit tests + 849 doctests = 1,739 total tests, all passing
- **Code Coverage**: Functions: 96.39%, Regions: 96.21%, Lines: 95.01%
- **Compilation**: Zero warnings, all features compile successfully
- **Documentation**: Comprehensive rustdoc with examples, cross-references, and mathematical rigor

## [0.1.2] - 2025-10-14

- **Added `flip_bound_side_and_type(self) -> IntervalBound<RealType, Side::Opposite, Type::Opposite>`** (in `bounds.rs`)
  - Combined compile-time transformation of both side and type
  - Particularly useful for interval difference operations and boundary complement
  - Example: `LowerBound<f64, Closed>` → `UpperBound<f64, Open>`
  - Involutive property: applying twice returns to original type

- **Added `Opposite` associated type to `BoundType` trait** (in `bounds.rs`)
  - Enables compile-time type inference for boundary type transformations
  - `Open::Opposite = Closed` and `Closed::Opposite = Open`
  - Bidirectional constraint: `Type::Opposite::Opposite = Type`
  - Eliminates need for manual type annotations in transformations

#### **New Interval Construction Methods from Bounds**

- **Added `try_from_bounds()` to `IntervalBounded`** (in `intervals.rs`)
  - Constructs intervals from pre-existing `LowerBound` and `UpperBound` objects
  - Validates that `lower_bound < upper_bound`
  - Type-safe: compiler enforces bound types match interval's type parameters
  - Returns `Result<Self, ErrorsIntervalConstruction<RealType>>`
  - Example: Build `IntervalClosed` from `LowerBoundClosed` and `UpperBoundClosed`

- **Added `from_bounds()` to `IntervalBounded`** (in `intervals.rs`)
  - Infallible version of `try_from_bounds()`
  - Debug mode: validates via `try_from_bounds()`, panics on error
  - Release mode: constructs interval without validation for performance
  - Useful when bounds are already validated or come from trusted sources

### Changed

#### **Code Simplification Using New Bound Transformation Methods**

- **Simplified interval difference operations** (in `intervals.rs`)
  - Reduced code from ~48 lines to ~16 lines using `flip_bound_side_and_type()`
  - Eliminated repetitive match statements for bound transformations
  - Improved maintainability while preserving mathematical correctness

- **Simplified gap calculation in `IntervalUnion`** (in `intervals.rs`)
  - Reduced code from ~20 lines to 2 lines using `flip_bound_side_and_type()`
  - More concise and readable implementation

- **Refactored `IntervalFinitePositiveLength::try_new()`** (in `intervals.rs`)
  - Changed from manual validation to delegation pattern
  - Now delegates to concrete interval types' `try_new()` methods
  - Single source of truth for validation logic
  - Improved maintainability and consistency

### Validated

#### **Quality Assurance**

- **All 574 unit tests pass** with no failures
- **All 829 doctests pass** (14 ignored as expected)
  - 3 new doctests for `try_from_bounds()` and `from_bounds()` methods
  - 1 compile-fail test verifying type safety of bound-based constructors
- **Zero compilation errors** in both debug and release modes
- **Comprehensive documentation** with mathematical semantics and usage examples
- **All new methods fully documented** with doctests demonstrating proper usage

### Added

#### **Convenience Enum and Methods for Runtime Bounds**

- **Added a new enum `IntervalBoundRuntime<RealType, Side>` for the dynamic management of lower/upper bounds**
  - Added convenience methods for its construction
  - Added the type aliases `LowerBoundRuntime<RealType>` and `UpperBoundRuntime<RealType>`.
  
- **Enhanced ergonomics for dynamic interval construction**
  - Simplifies creation of runtime bounds when inclusion/exclusion is determined at runtime
  - Reduces verbosity compared to manual `IntervalBoundRuntime::Open(IntervalBound::new(value))` construction
  - Zero-cost abstractions with compile-time optimizations
  
- **Comprehensive documentation with mathematical semantics**
  - Detailed examples for both lower and upper bounds
  - Mathematical notation for constraint semantics (e.g., `x > value`, `x ≥ value`)
  - Usage patterns for filtering, conditional logic, and dynamic construction
  - 266 lines of high-quality documentation with 14 code examples


## [0.1.1] - 2025-10-03

### Fixed

#### **Documentation Improvements**

- **Fixed broken intra-doc links** that were causing documentation build failures
  - Resolved unresolved link to `num_valid::RealRugStrictFinite` by using plain text references for feature-dependent types
  - Fixed malformed link syntax in `bounds.rs` where bracket placement was incorrect
  - All documentation now builds successfully with `#![deny(rustdoc::broken_intra_doc_links)]`

#### **Documentation Quality and Consistency**

- **Cleaned up documentation formatting** by removing temporary "" markers throughout the codebase
  - Affected files: `src/lib.rs`, `src/intervals.rs`, `src/bounds.rs`, `src/scalars.rs`
  - Improved professional appearance and readability of generated documentation
  - Maintained all mathematical accuracy and cross-references

#### **Project Structure Documentation**

- **Updated `.github/copilot-instructions.md`** to accurately reflect the current file structure
  - Corrected references to utility functions (`linspace`, `logspace`) which are located in `lib.rs`, not a non-existent `utilities.rs`
  - Fixed both module overview and references sections for accurate AI coding assistance

### Validated

#### **Quality Assurance**

- **All documentation builds successfully** with no errors or warnings
  - `cargo doc --document-private-items` passes without issues
  - All 548 doc tests pass (539 passed, 9 ignored as expected)
  - All 449 unit tests continue to pass
  - `cargo check` and `cargo clippy` pass without warnings

#### **Cross-References and Examples**

- **All internal documentation links** now resolve correctly
- **All code examples** in documentation compile and demonstrate correct usage
- **Mathematical formulas** and interval notation remain accurate and consistent
- **Type safety documentation** continues to provide detailed explanations of design patterns

## [0.1.0] - 2025-01-20 (Initial release)

### Added

#### **Core 1D Grid Framework**

- **One-dimensional grids and interval partitions** with mathematical rigor and performance optimization
- **Uniform grids** (`Grid1DUniform`) with O(1) point location using analytical formulas
- **Non-uniform grids** (`Grid1DNonUniform`) with O(log n) point location using optimized binary search
- **Unified interface** through `Grid1D` enum enabling seamless switching between grid types
- **Type-safe construction** preventing invalid grid states through compile-time guarantees

#### **Multiple Numerical Backends via num-valid**

- **Native backend** with `f64` for maximum performance
- **Debug-validated types** (`RealNative64StrictFiniteInDebug`) with f64 performance + debug safety
- **Always-validated types** (`RealNative64StrictFinite`) for safety-critical applications  
- **Arbitrary precision backend** with `RealRugStrictFinite<N>` (optional, `--features=rug`)
  - Support for 64, 128, 256, 512+ bit precision arithmetic
  - GNU Multiple Precision Arithmetic Library integration
- **Seamless API compatibility** across all scalar backends

#### **Comprehensive Interval System**

- **Type-safe intervals** with compile-time boundary semantics
  - `IntervalClosed` for `[a,b]` - both bounds included
  - `IntervalOpen` for `(a,b)` - both bounds excluded
  - `IntervalLowerClosedUpperOpen` for `[a,b)` - left closed, right open
  - `IntervalLowerOpenUpperClosed` for `(a,b]` - left open, right closed
  - `IntervalSingleton` for `{a}` - single point intervals
  - Unbounded intervals: `[a,+∞)`, `(a,+∞)`, `(-∞,b]`, `(-∞,b)`, `(-∞,+∞)`
- **Interval arithmetic** with proper boundary handling
- **Universal Interval enum** for dynamic programming scenarios
- **Automatic sub-interval construction** preserving domain semantics in partitions

#### **Advanced Grid Operations**

- **Adaptive mesh refinement** with bidirectional mappings
  - Uniform refinement (global resolution doubling)
  - Selective refinement (interval-specific refinement)
  - Refinement history tracking via `Grid1DRefinement`
- **Grid union operations** (`Grid1DUnion`) for multi-physics simulations
  - Optimal O(n+m) merge algorithm
  - Bidirectional interval mappings between original and unified grids
  - Support for different grid types and scalar backends

#### **Coordinate Management**

- **`Coords1D` container** for unique, sorted, non-empty coordinates
- **`Coords1DInDomain` validation** ensuring coordinates match domain boundaries
- **Efficient operations**: union, intersection, search, range queries
- **Zero-cost abstractions** with direct slice access for performance-critical operations
- **Generic construction utilities**: `linspace`, `logspace` for coordinate generation

#### **Type Safety and Validation**

- **Type-safe scalar wrappers** preventing value confusion
  - `NumIntervals` for interval count (≥ 1)
  - `IntervalId` for zero-based interval indexing
  - `PositiveNumPoints1D` for point count (≥ 1)
  - `PositiveSize` for positive counting
  - Tolerance types: `AbsoluteTolerance`, `RelativeTolerance`
  - `PositiveRealScalar` for strictly positive values
- **Strongly-typed boundaries** (`LowerBoundOpen`, `LowerBoundClosed`, etc.)
- **Runtime validation** with detailed error reporting and backtraces
- **Debug vs. release validation** balancing safety with performance

#### **Performance Optimizations**

- **O(1) point location** for uniform grids using analytical formulas
- **O(log n) binary search** for non-uniform grids with cache-friendly data structures
- **Zero-cost abstractions** - wrapper types have identical memory layout to primitives
- **SIMD-ready patterns** enabling vectorization optimizations
- **Memory-efficient layouts** with minimal overhead beyond coordinate storage

#### **Core Traits and Generic Programming**

- **`IntervalPartition`** for unified partition operations across grid types
- **`HasDomain1D`** and **`HasCoords1D`** for domain and coordinate access
- **`IntervalTrait`** for comprehensive interval operations and generic programming
- **`Contains`** for point and interval containment testing
- **`IntervalOperations`** for cross-type interval arithmetic
- **Generic scalar support** enabling same algorithms across different scalar types

#### **Utility Functions and Helpers**

- **Grid construction utilities**
  - `linspace` for uniformly spaced coordinate generation
  - `logspace` for logarithmically spaced coordinate generation
  - Automatic uniform/non-uniform grid detection
- **Coordinate operations**
  - Union, intersection, and difference operations
  - Binary search and range queries
  - Efficient batch operations
- **Type conversions** between related grid and interval types

### Features

#### **Arbitrary Precision Support** (optional, `--features=rug`)

- **GNU Multiple Precision Arithmetic Library integration**
- **User-defined N-bit precision** (64, 128, 256, 512+ bits)
- **Perfect for scientific computing** requiring exact arithmetic
- **Seamless API compatibility** with native scalar types
- **Validated arbitrary precision types** via `num-valid::RealRugStrictFinite<N>`

#### **Serialization Support**

- **Serde integration** for grid persistence and data exchange
- **Compatible formats**: JSON, YAML, binary, and custom formats
- **Cross-platform portability** for scientific data exchange
- **Metadata preservation** in serialized representations

### Documentation

#### **Comprehensive API Documentation**

- **Mathematical definitions** and theoretical foundations for all operations
- **Performance characteristics** and complexity analysis for each grid type
- **Usage examples** covering common numerical methods
  - Finite difference method setup and grid construction
  - Spectral method configuration with periodic boundaries
  - Adaptive mesh refinement workflows
  - Multi-physics grid coupling strategies
- **Best practices guide** for scalar type selection and performance optimization
- **Integration patterns** with numerical computing ecosystems

#### **Mathematical Foundations**

- **Interval arithmetic theory** and boundary semantics
- **Grid partition properties** and mathematical guarantees
- **Performance analysis** of different grid types and operations
- **Error handling philosophy** and validation strategies

#### **Advanced Usage Examples**

- **Computational Fluid Dynamics**: Boundary layer mesh generation with fine near-wall spacing
- **Finite Element Analysis**: Adaptive refinement based on error indicators
- **Spectral Methods**: Uniform grids for Fourier transforms and Chebyshev polynomials
- **Multi-physics Coupling**: Grid union operations for coupled simulations

### Dependencies

#### **Core Dependencies**

- **`num-valid`** (local path dependency) for validated numerical types and generic scalar arithmetic
- **`sorted-vec`** for efficient sorted container operations and O(log n) search
- **`nutype`** for type-safe scalar wrapper generation with compile-time validation
- **`serde`** for serialization support across all grid and interval types
- **`derive_more`**, **`getset`**, **`duplicate`** for ergonomic APIs and code generation
- **`thiserror`** for structured error handling with backtraces

#### **Optional Dependencies**

- **`rug`** for arbitrary precision arithmetic via GNU Multiple Precision Arithmetic Library
- **`criterion`** for comprehensive benchmarking (dev dependency)

### Requirements

#### **Rust Toolchain**

- **Nightly Rust required** (specified in `rust-toolchain.toml`)
- **Reason**: Advanced error handling features (`#![feature(error_generic_member_access)]`)
- **Platform**: Cross-platform support (Windows, macOS, Linux)

#### **External Libraries (Optional)**

- **GNU Multiple Precision Arithmetic Library** for arbitrary precision features
- **Installation**: System package manager or manual compilation

### Performance Benchmarks

#### **Grid Construction**

- **Uniform grids**: Linear O(n) construction with optimized memory allocation
- **Non-uniform grids**: O(n log n) due to sorting, with efficient deduplication
- **Grid union**: O(n+m) optimal merge algorithm outperforming naive approaches

#### **Point Location Performance**

- **Uniform grids**: Constant O(1) time using analytical index calculation
- **Non-uniform grids**: Logarithmic O(log n) with cache-friendly binary search
- **Batch operations**: Vectorized processing with SIMD optimization potential

#### **Memory Efficiency**

- **Coordinate storage**: Minimal overhead beyond essential coordinate arrays
- **Type wrappers**: Zero-cost abstractions with identical memory layout
- **Cache performance**: Contiguous memory layouts for optimal cache utilization

#### **Scalar Type Performance Comparison**

- **`f64`**: Baseline maximum performance (⚡⚡⚡)
- **`RealNative64StrictFiniteInDebug`**: Identical performance to f64 (⚡⚡⚡)
- **`RealNative64StrictFinite`**: Small validation overhead (⚡⚡)
- **`RealRugStrictFinite<N>`**: Precision-dependent performance (⚡)

### Testing and Quality Assurance

#### **Comprehensive Test Coverage**

- **Unit tests**: Core functionality validation for all grid types
- **Integration tests**: Cross-module interaction verification
- **Property-based tests**: Mathematical invariant preservation
- **Benchmark regression tests**: Performance characteristic validation
- **Documentation tests**: All code examples validated for correctness

#### **Mathematical Correctness Validation**

- **Invariant preservation**: Grid completeness, non-overlap, boundary consistency
- **Floating-point precision**: Edge case handling and numerical stability
- **Boundary semantics**: Proper open/closed interval behavior verification
- **Cross-scalar type consistency**: Identical behavior across different scalar backends

### Notes

#### **Release Philosophy**

- **Initial release** establishing core framework and mathematical foundations
- **Mathematical correctness first**: Rigorous validation and type safety prioritized
- **Performance second**: Optimizations built on solid mathematical foundation

#### **Future Roadmap**

- **Enhanced algorithms**: Additional refinement strategies and grid operations
- **Visualization tools**: Plotting and analysis capabilities for grid structures
- **Multi-dimensional extensions**: 2D/3D grid generalizations using same principles
- **GPU acceleration**: CUDA/OpenCL support for massively parallel grid operations
- **Advanced I/O**: HDF5, NetCDF, and other scientific data format support

[0.1.1]: https://gitlab.com/max.martinelli/grid1d/-/releases/v0.1.1
[0.1.0]: https://gitlab.com/max.martinelli/grid1d/-/releases/v0.1.0
