5
$\begingroup$

I am looking to simplify arbitrary algebraic expressions by invoking the mathematica kernel from C using WSTP. My initial attempt was the following, which was based on the online documentation and the example "factor.c"

algebra = "(a + a + a + a - b)";

WSPutFunction(lp, "EvaluatePacket", 1L);
WSPutFunction(lp, "FullSimplify", 1L);
WSPutString(lp, algebra);
WSEndPacket(lp);

WSFlush(lp);

while( (pkt = WSNextPacket(lp), pkt) && pkt != RETURNPKT ) {
    WSNewPacket(lp);
        if (WSError(lp)) {
            error(lp);
        }
}

const char *output;
if(! WSGetString(lp, &output)) {
    printf("Unable to read from link\n");
    return -1;
} else {
    printf("%s\n", output);
}
WSReleaseString(lp, symbol);

WSPutFunction(lp, "Exit", 0);

However, WSTP returns the still unsimplified expression from the WSGetString() call. I expected to see "4 a - b" as the result of "FullSimplify[(a + a + a + a - b)]".

I then attempted using EnterTextPacket and ReturnTextPacket but it isn't clear how these work.

My goal is to simplify algebraic expressions through WSTP. What is a working simple or common way to do this?

$\endgroup$
9
$\begingroup$

You are not evaluating

FullSimplify[(a + a + a + a - b)]

You are evaluating

FullSimplify["(a + a + a + a - b)"]

You used the PutString function. It does exactly that: it puts a string on the link.

There are three options:

Either put the correct expression structure, which is

Plus[a, a, a, a, Times[-1, b]]

and would involve something like this (untested):

MLPutFunction(lp, "Plus", 5);
  MLPutSymbol(lp, "a");
  MLPutSymbol(lp, "a");
  MLPutSymbol(lp, "a");
  MLPutSymbol(lp, "a");
  MLPutFunction(lp, "Times", 2);
    MLPutInteger(lp, -1);
    MLPutSymbol(lp, "b");

Or you can precede putting the string by MLPutFunction(lp, "ToExpression", 1). This will send ToExpression["(a + a + a + a - b)"] instead of "(a + a + a + a - b)".

Finally, you could use an EnterTextPacket instead of an EvaluatePacket.

Please read this tutorial, especially section 2. This document explains things much better than the documentation.


Additional comments:

  • FullSimplify is not necessary to compute a+a+a+a-b. The result would be the same as without FullSimplify

  • You used 1L in WSPutFunction(). Its third argument is in fact of type int (and not long), thus using 1L is not appropriate.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.