grid1d 0.3.1

A mathematically rigorous, type-safe Rust library for 1D grid operations and interval partitions, supporting both native and arbitrary-precision numerics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
# Grid1D Decision Guide

This guide helps you make informed choices about which grid types, scalar types, and features to use in your application.

## Quick Decision Trees

### ๐ŸŽฏ Which Grid Type Should I Use?

```
START: What kind of spacing do I need?
โ”‚
โ”œโ”€ Equal spacing everywhere?
โ”‚  โ””โ”€ โœ… Use Grid1DUniform
โ”‚     โ€ข O(1) point location
โ”‚     โ€ข Maximum performance
โ”‚     โ€ข Perfect for regular discretizations
โ”‚
โ”œโ”€ Custom/adaptive spacing?
โ”‚  โ””โ”€ โœ… Use Grid1DNonUniform
โ”‚     โ€ข O(log n) point location
โ”‚     โ€ข Flexible point distribution
โ”‚     โ€ข Ideal for boundary layers, shock capturing
โ”‚
โ””โ”€ Combining multiple grids?
   โ””โ”€ โœ… Use Grid1DUnion
      โ€ข Combines grids from different physics
      โ€ข Maintains mappings to original grids
      โ€ข For multi-physics simulations
```

### ๐Ÿ“ Which Interval Type Should I Use?

```
START: What are your domain boundaries?
โ”‚
โ”œโ”€ Both endpoints are part of the domain?
โ”‚  โ””โ”€ โœ… Use IntervalClosed [a, b]
โ”‚     โ€ข Most common choice
โ”‚     โ€ข Points at a and b are included
โ”‚     โ€ข Standard for boundary value problems
โ”‚
โ”œโ”€ Neither endpoint is part of the domain?
โ”‚  โ””โ”€ โœ… Use IntervalOpen (a, b)
โ”‚     โ€ข Points strictly between a and b
โ”‚     โ€ข For open sets, strict inequalities
โ”‚     โ€ข Rare in practice
โ”‚
โ”œโ”€ Periodic or partition-friendly boundary?
โ”‚  โ”œโ”€ Left closed, right open?
โ”‚  โ”‚  โ””โ”€ โœ… Use IntervalLowerClosedUpperOpen [a, b)
โ”‚  โ”‚     โ€ข Common for periodic domains
โ”‚  โ”‚     โ€ข Non-overlapping partitions
โ”‚  โ”‚     โ€ข Example: [0, 2ฯ€) for angles
โ”‚  โ”‚
โ”‚  โ””โ”€ Left open, right closed?
โ”‚     โ””โ”€ โœ… Use IntervalLowerOpenUpperClosed (a, b]
โ”‚        โ€ข Asymmetric boundaries
โ”‚        โ€ข Less common
โ”‚
โ”œโ”€ Semi-infinite domain?
โ”‚  โ”œโ”€ Bounded below only?
โ”‚  โ”‚  โ””โ”€ โœ… Use IntervalLowerClosedUpperUnbounded [a, +โˆž)
โ”‚  โ”‚     โ€ข Example: time t โ‰ฅ 0
โ”‚  โ”‚     โ€ข Example: distance r โ‰ฅ 0
โ”‚  โ”‚
โ”‚  โ””โ”€ Bounded above only?
โ”‚     โ””โ”€ โœ… Use IntervalLowerUnboundedUpperClosed (-โˆž, b]
โ”‚        โ€ข Example: x โ‰ค 0
โ”‚
โ””โ”€ Single point (degenerate)?
   โ””โ”€ โœ… Use IntervalSingleton {a}
      โ€ข Zero-measure domain
      โ€ข Special case handling
```

### ๐Ÿ”ข Which Scalar Type Should I Use?

```
START: What are your priorities?
โ”‚
โ”œโ”€ Maximum performance, fully trusted inputs?
โ”‚  โ””โ”€ โœ… Use f64
โ”‚     โ€ข Zero overhead
โ”‚     โ€ข Standard IEEE 754
โ”‚     โ€ข โš ๏ธ  No validation - can propagate NaN/Inf
โ”‚
โ”œโ”€ Good performance + safety during development?
โ”‚  โ””โ”€ โœ… Use RealNative64StrictFiniteInDebug (โญ RECOMMENDED)
โ”‚     โ€ข Same as f64 in release builds
โ”‚     โ€ข Validates in debug builds
โ”‚     โ€ข Perfect development โ†’ production workflow
โ”‚
โ”œโ”€ Safety-critical application?
โ”‚  โ””โ”€ โœ… Use RealNative64StrictFinite
โ”‚     โ€ข Always validates (small overhead ~5-10%)
โ”‚     โ€ข Guaranteed finite values
โ”‚     โ€ข For medical, aerospace, financial
โ”‚
โ””โ”€ Need arbitrary precision?
   โ””โ”€ โœ… Use RealRugStrictFinite<N>
      โ€ข N-bit precision (e.g., 256, 512, 1024)
      โ€ข For scientific computing, symbolic math
      โ€ข Requires `--features=rug`
```

## Detailed Comparison Tables

### Grid Type Comparison

| Feature | Grid1DUniform | Grid1DNonUniform | Grid1DUnion |
|---------|--------------|------------------|-------------|
| **Point Location** | O(1) analytical | O(log n) binary search | O(log n) on unified grid |
| **Memory Usage** | 8n + 40 bytes | 8n + 40 bytes | 8(n+m) + overhead |
| **Construction** | O(n) | O(n) | O(n+m) |
| **Best For** | Regular meshes, FDM | Adaptive meshes, FEM | Multi-physics coupling |
| **Spacing** | Uniform | Arbitrary | Combined |
| **Flexibility** | Low | High | Very High |
| **Performance** | โšกโšกโšก Excellent | โšกโšก Good | โšกโšก Good |

*Where n = number of points, m = points in second grid*

### Scalar Type Comparison

| Scalar Type | Validation | Debug | Release | Use Case |
|-------------|-----------|--------|---------|----------|
| **f64** | โŒ None | โšกโšกโšก | โšกโšกโšก | Trusted inputs, maximum speed |
| **RealNative64StrictFiniteInDebug** | โœ… Debug only | โšกโšก | โšกโšกโšก | **Recommended default** |
| **RealNative64StrictFinite** | โœ… Always | โšกโšก | โšกโšก | Safety-critical |
| **RealRugStrictFinite\<N\>** | โœ… Always | โšก | โšก | Arbitrary precision |

### Interval Type Selection

| Mathematical Need | Interval Type | Notation | Use Case |
|------------------|---------------|----------|----------|
| Include both endpoints | `IntervalClosed` | [a, b] | Standard bounded domains |
| Exclude both endpoints | `IntervalOpen` | (a, b) | Open sets, strict inequalities |
| Include left, exclude right | `IntervalLowerClosedUpperOpen` | [a, b) | Periodic domains, half-open ranges |
| Include right, exclude left | `IntervalLowerOpenUpperClosed` | (a, b] | Asymmetric boundaries |
| Unbounded above | `IntervalLowerClosedUpperUnbounded` | [a, +โˆž) | Semi-infinite domains |
| Unbounded below | `IntervalLowerUnboundedUpperClosed` | (-โˆž, b] | Semi-infinite domains |
| Single point | `IntervalSingleton` | {a} | Degenerate intervals |

### ๐Ÿ”€ Which Refinement Strategy Should I Use?

```
START: How do you want to refine your grid?
โ”‚
โ”œโ”€ Same refinement everywhere?
โ”‚  โ””โ”€ โœ… Use refine_uniform()
โ”‚     โ€ข Every interval gets the same number of extra points
โ”‚     โ€ข Simple API: grid.refine_uniform(&num_extra_points)
โ”‚     โ€ข Best for: uniform quality improvement
โ”‚
โ”œโ”€ Different refinement in different regions?
โ”‚  โ””โ”€ โœ… Use refine() with BTreeMap
โ”‚     โ€ข Specify extra points per interval ID
โ”‚     โ€ข Only refine where needed
โ”‚     โ€ข Best for: adaptive mesh refinement (AMR)
โ”‚
โ””โ”€ Combining two existing grids?
   โ””โ”€ โœ… Use Grid1DUnion instead
      โ€ข Not refinement, but unification
      โ€ข Preserves both original grid structures
      โ€ข Best for: multi-physics coupling
```

### ๐Ÿ”„ Grid Union vs Grid Refinement: When to Use Each?

```
START: What is your goal?
โ”‚
โ”œโ”€ Make current grid finer?
โ”‚  โ”‚
โ”‚  โ”œโ”€ Uniformly finer everywhere?
โ”‚  โ”‚  โ””โ”€ โœ… Use refine_uniform()
โ”‚  โ”‚
โ”‚  โ””โ”€ Finer only in specific regions?
โ”‚     โ””โ”€ โœ… Use refine() with BTreeMap
โ”‚
โ”œโ”€ Couple two independent grids?
โ”‚  โ””โ”€ โœ… Use Grid1DUnion
โ”‚     โ€ข Both grids retain their identity
โ”‚     โ€ข Bidirectional mapping preserved
โ”‚     โ€ข For multi-physics data exchange
โ”‚
โ””โ”€ Create grid from scratch with custom points?
   โ””โ”€ โœ… Use Grid1D::try_from_sorted()
      โ€ข Direct construction from coordinates
      โ€ข Maximum flexibility
      โ€ข When refinement hierarchy not needed
```

| Feature | `refine_uniform()` | `refine()` | `Grid1DUnion` |
|---------|-------------------|------------|---------------|
| **Purpose** | Global refinement | Selective refinement | Grid coupling |
| **Tracks parent intervals** | โœ… Yes | โœ… Yes | โœ… Yes (both grids) |
| **Preserves original grid** | As parent | As parent | Both grids intact |
| **Best for** | h-refinement FEM | AMR, error-driven | Multi-physics |
| **Memory overhead** | Low | Low | Medium |
| **Complexity** | Simple | Medium | Higher |

### Refinement Strategy Examples

**Uniform refinement** - Every interval gets 2 extra points (โ†’ 3 sub-intervals each):

```rust
use grid1d::{Grid1D, IntervalPartition, intervals::*, scalars::{NumIntervals, PositiveNumPoints1D}};
use try_create::TryNew;

let grid = Grid1D::uniform(IntervalClosed::new(0.0, 1.0), NumIntervals::try_new(4).unwrap());
// Original: 4 intervals

let refinement = grid.refine_uniform(&PositiveNumPoints1D::try_new(2).unwrap());
// Refined: 12 intervals (4 ร— 3)

// Track parent-child relationships
for (refined_id, original_id) in refinement.iter_refined_with_mapping() {
    println!("Refined interval {} came from original interval {}", 
             refined_id.as_ref(), original_id.as_ref());
}
```

**Selective refinement** - Only refine where needed (adaptive mesh refinement):

```rust
use grid1d::{Grid1D, IntervalPartition, intervals::*, scalars::{NumIntervals, PositiveNumPoints1D, IntervalId}};
use std::collections::BTreeMap;
use try_create::TryNew;

let grid = Grid1D::uniform(IntervalClosed::new(0.0, 1.0), NumIntervals::try_new(4).unwrap());

// Refine only intervals 0 and 2
let plan = BTreeMap::from([
    (IntervalId::new(0), PositiveNumPoints1D::try_new(3).unwrap()), // 4 sub-intervals
    (IntervalId::new(2), PositiveNumPoints1D::try_new(1).unwrap()), // 2 sub-intervals
]);

let refinement = grid.refine(&plan);
// Result: intervals 1 and 3 unchanged, 0 and 2 refined
```

**Grid union** - Couple two grids for multi-physics:

```rust
use grid1d::{Grid1D, Grid1DUnion, IntervalPartition, intervals::*, scalars::NumIntervals};
use try_create::TryNew;

// Flow solver: coarse grid
let flow_grid = Grid1D::uniform(
    IntervalClosed::new(0.0, 1.0), 
    NumIntervals::try_new(10).unwrap()
);

// Chemistry solver: fine grid in reaction zone
let chem_grid = Grid1D::uniform(
    IntervalClosed::new(0.0, 1.0), 
    NumIntervals::try_new(50).unwrap()
);

// Unified grid for coupling
let coupled = Grid1DUnion::try_new(&flow_grid, &chem_grid).unwrap();

// Transfer data between physics
for (unified_id, flow_id, chem_id) in coupled.iter_interval_mappings() {
    // Map solution from flow grid to chemistry grid and vice versa
}
```

## Use Case โ†’ Recommended Configuration

### Finite Difference Methods (Regular Mesh)

**Scenario**: Solving PDEs on uniform grids

```rust
// Recommended configuration
type Real = RealNative64StrictFiniteInDebug;  // Debug safety
type Domain = IntervalClosed<Real>;            // Closed boundaries

let grid = Grid1D::uniform(
    Domain::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap()),
    NumIntervals::try_new(1000).unwrap()
);
```

**Why?**

- โœ… Uniform grid: O(1) point location for maximum performance
- โœ… Debug validation: Catches NaN/Inf during development
- โœ… Closed interval: Standard for boundary value problems
- โœ… Release performance: Same as raw f64

### Finite Element Methods (Adaptive Mesh)

**Scenario**: FEM with mesh refinement in regions of interest

```rust
use grid1d::{Grid1D, IntervalPartition, intervals::*, scalars::{NumIntervals, PositiveNumPoints1D, IntervalId}};
use num_valid::RealNative64StrictFinite;
use std::collections::BTreeMap;
use try_create::TryNew;

// Recommended configuration
type Real = RealNative64StrictFinite;  // Always validated
type Domain = IntervalClosed<Real>;

// Start with coarse base mesh
let base_grid = Grid1D::uniform(
    Domain::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap()),
    NumIntervals::try_new(10).unwrap()
);

// Compute error estimator, identify intervals needing refinement
let error_threshold = 0.01;
let refinement_plan: BTreeMap<IntervalId, PositiveNumPoints1D> = (0..*base_grid.num_intervals().as_ref())
    .filter(|&i| estimate_error(i) > error_threshold)
    .map(|i| (IntervalId::new(i), PositiveNumPoints1D::try_new(1).unwrap()))
    .collect();

// Refine selectively where solution changes rapidly
let refined = base_grid.refine(&refinement_plan);

fn estimate_error(_interval: usize) -> f64 { 0.02 } // Placeholder
```

**Why?**

- โœ… Selective refinement: Only refine where errors are large
- โœ… Always validated: Prevents propagation of numerical errors
- โœ… Refinement tracking: Maintains parent-child relationships
- โœ… Flexible spacing: Optimal resolution where needed

### Computational Fluid Dynamics (Boundary Layers)

**Scenario**: Viscous flow with wall boundary layers

```rust
use grid1d::{Grid1D, intervals::*};
use num_valid::RealNative64StrictFiniteInDebug;
use sorted_vec::partial::SortedSet;

// Recommended configuration
type Real = RealNative64StrictFiniteInDebug;
type Domain = IntervalClosed<Real>;

// Generate boundary layer mesh with geometric stretching
fn create_boundary_layer_distribution(
    wall_position: f64,
    outer_position: f64,
    first_cell_height: f64,
    stretching_ratio: f64,
    max_points: usize,
) -> Vec<f64> {
    let mut coords = vec![wall_position];
    let mut y = wall_position;
    let mut dy = first_cell_height;
    
    for _ in 1..max_points {
        y += dy;
        if y >= outer_position {
            coords.push(outer_position);
            break;
        }
        coords.push(y);
        dy *= stretching_ratio;
    }
    coords
}

let coords = create_boundary_layer_distribution(0.0, 1.0, 0.001, 1.2, 50);

// Domain is inferred from first and last coordinates
let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(
    SortedSet::from_unsorted(coords)
).unwrap();
```

**Why?**

- โœ… Non-uniform grid: Fine near wall, coarse in freestream
- โœ… Custom distribution: Precise control over point clustering
- โœ… Performance: Fast lookups even with non-uniform spacing
- โœ… Simplified API: Domain inferred from coordinates

### Multi-Physics Coupling

**Scenario**: Coupling fluid flow with chemical reactions

```rust
use grid1d::{Grid1D, Grid1DUnion, IntervalPartition, intervals::*, scalars::NumIntervals};
use num_valid::RealNative64StrictFinite;
use sorted_vec::partial::SortedSet;
use try_create::TryNew;

// Recommended configuration
type Real = RealNative64StrictFinite;  // Safety for complex coupling
type Domain = IntervalClosed<Real>;

// Flow grid: coarse global mesh
let flow_grid = Grid1D::uniform(
    Domain::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap()),
    NumIntervals::try_new(20).unwrap()
);

// Chemistry grid: fine mesh in reaction zone (non-uniform)
let chem_coords: Vec<f64> = (0..=100).map(|i| {
    let t = i as f64 / 100.0;
    // Cluster points near x=0.5 (reaction zone)
    0.5 + 0.5 * (std::f64::consts::PI * (t - 0.5)).tanh()
}).collect();

let chemistry_grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(
    SortedSet::from_unsorted(chem_coords)
).unwrap();

// Unified grid for data transfer
let coupled = Grid1DUnion::try_new(&flow_grid, &chemistry_grid).unwrap();

// Map between grids for data exchange
for (unified_id, flow_id, chem_id) in coupled.iter_interval_mappings() {
    // Transfer temperature from flow โ†’ chemistry
    // Transfer reaction rates from chemistry โ†’ flow
    println!("Unified {} maps to flow {}, chemistry {}", 
             unified_id.as_ref(), flow_id.as_ref(), chem_id.as_ref());
}
```

**Why?**

- โœ… Grid union: Preserves both discretizations
- โœ… Bidirectional mapping: Efficient data transfer
- โœ… Validated scalars: Prevents coupling instabilities
- โœ… Mixed grid types: Uniform flow + non-uniform chemistry

### High-Precision Scientific Computing

**Scenario**: Numerical analysis requiring exact arithmetic

```rust
#[cfg(feature = "rug")]
{
    // Recommended configuration
    type Real = RealRugStrictFinite<256>;  // 256-bit precision
    type Domain = IntervalClosed<Real>;
    
    let grid = Grid1D::uniform(
        Domain::new(
            Real::try_new(0.0).unwrap(),
            Real::try_new(1.0).unwrap()
        ),
        NumIntervals::try_new(100).unwrap()
    );
}
```

**Why?**

- โœ… Arbitrary precision: Eliminates rounding errors
- โœ… Validated: Maintains numerical integrity
- โœ… Same API: Easy to switch from f64

### Real-Time Applications

**Scenario**: Simulation loop with strict timing requirements

```rust
// Recommended configuration
type Real = f64;  // Maximum performance, no validation
type Domain = IntervalClosed<Real>;

let grid = Grid1D::uniform(
    Domain::new(0.0, 1.0),
    NumIntervals::try_new(1000).unwrap()
);

// In real-time loop
loop {
    // O(1) point location - predictable timing
    let interval_id = grid.find_interval_id_of_point(&sensor_value);
    // ... process ...
}
```

**Why?**

- โœ… Raw f64: Zero overhead, predictable performance
- โœ… Uniform grid: O(1) lookups, no branch prediction issues
- โœ… No validation: No runtime checks in critical path

## Performance Tuning Guidelines

### When to Choose Uniform Grid

โœ… **Choose uniform grid when:**

- All intervals need equal spacing
- Maximum performance is critical
- Simple, regular domain discretization
- Point location happens frequently

โŒ **Avoid uniform grid when:**

- Features occur at different scales
- Adaptive refinement is needed
- Boundary layer resolution required

### When to Choose Non-Uniform Grid

โœ… **Choose non-uniform grid when:**

- Adaptive spacing is beneficial
- Multiple length scales present
- Boundary layer capture needed
- Features localized in space

โŒ **Avoid non-uniform grid when:**

- Uniform spacing is sufficient
- Maximum performance is critical
- Simple regular problem

### When to Use Parallel Point Location

โœ… **Use `find_intervals_for_points_parallel()` when:**

- Locating โ‰ฅ1,000 points at once
- Running on multi-core systems
- Point location is a bottleneck
- Processing large datasets

โŒ **Use sequential `find_intervals_for_points()` when:**

- Locating < 1,000 points
- Single-threaded environment required
- Need deterministic ordering
- Rayon overhead would dominate

**Performance guidance:**

| Points | Sequential | Parallel | Speedup |
|--------|------------|----------|------|
| 100 | โœ… Faster | โŒ Overhead | N/A |
| 1,000 | โ‰ˆ Equal | โ‰ˆ Equal | ~1ร— |
| 10,000 | Slower | โœ… Faster | ~3-4ร— |
| 100,000+ | Much slower | โœ… Much faster | ~6-8ร— |

### When to Use Grid Union

โœ… **Use grid union when:**

- Coupling multiple physics
- Different solvers on different grids
- Need to preserve original grid structure
- Frequent data transfer between grids

โŒ **Avoid grid union when:**

- Single physics problem
- Don't need grid mapping
- Memory is constrained

## Scalar Type Performance Impact

### Benchmarked Overheads (relative to f64)

| Operation | f64 | RealNative64StrictFiniteInDebug (Debug) | RealNative64StrictFiniteInDebug (Release) | RealNative64StrictFinite |
|-----------|-----|----------------------------------------|-------------------------------------------|--------------------------|
| Arithmetic | 1.0ร— | 1.5-2.0ร— | 1.0ร— | 1.05-1.10ร— |
| Comparison | 1.0ร— | 1.3-1.5ร— | 1.0ร— | 1.02-1.05ร— |
| Grid creation | 1.0ร— | 1.5ร— | 1.0ร— | 1.10ร— |
| Point location | 1.0ร— | 1.2ร— | 1.0ร— | 1.05ร— |

**Key takeaway**: `RealNative64StrictFiniteInDebug` has zero overhead in release builds.

## Migration Strategies

### From f64 to Validated Types

**Step 1**: Start with raw f64

```rust
let grid = Grid1D::uniform(
    IntervalClosed::new(0.0_f64, 1.0_f64),
    NumIntervals::try_new(100).unwrap()
);
```

**Step 2**: Add debug validation (no code changes needed in release!)

```rust
type Real = RealNative64StrictFiniteInDebug;
let grid = Grid1D::uniform(
    IntervalClosed::new(
        Real::try_new(0.0).unwrap(),
        Real::try_new(1.0).unwrap()
    ),
    NumIntervals::try_new(100).unwrap()
);
```

**Step 3**: If safety-critical, use always-validated

```rust
type Real = RealNative64StrictFinite;
// Same code as Step 2
```

### From Uniform to Non-Uniform

**Before** (uniform):

```rust
use grid1d::{Grid1D, intervals::*, scalars::NumIntervals};
use try_create::TryNew;

let grid = Grid1D::uniform(
    IntervalClosed::new(0.0, 1.0),
    NumIntervals::try_new(100).unwrap()
);
```

**After** (non-uniform with custom spacing):

```rust
use grid1d::{Grid1D, intervals::*};
use sorted_vec::partial::SortedSet;

fn generate_custom_distribution() -> Vec<f64> {
    // Example: cluster points near boundaries
    (0..=100).map(|i| {
        let t = i as f64 / 100.0;
        // Chebyshev-like distribution
        0.5 * (1.0 - (std::f64::consts::PI * t).cos())
    }).collect()
}

let coords = generate_custom_distribution();
// Domain is inferred from first and last coordinates
let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(
    SortedSet::from_unsorted(coords)
).unwrap();
```

## Common Pitfalls and Solutions

### Pitfall 1: Using Wrong Grid Type

โŒ **Wrong**:

```rust
use grid1d::{Grid1D, intervals::*};
use sorted_vec::partial::SortedSet;

// Using non-uniform grid when uniform would work
let coords: Vec<f64> = (0..=100).map(|i| i as f64 / 100.0).collect();
let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(
    SortedSet::from_unsorted(coords)
).unwrap();  // O(log n) lookups - unnecessary overhead!
```

โœ… **Correct**:

```rust
use grid1d::{Grid1D, intervals::*, scalars::NumIntervals};
use try_create::TryNew;

// Use uniform grid for better performance
let grid = Grid1D::uniform(
    IntervalClosed::new(0.0, 1.0),
    NumIntervals::try_new(100).unwrap()
);  // O(1) lookups!
```

### Pitfall 2: Over-validating in Performance-Critical Code

โŒ **Wrong**:

```rust
type Real = RealNative64StrictFinite;  // Always validates

// In hot loop
for _ in 0..1_000_000 {
    let result = a + b;  // Validates every operation
}
```

โœ… **Correct**:

```rust
type Real = RealNative64StrictFiniteInDebug;  // Validates only in debug

// In hot loop - no overhead in release
for _ in 0..1_000_000 {
    let result = a + b;  // Fast in release
}
```

### Pitfall 3: Forgetting to Handle Errors

โŒ **Wrong**:

```rust
use grid1d::{Grid1D, intervals::*};
use sorted_vec::partial::SortedSet;

let coords = SortedSet::from_unsorted(vec![0.0, 0.5, 1.0]);
let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords).unwrap();  // Panics on error!
```

โœ… **Correct**:

```rust
use grid1d::{Grid1D, intervals::*};
use sorted_vec::partial::SortedSet;

let coords = SortedSet::from_unsorted(vec![0.0, 0.5, 1.0]);
let grid = Grid1D::<IntervalClosed<f64>>::try_from_sorted(coords)
    .map_err(|e| {
        eprintln!("Grid creation failed: {:?}", e);
        e
    })?;
```

### Pitfall 4: Using new() with Untrusted Input

โŒ **Wrong**:

```rust
use grid1d::intervals::*;

// new() panics if lower > upper!
let user_input_lo = get_user_input(); // Could be anything
let user_input_hi = get_user_input();
let interval = IntervalClosed::new(user_input_lo, user_input_hi); // ๐Ÿ’ฅ May panic!

fn get_user_input() -> f64 { 5.0 } // Placeholder
```

โœ… **Correct**:

```rust
use grid1d::intervals::*;

let user_input_lo = get_user_input();
let user_input_hi = get_user_input();
let interval = IntervalClosed::try_new(user_input_lo, user_input_hi)
    .map_err(|e| format!("Invalid interval: {:?}", e))?;

fn get_user_input() -> f64 { 5.0 } // Placeholder
```

## Summary Recommendations

### For Most Users (โญ Recommended)

```rust
use grid1d::{Grid1D, intervals::*, scalars::NumIntervals};
use num_valid::RealNative64StrictFiniteInDebug;
use try_create::TryNew;

type Real = RealNative64StrictFiniteInDebug;
type Domain = IntervalClosed<Real>;

// Uniform grid for regular problems
let grid = Grid1D::uniform(
    Domain::new(Real::try_new(0.0).unwrap(), Real::try_new(1.0).unwrap()),
    NumIntervals::try_new(100).unwrap()
);
```

**This gives you**:

- โœ… Maximum performance in release builds
- โœ… Safety validation during development
- โœ… O(1) point location for uniform grids
- โœ… Easy to change if needs evolve

### Quick Reference Card

| Need | Use |
|------|-----|
| Regular mesh, maximum speed | `Grid1DUniform` + `f64` |
| **Most applications** | **`Grid1DUniform` + `RealNative64StrictFiniteInDebug`** |
| Adaptive mesh | `Grid1DNonUniform` + `RealNative64StrictFiniteInDebug` |
| Safety-critical | Any grid + `RealNative64StrictFinite` |
| Multi-physics | `Grid1DUnion` + `RealNative64StrictFinite` |
| High precision | Any grid + `RealRugStrictFinite<N>` |
| Periodic domains | Any grid + `IntervalLowerClosedUpperOpen` |

---

For more details, see:

- [Complete Tutorial]./TUTORIAL.md
- [API Documentation]https://docs.rs/grid1d
- [README]./README.md