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
//! Summation, products, and series extension methods on [`Ex`].
//!
//! * [`Ex::summation`] / [`Ex::try_summation`] — symbolic `Σ`
//! * [`Ex::product_over`] / [`Ex::try_product_over`] — symbolic `Π`
//! * [`Ex::hypergeometric_ratio`] — the term ratio `t(k+1)/t(k)`
//! * [`Ex::is_absolutely_convergent`] — absolute convergence of `Σ t(k)`
//! * [`Ex::series_at_infinity`] / [`Ex::series_at_neg_infinity`] — asymptotic expansions
use tracing::debug_span;
use crate::api::expr::{Ex, Expr, Numeric};
use crate::base::errors::SymplexError;
use crate::base::node::ExprNode;
use crate::calculus::summation::{self, SumOutcome};
impl Expr<Numeric> {
// ── Summation ──────────────────────────────────────────────────
/// Evaluate `Σ_{var=lower}^{upper} self` symbolically.
///
/// Bounds may be concrete integers, symbolic expressions, or
/// `ctx.infinity()` / `ctx.neg_infinity()`. Strategies include exact
/// enumeration for small concrete ranges, Faulhaber's formula (any
/// degree, Bernoulli numbers), partial-fraction telescoping, harmonic
/// numbers, geometric and arithmetico-geometric series, binomial
/// identities (`Σ P(k)·C(n,k)·xᵏ` for any polynomial `P`), Gosper's
/// algorithm, and — for infinite sums — p-series (`ζ(2m)` in closed
/// form, `ζ(2m+1)` as a `zeta` node, `Σ (−1)ᵏ/(2k+1)² = G`), alternating
/// series, and a table of classical power series (`Σ xᵏ/k! = eˣ`, `sin`,
/// `cos`, `atan`, …).
///
/// Convergence of a geometric series with a *symbolic* ratio cannot be
/// decided (there is no `|r| < 1` assumption), so `Σ_{k≥0} rᵏ` with
/// symbolic `r` stays unevaluated; numeric ratios are decided exactly.
///
/// When no closed form is known the formal `Sum` node is returned.
/// Sums that provably diverge to `±∞` evaluate to `oo` / `-oo`; for
/// oscillating divergence the formal `Sum` is kept. Use
/// [`try_summation`](Self::try_summation) to get an error instead.
///
/// # Examples
///
/// ```
/// use symplex::prelude::*;
///
/// let ctx = Context::new();
/// let k = ctx.symbol("k");
/// let n = ctx.symbol("n");
///
/// // Σ_{k=1}^{n} k² = n³/3 + n²/2 + n/6
/// let s = k.powi(2).summation(&k, &ctx.int(1), &n);
/// assert_eq!(s.subs_i64(&n, 10).eval().to_string(), "385");
///
/// // Σ_{k=1}^{∞} 1/k² = π²/6
/// let basel = k.powi(-2).summation(&k, &ctx.int(1), &ctx.infinity());
/// assert_eq!(basel.to_string(), "1/6*pi^2");
///
/// // Σ_{k=0}^{∞} x^k/k! = e^x
/// let x = ctx.symbol("x");
/// let e = (x.pow(&k) / k.factorial()).summation(&k, &ctx.int(0), &ctx.infinity());
/// assert_eq!(e.to_string(), "exp(x)");
///
/// // Σ_{k=1}^{∞} 1/k³ = ζ(3)
/// let apery = k.powi(-3).summation(&k, &ctx.int(1), &ctx.infinity());
/// assert_eq!(apery.to_string(), "zeta(3)");
/// ```
#[must_use = "returns the evaluated sum; does not modify in place"]
pub fn summation(&self, var: &Ex, lower: &Ex, upper: &Ex) -> Ex {
let var_id = self.checked_id(var);
let lo_id = self.checked_id(lower);
let hi_id = self.checked_id(upper);
let _span = debug_span!("summation", body = ?self.raw_id()).entered();
let mut inner = self.inner.write();
let outcome = summation::summation(&mut inner.arena, self.raw_id(), var_id, lo_id, hi_id);
let id = match outcome {
SumOutcome::Closed(id) => id,
SumOutcome::Divergent(Some(inf)) => inf,
SumOutcome::Divergent(None) | SumOutcome::Unevaluated => inner
.arena
.intern(ExprNode::Sum(self.raw_id(), var_id, lo_id, hi_id)),
};
drop(inner);
self.wrap(id)
}
/// Like [`summation`](Self::summation), but returns `Err` when the sum
/// diverges ([`SymplexError::Divergent`]) or no closed form was found
/// ([`SymplexError::ComputationFailed`]).
///
/// # Examples
///
/// ```
/// use symplex::prelude::*;
///
/// let ctx = Context::new();
/// let k = ctx.symbol("k");
/// let harmonic = k.powi(-1).try_summation(&k, &ctx.int(1), &ctx.infinity());
/// assert!(matches!(harmonic, Err(SymplexError::Divergent { .. })));
///
/// let geometric = ctx.rational(1, 2).pow(&k).try_summation(&k, &ctx.int(0), &ctx.infinity());
/// assert_eq!(geometric.unwrap().to_string(), "2");
/// ```
pub fn try_summation(&self, var: &Ex, lower: &Ex, upper: &Ex) -> Result<Ex, SymplexError> {
let var_id = self.checked_id(var);
let lo_id = self.checked_id(lower);
let hi_id = self.checked_id(upper);
let _span = debug_span!("try_summation", body = ?self.raw_id()).entered();
let mut inner = self.inner.write();
let outcome = summation::summation(&mut inner.arena, self.raw_id(), var_id, lo_id, hi_id);
drop(inner);
match outcome {
SumOutcome::Closed(id) => {
let result = self.wrap(id);
if result.has_unevaluated() {
Err(SymplexError::ComputationFailed {
operation: "summation",
reason: "no closed form for part of the sum".into(),
})
} else {
Ok(result)
}
}
SumOutcome::Divergent(Some(inf)) => Err(SymplexError::Divergent {
operation: "summation",
reason: format!("the series diverges to {}", self.wrap(inf)),
}),
SumOutcome::Divergent(None) => Err(SymplexError::Divergent {
operation: "summation",
reason: "the series diverges (terms do not tend to zero)".into(),
}),
SumOutcome::Unevaluated => Err(SymplexError::ComputationFailed {
operation: "summation",
reason: "no closed form found".into(),
}),
}
}
// ── Products ───────────────────────────────────────────────────
/// Evaluate `Π_{var=lower}^{upper} self` symbolically.
///
/// Handles constant factors (`cⁿ`), `Π k = n!`, `Π (k+a)` as Gamma /
/// factorial ratios, `Π aᶠ⁽ᵏ⁾ = a^{Σ f(k)}`, products of factors, and
/// rational functions whose numerator and denominator factor into
/// linear factors over ℚ (`Π (1 − 1/k²) = (n+1)/(2n)`). Infinite
/// products are evaluated through the limit of the finite closed form
/// when that limit is exactly computable.
///
/// Returns the formal `Product` node when no closed form is known.
///
/// # Examples
///
/// ```
/// use symplex::prelude::*;
///
/// let ctx = Context::new();
/// let k = ctx.symbol("k");
/// let n = ctx.symbol("n");
///
/// assert_eq!(k.product_over(&k, &ctx.int(1), &n).to_string(), "n!");
///
/// // Π_{k=1}^{n} (1 + 1/k) = n + 1
/// let p = (&ctx.int(1) + &k.powi(-1)).product_over(&k, &ctx.int(1), &n);
/// assert_eq!(p.to_string(), "n + 1");
///
/// // Π_{k=2}^{∞} (1 − 1/k²) = 1/2
/// let p = (&ctx.int(1) - &k.powi(-2)).product_over(&k, &ctx.int(2), &ctx.infinity());
/// assert_eq!(p.to_string(), "1/2");
/// ```
#[must_use = "returns the evaluated product; does not modify in place"]
pub fn product_over(&self, var: &Ex, lower: &Ex, upper: &Ex) -> Ex {
let var_id = self.checked_id(var);
let lo_id = self.checked_id(lower);
let hi_id = self.checked_id(upper);
let _span = debug_span!("product_over", body = ?self.raw_id()).entered();
let mut inner = self.inner.write();
let outcome = summation::product(&mut inner.arena, self.raw_id(), var_id, lo_id, hi_id);
let id = match outcome {
SumOutcome::Closed(id) => id,
SumOutcome::Divergent(Some(inf)) => inf,
SumOutcome::Divergent(None) | SumOutcome::Unevaluated => inner
.arena
.intern(ExprNode::Product_(self.raw_id(), var_id, lo_id, hi_id)),
};
drop(inner);
self.wrap(id)
}
/// Like [`product_over`](Self::product_over), but returns `Err` when the
/// product diverges or no closed form was found.
pub fn try_product_over(&self, var: &Ex, lower: &Ex, upper: &Ex) -> Result<Ex, SymplexError> {
let var_id = self.checked_id(var);
let lo_id = self.checked_id(lower);
let hi_id = self.checked_id(upper);
let mut inner = self.inner.write();
let outcome = summation::product(&mut inner.arena, self.raw_id(), var_id, lo_id, hi_id);
drop(inner);
match outcome {
SumOutcome::Closed(id) => {
let result = self.wrap(id);
if result.has_unevaluated() {
Err(SymplexError::ComputationFailed {
operation: "product",
reason: "no closed form for part of the product".into(),
})
} else {
Ok(result)
}
}
SumOutcome::Divergent(_) => Err(SymplexError::Divergent {
operation: "product",
reason: "the infinite product diverges".into(),
}),
SumOutcome::Unevaluated => Err(SymplexError::ComputationFailed {
operation: "product",
reason: "no closed form found".into(),
}),
}
}
// ── Hypergeometric terms ───────────────────────────────────────
/// If `self` is a hypergeometric term in `var`, return the ratio
/// `self(var+1) / self(var)` as a rational function of `var`.
///
/// Returns `None` when the ratio is not a rational function of `var`
/// (e.g. for `sin(k)` or `k^k`). Symbolic parameters other than `var`
/// are allowed.
///
/// # Examples
///
/// ```
/// use symplex::prelude::*;
///
/// let ctx = Context::new();
/// let k = ctx.symbol("k");
/// let n = ctx.symbol("n");
///
/// let r = k.factorial().hypergeometric_ratio(&k).unwrap();
/// assert_eq!(r.to_string(), "k + 1");
///
/// let r = n.binomial(&k).hypergeometric_ratio(&k).unwrap();
/// assert_eq!(r.subs_i64(&n, 5).subs_i64(&k, 2).eval().to_string(), "1");
///
/// assert!(k.sin().hypergeometric_ratio(&k).is_none());
/// ```
#[must_use]
pub fn hypergeometric_ratio(&self, var: &Ex) -> Option<Ex> {
let var_id = self.checked_id(var);
let mut inner = self.inner.write();
let r = crate::calculus::gosper::is_hypergeometric(&mut inner.arena, self.raw_id(), var_id);
drop(inner);
r.map(|id| self.wrap(id))
}
// ── Convergence ────────────────────────────────────────────────
/// Test whether `Σ |self(var)|` converges (absolute convergence).
///
/// Sign-alternating factors such as `(−1)^k` are stripped before the
/// convergence tests run, so conditionally convergent series like
/// `Σ (−1)^k/k` return `Some(false)` here but `Some(true)` from
/// [`is_convergent`](Self::is_convergent).
///
/// # Examples
///
/// ```
/// use symplex::prelude::*;
///
/// let ctx = Context::new();
/// let k = ctx.symbol("k");
/// let alt = ctx.int(-1).pow(&k) / &k;
/// assert_eq!(alt.is_convergent(&k), Some(true));
/// assert_eq!(alt.is_absolutely_convergent(&k), Some(false));
/// ```
#[must_use]
pub fn is_absolutely_convergent(&self, var: &Ex) -> Option<bool> {
let var_id = self.checked_id(var);
let _span = debug_span!("is_absolutely_convergent").entered();
let mut inner = self.inner.write();
crate::calculus::convergence::is_absolutely_convergent(
&mut inner.arena,
self.raw_id(),
var_id,
)
}
// ── Asymptotic expansions ──────────────────────────────────────
/// Asymptotic expansion of `self` as `var → +∞`, with `n_terms` terms
/// in powers of `1/var`.
///
/// Internally substitutes `var = 1/t`, expands (Laurent-)series at
/// `t = 0`, and substitutes back. Returns a formal `Series` node when
/// the expansion cannot be computed.
///
/// # Examples
///
/// ```
/// use symplex::prelude::*;
///
/// let ctx = Context::new();
/// let x = ctx.symbol("x");
/// // x/(x+1) = 1 − 1/x + 1/x² − …
/// let s = (&x / &(&x + 1)).series_at_infinity(&x, 3);
/// let at_10 = s.subs_i64(&x, 10).eval_f64().unwrap();
/// assert!((at_10 - 0.91).abs() < 1e-12);
/// ```
#[must_use = "returns the expansion; does not modify in place"]
pub fn series_at_infinity(&self, var: &Ex, n_terms: u32) -> Ex {
self.series_at_infinity_impl(var, n_terms, false)
}
/// Asymptotic expansion of `self` as `var → −∞` (see
/// [`series_at_infinity`](Self::series_at_infinity)).
#[must_use = "returns the expansion; does not modify in place"]
pub fn series_at_neg_infinity(&self, var: &Ex, n_terms: u32) -> Ex {
self.series_at_infinity_impl(var, n_terms, true)
}
/// Like [`series_at_infinity`](Self::series_at_infinity), but returns
/// `Err` if the expansion could not be computed.
pub fn try_series_at_infinity(&self, var: &Ex, n_terms: u32) -> Result<Ex, SymplexError> {
let r = self.series_at_infinity(var, n_terms);
if r.has_unevaluated() {
Err(SymplexError::ComputationFailed {
operation: "series_at_infinity",
reason: "could not compute asymptotic expansion".into(),
})
} else {
Ok(r)
}
}
fn series_at_infinity_impl(&self, var: &Ex, n_terms: u32, negative: bool) -> Ex {
let var_id = self.checked_id(var);
let _span = debug_span!("series_at_infinity", expr = ?self.raw_id()).entered();
let mut inner = self.inner.write();
let id = crate::calculus::series::series_at_infinity(
&mut inner.arena,
self.raw_id(),
var_id,
n_terms,
negative,
);
let id = match id {
Ok(id) => id,
Err(_) => {
let point = if negative {
inner.arena.neg_infinity
} else {
inner.arena.infinity
};
let order = inner.arena.int(n_terms as i64);
inner
.arena
.intern(ExprNode::Series(self.raw_id(), var_id, point, order))
}
};
drop(inner);
self.wrap(id)
}
}