/
sym_symbol.R
458 lines (381 loc) · 9.31 KB
/
sym_symbol.R
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
TXT_NOT_CARACAS_SYMBOL <- paste0("must be a caracas_symbol, ",
"e.g. constructed by symbol() ",
"followed by elementary operations")
PATTERN_PYHTON_VARIABLE <- "[a-zA-Z]+[a-zA-Z0-9_]*"
stopifnot_symbol <- function(x) {
if (!inherits(x, "caracas_symbol")) {
stop(paste0("'x' ", TXT_NOT_CARACAS_SYMBOL))
}
}
verify_variable_name <- function(x) {
if (length(x) != 1L) {
stop("The name must have length 1")
}
pattern <- paste0("^", PATTERN_PYHTON_VARIABLE, "$")
if (!grepl(pattern, x)) {
stop(paste0("'", x, "' is not a valid variable name"))
}
}
construct_symbol_from_pyobj <- function(pyobj) {
y <- list(pyobj = pyobj)
class(y) <- "caracas_symbol"
return(y)
}
#' Create a symbol from a string
#'
#' @param x String to evaluate
#'
#' @examples
#' if (has_sympy()) {
#' x <- symbol('x')
#' (1+1)*x^2
#' lim(sin(x)/x, "x", 0)
#' }
#'
#' @return A `caracas_symbol`
#'
#' @concept lowlevel
#' @importFrom reticulate py_eval
#' @export
eval_to_symbol <- function(x) {
ensure_sympy()
# --------------------------------------------
# 1/3 should be caught
# --------------------------------------------
# https://docs.sympy.org/latest/gotchas.html#python-numbers-vs-sympy-numbers
# y1/3 should not be caught
if (grepl("[0-9-.]+/[0-9-.]+", x, perl = TRUE)) {
# Now there is a fraction that looks like '1/3';
# we need to be sure that there are no characters in front of the
# number in the numerator
if (grepl("[a-zA-Z_]+[0-9-.]+/[0-9-.]+", x, perl = TRUE)) {
# There was a character (e.g. 'x1/2')
# or a subscript/underscore (e.g. 3*y_11/4)
# do nothing
} else {
# S(): Sympify
x <- gsub("([0-9-.]+)/([0-9-.]+)", "S(\\1)/S(\\2)", x, perl = TRUE)
}
}
# --------------------------------------------
# (1)/(3) should be caught
# --------------------------------------------
# https://docs.sympy.org/latest/gotchas.html#python-numbers-vs-sympy-numbers
if (grepl("\\([0-9-.]+\\) */ *\\([0-9-.]+\\)", x, perl = TRUE)) {
# Now there is a fraction that looks like '(1)/(3)';
# S(): Sympify
# This gives S(1)/S(2), okay with no extra parentheses
x <- gsub("\\(([0-9-.]+)\\) */ *\\(([0-9-.]+)\\)", "S(\\1)/S(\\2)", x, perl = TRUE)
}
x <- r_strings_to_python(x)
# x <- "a/sqrt(a*conjugate(a))" fail
s <- reticulate::py_eval(x, convert = FALSE)
y <- construct_symbol_from_pyobj(s)
return(y)
}
#' Create a symbol
#'
#' Find available assumptions at
#' <https://docs.sympy.org/latest/modules/core.html#module-sympy.core.assumptions>.
#'
#' @param x Name to turn into symbol
#' @param \dots Assumptions like `positive = TRUE`
#'
#' @examples
#' if (has_sympy()) {
#' x <- symbol("x")
#' 2*x
#'
#' x <- symbol("x", positive = TRUE)
#' ask(x, "positive")
#' }
#'
#' @return A `caracas_symbol`
#'
#' @seealso [as_sym()]
#' @concept caracas_symbol
#' @importFrom reticulate py_run_string
#' @export
symbol <- function(x, ...) {
ensure_sympy()
verify_variable_name(x)
dots <- list(...)
extra_cmd <- ""
if (length(dots) > 0L) {
arg_nm <- names(dots)
arg_val <- rep("None", length(dots))
arg_val[unlist(lapply(dots, function(l) isTRUE(l)))] <- "True"
# isFALSE req. R >= 3.5, hence explicit:
arg_val[unlist(lapply(dots, function(l) is.logical(l) && length(l) == 1L && !is.na(l) && !l))] <- "False"
extra_cmd <- paste0(arg_nm, " = ", arg_val, collapse = ", ")
extra_cmd <- paste0(", ", extra_cmd)
}
cmd <- paste0(x, " = symbols('", x, "'", extra_cmd, ")")
# py_run_string instead of py_eval because we need to assign inside Python
s <- reticulate::py_run_string(cmd, convert = FALSE)
res <- s[[x]]
y <- construct_symbol_from_pyobj(res)
return(y)
}
#' Perform calculations setup previously
#'
#' @param x A `caracas_symbol`
#'
#' @examples
#' if (has_sympy()) {
#' x <- symbol('x')
#' res <- lim(sin(x)/x, "x", 0, doit = FALSE)
#' res
#' doit(res)
#' }
#'
#' @concept caracas_symbol
#'
#' @export
doit <- function(x) {
stopifnot_symbol(x)
ensure_sympy()
if (!is.null(x$pyobj) && !is.null(x$pyobj$doit)) {
y <- construct_symbol_from_pyobj(x$pyobj$doit())
return(y)
}
stop("Could not doit()")
}
try_doit <- function(x) {
# if (!is.null(x$pyobj) && "doit" %in% names(x$pyobj)) {
# y <- construct_symbol_from_pyobj(x$pyobj$doit())
# return(y)
# }
try({
y <- construct_symbol_from_pyobj(x$pyobj$doit())
return(y)
}, silent = TRUE)
return(x)
}
#' Remove inner-most dimension
#'
#' @param x Array symbol to collapse dimension from
#'
#' @examples
#' if (has_sympy()) {
#' x <- as_sym(paste0("x", 1:3))
#' y <- as_sym("y")
#' l <- list(x, y)
#' l
#' unbracket(l)
#' }
#'
#' @concept caracas_symbol
#'
#' @export
unbracket <- function(x) {
if (!inherits(x, "caracas_symbol") && is.list(x)) {
z <- lapply(x, as_character)
z <- do.call(rbind, z)
z <- as_sym(z)
#z <- to_vector(z)
return(z)
}
z <- as.character(x)
zz <- gsub("\\[([^]]+)\\]", "\\1", z)
zz
y <- eval_to_symbol(zz)
return(y)
}
extract_elements <- function(x) {
z <- as.character(x)
zz <- gsub("[", "", z, fixed = TRUE)
zz <- gsub("]", "", zz, fixed = TRUE)
zz <- remove_mat_prefix(zz)
return(zz)
}
## concatenate
#' @export
c.caracas_symbol <- function(...) {
ensure_sympy()
# v <- vector_sym(2)
# c(v)
# c(v, v)
# A <- matrix_sym(3, 4)
# c(A)
# c(A, A)
z <- list(...)
z <- lapply(z, as_character)
z <- unlist(z)
z <- base::c(z)
z <- as_sym(z)
return(z)
# # FIXME: To Python vector?
# # In that case, see der() too.
# #x <- list(...)
# x <- vectorfy(list(...))
#
# # FIXME: Use? In that case ensure that all "[..., ...]" from elsewhere (e.g. der())
# # is also caught.
# class(x) <- c("caracas_vector", class(x))
#
# return(x)
}
#' Get numerator and denominator of a fraction
#'
#' @param x Fraction
#'
#' @name fraction_parts
#' @examples
#' if (has_sympy()) {
#' x <- as_sym("a/b")
#' frac <- fraction_parts(x)
#' frac
#' frac$numerator
#' frac$denominator
#' }
#'
#' @concept caracas_symbol
#'
#' @export
fraction_parts <- function(x) {
ensure_sympy()
stopifnot_symbol(x)
frac <- x$pyobj$as_numer_denom()
y <- list(
numerator = construct_symbol_from_pyobj(frac[0]), # Python 0-indexed
denominator = construct_symbol_from_pyobj(frac[1])
)
return(y)
}
#' @export
#' @rdname fraction_parts
numerator <- function(x) {
return(fraction_parts(x)$numerator)
}
#' @export
#' @rdname fraction_parts
denominator <- function(x) {
return(fraction_parts(x)$denominator)
}
#' Call a SymPy function directly on x
#'
#' Extend caracas by calling SymPy functions directly.
#'
#' @param x Object to call `fun` on
#' @param fun Function to call
#' @param \dots Passed on to `fun`
#'
#' @examples
#' if (has_sympy()) {
#' def_sym(x, a)
#' p <- (x-a)^4
#' p
#' q <- p %>% sympy_func("expand")
#' q
#' q %>% sympy_func("factor")
#'
#' def_sym(x, y, z)
#' expr <- x*y + x - 3 + 2*x^2 - z*x^2 + x^3
#' expr
#' expr %>% sympy_func("collect", x)
#'
#' x <- symbol("x")
#' y <- gamma(x+3)
#' sympy_func(y, "expand_func")
#' expand_func(y)
#' }
#'
#' @concept caracas_symbol
#'
#' @export
sympy_func <- function(x, fun, ...) {
args <- list(...)
args <- lapply(args, function(a) {
if (inherits(a, "caracas_symbol")) {
return(as.character(a))
}
return(a)
})
convert_res <- function(o) {
o <- if (is.list(o)) {
lapply(o, construct_symbol_from_pyobj)
} else {
construct_symbol_from_pyobj(o)
}
o
}
# See if x has fun method
out <- tryCatch({
p <- do.call(x$pyobj[[fun]], args)
#res <- construct_symbol_from_pyobj(p)
res <- convert_res(p)
res
}, error = function(cond) {
# ...it did not, try from global namespace:
s <- get_sympy()
args <- c(x$pyobj, args)
p <- do.call(s[[fun]], args)
#print(p)
#res <- construct_symbol_from_pyobj(p)
res <- convert_res(p)
return(res)
})
return(out)
}
#' Get free symbol in expression
#'
#' @param x Expression in which to get the free symbols in
#'
#' @examples
#' if (has_sympy()) {
#' def_sym(a, b)
#' x <- (a - b)^4
#' free_symbols(x)
#' }
#'
#' @concept caracas_symbol
#'
#' @export
free_symbols <- function(x) {
y <- x$pyobj$free_symbols
z <- reticulate::py_eval(paste0("list(", as.character(y), ")"), convert = TRUE)
z <- lapply(z, construct_symbol_from_pyobj)
return(z)
}
#' All variables
#'
#' Return all variables in caracas symbol
#'
#' @param x caracas symbol
#'
#' @examples
#' if (has_sympy()){
#' x <- vector_sym(5)
#' all_vars(x)
#' }
#'
#' @concept caracas_symbol
#'
#' @export
all_vars <- function(x) {
all.vars(as_expr(x))
}
#' Coerce symbol to character
#'
#' Coerce symbol to character
#' @param x caracas symbol
#'
#' @concept caracas_symbol
#'
#' @export
as_character <- function(x) {
ensure_sympy()
stopifnot_symbol(x)
switch(symbol_class(x),
"matrix" = {
as_character_matrix(x)
},
"vector" = {
c(as_character_matrix(x))
},
"atomic" = {
as.character(x)
}
)
}