series 0.15.0

Laurent series and polynomials
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
use crate::ops::{Exp, Ln, Pow};
use crate::traits::{ExpCoeff, MulInverse};
use crate::util::trim_slice_start_zero;
use crate::zero_ref::zero_ref;
use crate::{Coeff, Iter, SeriesSlice, anon_series::AnonSeries};

use std::ops::{
    Add, AddAssign, Div, DivAssign, Index, Mul, MulAssign, Neg, Sub, SubAssign,
};

/// View into a Laurent series with an anonymous variable
#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd)]
pub struct AnonSeriesSlice<'a, C: Coeff> {
    pub(crate) min_pow: isize,
    pub(crate) coeffs: &'a [C],
}

// needs manual implementation,
// #[derive(Copy)] can't deal with lifetimes in rust 1.36
impl<C: Coeff> std::marker::Copy for AnonSeriesSlice<'_, C> {}

impl<C: Coeff> std::clone::Clone for AnonSeriesSlice<'_, C> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, C: Coeff> AnonSeriesSlice<'a, C> {
    pub(super) fn new(min_pow: isize, coeffs: &'a [C]) -> Self {
        let mut res = AnonSeriesSlice { min_pow, coeffs };
        res.trim();
        res
    }

    fn trim(&mut self) {
        let removed = trim_slice_start_zero(&mut self.coeffs);
        self.min_pow += removed as isize;
    }

    /// Get the leading power of the series expansion variable
    ///
    /// # Example
    ///
    /// ```rust
    /// # use series::{anon_series::AnonSeries, AsSlice};
    ///
    /// let s = AnonSeries::new(-1, vec![1, 2, 3]);
    /// assert_eq!(s.as_slice(..).min_pow(), -1);
    /// assert_eq!(s.as_slice(0..).min_pow(), 0);
    /// ```
    pub fn min_pow(&self) -> isize {
        self.min_pow
    }

    /// Get the power of the expansion variable where the slice is
    /// truncated.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use series::{anon_series::AnonSeries, AsSlice};
    ///
    /// let s = AnonSeries::new(-1, vec![1, 2, 3]);
    /// assert_eq!(s.as_slice(..).cutoff_pow(), 2);
    /// assert_eq!(s.as_slice(..1).cutoff_pow(), 1);
    /// ```
    pub fn cutoff_pow(&self) -> isize {
        self.min_pow + (self.coeffs.len() as isize)
    }

    /// Get the number of known coefficients in the series.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use series::{anon_series::AnonSeries, AsSlice};
    /// let s = AnonSeries::with_cutoff(-1..5, vec![1, 2, 3]);
    /// assert_eq!(s.as_slice(..).len(), 6);
    /// // This holds true for any series
    /// assert_eq!(s.as_slice(..).len(), (s.cutoff_pow() - s.min_pow()) as usize);
    /// ```
    pub fn len(&self) -> usize {
        self.coeffs.len()
    }

    /// Iterator over the series powers and coefficients.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use series::{anon_series::AnonSeries, AsSlice};
    ///
    /// let s = AnonSeries::new(-1, vec![1, 2, 3]);
    /// let slice = s.as_slice(..);
    /// let mut iter = slice.iter();
    /// assert_eq!(iter.next(), Some((-1, &1)));
    /// assert_eq!(iter.next(), Some((0, &2)));
    /// assert_eq!(iter.next(), Some((1, &3)));
    /// assert_eq!(iter.next(), None);
    /// ```
    pub fn iter(&self) -> Iter<'a, C> {
        (self.min_pow..).zip(self.coeffs.iter())
    }

    /// Split a series slice into two at the given power
    /// of the expansion variable.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use series::{anon_series::AnonSeries, AsSlice};
    ///
    /// let s = AnonSeries::new(-1, vec![1, 2, 3]);
    /// let (lower, upper) = s.as_slice(..).split_at(0);
    /// assert_eq!(lower.min_pow(), -1);
    /// assert_eq!(upper.min_pow(), 0);
    /// ```
    pub fn split_at(&self, pos: isize) -> (Self, Self) {
        let upos = (pos - self.min_pow()) as usize;
        let (lower, upper) = self.coeffs.split_at(upos);
        let lower = AnonSeriesSlice {
            min_pow: self.min_pow(),
            coeffs: lower,
        };
        let upper = AnonSeriesSlice {
            min_pow: pos,
            coeffs: upper,
        };
        (lower, upper)
    }

    /// Turn into a slice with a named expansion variable
    ///
    /// # Example
    ///
    /// ```rust
    /// # use series::{anon_series::AnonSeries, AsSlice};
    ///
    /// let s = AnonSeries::new(-1, vec![1, 2, 3]);
    /// let s = s.as_slice(..).in_var(&"x");
    /// assert_eq!(s.var(), &"x");
    /// ```
    pub fn in_var<Var>(self, var: &'a Var) -> SeriesSlice<'a, Var, C> {
        SeriesSlice { var, series: self }
    }

    /// Try to get the series coefficient of the expansion variable to
    /// the given power.
    ///
    /// Returns [None] if the requested power is above the highest known
    /// power or below the leading power.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use series::{anon_series::AnonSeries, AsSlice};
    ///
    /// let s = AnonSeries::new(-1, vec![1, 2, 3]);
    /// let slice = s.as_slice(..);
    /// assert_eq!(slice.try_coeff(-5), None);
    /// assert_eq!(slice.try_coeff(-2), None);
    /// assert_eq!(slice.try_coeff(-1), Some(&1));
    /// assert_eq!(slice.try_coeff(0), Some(&2));
    /// assert_eq!(slice.try_coeff(1), Some(&3));
    /// assert_eq!(slice.try_coeff(2), None);
    /// assert_eq!(slice.try_coeff(5), None);
    /// ```
    pub fn try_coeff(&self, pow: isize) -> Option<&'a C> {
        if pow >= self.min_pow() && pow < self.cutoff_pow() {
            Some(self.coeff_in_range(pow))
        } else {
            None
        }
    }

    fn coeff_in_range(&self, pow: isize) -> &'a C {
        debug_assert!(pow >= self.min_pow());
        debug_assert!(pow < self.cutoff_pow());
        let idx = (pow - self.min_pow()) as usize;
        &self.coeffs[idx]
    }
}

impl<'a, C: 'static + Coeff + Send + Sync> AnonSeriesSlice<'a, C> {
    /// Get the series coefficient of the expansion variable to the
    /// given power.
    ///
    /// Returns None if the requested power is above the highest known
    /// power. Coefficients below the leading power are zero.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use series::{anon_series::AnonSeries, AsSlice};
    ///
    /// let s = AnonSeries::new(-1, vec![1, 2, 3]);
    /// let slice = s.as_slice(..);
    /// assert_eq!(slice.coeff(-5), Some(&0));
    /// assert_eq!(slice.coeff(-2), Some(&0));
    /// assert_eq!(slice.coeff(-1), Some(&1));
    /// assert_eq!(slice.coeff(0), Some(&2));
    /// assert_eq!(slice.coeff(1), Some(&3));
    /// assert_eq!(slice.coeff(2), None);
    /// assert_eq!(slice.coeff(5), None);
    /// ```
    pub fn coeff(&self, pow: isize) -> Option<&'a C> {
        if pow < self.min_pow() {
            return Some(zero_ref());
        }
        if pow >= self.cutoff_pow() {
            return None;
        }
        Some(self.coeff_in_range(pow))
    }
}

impl<C: Coeff> Index<isize> for AnonSeriesSlice<'_, C> {
    type Output = C;

    fn index(&self, index: isize) -> &Self::Output {
        &self.coeffs[(index - self.min_pow) as usize]
    }
}

impl<C> MulInverse for AnonSeriesSlice<'_, C>
where
    C: Coeff + SubAssign,
    for<'b> &'b C: Div<Output = C> + Mul<Output = C>,
{
    type Output = AnonSeries<C>;

    fn mul_inverse(self) -> Self::Output {
        let inv_min_pow = -self.min_pow;
        if self.coeffs.is_empty() {
            return AnonSeries::new(inv_min_pow, vec![]);
        }
        let a: Vec<_> =
            self.coeffs.iter().map(|c| c / &self.coeffs[0]).collect();
        let mut b = Vec::with_capacity(a.len());
        b.push(C::one());
        for n in 1..a.len() {
            let mut b_n = C::zero();
            for i in 0..n {
                b_n -= &a[n - i] * &b[i];
            }
            b.push(b_n);
        }
        let inv_coeffs: Vec<_> =
            b.iter().map(|b| b / &self.coeffs[0]).collect();
        AnonSeries::new(inv_min_pow, inv_coeffs)
    }
}

impl<'a, C: Coeff> Neg for AnonSeriesSlice<'a, C>
where
    &'a C: Neg<Output = C>,
{
    type Output = AnonSeries<C>;

    fn neg(self) -> Self::Output {
        let neg_coeff = self.coeffs.iter().map(|c| -c).collect();
        AnonSeries::new(self.min_pow, neg_coeff)
    }
}

impl<C: Coeff + Clone, Rhs> Add<Rhs> for AnonSeriesSlice<'_, C>
where
    AnonSeries<C>: AddAssign<Rhs>,
{
    type Output = AnonSeries<C>;

    fn add(self, other: Rhs) -> Self::Output {
        let mut res = AnonSeries::from(self);
        res += other;
        res
    }
}

impl<C: Coeff, T> Sub<T> for AnonSeriesSlice<'_, C>
where
    C: Clone,
    AnonSeries<C>: SubAssign<T>,
{
    type Output = AnonSeries<C>;

    fn sub(self, other: T) -> Self::Output {
        let mut res = AnonSeries::from(self);
        res -= other;
        res
    }
}

impl<'a, C: Coeff> Mul<AnonSeries<C>> for AnonSeriesSlice<'a, C>
where
    AnonSeries<C>: Mul<AnonSeriesSlice<'a, C>, Output = AnonSeries<C>>,
{
    type Output = AnonSeries<C>;

    fn mul(self, other: AnonSeries<C>) -> Self::Output {
        // TODO: assumes multiplication commutes
        other.mul(self)
    }
}

macro_rules! impl_mul_as_owned {
    ($($t:ty), *) => {
        $(
            impl<'a, C: Coeff> Mul<$t> for AnonSeriesSlice<'a, C>
            where
                AnonSeries<C>: Mul<$t, Output = AnonSeries<C>> + From<AnonSeriesSlice<'a, C>>,
            {
                type Output = AnonSeries<C>;

                fn mul(self, other: $t) -> Self::Output {
                    AnonSeries::from(self).mul(other)
                }
            }
        )*
    };
}

impl_mul_as_owned!(AnonSeriesSlice<'a, C>, &'a AnonSeries<C>, C, &'a C);

impl<C: Coeff, T> Div<T> for AnonSeriesSlice<'_, C>
where
    C: Clone,
    AnonSeries<C>: DivAssign<T>,
{
    type Output = AnonSeries<C>;

    fn div(self, other: T) -> Self::Output {
        let mut res = AnonSeries::from(self);
        res /= other;
        res
    }
}

impl<C: Coeff> Exp for AnonSeriesSlice<'_, C>
where
    for<'b> &'b C: Mul<Output = C>,
    for<'b> C: MulAssign<&'b C>,
    C: Clone
        + Div<Output = C>
        + Mul<Output = C>
        + AddAssign
        + Exp<Output = C>
        + From<i32>,
{
    type Output = AnonSeries<C>;

    fn exp(self) -> Self::Output {
        AnonSeries::new(0, self.exp_coeff())
    }
}

impl<C: Coeff> Ln for AnonSeriesSlice<'_, C>
where
    for<'b> C: Div<&'b C, Output = C>,
    for<'b> &'b C: Mul<Output = C> + Ln<Output = C>,
    C: Clone
        + SubAssign
        + Add<Output = C>
        + Mul<Output = C>
        + Div<Output = C>
        + From<i32>,
{
    type Output = AnonSeries<C>;

    /// Computes the logarithm of a series
    ///
    /// # Panics
    ///
    /// Panics if the series has only vanishing coefficients or does
    /// not start with power 0. Adjoin a variable with `in_var` to
    /// compute the logarithm of a series with a non-vanishing leading
    /// power.
    fn ln(self) -> Self::Output {
        assert_eq!(self.min_pow(), 0);
        assert!(!self.coeffs.is_empty());
        let c_k0 = &self.coeffs[0];
        // self.coeffs[0] = C::one();
        // for i in 1..self.coeffs.len() {
        //     self.coeffs[i] /= &c_k0;
        // }
        let a = &self.coeffs;
        let mut b = Vec::with_capacity(a.len());
        let b_0 = c_k0.ln();
        b.push(b_0);
        for n in 1..a.len() {
            b.push(a[n].clone() / c_k0);
            for i in 1..n {
                let num_factor = C::from(i as i32) / C::from(n as i32);
                let tmp = num_factor * (&a[n - i] * &b[i]) / c_k0;
                b[n] -= tmp;
            }
        }
        AnonSeries::new(0, b)
    }
}

impl<C: Coeff, T> Pow<T> for AnonSeriesSlice<'_, C>
where
    for<'b> AnonSeriesSlice<'b, C>: Ln<Output = AnonSeries<C>>,
    AnonSeries<C>: Mul<T>,
    <AnonSeries<C> as Mul<T>>::Output: Exp,
{
    type Output = <<AnonSeries<C> as Mul<T>>::Output as Exp>::Output;

    fn pow(self, exponent: T) -> Self::Output {
        (self.ln() * exponent).exp()
    }
}

impl<'a, C: Coeff, Var> From<SeriesSlice<'a, Var, C>>
    for AnonSeriesSlice<'a, C>
{
    fn from(source: SeriesSlice<'a, Var, C>) -> Self {
        source.series
    }
}