Skip to content

Commit

Permalink
Merge pull request gyorilab#405 from gyorilab/optimize_parsing
Browse files Browse the repository at this point in the history
Precompile patterns and use cache when parsing
  • Loading branch information
bgyori authored Dec 6, 2024
2 parents 32ee356 + 2f244a9 commit 420832f
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions mira/metamodel/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,28 @@
import sympy
import re
import unicodedata

from typing import Any
from functools import lru_cache

from pydantic import GetCoreSchemaHandler
from pydantic_core import core_schema


# Pre-compile the regular expression for performance
re_dots = re.compile(r'\.(?=\D)')
re_superscripts = re.compile(r"\^{(.*?)}")
re_curly_braces = re.compile(r'[{}]')


@lru_cache(maxsize=10000)
def get_parseable_expression(s: str) -> str:
"""Return an expression that can be parsed using sympy."""
# Handle lambda which cannot be parsed by sympy
s = s.replace('lambda', 'XXlambdaXX')
# Handle dots which also cannot be parsed
s = re.sub(r'\.(?=\D)', 'XX_XX', s)
s = re_dots.sub('XX_XX', s)
# Handle superscripts which are not allowed in sympy
s = re.sub(r"\^{(.*?)}", r"XXCXX{_\1}", s)
s = re_superscripts.sub(r"XXCXX{\1}", s)
# Handle curly braces which are not allowed in sympy
s = s.replace('{', 'XXCBO').replace('}', 'XXCBC')
s = unicodedata.normalize('NFKC', s)
Expand Down

0 comments on commit 420832f

Please sign in to comment.