Skip to content

Commit 3af47e1

Browse files
committed
Improved formatting and removed several unnecessary brackets
1 parent 48ca71e commit 3af47e1

File tree

3 files changed

+93
-1986
lines changed

3 files changed

+93
-1986
lines changed

ToPython.wl

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,28 +32,40 @@ ToPythonEquation::usage = "ToPythonEquation[equation, numpyprefix, copy] convert
3232
Begin["Private`"]
3333

3434

35+
(* list of function heads that do not need to be enclosed in brackets *)
36+
singleFunctions={Log, Sin, Cos, Tan, Sinh, Cosh, Tanh};
37+
38+
3539
ToPython[expression_, numpyprefix_:"np", copy_:False] := Module[
36-
{result, greekrule, format, PythonForm, np, a, b, l, m, args},
40+
{result, greekrule, format, PythonForm, np, br, brackets, a, b, l, m, args},
3741

3842
(* determine the correct numpy prefix *)
3943
If[numpyprefix=="", np=numpyprefix, np=numpyprefix<>"."];
4044

4145
(* general function for formating output *)
42-
format[pattern_String, args__] := ToString @ StringForm[
43-
StringReplace[pattern, "numpy."->np],
44-
Sequence @@ PythonForm /@ List[args]];
46+
format[pattern_String, args__] := Module[{s},
47+
s = StringReplace[pattern, "numpy."->np];
48+
ToString @ StringForm[s, Sequence @@ PythonForm /@ List[args]]
49+
];
50+
51+
(* helper function deciding when to use brackets *)
52+
br[a_] := If[AtomQ[a] || MemberQ[singleFunctions, Head[a]], a, brackets[a]];
53+
PythonForm[brackets[a_]] := format["(``)", a];
4554

4655
(* special forms that are recognized *)
47-
PythonForm[Times[-1, a_]] := format["-(``)", a];
56+
PythonForm[Times[-1, a_]] := format["-``", br[a]];
4857
PythonForm[Power[a_, Rational[1, 2]]] := format["numpy.sqrt(``)", a];
49-
PythonForm[Times[a_, Power[b_, -1]]] := format["(``) / (``)", a, b];
58+
PythonForm[Times[a_, Power[b_, -1]]] := format["`` / ``", br[a], br[b]];
5059

5160
(* Simple math *)
52-
PythonForm[Rational[a_, b_]] := format["(``) / (``)", a, b];
61+
PythonForm[Rational[a_, b_]] := format["`` / ``", br[a], br[b]];
5362
PythonForm[Complex[a_, b_]] := format["complex(``, ``)", a, b];
54-
PythonForm[Times[a_, b_]] := format["(``) * (``)", a, b];
55-
PythonForm[Plus[a_, b_]] := format["`` + ``", a, b];
56-
PythonForm[Power[a_, b_]] := format["(``) ** (``)", a, b];
63+
PythonForm[a_ * b__] := Module[{fs, bl={b}},
64+
fs = StringRiffle[ConstantArray["``", 1 + Length@bl], " * "];
65+
format[fs, br@a, Sequence @@ br /@ bl]
66+
];
67+
PythonForm[a_ + b_] := format["`` + ``", a, b];
68+
PythonForm[Power[a_, b_]] := format["`` ** ``", br[a], br[b]];
5769
PythonForm[Exp[a_]] := format["numpy.exp(``)", a];
5870

5971
(* Some special functions *)

0 commit comments

Comments
 (0)