Defining the difference of compositions in the Wolfram Language - symbolic-math

I've been trying to define a function compdiff on the Wolfram Language that takes two mathematical expressions f and g and a variable x as input and outputs the difference of their compositions f[g[x]]-g[f[x]] (a sort of commutator if you are into abstract algebra).
For example: compdiff[x^2,x+1,x] = (x+1)^2-(x^2+1).
I've tried with
compdiff[f_,g_,x_]:= Composition[f,g][x]-Composition[g,f][x]
and
compdiff[f_,g_,x_]:= f #* g # x-g #* f # x
but when I input
compdiff[x^2,x+1,x]
it outputs
(x^2)[(1 + x)[x]] - (1 + x)[(x^2)[x]]
What am I doing wrong?

You need to use functions instead of expressions. For example:
f[x_] := x^2
g[x_] := x+1
Then compdiff[f, g, x] will work:
In[398]:= compdiff[f,g,x]
Out[398]= -1-x^2+(1+x)^2
Alternatively, you could use pure functions, as in:
In[399]:= compdiff[#^2&,#+1&,x]
Out[399]= -1-x^2+(1+x)^2

Related

make sub-expressions based on addition(+) operator MAPLE

Arbitrary expression be
test := a*b*c+x+a*y+c*z;
output := SomeCommand(test, `+`);
output
[a*b*c,x,a*y,c*z];
Is there any command to do it as a expression.
I did this by converting it into string and using StringSplit command. converting each element from list to expression and in for loop.
test := convert(test, string)
with(StringTools):
output:=StringSplit(test, "+")
["a*b*c", "a*y", "c*z", "x"]
InertForm:-Parse(output[1])
value(output[1])
a*b*c
but, My interest is to get this done as a expression. is there any possibility??
You're question has input but no output. You should observe that the expression that you've assigned to test may have its addends stored in a different order from which they are typed in the input.
It is possible to pick off the addends of a sum, and put them in a list. The very simple code for this is below.
The order in which the addends appear in the list match the order in which they are stored internally.
restart;
f := proc(expr)
if type(expr, `+`) then
[op(expr)];
else
expr;
end if;
end proc:
test := a*b*c+x+a*y+c*z;
test := a b c + a y + c z + x
f( test );
[a b c, a y, c z, x]
Are you the same fellow who's asked all these (somewhat related) questions? Or taking the same course? Q1 Q2 Q3 Q4
If so then could you just tell use what you're really trying to accomplish?

Converting C code into R code: parsing to change a C function in R (pow(a,b) to a^b)

I am using Mathematica to generate equations as C code (using CForm[]), in order to export the equation as a character string and use it in R.
For example, the CForm[] output imported into R as a character string looks like this:
"Tau * Power(Omega * (-(R * Gamma) + R),(Tau + R))"
My question is how best to convert the above C code into an R expression like this:
Tau * (Omega * (-(R * Gamma) + R ))^(Tau + R)
Following a suggestion from an earlier post about converting Mathematica code into R code (Convert Mathematica equations into R code), I'm aware that a reasonable thing to do is to redefine Power() as a function, i.e.,:
Power <- function(a,b) {a^b}
But, through a series of tests, I discovered that evaluating an expression that's in the form of:
eval(parse(text="Tau * (Omega * (-(R * Gamma) + R ))^(Tau + R)"))
is much faster (about 4 times fast on my mac) than the alternative of defining Power() as a function and evaluating the following:
eval(parse(text="Tau * Power(Omega * (-(R * Gamma) + R),(Tau + R))"))
It seems like a complex pattern matching problem, but I could not find any solutions. I appreciate any suggestions.
There are multiple issues here:
Your equation is not standard C code. CForm[] from Mathematica is not translating your code to proper C syntax. Perhaps you could follow this answer and use SymbolicC to solve this part
Your question is more about parsing from Language A to Language B. As mentioned by #Olaf in the comments: You might be better of either using a true C function and call it from R or convert it manually, depending on how often you do this
But, as per your request (if I understood correctly what you want to achieve) and for educational purposes; here's an example in which we will use R to convert your "pseudo-C" string and create an in-lined cfunction()
Note: This is by no mean intended to be elegant or practical, but the general idea should hopefully help you getting started
Assuming the following equation:
v1 <- "4 * Power(Omega * (-(R * Gamma) + R),(Tau + R))"
Extract all variables and functions from the original string
n1 <- stringi::stri_extract_all_words(v1)[[1]]
Create a named vector of "functions to recode" (and a subset without them and without numerics)
newFunc <- c("Power" = "pow")
n2 <- setdiff(n1, names(newFunc))
n3 <- n2[is.na(as.numeric(n2))]
Build a replacement list to feed gsubfn(). For the sake of this example, we replace the old function with the new one and wrap asReal() around the variables
toreplace <- setNames(
as.list(c(newFunc, paste0("asReal(", n3, ")"))),
c(names(newFunc), n3)
)
v2 <- gsubfn::gsubfn(paste(names(toreplace), collapse = "|"), toreplace, v1)
You could then pass this new string to a cfunction() to execute in R
#install.packages("inline")
library(inline)
foo <- cfunction(
sig = setNames(rep("integer", length(n3)), n3),
body = paste0(
"SEXP result = PROTECT(allocVector(REALSXP, 1));
REAL(result)[0] = ", v2, ";
UNPROTECT(1);
return result;"
)
)
This should be faster than using eval(parse("...")) with ^ or defining a Power() function
Tau = 21; Omega = 22; R = 42; Gamma = 34
Power <- function(x,y) {x^y}
microbenchmark::microbenchmark(
C = foo(Omega, R, Gamma, Tau),
R1 = eval(parse(text="4 * ((Omega * (-(R * Gamma) + R ))^(Tau + R))")),
R2 = eval(parse(text="4 * Power(Omega * (-(R * Gamma) + R),(Tau + R))")),
times = 10L
)
#Unit: microseconds
# expr min lq mean median uq max neval
# C 1.233 2.194 5.9555 2.9955 3.302 34.194 10
# R1 190.012 202.781 230.5187 218.1035 243.891 337.209 10
# R2 189.162 191.798 374.5778 207.6875 225.078 1868.746 10

Converting squared and cube terms into multiplication

I am trying to convert a big expression from sage into valid C code using ccode() from sympy. However, my expression has many squared and cube terms. As pow(x,2) is far slower than x*x, I'm trying to expand those terms in my expression before the conversion.
Based on this conversation, I wrote the following code :
from sympy import Symbol, Mul, Pow, pprint, Matrix, symbols
from sympy.core import numbers
def pow_to_mul(expr):
"""
Convert integer powers in an expression to Muls, like a**2 => a*a.
"""
pows = list(expr.atoms(Pow))
pows = [p for p in pows if p.as_base_exp()[1]>=0]
if any(not e.is_Integer for b, e in (i.as_base_exp() for i in pows)):
raise ValueError("A power contains a non-integer exponent")
repl = zip(pows, (Mul(*[b]*e,evaluate=False) for b,e in (i.as_base_exp() for i in pows)))
return expr.subs(repl)
It partially works, but fails as long as the power is argument of a multiplication:
>>>_=var('x')
>>>print pow_to_mul((x^3+2*x^2)._sympy_())
2*x**2 + x*x*x
>>>print pow_to_mul((x^2/(1+x^2)+(1-x^2)/(1+x^2))._sympy_())
x**2/(x*x + 1) - (x*x - 1)/(x*x + 1)
Why? And how can I change that ?
Thank you very much,
If you compile with -ffast-math the compiler will do this optimization for you. If you are using an ancient compiler or cannot affect the level of optimization used in the build process you may pass a user defined function to ccode (using SymPy master branch):
>>> ccode(x**97 + 4*x**7 + 5*x**3 + 3**pi, user_functions={'Pow': [
... (lambda b, e: e.is_Integer and e < 42, lambda b, e: '*'.join([b]*int(e))),
... (lambda b, e: not e.is_Integer, 'pow')]})
'pow(x, 97) + 4*x*x*x*x*x*x*x + 5*x*x*x + pow(3, M_PI)'

Function handle applied to array in MATLAB

I've searched and there are many answers to this kind of question, suggesting functions like arrayfun, bsxfun, and so on. I haven't been able to resolve the issue due to dimension mismatches (and probably a fundamental misunderstanding as to how MATLAB treats anonymous function handles).
I have a generic function handle of more than one variable:
f = #(x,y) (some function of x, y)
Heuristically, I would like to define a new function handle like
g = #(x) sum(f(x,1:3))
More precisely, the following does exactly what I need, but is tedious to write out for larger arrays (say, 1:10 instead of 1:3):
g = #(x) f(x,1)+f(x,2)+f(x,3)
I tried something like
g = #(x) sum(arrayfun(#(y) f(x,y), 1:3))
but this does not work as soon as the size of x exceeds 1x1.
Thanks in advance.
Assuming you cannot change the definition of f to be more vector-friendly, you can use your last solution by specifying a non-uniform output and converting the output cell array to a matrix:
g = #(x) sum(cell2mat(arrayfun(#(y) f(x,y), 1:3,'UniformOutput',false)),2);
This should work well if f(x,y) outputs column vectors and you wish to sum them together. For rows vectors, you can use
g = #(x) sum(cell2mat(arrayfun(#(y) f(x,y), 1:3,'UniformOutput',false).'));
If the arrays are higher in dimension, I actually think a function accumulator would be quicker and easier. For example, consider the (extremely simple) function:
function acc = accumfun(f,y)
acc = f(y(1));
for k = 2:numel(y)
acc = acc + f(y(k));
end
end
Then, you can make the one-liner
g = #(x) accumfun(#(y) f(x,y),y);

What does the perm_invK lemma in Ssreflect prove?

The following code is from perm.v in the Ssreflect Coq library.
I want to know what this result is.
Lemma perm_invK s : cancel (fun x => iinv (perm_onto s x)) s.
Proof. by move=> x /=; rewrite f_iinv. Qed.
Definitions in Ssreflect can involve lots of concepts, and sometimes it is hard to understand what is actually going on. Let's analyze this by parts.
iinv (defined in fintype.v) has type
iinv : forall (T : finType) (T' : eqType) (f : T -> T')
(A : pred T) (y : T'),
y \in [seq f x | x in A] -> T
What this does is to invert any function f : T -> T' whose restriction to a subdomain A \subset T is surjective on T'. Put in other words, if you give me an y that is in the list of results of applying f to all elements of A, then I can find you an x \in A such that f x = y. Notice that this relies crucially on the fact that T is a finite type and that T' has decidable equality. The correctness of iinv is stated in lemma f_iinv, which is used above.
perm_onto has type codom s =i predT, where s is some permutation defined on a finite type T. This is saying, as its name implies, that s is surjective (which is obvious, since it is injective, by the definition of permutations in perm.v, and by the fact that the domain and codomain are the same). Thus, fun x => iinv (perm_onto s x) is a function that maps an element x to an element y such that s y = x. In other words, its the inverse of s. perm_invK is simply stating that this function is indeed the inverse (to be more precise, it is saying that it is the left inverse of s).
The definition that is actually useful, however, is perm_inv, which appears right below. What it does is that it packages fun x => iinv (perm_onto s x) with its proof of correctness perm_invK to define an element of perm_inv s of type {perm T} such that perm_inv s * s = s * perm_inv s = 1. Thus, you can view it as saying that the type {perm T} is closed under inverses, which allows you to use a lot of the ssr machinery for e.g. finite groups and monoids.

Resources