Skip to content

Instantly share code, notes, and snippets.

@jlumbroso
Created October 23, 2023 19:56
Show Gist options
  • Save jlumbroso/36a3c7323f6c80ca0f5ef72b42c6eb17 to your computer and use it in GitHub Desktop.
Save jlumbroso/36a3c7323f6c80ca0f5ef72b42c6eb17 to your computer and use it in GitHub Desktop.
Snippet to convert between Unicode and LaTeX representations of logical propositions.
import re
_LATEX_POST_ENTITY = "{}"
# Mapping of Unicode characters to LaTeX expressions
MAPPING = {
"∀": "\\forall",
"∃": "\\exists",
"→": "\\rightarrow",
"↔": "\\leftrightarrow",
"¬": "\\neg",
"∧": "\\land",
"∨": "\\lor",
# Add more mappings if needed
}
def to_latex(expression: str) -> str:
"""
Convert a logical expression with Unicode characters into its LaTeX representation.
Parameters:
- expression (str): The logical expression containing Unicode characters.
Returns:
- str: The LaTeX representation of the given expression.
Example:
>>> to_latex("∀x∀y(Congruent(x,y) → SameArea(x,y))")
'\\forall{}x\\forall{}y(Congruent(x,y) \\rightarrow SameArea(x,y))'
"""
for char, latex in MAPPING.items():
expression = expression.replace(char, latex + _LATEX_POST_ENTITY)
# Convert predicates to \text{\textsc{Predicate}} format
expression = re.sub(r'([A-Za-z]+)\(', r'\\text{\\textsc{\1}}(', expression)
return expression
def from_latex(expression: str) -> str:
"""
Convert a LaTeX logical expression into its Unicode representation.
Parameters:
- expression (str): The LaTeX representation of a logical expression.
Returns:
- str: The logical expression with Unicode characters.
Example:
>>> from_latex('\\forall{}x\\forall{}y(Congruent(x,y) \\rightarrow SameArea(x,y))')
'∀x∀y(Congruent(x,y) → SameArea(x,y))'
"""
reversed_mapping = {latex: char for char, latex in MAPPING.items()}
for latex, char in reversed_mapping.items():
expression = expression.replace(latex, char)
# Remove \s*{\s*}\s* from from expression using re
expression = re.sub(r'\\s*\{\s*\}\s*', '', expression)
# Convert \text{\textsc{Predicate}} format to predicates
expression = re.sub(r'\\text{\\textsc{([A-Za-z]+)}}\(', r'\1(', expression)
return expression
if __name__ == "__main__":
# Test
options = [
"∀x∀y(Congruent(x,y) → SameArea(x,y))",
"∀x∀y(Congruent(x,y) ↔ SameArea(x,y))",
# ... (rest of the options)
]
latex_options = [to_latex(option) for option in options]
for option in latex_options:
print(option)
print("\nInverse conversion:")
for option in latex_options:
print(from_latex(option))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment