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
//! Integration methods for cubic splines
//!
//! This module provides integration functionality for cubic splines, including
//! basic integration within the spline domain and extrapolation-aware integration
//! for compatibility with SciPy's CubicSpline.
use crate::error::{InterpolateError, InterpolateResult};
use crate::traits::InterpolationFloat;
use super::core::CubicSpline;
use super::types::IntegrationRegion;
impl<F: InterpolationFloat + ToString> CubicSpline<F> {
/// Integrate the spline from a to b
///
/// Computes the definite integral of the cubic spline over the interval [a, b].
/// The integration is performed analytically using the polynomial coefficients.
///
/// # Arguments
///
/// * `a` - Lower bound of integration
/// * `b` - Upper bound of integration
///
/// # Returns
///
/// The definite integral of the spline from a to b
///
/// # Errors
///
/// Returns `InterpolateError::OutOfBounds` if either `a` or `b` is outside
/// the interpolation domain.
///
/// # Examples
///
/// ```rust
/// use scirs2_core::ndarray::array;
/// use scirs2_interpolate::spline::CubicSpline;
///
/// let x = array![0.0, 1.0, 2.0, 3.0];
/// let y = array![0.0, 1.0, 4.0, 9.0];
/// let spline = CubicSpline::new(&x.view(), &y.view()).expect("Operation failed");
///
/// let integral = spline.integrate(0.5, 2.5).expect("Operation failed");
/// println!("Integral from 0.5 to 2.5: {}", integral);
/// ```
pub fn integrate(&self, a: F, b: F) -> InterpolateResult<F> {
// Handle reversed bounds
if a > b {
return Ok(-self.integrate(b, a)?);
}
if a == b {
return Ok(F::zero());
}
// Check bounds
let x_min = self.x()[0];
let x_max = self.x()[self.x().len() - 1];
if a < x_min || b > x_max {
return Err(InterpolateError::OutOfBounds(
"Integration bounds outside interpolation range".to_string(),
));
}
// Find the segments containing a and b
let mut idx_a = 0;
let mut idx_b = 0;
for i in 0..self.x().len() - 1 {
if a >= self.x()[i] && a <= self.x()[i + 1] {
idx_a = i;
}
if b >= self.x()[i] && b <= self.x()[i + 1] {
idx_b = i;
}
}
let mut integral = F::zero();
// If both points are in the same segment
if idx_a == idx_b {
integral = self.integrate_segment(idx_a, a, b)?;
} else {
// Integrate from a to the end of its segment
integral += self.integrate_segment(idx_a, a, self.x()[idx_a + 1])?;
// Integrate all complete segments in between
for i in (idx_a + 1)..idx_b {
integral += self.integrate_segment(i, self.x()[i], self.x()[i + 1])?;
}
// Integrate from the start of b's segment to b
integral += self.integrate_segment(idx_b, self.x()[idx_b], b)?;
}
Ok(integral)
}
/// SciPy-compatible integration method
///
/// This is an alias for the `integrate` method to maintain compatibility
/// with SciPy's CubicSpline interface.
///
/// # Arguments
///
/// * `a` - Lower bound of integration
/// * `b` - Upper bound of integration
///
/// # Returns
///
/// The definite integral from a to b
pub fn integrate_scipy(&self, a: F, b: F) -> InterpolateResult<F> {
self.integrate(a, b)
}
/// Integrate the spline from a to b with extrapolation support
///
/// This enhanced integration method supports extrapolation when integration bounds
/// extend beyond the spline domain, providing full SciPy compatibility.
///
/// # Arguments
///
/// * `a` - Lower bound of integration
/// * `b` - Upper bound of integration
/// * `extrapolate` - Extrapolation mode for out-of-bounds integration
/// - `None`: Use default behavior (error for out-of-bounds)
/// - `Some(ExtrapolateMode::Error)`: Raise error for out-of-bounds
/// - `Some(ExtrapolateMode::Extrapolate)`: Linear extrapolation using endpoint derivatives
/// - `Some(ExtrapolateMode::Nearest)`: Constant extrapolation using boundary values
///
/// # Returns
///
/// The definite integral of the spline from a to b
///
/// # Examples
///
/// ```rust
/// use scirs2_core::ndarray::array;
/// use scirs2_interpolate::spline::CubicSpline;
/// use scirs2_interpolate::interp1d::ExtrapolateMode;
///
/// let x = array![0.0, 1.0, 2.0, 3.0];
/// let y = array![0.0, 1.0, 4.0, 9.0];
/// let spline = CubicSpline::new(&x.view(), &y.view()).expect("Operation failed");
///
/// // Integrate within domain
/// let integral1 = spline.integrate_with_extrapolation(0.5, 2.5, None).expect("Operation failed");
///
/// // Integrate with extrapolation beyond domain
/// let integral2 = spline.integrate_with_extrapolation(-1.0, 4.0,
/// Some(ExtrapolateMode::Extrapolate)).expect("Operation failed");
/// ```
pub fn integrate_with_extrapolation(
&self,
a: F,
b: F,
extrapolate: Option<crate::interp1d::ExtrapolateMode>,
) -> InterpolateResult<F> {
if a == b {
return Ok(F::zero());
}
// Handle reversed bounds
if a > b {
return Ok(-self.integrate_with_extrapolation(b, a, extrapolate)?);
}
let x_min = self.x()[0];
let x_max = self.x()[self.x().len() - 1];
// If both bounds are within domain, use standard integration
if a >= x_min && b <= x_max {
return self.integrate(a, b);
}
// Handle extrapolation cases
let extrapolate_mode = extrapolate.unwrap_or(crate::interp1d::ExtrapolateMode::Error);
match extrapolate_mode {
crate::interp1d::ExtrapolateMode::Error => {
Err(InterpolateError::OutOfBounds(
"Integration bounds outside interpolation range and extrapolate=false".to_string(),
))
}
crate::interp1d::ExtrapolateMode::Extrapolate => {
self.integrate_with_linear_extrapolation(a, b)
}
crate::interp1d::ExtrapolateMode::Nearest => {
self.integrate_with_constant_extrapolation(a, b)
}
}
}
/// Integrate a single polynomial segment from x1 to x2
///
/// This method computes the definite integral of a cubic polynomial
/// over the specified interval.
///
/// # Arguments
///
/// * `segment` - Index of the polynomial segment
/// * `x1` - Lower bound of integration
/// * `x2` - Upper bound of integration
///
/// # Returns
///
/// The integral of the polynomial segment from x1 to x2
///
/// # Errors
///
/// Returns an error if float conversion fails.
pub(crate) fn integrate_segment(&self, segment: usize, x1: F, x2: F) -> InterpolateResult<F> {
if x1 == x2 {
return Ok(F::zero());
}
let x_base = self.x()[segment];
let dx1 = x1 - x_base;
let dx2 = x2 - x_base;
let a = self.coeffs()[[segment, 0]];
let b = self.coeffs()[[segment, 1]];
let c = self.coeffs()[[segment, 2]];
let d = self.coeffs()[[segment, 3]];
// Convert constants
let two = F::from_f64(2.0).ok_or_else(|| {
InterpolateError::ComputationError(
"Failed to convert constant 2.0 to float type".to_string(),
)
})?;
let three = F::from_f64(3.0).ok_or_else(|| {
InterpolateError::ComputationError(
"Failed to convert constant 3.0 to float type".to_string(),
)
})?;
let four = F::from_f64(4.0).ok_or_else(|| {
InterpolateError::ComputationError(
"Failed to convert constant 4.0 to float type".to_string(),
)
})?;
// Antiderivative of a + b*dx + c*dx^2 + d*dx^3 is:
// a*dx + b*dx^2/2 + c*dx^3/3 + d*dx^4/4
let antiderivative = |dx: F| -> InterpolateResult<F> {
Ok(a * dx
+ b * dx * dx / two
+ c * dx * dx * dx / three
+ d * dx * dx * dx * dx / four)
};
let upper = antiderivative(dx2)?;
let lower = antiderivative(dx1)?;
Ok(upper - lower)
}
/// Integrate with linear extrapolation beyond domain boundaries
///
/// This method extends the spline linearly beyond its domain using the
/// endpoint derivatives, then integrates over the extended range.
///
/// # Arguments
///
/// * `a` - Lower bound of integration
/// * `b` - Upper bound of integration
///
/// # Returns
///
/// The integral including extrapolated regions
fn integrate_with_linear_extrapolation(&self, a: F, b: F) -> InterpolateResult<F> {
let x_min = self.x()[0];
let x_max = self.x()[self.x().len() - 1];
let mut integral = F::zero();
// Determine integration regions
let a_clamped = a.max(x_min);
let b_clamped = b.min(x_max);
// Left extrapolation region
if a < x_min {
let region_end = b.min(x_min);
integral += self.integrate_left_extrapolation(a, region_end)?;
}
// Interior region
if a_clamped < b_clamped {
integral += self.integrate(a_clamped, b_clamped)?;
}
// Right extrapolation region
if b > x_max {
let region_start = a.max(x_max);
integral += self.integrate_right_extrapolation(region_start, b)?;
}
Ok(integral)
}
/// Integrate with constant extrapolation beyond domain boundaries
///
/// This method extends the spline with constant values beyond its domain,
/// then integrates over the extended range.
///
/// # Arguments
///
/// * `a` - Lower bound of integration
/// * `b` - Upper bound of integration
///
/// # Returns
///
/// The integral including extrapolated regions
fn integrate_with_constant_extrapolation(&self, a: F, b: F) -> InterpolateResult<F> {
let x_min = self.x()[0];
let x_max = self.x()[self.x().len() - 1];
let mut integral = F::zero();
// Determine integration regions
let a_clamped = a.max(x_min);
let b_clamped = b.min(x_max);
// Left extrapolation region (constant y[0])
if a < x_min {
let region_end = b.min(x_min);
let width = region_end - a;
integral += self.y()[0] * width;
}
// Interior region
if a_clamped < b_clamped {
integral += self.integrate(a_clamped, b_clamped)?;
}
// Right extrapolation region (constant y[n-1])
if b > x_max {
let region_start = a.max(x_max);
let width = b - region_start;
let n = self.y().len() - 1;
integral += self.y()[n] * width;
}
Ok(integral)
}
/// Integrate the left linear extrapolation from a to b
///
/// Uses linear extrapolation based on the left endpoint derivative.
///
/// # Arguments
///
/// * `a` - Lower bound (must be < x_min)
/// * `b` - Upper bound (must be <= x_min)
///
/// # Returns
///
/// The integral of the left extrapolation
fn integrate_left_extrapolation(&self, a: F, b: F) -> InterpolateResult<F> {
let x0 = self.x()[0];
let y0 = self.y()[0];
let dy0 = self.derivative_n(x0, 1)?;
// Linear function: y(x) = y0 + dy0 * (x - x0)
// Integral from a to b: (b-a) * y0 + dy0 * (b^2 - a^2)/2 - dy0 * x0 * (b-a)
let width = b - a;
let two = F::from_f64(2.0).ok_or_else(|| {
InterpolateError::ComputationError(
"Failed to convert constant 2.0 to float type".to_string(),
)
})?;
let linear_term = width * y0;
let quadratic_term = dy0 * (b * b - a * a) / two;
let offset_term = dy0 * x0 * width;
Ok(linear_term + quadratic_term - offset_term)
}
/// Integrate the right linear extrapolation from a to b
///
/// Uses linear extrapolation based on the right endpoint derivative.
///
/// # Arguments
///
/// * `a` - Lower bound (must be >= x_max)
/// * `b` - Upper bound (must be > x_max)
///
/// # Returns
///
/// The integral of the right extrapolation
fn integrate_right_extrapolation(&self, a: F, b: F) -> InterpolateResult<F> {
let n = self.x().len() - 1;
let xn = self.x()[n];
let yn = self.y()[n];
let dyn_val = self.derivative_n(xn, 1)?;
// Linear function: y(x) = yn + dyn * (x - xn)
let width = b - a;
let two = F::from_f64(2.0).ok_or_else(|| {
InterpolateError::ComputationError(
"Failed to convert constant 2.0 to float type".to_string(),
)
})?;
let linear_term = width * yn;
let quadratic_term = dyn_val * (b * b - a * a) / two;
let offset_term = dyn_val * xn * width;
Ok(linear_term + quadratic_term - offset_term)
}
/// Classify the integration region relative to the spline domain
///
/// This helper function determines whether the integration bounds fall
/// within the spline domain or require extrapolation.
///
/// # Arguments
///
/// * `a` - Lower bound of integration
/// * `b` - Upper bound of integration
///
/// # Returns
///
/// Classification of the integration region
pub(crate) fn classify_integration_region(&self, a: F, b: F) -> IntegrationRegion {
let x_min = self.x()[0];
let x_max = self.x()[self.x().len() - 1];
if b <= x_min {
IntegrationRegion::LeftExtrapolation
} else if a >= x_max {
IntegrationRegion::RightExtrapolation
} else {
IntegrationRegion::Interior
}
}
}