Preamble Sometimes I have to solve nonlinear PDEs using Comsol. Often these equations I already have in Mma, written in a Mma notations. For this reason I would like to be able to transform them so that I could copy-paste them directly into Comsol.
There is one more reason to do in such a way. The point is that the Comsol service is poor: the slot to type equations is narrow and short, as if it is created to force the user to make typing errors. In addition, if Comsol is not sure in syntax, it makes equations yellow. I simply do not see them afterwards.
In Mma, in contrast, one can type a well-visible equation, and then... what? One cannot copy-paste it, since Comsol has another syntax.
a) One needs to introduce dependent variables without their arguments. That is u[x]
in Mma, but u
in Comsol
b) In functions one needs to replace the square brackets by round ones and should not use the Capitals. That is, Sin[x]
in Mma, but sin(x)
in Comsol.
c) One has to use another expressions for the derivatives. That is D[u[x],x]
and D[u[x],{x,2}]
or u'[x]
and u''[x]
in Mma, but ux
and uxx
in Comsol.
Minor addition: if the differential equation is non-stationary, one does not need to take care of time derivatives, since Comsol has a special template for that purpose.
My question is: How to do it programmatically?
What I already do is as follows. Say, I need to transform an expression: expr = D[y[x, t], {x, 2}] + D[y[x, t], x] + Sin[x] + y[x, t] -y[x, t]^3
. I do as follows:
expr = D[y[x, t], {x, 2}] + D[y[x, t], x] + Sin[x] + y[x, t] -y[x, t]^3;
expr /. y -> (u[#] &) /. {u[x]^n_ -> u^n, u[x] -> u} /. {u'[x] -> ux, u''[x] -> uxx}
//TraditionalForm
In principle, it almost gives what I need. This expression can be copy-pasted into Comsol.
There is still a problem, however. The resulting expression contains spaces between some characters. For example, each sign +
is flanked by the spaces. Comsol treats these as errors. Do you see any way to programmatically eliminate these spaces?
// ToString // StringReplace[#, " " .. -> ""] &
instead ofTraditionalForm
does not work? $\endgroup$ – gpap Nov 25 '14 at 10:59-u^3+u+ux+uxx+sin(x)
$\endgroup$ – Chris Degnen Nov 25 '14 at 11:20toComsol[expr_, y_, u_] := Module[{n}, expr /. y -> (u[#] &) /. {u[x]^n_ -> u^n, u[x] -> u} /. {u'[x] -> ToExpression[ToString[u] <> "x"], u''[x] -> ToExpression[ToString[u] <> "xx"]} // InputForm // ToString // ToLowerCase // StringReplace[#, {" " .. -> "", "[" -> "(", "]" -> ")"}] &]
. Why do not you give your idea as a regular answer? $\endgroup$ – Alexei Boulbitch Nov 25 '14 at 12:29