-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
polynomial.cljc
1747 lines (1479 loc) · 58.6 KB
/
polynomial.cljc
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#_"SPDX-License-Identifier: GPL-3.0"
^#:nextjournal.clerk
{:toc true
:visibility :hide-ns}
(ns emmy.polynomial
(:refer-clojure :exclude [extend divide identity abs])
(:require [clojure.set :as set]
[clojure.string :as cs]
[emmy.collection]
[emmy.differential :as sd]
[emmy.expression :as x]
[emmy.expression.analyze :as a]
[emmy.function :as f]
[emmy.generic :as g]
[emmy.modint :as mi]
[emmy.numsymb :as sym]
[emmy.polynomial.exponent :as xpt]
[emmy.polynomial.impl :as i]
[emmy.polynomial.interpolate :as pi]
[emmy.series :as series]
[emmy.special.factorial :as sf]
[emmy.structure :as ss]
[emmy.util :as u]
[emmy.util.aggregate :as ua]
[emmy.value :as v])
#?(:clj
(:import (clojure.lang AFn IFn IObj Seqable))))
;; # Flat Polynomial Form, for Commutative Rings
;;
;; This namespace builds up an implementation of a
;; multivariate [polynomial](https://en.wikipedia.org/wiki/Polynomial) data
;; structure and installs it into the tower of generic operations.
;;
;; Summarizing the [Wikipedia entry](https://en.wikipedia.org/wiki/Polynomial),
;; a polynomial is an expression of any number of 'variables', or
;; 'indeterminates' and concrete 'coefficients', combined using only the
;; operations of addition, subtraction and multiplication of coefficients and
;; variables.
;;
;; Here's an example of a polynomial of arity 2, i.e., a polynomial in two
;; variables:
;;
;; $$4 + 3x^2y + 5y^3 + 6x^4$$
;;
;; ## Terminology
;;
;; In the above example:
;;
;; - The full expression is called a 'polynomial'.
;;
;; - A polynomial is a sum of
;; many ['monomial'](https://en.wikipedia.org/wiki/Monomial) terms; these are
;; $4$, $3x^2y$, $5y^3$ and $6x^4$ in the example above.
;;
;; - Each monomial term is a product of a coefficient and a sequence of
;; 'exponents', some product of the term's variables. The monomial $3x^2y$ has
;; coefficient $3$ and exponents $x^2y$.
;;
;; NOTE that sometimes the exponents here are called "monomials", without the
;; coefficient. If you find that usage, the full 'coefficient * exponents' is
;; usually called a 'polynomial term'.
;;
;; - The number of variables present in a polynomial is called the 'arity' of
;; the polynomial. (The arity of our example is 2.)
;;
;; - A polynomial with a single variable is called a 'univariate' polynomial; a
;; multivariable polynomial is called a 'multivariate' polynomial.
;;
;; - The [degree](https://en.wikipedia.org/wiki/Degree_of_a_polynomial#Multiplication)
;; of a monomial term is the sum of the exponents of each variable in the
;; term, with the special case that the [degree of a 0
;; term](https://en.wikipedia.org/wiki/Degree_of_a_polynomial#Degree_of_the_zero_polynomial)
;; is defined as -1. The degrees of each term in our example are 0, 3, 3 and
;; 4, respectively.
;;
;; - The degree of a polynomial is the maximum of the degrees of the
;; polynomial's terms.
;;
;; There are, of course, more definitions! Whenever these come up in the
;; implementation below, see the documentation for explanation.
;;
;; ## Implementation
;;
;; Emmy makes the following implementation choices:
;;
;; - The exponents of a monomial are represented by an ordered mapping of
;; variable index => the exponent of that variable. $x^2z^3$ is represented as
;; `{0 2, 2 3}`, for example. See `emmy.polynomial.exponent` for the full
;; set of operations you can perform on a term's exponents.
;;
;; This representation is called `sparse` because variables with a 0 exponent
;; aren't included.
;;
;; - A monomial term is a vector of the form `[<exponents>, <coefficient>]`. The
;; coefficient can be any type! It's up to the user to supply coefficients
;; drawn from a commutative ring. See [[emmy.laws/ring]] for a
;; description of the properties coefficients should satisfy.
;;
;; - A polynomial is a sorted vector of monomials, sorted in some
;; consistent [Monomial order](https://en.wikipedia.org/wiki/Monomial_order).
;; See [[emmy.polynomial.impl/*monomial-order*]] for the current default.
;;
;; `emmy.polynomial.impl` builds up polynomial arithmetic on bare vectors
;; of monomials, for efficiency's sake. This namespace builds this base out into
;; a full [[Polynomial]] data structure with a fleshed-out API.
;;
;; To follow along in full, first read `emmy.polynomial.exponent`, then
;; `emmy.polynomial.impl`... then come back and continue from here.
;;
;; ## Polynomial Type Definition
;;
;; As noted above, a polynomial is defined by a sorted vector of terms.
;; The [[Polynomial]] type wraps up these `terms`, the `arity` of the polynomial
;; and optional metadata `m`.
(declare evaluate constant ->str eq map-coefficients)
(deftype Polynomial [arity terms m]
;; Polynomial evaluation works for any number of arguments up to and including
;; the full arity. Evaluating a polynomial with fewer arguments `n` than arity
;; triggers a partial evaluation of the first `n` indeterminates.
f/IArity
(arity [_] [:between 0 arity])
sd/IPerturbed
(perturbed? [_]
(let [coefs (map i/coefficient terms)]
(boolean (some sd/perturbed? coefs))))
(replace-tag [this old new]
(map-coefficients #(sd/replace-tag % old new) this))
(extract-tangent [this tag]
(map-coefficients #(sd/extract-tangent % tag) this))
v/Value
(zero? [_]
(empty? terms))
(one? [_]
(and (= (count terms) 1)
(let [[term] terms]
(and (i/constant-term? term)
(v/one? (i/coefficient term))))))
(identity? [_]
(and (v/one? arity)
(= (count terms) 1)
(let [[term] terms]
(and (= {0 1} (i/exponents term))
(v/one? (i/coefficient term))))))
(zero-like [_]
(if-let [term (nth terms 0)]
(v/zero-like (i/coefficient term))
0))
(one-like [_]
(if-let [term (nth terms 0)]
(v/one-like (i/coefficient term))
1))
(identity-like [_]
(assert (v/one? arity)
"identity-like unsupported on multivariate monomials!")
(let [one (if-let [term (nth terms 0)]
(v/one-like (i/coefficient term))
1)
term (i/make-term (xpt/make 0 1) one)]
(Polynomial. 1 [term] m)))
(exact? [_] false)
(freeze [_] `(~'polynomial ~arity ~terms))
(kind [_] ::polynomial)
#?@(:clj
[Object
(equals [this that] (eq this that))
(toString [p] (->str p))
IObj
(meta [_] m)
(withMeta [_ meta] (Polynomial. arity terms meta))
Seqable
(seq [_] (seq terms))
IFn
(invoke [this]
(evaluate this []))
(invoke [this a]
(evaluate this [a]))
(invoke [this a b]
(evaluate this [a b]))
(invoke [this a b c]
(evaluate this [a b c]))
(invoke [this a b c d]
(evaluate this [a b c d]))
(invoke [this a b c d e]
(evaluate this [a b c d e]))
(invoke [this a b c d e f]
(evaluate this [a b c d e f]))
(invoke [this a b c d e f g]
(evaluate this [a b c d e f g]))
(invoke [this a b c d e f g h]
(evaluate this [a b c d e f g h]))
(invoke [this a b c d e f g h i]
(evaluate this [a b c d e f g h i]))
(invoke [this a b c d e f g h i j]
(evaluate this [a b c d e f g h i j]))
(invoke [this a b c d e f g h i j k]
(evaluate this [a b c d e f g h i j k]))
(invoke [this a b c d e f g h i j k l]
(evaluate this [a b c d e f g h i j k l]))
(invoke [this a b c d e f g h i j k l m]
(evaluate this [a b c d e f g h i j k l m]))
(invoke [this a b c d e f g h i j k l m n]
(evaluate this [a b c d e f g h i j k l m n]))
(invoke [this a b c d e f g h i j k l m n o]
(evaluate this [a b c d e f g h i j k l m n o]))
(invoke [this a b c d e f g h i j k l m n o p]
(evaluate this [a b c d e f g h i j k l m n o p]))
(invoke [this a b c d e f g h i j k l m n o p q]
(evaluate this [a b c d e f g h i j k l m n o p q]))
(invoke [this a b c d e f g h i j k l m n o p q r]
(evaluate this [a b c d e f g h i j k l m n o p q r]))
(invoke [this a b c d e f g h i j k l m n o p q r s]
(evaluate this [a b c d e f g h i j k l m n o p q r s]))
(invoke [this a b c d e f g h i j k l m n o p q r s t]
(evaluate this [a b c d e f g h i j k l m n o p q r s t]))
(invoke [this a b c d e f g h i j k l m n o p q r s t rest]
(evaluate this (into [a b c d e f g h i j k l m n o p q r s t] rest)))
(applyTo [this xs] (AFn/applyToHelper this xs))]
:cljs
[Object
(toString [p] (->str p))
IEquiv
(-equiv [this that] (eq this that))
IMeta
(-meta [_] m)
IWithMeta
(-with-meta [_ m] (Polynomial. arity terms m))
ISeqable
(-seq [_] (seq terms))
IFn
(-invoke [this]
(evaluate this []))
(-invoke [this a]
(evaluate this [a]))
(-invoke [this a b]
(evaluate this [a b]))
(-invoke [this a b c]
(evaluate this [a b c]))
(-invoke [this a b c d]
(evaluate this [a b c d]))
(-invoke [this a b c d e]
(evaluate this [a b c d e]))
(-invoke [this a b c d e f]
(evaluate this [a b c d e f]))
(-invoke [this a b c d e f g]
(evaluate this [a b c d e f g]))
(-invoke [this a b c d e f g h]
(evaluate this [a b c d e f g h]))
(-invoke [this a b c d e f g h i]
(evaluate this [a b c d e f g h i]))
(-invoke [this a b c d e f g h i j]
(evaluate this [a b c d e f g h i j]))
(-invoke [this a b c d e f g h i j k]
(evaluate this [a b c d e f g h i j k]))
(-invoke [this a b c d e f g h i j k l]
(evaluate this [a b c d e f g h i j k l]))
(-invoke [this a b c d e f g h i j k l m]
(evaluate this [a b c d e f g h i j k l m]))
(-invoke [this a b c d e f g h i j k l m n]
(evaluate this [a b c d e f g h i j k l m n]))
(-invoke [this a b c d e f g h i j k l m n o]
(evaluate this [a b c d e f g h i j k l m n o]))
(-invoke [this a b c d e f g h i j k l m n o p]
(evaluate this [a b c d e f g h i j k l m n o p]))
(-invoke [this a b c d e f g h i j k l m n o p q]
(evaluate this [a b c d e f g h i j k l m n o p q]))
(-invoke [this a b c d e f g h i j k l m n o p q r]
(evaluate this [a b c d e f g h i j k l m n o p q r]))
(-invoke [this a b c d e f g h i j k l m n o p q r s]
(evaluate this [a b c d e f g h i j k l m n o p q r s]))
(-invoke [this a b c d e f g h i j k l m n o p q r s t]
(evaluate this [a b c d e f g h i j k l m n o p q r s t]))
(-invoke [this a b c d e f g h i j k l m n o p q r s t rest]
(evaluate this (into [a b c d e f g h i j k l m n o p q r s t] rest)))
IPrintWithWriter
(-pr-writer [x writer _]
(write-all writer
"#object[emmy.polynomial.Polynomial \""
(.toString x)
"\"]"))]))
(defn polynomial?
"Returns true if the supplied argument is an instance of [[Polynomial]], false
otherwise."
[x]
(instance? Polynomial x))
(defn coeff?
"Returns true if the input `x` is explicitly _not_ an instance
of [[Polynomial]], false otherwise.
Equivalent to `(not (polynomial? x))`."
[x]
(not (polynomial? x)))
(defn ^:no-doc bare-arity
"Given a [[Polynomial]] instance `p`, returns the `arity` field."
[p]
{:pre [(polynomial? p)]}
(.-arity ^Polynomial p))
(defn ^:no-doc bare-terms
"Given a [[Polynomial]] instance `p`, returns the `terms` field."
[p]
{:pre [(polynomial? p)]}
(.-terms ^Polynomial p))
;; ## Constructors
(defn ^:no-doc terms->polynomial
"Accepts an explicit `arity` and a vector of terms and returns either:
- `0`, in the case of an empty list
- a bare coefficient, given a singleton term list with a constant term
- else, a [[Polynomial]] instance.
In the second case, if the coefficient is _itself_ a [[Polynomial]], wraps
that [[Polynomial]] instance up in an explicit [[Polynomial]]. In cases where
polynomials have polynomial coefficients, this flattening should never happen
automatically.
NOTE this method assumes that the terms are properly sorted, and contain no
zero coefficients."
[arity terms]
(cond (empty? terms) 0
(and (= (count terms) 1)
(i/constant-term? (nth terms 0)))
(let [c (i/coefficient (nth terms 0))]
(if (polynomial? c)
(->Polynomial arity terms nil)
c))
:else (->Polynomial arity terms nil)))
(defn make
"Generates a [[Polynomial]] instance (or a bare coefficient!) from either:
- a sequence of dense coefficients of a univariate polynomial (in ascending
order)
- an explicit `arity`, and a sparse mapping (or sequence of pairs) of exponent
=> coefficient
In the first case, the sequence is interpreted as a dense sequence of
coefficients of an arity-1 (univariate) polynomial. The coefficients begin
with the constant term and proceed to each higher power of the indeterminate.
For example, x^2 - 1 can be constructed by (make [-1 0 1]).
In the 2-arity case,
- `arity` is the number of indeterminates
- `expts->coef` is a map of an exponent representation to a coefficient.
The `exponent` portion of the mapping can be any of:
- a proper exponent entry created by `emmy.polynomial.exponent`
- a map of the form `{variable-index, power}`
- a dense vector of variable powers, like `[3 0 1]` for $x^3z$. The length of
each vector should be equal to `arity`, in this case.
For example, any of the following would generate $4x^2y + 5xy^2$:
```clojure
(make 2 [[[2 1] 4] [[1 2] 5]])
(make 2 {[2 1] 4, [1 2] 5})
(make 2 {{0 2, 1 1} 4, {0 1, 1 2} 5})
```
NOTE: [[make]] will try and return a bare coefficient if possible. For
example, the following form will return a constant, since there are no
explicit indeterminates with powers > 0:
```clojure
(make 10 {{} 1 {} 2})
;;=> 3
```
See [[constant]] if you need an explicit [[Polynomial]] instance wrapping a
constant."
([dense-coefficients]
(let [terms (i/dense->terms dense-coefficients)]
(terms->polynomial 1 terms)))
([arity expts->coef]
(let [terms (i/sparse->terms expts->coef)]
(terms->polynomial arity terms))))
(defn constant
"Given some coefficient `c`, returns a [[Polynomial]] instance with a single
constant term referencing `c`.
`arity` defaults to 1; supply it to set the arity of the
returned [[Polynomial]]."
([c] (constant 1 c))
([arity c]
(->Polynomial arity (i/constant->terms c) nil)))
(defn identity
"Generates a [[Polynomial]] instance representing a single indeterminate with
constant 1.
When called with no arguments, returns a monomial of arity 1 that acts as
identity in the first indeterminate.
The one-argument version takes an explicit `arity`, but still sets the
identity to the first indeterminate.
The two-argument version takes an explicit `i` and returns a monomial of arity
`arity` with an exponent of 1 in the `i`th indeterminate."
([]
(identity 1 0))
([arity]
(identity arity 0))
([arity i]
{:pre [(and (>= i 0) (< i arity))]}
(let [expts (xpt/make i 1)]
(->Polynomial arity [(i/make-term expts 1)] nil))))
(defn new-variables
"Returns a sequence of `n` monomials of arity `n`, each with an exponent of `1`
for the `i`th indeterminate (where `i` matches the position in the returned
sequence)."
[n]
(map #(identity n %)
(range 0 n)))
(defn from-points
"Given a sequence of points of the form `[x, f(x)]`, returns a univariate
polynomial that passes through each input point.
The degree of the returned polynomial is equal to `(dec (count xs))`."
[xs]
(g/simplify
(pi/lagrange xs (identity))))
(declare add)
(defn linear
"Given some `arity`, an indeterminate index `i` and some constant `root`,
returns a polynomial of the form `x_i - root`. The returned polynomial
represents a linear equation in the `i`th indeterminate.
If `root` is 0, [[linear]] is equivalent to the two-argument version
of [[identity]]."
[arity i root]
(if (v/zero? root)
(identity arity i)
(add (constant arity (g/negate root))
(identity arity i))))
(defn c*xn
"Given some `arity`, a coefficient `c` and an exponent `n`, returns a monomial
representing $c{x_0}^n$. The first indeterminate is always exponentiated.
Similar to [[make]], this function attempts to drop down to scalar-land if
possible:
- If `c` is [[emmy.value/zero?]], returns `c`
- if `n` is `zero?`, returns `(constant arity c)`
NOTE that negative exponents are not allowed."
[arity c n]
{:pre [(>= n 0)]}
(cond (v/zero? c) c
(zero? n) (constant arity c)
:else
(let [term (i/make-term (xpt/make 0 n) c)]
(->Polynomial arity [term] nil))))
;; ## Constructors of Special Polynomials
(defn touchard
"Returns the nth [Touchard
polynomial](https://en.wikipedia.org/wiki/Touchard_polynomials).
These are also called [Bell
polynomials](https://mathworld.wolfram.com/BellPolynomial.html) (in
Mathematica, implemented as `BellB`) or /exponential polynomials/."
[n]
(make
(map #(sf/stirling-second-kind n %)
(range (inc n)))))
;; ### Accessors, Predicates
;;
;; The functions in the next section all work on both explicit [[Polynomial]]
;; instances _and_ on bare coefficients. Any non-polynomial type is treated as a
;; constant polynomial.
(def ^:no-doc coeff-arity 0)
(def ^:no-doc zero-degree -1)
(defn arity
"Returns the declared arity of the supplied [[Polynomial]], or `0` for
non-polynomial arguments."
[p]
(if (polynomial? p)
(bare-arity p)
coeff-arity))
(defn ->terms
"Given some [[Polynomial]], returns the `terms` entry of the type. Handles other types as well:
- Acts as identity on vectors, interpreting them as vectors of terms
- any zero-valued `p` returns `[]`
- any other coefficient returns a vector of a single constant term."
[p]
(cond (polynomial? p) (bare-terms p)
(vector? p) p
(v/zero? p) []
:else [(i/make-term p)]))
(defn ^:no-doc check-same-arity
"Given two polynomials (or coefficients) `p` and `q`, checks that their arities
are equal and returns the value, or throws an exception if not.
If either `p` or `q` is a coefficient, [[check-same-arity]] successfully
returns the other argument's arity."
[p q]
(let [poly-p? (polynomial? p)
poly-q? (polynomial? q)]
(cond (and poly-p? poly-q?)
(let [ap (bare-arity p)
aq (bare-arity q)]
(if (= ap aq)
ap
(u/arithmetic-ex
(str "mismatched polynomial arity: " ap ", " aq))))
poly-p? (bare-arity p)
poly-q? (bare-arity q)
:else coeff-arity)))
(defn valid-arity?
"Given some input `p` and an indeterminate index `i`, returns true if `0 <= i
< (arity p)`, false otherwise."
[p i]
(and (>= i 0)
(< i (arity p))))
(defn ^:no-doc validate-arity!
"Given some input `p` and an indeterminate index `i`, returns `i` if `0 <= i
< (arity p)`, and throws an exception otherwise.
NOTE [[validate-arity]] is meant to validate indeterminate indices; thus it
will always throw for non-[[Polynomial]] inputs."
[p i]
(if (valid-arity? p i)
i
(u/arithmetic-ex
(str "Supplied i " i " outside the bounds of arity " (arity p) " for input " p))))
(declare leading-term)
(defn degree
"Returns the [degree](https://en.wikipedia.org/wiki/Degree_of_a_polynomial) of
the supplied polynomial.
the degree of a polynomial is the highest of the degrees of the polynomial's
individual terms with non-zero coefficients. The degree of an individual term
is the sum of all exponents in the term.
Optionally, [[degree]] takes an indeterminate index `i`; in this
case, [[degree]] returns the maximum power found for the `i`th indeterminate
across all terms.
NOTE when passed either a `0` or a zero-polynomial, [[degree]] returns -1. See
Wikipedia's ['degree of the zero
polynomial'](https://en.wikipedia.org/wiki/Degree_of_a_polynomial#Degree_of_the_zero_polynomial)
for color on why this is the case.
"
([p]
(cond (v/zero? p) zero-degree
(polynomial? p)
(xpt/monomial-degree
(i/exponents
(leading-term p)))
:else coeff-arity))
([p i]
(let [i (validate-arity! p i)]
(cond (v/zero? p) zero-degree
(polynomial? p)
(letfn [(i-degree [term]
(-> (i/exponents term)
(xpt/monomial-degree i)))]
(transduce (map i-degree)
max
0
(bare-terms p)))
:else coeff-arity))))
(defn eq
"Returns true if the [[Polynomial]] this is equal to `that`. If `that` is
a [[Polynomial]], `this` and `that` are equal if they have equal terms and
equal arity. Coefficients are compared using [[emmy.value/=]].
If `that` is non-[[Polynomial]], `eq` only returns true if `this` is a
monomial and its coefficient is equal to `that` (again
using [[emmy.value/=]])."
[^Polynomial this that]
(if (instance? Polynomial that)
(let [p ^Polynomial that]
(and (= (.-arity this) (.-arity p))
(v/= (.-terms this)
(.-terms p))))
(let [terms (.-terms this)]
(and (<= (count terms) 1)
(let [term (peek terms)]
(and (i/constant-term? term)
(v/= that (i/coefficient term))))))))
(defn ->str
"Returns a string representation of the supplied [[Polynomial]] instance `p`.
The optional argument `n` specifies how many terms to include in the returned
string before an ellipsis cuts them off."
([p] (->str p 10))
([p n]
{:pre [polynomial? p]}
(let [terms (bare-terms p)
arity (bare-arity p)
n-terms (count terms)
term-strs (take n (map i/term->str terms))
suffix (when (> n-terms n)
(str "... and " (- n-terms n) " more terms"))]
(str arity ": (" (cs/join " + " term-strs) suffix ")"))))
(defn coefficients
"Returns a sequence of the coefficients of the supplied polynomial `p`. A
coefficient is treated here as a monomial, and returns a sequence of itself.
If `p` is zero, returns an empty list."
[p]
(cond (polynomial? p) (map i/coefficient (->terms p))
(v/zero? p) []
:else [p]))
(defn leading-term
"Returns the leading (highest degree) term of the [[Polynomial]] `p`.
If `p` is a non-[[Polynomial]] coefficient, returns a term with zero exponents
and `p` as its coefficient."
[p]
(or (peek (->terms p))
[xpt/empty 0]))
(defn leading-coefficient
"Returns the coefficient of the leading (highest degree) term of
the [[Polynomial]] `p`.
If `p` is a non-[[Polynomial]] coefficient, acts as identity."
[p]
(if (polynomial? p)
(i/coefficient
(peek (bare-terms p)))
p))
(defn leading-exponents
"Returns the exponents of the leading (highest degree) term of
the [[Polynomial]] `p`.
If `p` is a non-[[Polynomial]] coefficient, returns [[exponent/empty]]."
[p]
(if (polynomial? p)
(i/exponents
(peek (bare-terms p)))
xpt/empty))
(defn leading-base-coefficient
"Similar to [[leading-coefficient]], but of the coefficient itself is
a [[Polynomial]], recurses down until it reaches a non-[[Polynomial]] lead
coefficient.
If `p` is a non-[[Polynomial]] coefficient, acts as identity."
[p]
(if (polynomial? p)
(recur (leading-coefficient p))
p))
(defn trailing-coefficient
"Returns the coefficient of the trailing (lowest degree) term of
the [[Polynomial]] `p`.
If `p` is a non-[[Polynomial]] coefficient, acts as identity."
[p]
(if (polynomial? p)
(i/coefficient
(nth (bare-terms p) 0 []))
p))
(defn lowest-degree
"Returns the lowest degree found across any term in the supplied [[Polynomial]].
If a non-[[Polynomial]] is supplied, returns either `0` or `-1` if the input
is itself a `0`.
See [[degree]] for a discussion of this `-1` case."
[p]
(cond (polynomial? p)
(xpt/monomial-degree
(i/exponents
(nth (bare-terms p) 0)))
(v/zero? p) zero-degree
:else coeff-arity))
(defn monomial?
"Returns true if `p` is either:
- a [[Polynomial]] instance with a single term, or
- a non-[[Polynomial]] coefficient,
false otherwise."
[p]
(or (not (polynomial? p))
(= 1 (count (bare-terms p)))))
(defn monic?
"Returns true if `p` is a [monic
polynomial](https://en.wikipedia.org/wiki/Monic_polynomial), false otherwise.
A monic polynomial is a univariate polynomial with a leading coefficient that
responds `true` to [[emmy.value/one?]]. This means that any coefficient
that responds `true` to [[emmy.value/one?]] also qualifies as a monic
polynomial."
[p]
(if (polynomial? p)
(and (= 1 (arity p))
(v/one?
(leading-coefficient p)))
(v/one? p)))
(defn univariate?
"Returns true if `p` is a [[Polynomial]] of arity 1, false otherwise."
[p]
(and (polynomial? p)
(= (bare-arity p) 1)))
(defn multivariate?
"Returns true if `p` is a [[Polynomial]] of arity > 1, false otherwise."
[p]
(and (polynomial? p)
(> (bare-arity p) 1)))
(defn negative?
"Returns true if the [[leading-base-coefficient]] of `p`
is [[generic/negative?]], false otherwise."
[p]
(g/negative?
(leading-base-coefficient p)))
;; ## Polynomial API
(defn map-coefficients
"Given a [[Polynomial]], returns a new [[Polynomial]] instance generated by
applying `f` to the coefficient of each term in `p` and filtering out all
resulting zeros.
Given a non-[[Polynomial]] coefficient, returns `(f p)`.
NOTE that [[map-coefficients]] will return a non-[[Polynomial]] if the result
of the mapping has only a constant term."
[f p]
(if (polynomial? p)
(terms->polynomial
(bare-arity p)
(i/map-coefficients f (bare-terms p)))
(f p)))
(defn map-exponents
"Given a [[Polynomial]], returns a new [[Polynomial]] instance generated by
applying `f` to the exponents of each term in `p` and filtering out all
resulting zeros. The resulting [[Polynomial]] will have either the
same [[arity]] as `p`, or the explicit, optional `new-arity` argument. (This
is because `f` might increase or decrease the total arity.)
Given a non-[[Polynomial]] coefficient, if `(f empty-exponents)` produces a
non-zero result, errors without an explicit `new-arity` argument..
NOTE that [[map-exponents]] will return a non-[[Polynomial]] if the result
of the mapping has only a constant term."
([f p]
(map-exponents f p nil))
([f p new-arity]
(letfn [(force-arity []
(or new-arity
(u/illegal
"`new-arity` argument to `map-exponents` required when promoting constant.")))
(handle-constant []
(let [f-expts (f xpt/empty)]
(if (empty? f-expts)
p
(let [arity (force-arity)]
(->Polynomial arity [(i/make-term f-expts p)] nil)))))]
(cond (polynomial? p)
(make (or new-arity (bare-arity p))
(for [[expts c] (bare-terms p)
:let [f-expts (f expts)]]
(i/make-term f-expts c)))
(v/zero? p) p
:else (handle-constant)))))
;; ## Manipulations
(defn univariate->dense
"Given a univariate [[Polynomial]] (see [[univariate?]]) returns a dense vector
of the coefficients of each term in ascending order.
For example:
```clojure
(univariate->dense (make [1 0 0 2 3 4]))
;;=> [1 0 0 2 3 4]
```
Supplying the second argument `x-degree` will pad the right side of the
returning coefficient vector to be the max of `x-degree` and `(degree x)`.
NOTE use [[lower-arity]] to generate a univariate polynomial in the first
indeterminate, given a multivariate polynomial."
([x] (univariate->dense x (degree x)))
([x x-degree]
(if (coeff? x)
(into [x] (repeat x-degree 0))
(do (assert (univariate? x))
(let [d (degree x)]
(loop [terms (bare-terms x)
acc (transient [])
i 0]
(if (> i d)
(into (persistent! acc)
(repeat (- x-degree d) 0))
(let [t (first terms)
e (i/exponents t)
md (xpt/monomial-degree e 0)]
(if (= md i)
(recur (rest terms)
(conj! acc (i/coefficient t))
(inc i))
(recur terms
(conj! acc 0)
(inc i)))))))))))
(defn ->power-series
"Given a univariate polynomial `p`, returns a [[series/PowerSeries]]
representation of the supplied [[Polynomial]].
Given a [[series/PowerSeries]], acts as identity.
Non-[[Polynomial]] coefficients return [[series/PowerSeries]] instances
via [[series/constant]]; any multivariate [[Polynomial]] throws an exception.
NOTE use [[lower-arity]] to generate a univariate polynomial in the first
indeterminate, given a multivariate polynomial."
[p]
(cond (series/power-series? p) p
(univariate? p)
(series/power-series*
(univariate->dense p))
(polynomial? p)
(u/illegal
"Only univariate polynomials can be converted to [[PowerSeries]].
Use [[polynomial/lower]] to generate a univariate.")
:else (series/constant p)))
(defn from-power-series
"Returns a univariate polynomial of all terms in the
supplied [[series/PowerSeries]] instance, up to (and including) order
`n-terms`.
```clojure
(g/simplify
((from-power-series series/exp-series 3) 'x))
;; => (+ (* 1/6 (expt x 3)) (* 1/2 (expt x 2)) x 1)
```"
[s n-terms]
{:pre [(series/power-series? s)]}
(-> (s (identity))
(series/sum n-terms)))
(defn scale
"Given some polynomial `p` and a coefficient `c`, returns a new [[Polynomial]]
generated by multiplying each coefficient of `p` by `c` (on the right).
See [[scale-l]] if left multiplication is important.
NOTE that [[scale]] will return a non-[[Polynomial]] if the result of the
mapping has only a constant term."
[p c]
(if (v/zero? c)
c
(map-coefficients #(g/* % c) p)))
(defn scale-l
"Given some polynomial `p` and a coefficient `c`, returns a new [[Polynomial]]
generated by multiplying each coefficient of `p` by `c` (on the left).
See [[scale]] if right multiplication is important.
NOTE that [[scale-l]] will return a non-[[Polynomial]] if the result of the
mapping has only a constant term."
[c p]
(if (v/zero? c)
c
(map-coefficients #(g/* c %) p)))
(declare evenly-divide)
(defn normalize
"Given a polynomial `p`, returns a normalized polynomial generated by dividing
through either the [[leading-coefficient]] of `p` or an optional, explicitly
supplied scaling factor `c`.
For example:
```clojure
(let [p (make [5 3 2 2 10])]
(univariate->dense (normalize p)))
;;=> [1/2 3/10 1/5 1/5 1]
```"
([p]
(normalize p (leading-coefficient p)))
([p c]
(cond (v/one? c) p
(v/zero? c) (u/arithmetic-ex
(str "Divide by zero: " p c))
(polynomial? c) (evenly-divide p c)
:else (scale p (g/invert c)))))
(defn reciprocal
"Given a polynomial `p`, returns the [reciprocal
polynomial](https://en.wikipedia.org/wiki/Reciprocal_polynomial) with respect
to the `i`th indeterminate. `i` defaults to 0.
The reciprocal polynomial of `p` with respect to `i` is generated by
- treating the polynomial as univariate with respect to `i` and pushing all
other terms into the coefficients of the polynomial
- reversing the order of these coefficients
- flattening the polynomial out again
For example, note that the entries for the first indeterminate are reversed:
```clojure
(= (make 3 {[3 0 0] 5 [2 0 1] 2 [0 2 1] 3})
(reciprocal
(make 3 {[0 0 0] 5 [1 0 1] 2 [3 2 1] 3})))
```"
([p] (reciprocal p 0))
([p i]
(if (polynomial? p)
(let [d (degree p i)]
(if (zero? d)
p
(map-exponents
(fn [m]
(let [v (xpt/monomial-degree m i)
v' (- d v)]
(xpt/assoc m i v')))
p)))
p)))
(defn drop-leading-term
"Given some [[Polynomial]] `p`, returns `p` without its [[leading-term]].
non-[[Polynomial]] `p` inputs are treated at constant polynomials and return
`0`.
NOTE that [[drop-leading-term]] will return a non-[[Polynomial]] if the result
of the mapping has only a constant term."
[p]
(if (polynomial? p)
(let [a (bare-arity p)
terms (pop (bare-terms p))]
(terms->polynomial a terms))
0))