Skip to content

Instantly share code, notes, and snippets.

@bkanuka
Created April 15, 2014 16:06
Show Gist options
  • Save bkanuka/10744247 to your computer and use it in GitHub Desktop.
Save bkanuka/10744247 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
# define the mapping from Mathematica vars to python vars
$r1 = "MIX_RATE";
$r2 = "FADE_RATE";
$s = "SCALE";
$u1 = "last_signal";
$u2 = "NOISE_FLOOR";
$y = "ss_old";
$v = "v_old";
# loop through every line on stdin
while (<>) {
s/[^!-~\s]//g; # strip non-ascii characters
s/{{x\[t\]->//g; # remove beginning {{x[t]->
s/}}//g; # remove ending }}
s/\+\n/\+/g; # add line breaks at ever + or -
s/\-\n/\-/g;
s/Box//g; # Mathematica sometimes adds 'Box'
# I don't know why
# replace r_1 with python var
s/Subscript\[r, 1\]/$r1/g;
# replace r_1^x with python's r1**x
s/Subsuperscript\[r, 1, ([0-9]+)\]/$r1**$1/g;
# repeat for r_2, u_1, and u_2
s/Subscript\[r, 2\]/$r2/g;
s/Subsuperscript\[r, 2, ([0-9]+)\]/$r2**$1/g;
s/Subscript\[u, 1\]/$u1/g;
s/Subsuperscript\[u, 1, ([0-9]+)\]/$u1**$1/g;
s/Subscript\[u, 2\]/$u2/g;
s/Subsuperscript\[u, 2, ([0-9]+)\]/$u2**$1/g;
# replace E^( with np.exp(
s/E\^\(/np.exp(/g;
# replace E^x with np.exp(x)
s/E\^([0-9a-z]+)/np.exp($1)/g;
# replace ^x with **x
s/\^([0-9a-z]+)/**$1/g;
# replace integer x/y with x.0/y so that python does float division
s/([0-9]+)\/([0-9]+)/($1.0\/$2)/g;
# replace whitespace with * (for multiplication)
s/([a-z0-9)])\s+(?=[a-z0-9(])/$1 * /ig;
# put a space around - and +
s/([^(])-/$1 - /g;
s/(.)\+(.)/$1 + $2/g;
# put ever instance of np.exp on a new line.
# this is totally for aesthetics and specific to my use
s/([-+] [^-+n]*(?:np.exp\([^\)]*\)[^-+])?)/\\\n$1/g;
# replace s, y and v in Mathematica with python vars
# assert that s, v, and y are surrounded by word boundaries
s/\bs\b/$s/g;
s/\by\b/$y/g;
s/\bv\b/$v/g;
print;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment