-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathREADME.Rmd
More file actions
419 lines (292 loc) · 10.7 KB
/
README.Rmd
File metadata and controls
419 lines (292 loc) · 10.7 KB
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
---
output:
md_document:
variant: markdown_github
---
<!-- README.md is generated from README.Rmd. Please edit that file -->
```{r, echo = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#",
fig.path = "tools/README-",
dpi = 250
)
```
# mpoly
<!-- badges: start -->
[](https://cran.r-project.org/package=mpoly)
[]( https://app.travis-ci.com/dkahle/mpoly)
[](https://ci.appveyor.com/project/dkahle/mpoly)
[](https://app.codecov.io/github/dkahle/mpoly?branch=master)
<!-- badges: end -->
## Specifying polynomials
__mpoly__ is a simple collection of tools to help deal with multivariate polynomials _symbolically_ and functionally in R. Polynomials are defined with the `mp()` function:
```{r mp, echo = TRUE}
library("mpoly")
mp("x + y")
mp("(x + 4 y)^2 (x - .25)")
```
[Term orders](https://en.wikipedia.org/wiki/Lexicographical_order#Monomials) are available with the reorder function:
```{r reordering}
(p <- mp("(x + y)^2 (1 + x)"))
reorder(p, varorder = c("y","x"), order = "lex")
reorder(p, varorder = c("x","y"), order = "glex")
```
Vectors of polynomials (`mpolyList`'s) can be specified in the same way:
```{r mpolyLists}
mp(c("(x+y)^2", "z"))
```
## Polynomial parts
You can extract pieces of polynoimals using the standard `[` operator, which works on its terms:
```{r subsetting}
p[1]
p[1:3]
p[-1]
```
There are also many other functions that can be used to piece apart polynomials, for example the leading term (default lex order):
```{r lt_lc_lm}
LT(p)
LC(p)
LM(p)
```
You can also extract information about exponents:
```{r degs}
exponents(p)
multideg(p)
totaldeg(p)
monomials(p)
```
## Polynomial arithmetic
Arithmetic is defined for both polynomials (`+`, `-`, `*` and `^`)...
```{r arithmetic}
p1 <- mp("x + y")
p2 <- mp("x - y")
p1 + p2
p1 - p2
p1 * p2
p1^2
```
... and vectors of polynomials:
```{r vector-arithmetic}
(ps1 <- mp(c("x", "y")))
(ps2 <- mp(c("2 x", "y + z")))
ps1 + ps2
ps1 - ps2
ps1 * ps2
```
## Some calculus
You can compute derivatives easily:
```{r calculus}
p <- mp("x + x y + x y^2")
deriv(p, "y")
gradient(p)
```
## Function coercion
You can turn polynomials and vectors of polynomials into functions you can evaluate with `as.function()`. Here's a basic example using a single multivariate polynomial:
```{r as-function-basic-single}
f <- as.function(mp("x + 2 y")) # makes a function with a vector argument
f(c(1,1))
f <- as.function(mp("x + 2 y"), vector = FALSE) # makes a function with all arguments
f(1, 1)
```
Here's a basic example with a vector of multivariate polynomials:
```{r as-function-basic-vector}
(p <- mp(c("x", "2 y")))
f <- as.function(p)
f(c(1,1))
f <- as.function(p, vector = FALSE)
f(1, 1)
```
Whether you're working with a single multivariate polynomial or a vector of them (`mpolyList`), if it/they are actually univariate polynomial(s), the resulting function is vectorized. Here's an example with a single univariate polynomial.
```{r as-function-vectorized}
f <- as.function(mp("x^2"))
f(1:3)
(mat <- matrix(1:4, 2))
f(mat) # it's vectorized properly over arrays
```
Here's an example with a vector of univariate polynomials:
```{r as-function-vectorized2}
(p <- mp(c("t", "t^2")))
f <- as.function(p)
f(1)
f(1:3)
```
You can use this to visualize a univariate polynomials like this:
```{r packages, message=FALSE}
library("tidyverse"); theme_set(theme_classic())
```
```{r as-function, fig.height=3}
f <- as.function(mp("(x-2) x (x+2)"))
x <- seq(-2.5, 2.5, .1)
qplot(x, f(x), geom = "line")
```
For multivariate polynomials, it's a little more complicated:
```{r as-function-multi}
f <- as.function(mp("x^2 - y^2"))
s <- seq(-2.5, 2.5, .1)
df <- expand.grid(x = s, y = s)
df$f <- apply(df, 1, f)
qplot(x, y, data = df, geom = "raster", fill = f)
```
Using [tidyverse-style coding](https://www.tidyverse.org) (install tidyverse packages with `install.packages("tidyverse")`), this looks a bit cleaner:
```{r as-function-multi-tidy}
f <- as.function(mp("x^2 - y^2"), vector = FALSE)
seq(-2.5, 2.5, .1) %>%
list("x" = ., "y" = .) %>%
cross_df() %>%
mutate(f = f(x, y)) %>%
ggplot(aes(x, y, fill = f)) +
geom_raster()
```
## Algebraic geometry
__Grobner bases are no longer implemented in mpoly; they're now in [m2r](https://github.com/coneill-math/m2r).__
```{r grobner}
# polys <- mp(c("t^4 - x", "t^3 - y", "t^2 - z"))
# grobner(polys)
```
Homogenization and dehomogenization:
```{r homogenization}
(p <- mp("x + 2 x y + y - z^3"))
(hp <- homogenize(p))
dehomogenize(hp, "t")
homogeneous_components(p)
```
## Special polynomials
__mpoly__ can make use of many pieces of the __polynom__ and __orthopolynom__ packages with `as.mpoly()` methods. In particular, many special polynomials are available.
#### [Chebyshev polynomials](https://en.wikipedia.org/wiki/Chebyshev_polynomials)
You can construct [Chebyshev polynomials](https://en.wikipedia.org/wiki/Chebyshev_polynomials) as follows:
```{r chebyshev1}
chebyshev(1)
chebyshev(2)
chebyshev(0:5)
```
And you can visualize them:
```{r chebyshev, fig.height=3}
s <- seq(-1, 1, length.out = 201); N <- 5
(chebPolys <- chebyshev(0:N))
df <- as.function(chebPolys)(s) %>% cbind(s, .) %>% as.data.frame()
names(df) <- c("x", paste0("T_", 0:N))
mdf <- df %>% gather(degree, value, -x)
qplot(x, value, data = mdf, geom = "path", color = degree)
```
#### [Jacobi polynomials](https://en.wikipedia.org/wiki/Jacobi_polynomials)
```{r jacobi, fig.height=3}
s <- seq(-1, 1, length.out = 201); N <- 5
(jacPolys <- jacobi(0:N, 2, 2))
df <- as.function(jacPolys)(s) %>% cbind(s, .) %>% as.data.frame
names(df) <- c("x", paste0("P_", 0:N))
mdf <- df %>% gather(degree, value, -x)
qplot(x, value, data = mdf, geom = "path", color = degree) +
coord_cartesian(ylim = c(-25, 25))
```
#### [Legendre polynomials](https://en.wikipedia.org/wiki/Legendre_polynomials)
```{r legendre, fig.height=3}
s <- seq(-1, 1, length.out = 201); N <- 5
(legPolys <- legendre(0:N))
df <- as.function(legPolys)(s) %>% cbind(s, .) %>% as.data.frame
names(df) <- c("x", paste0("P_", 0:N))
mdf <- df %>% gather(degree, value, -x)
qplot(x, value, data = mdf, geom = "path", color = degree)
```
#### [Hermite polynomials](https://en.wikipedia.org/wiki/Hermite_polynomials)
```{r hermite, fig.height=3}
s <- seq(-3, 3, length.out = 201); N <- 5
(hermPolys <- hermite(0:N))
df <- as.function(hermPolys)(s) %>% cbind(s, .) %>% as.data.frame
names(df) <- c("x", paste0("He_", 0:N))
mdf <- df %>% gather(degree, value, -x)
qplot(x, value, data = mdf, geom = "path", color = degree)
```
#### [(Generalized) Laguerre polynomials](https://en.wikipedia.org/wiki/Laguerre_polynomials)
```{r laguerre, fig.height=3}
s <- seq(-5, 20, length.out = 201); N <- 5
(lagPolys <- laguerre(0:N))
df <- as.function(lagPolys)(s) %>% cbind(s, .) %>% as.data.frame
names(df) <- c("x", paste0("L_", 0:N))
mdf <- df %>% gather(degree, value, -x)
qplot(x, value, data = mdf, geom = "path", color = degree) +
coord_cartesian(ylim = c(-25, 25))
```
#### [Bernstein polynomials](https://en.wikipedia.org/wiki/Bernstein_polynomial)
[Bernstein polynomials](https://en.wikipedia.org/wiki/Bernstein_polynomial) are not in __polynom__ or __orthopolynom__ but are available in __mpoly__ with `bernstein()`:
```{r bernstein, fig.height=3}
bernstein(0:4, 4)
s <- seq(0, 1, length.out = 101)
N <- 5 # number of bernstein polynomials to plot
(bernPolys <- bernstein(0:N, N))
df <- as.function(bernPolys)(s) %>% cbind(s, .) %>% as.data.frame
names(df) <- c("x", paste0("B_", 0:N))
mdf <- df %>% gather(degree, value, -x)
qplot(x, value, data = mdf, geom = "path", color = degree)
```
You can use the `bernstein_approx()` function to compute the Bernstein polynomial approximation to a function. Here's an approximation to the standard normal density:
```{r bernstein-approx, fig.height=3}
p <- bernstein_approx(dnorm, 15, -1.25, 1.25)
round(p, 4)
x <- seq(-3, 3, length.out = 101)
df <- data.frame(
x = rep(x, 2),
y = c(dnorm(x), as.function(p)(x)),
which = rep(c("actual", "approx"), each = 101)
)
qplot(x, y, data = df, geom = "path", color = which)
```
## [Bezier polynomials and curves](https://en.wikipedia.org/wiki/Bézier_curve)
You can construct [Bezier polynomials](https://en.wikipedia.org/wiki/Bézier_curve) for a given collection of points with `bezier()`:
```{r bezier, fig.height=3}
points <- data.frame(x = c(-1,-2,2,1), y = c(0,1,1,0))
(bezPolys <- bezier(points))
```
And viewing them is just as easy:
```{r bezier-plot, fig.height = 3}
df <- as.function(bezPolys)(s) %>% as.data.frame
ggplot(aes(x = x, y = y), data = df) +
geom_point(data = points, color = "red", size = 4) +
geom_path(data = points, color = "red", linetype = 2) +
geom_path(size = 2)
```
Weighting is available also:
```{r bezier-weighting, fig.height = 3}
points <- data.frame(x = c(1,-2,2,-1), y = c(0,1,1,0))
(bezPolys <- bezier(points))
df <- as.function(bezPolys, weights = c(1,5,5,1))(s) %>% as.data.frame
ggplot(aes(x = x, y = y), data = df) +
geom_point(data = points, color = "red", size = 4) +
geom_path(data = points, color = "red", linetype = 2) +
geom_path(size = 2)
```
To make the evaluation of the Bezier polynomials stable, `as.function()` has a special method for Bezier polynomials that makes use of [de Casteljau's algorithm](https://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm). This allows `bezier()` to be used as a smoother:
```{r bezier-smooth, fig.height=3}
s <- seq(0, 1, length.out = 201)
df <- as.function(bezier(cars))(s) %>% as.data.frame
qplot(speed, dist, data = cars) +
geom_path(data = df, color = "red")
```
## Other stuff
I'm starting to put in methods for some other R functions:
```{r lm, fig.height=3}
set.seed(1)
n <- 101
df <- data.frame(x = seq(-5, 5, length.out = n))
df$y <- with(df, -x^2 + 2*x - 3 + rnorm(n, 0, 2))
mod <- lm(y ~ x + I(x^2), data = df)
(p <- mod %>% as.mpoly %>% round)
qplot(x, y, data = df) +
stat_function(fun = as.function(p), colour = 'red')
```
```{r lm-poly, fig.height=3}
s <- seq(-5, 5, length.out = n)
df <- expand.grid(x = s, y = s) %>%
mutate(z = x^2 - y^2 + 3*x*y + rnorm(n^2, 0, 3))
(mod <- lm(z ~ poly(x, y, degree = 2, raw = TRUE), data = df))
as.mpoly(mod)
```
## Installation
* From CRAN: `install.packages("mpoly")`
* From Github (dev version):
```R
# install.packages("devtools")
devtools::install_github("dkahle/mpoly")
```
## Acknowledgements
This material is based upon work partially supported by the National Science Foundation under Grant No. [1622449](https://www.nsf.gov/awardsearch/showAward?AWD_ID=1622449).