Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Post-processing python phenotypes is slow #157

Open
MihaiBabiac opened this issue May 4, 2022 · 0 comments
Open

Post-processing python phenotypes is slow #157

MihaiBabiac opened this issue May 4, 2022 · 0 comments

Comments

@MihaiBabiac
Copy link

The python_filter function which converts {:, :} and {::} into newlines and indentation is slower than it has to be. It takes a significant amount of time when the operations used and the evaluation is fast. Replacing the per-char for loop with calls to builtins and a per-line for loop is faster.

See my changes below:

--- a/PonyGE2/src/utilities/representation/python_filter.py
+++ b/PonyGE2/src/utilities/representation/python_filter.py
@@ -5,20 +5,21 @@ def python_filter(txt):
     it's not possible to specify indentation correctly in a BNF
     grammar without this type of scheme."""
 
+    # Split input into lines
+    split_code = (txt
+                  .replace("{::}", "\n")
+                  .replace("{:", "{:\n")
+                  .replace(":}", ":}\n")
+                  .split("\n"))
+
+    new_line_list = []
     indent_level = 0
-    tmp = txt[:]
-    i = 0
-    while i < len(tmp):
-        tok = tmp[i:i + 2]
-        if tok == "{:":
-            indent_level += 1
-        elif tok == ":}":
-            indent_level -= 1
-        tabstr = "\n" + "  " * indent_level
-        if tok == "{:" or tok == ":}":
-            tmp = tmp.replace(tok, tabstr, 1)
-        i += 1
-    # Strip superfluous blank lines.
-    txt = "\n".join([line for line in tmp.split("\n")
-                     if line.strip() != ""])
-    return txt
+    for line in split_code:
+        if line != ":}" and line != "":
+            clean_line = line.replace("{:", "").replace(":}", "")
+            new_line_list.append("  " * indent_level + clean_line)
+        indent_level += line.count("{:")
+        indent_level -= line.count(":}")
+
+    new_code = "\n".join(new_line_list)
+    return new_code
@MihaiBabiac MihaiBabiac changed the title Post-processing python is slow Post-processing python phenotypes is slow May 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant