Eine aufbereitete Darstellung der Quelle

 
     
 
 
 
Anforderungen  |   Konzepte  |   Entwurf  |   Entwicklung  |   Qualitätssicherung  |   Lebenszyklus  |   Steuerung


Quelle  latex_parser.py   Sprache: Python

 

from __future__ import annotations
import os
import logging
import re
from pathlib import Path

from sympy.external import import_module
from sympy.utilities.decorator import doctest_depends_on
from sympy.parsing.latex.errors import LaTeXParsingError
from sympy.parsing.latex.lark.transformer import TransformToSymPyExpr

_lark = import_module("lark")

__doctest_requires__ = {('parse_latex_lark', 'parse_latex_lark_all'): ['lark']}


class LarkLaTeXParser:
    r"""Class for converting input `\mathrm{\LaTeX}` strings into SymPy Expressions.
    It holds all the necessary internal data for doing so, and exposes hooks for
    customizing its behavior.

    Parameters
    ==========

    print_debug_output : bool, optional

        If set to ``True``, prints debug output to the logger. Defaults to ``False``.

    transform : bool, optional

        If set to ``True``, the class runs the Transformer class on the parse tree
        generated by running ``Lark.parse`` on the input string. Defaults to ``True``.

        Setting it to ``False`` can help with debugging the `\mathrm{\LaTeX}` grammar.

    grammar_file : str, optional

        The path to the grammar file that the parser should use. If set to ``None``,
        it uses the default grammar, which is in ``grammar/latex.lark``, relative to
        the ``sympy/parsing/latex/lark/`` directory.

    transformer : str, optional

        The name of the Transformer class to use. If set to ``None``, it uses the
        default transformer class, which is :py:func:`TransformToSymPyExpr`.

    "
""
    def __init__(self, print_debug_output=False, transform=True, grammar_file=None, transformer=None):
        grammar_dir_path = os.path.join(os.path.dirname(__file__), "grammar/")

        if grammar_file is None:
            latex_grammar = Path(os.path.join(grammar_dir_path, "latex.lark")).read_text(encoding="utf-8")
        else:
            latex_grammar = Path(grammar_file).read_text(encoding="utf-8")

        self.parser = _lark.Lark(
            latex_grammar,
            source_path=grammar_dir_path,
            parser="earley",
            start="latex_string",
            lexer="auto",
            ambiguity="explicit",
            propagate_positions=False,
            maybe_placeholders=False,
            keep_all_tokens=True)

        # The control words defined in the grammar, e.g. "frac" for "\\frac", so that
        # an unknown one is not split into a known command followed by symbols.
        self.control_words = {word for _, (tree, _) in self.parser.grammar.term_defs
                              for token in tree.scan_values(lambda v: isinstance(v, _lark.Token))
                              for word in re.findall(r"\\\\([a-zA-Z]+)", token)}

        self.print_debug_output = print_debug_output
        self.transform_expr = transform

        if transformer is None:
            self.transformer = TransformToSymPyExpr()
        else:
            self.transformer = transformer()

    def doparse(self, s: str, locals=None):
        if self.print_debug_output:
            _lark.logger.setLevel(logging.DEBUG)

        parse_tree = self._parse(s)

        if not self.transform_expr:
            # exit early and return the parse tree
            _lark.logger.debug("expression = %s", s)
            _lark.logger.debug(parse_tree)
            _lark.logger.debug(parse_tree.pretty())
            return parse_tree

        if self.print_debug_output:
            # print this stuff before attempting to run the transformer
            _lark.logger.debug("expression = %s", s)
            # print the `parse_tree` variable
            _lark.logger.debug(parse_tree.pretty())

        sympy_expression = self._transform(parse_tree, locals)

        if self.print_debug_output:
            _lark.logger.debug("SymPy expression = %s", sympy_expression)

        return sympy_expression

    def doparse_all(self, s: str, locals=None):
        """The list of the readings of ``s``, see :func:`parse_latex_lark_all`.

        When ``transform`` is ``False``, the list holds the parse trees of the
        readings instead of the expressions.
        "
""
        trees = _lark.visitors.CollapseAmbiguities().transform(self._parse(s))
        trees = _parallel_readings(trees)

        if not self.transform_expr:
            return trees

        expressions = []
        for tree in trees:
            expression = self._transform(tree, locals)
            if expression not in expressions:
                expressions.append(expression)
        return expressions

    def _parse(self, s):
        for match in re.finditer(r"\\(?:\\|([a-zA-Z]+)|.)", s):
            if match.group(1) and match.group(1) not in self.control_words:
                raise LaTeXParsingError("Unknown command %s" % match.group(0))

        return self.parser.parse(s)

    def _transform(self, parse_tree, locals):
        transformer = self.transformer
        if locals:
            transformer = transformer.with_locals(locals)

        try:
            return transformer.transform(parse_tree)
        except _lark.exceptions.VisitError as error:
            # a parsing error found while building the expression is reported as itself
            if isinstance(error.orig_exc, LaTeXParsingError):
                raise error.orig_exc from error
            raise


def _node_spans(tree):
    """The span of the input covered by each node of ``tree``, and the outermost
    node covering each span."
""
    span_of = {}
    node_at = {}

    def visit(node):
        if isinstance(node, _lark.Token):
            span = (node.start_pos, node.end_pos)
        else:
            spans = [visit(child) for child in node.children]
            span = (spans[0][0], spans[-1][1])
        span_of[id(node)] = span
        node_at[span] = node
        return span

    visit(tree)
    return span_of, node_at


def _signature(node, span_of, sites):
    """The shape of ``node``, where the nodes covering one of ``sites`` count as
    equal whatever they hold."
""
    if isinstance(node, _lark.Token):
        return (node.type, node.value)
    span = span_of[id(node)]
    return (node.data, tuple(
        None if span_of[id(child)] != span and span_of[id(child)] in sites
        else _signature(child, span_of, sites)
        for child in node.children))


def _choice(node, span_of):
    """The rules applied to the span of ``node``, from the outermost one."""
    span = span_of[id(node)]
    labels = []
    while isinstance(node, _lark.Tree):
        labels.append(node.data)
        inner = [child for child in node.children if span_of[id(child)] == span]
        if not inner:
            return tuple(labels)
        node = inner[0]
    labels.append(node.type)
    return tuple(labels)


def _parallel_readings(trees):
    """The parse trees among ``trees`` choosing the same way at every place
    where the input is ambiguous in the same way.

    A site of ambiguity is a span of the input covered in every tree by a node
    whose shape is not the same in every tree, apart from the sites it holds.
    Two sites are of the same kind when the rules they may be read with are the
    same, and the choice at a site is the rule it is read with. If no tree makes
    the same choice at the sites of each kind, all the trees are returned.
    "
""
    if len(trees) < 2:
        return trees

    spans = [_node_spans(tree) for tree in trees]
    common = set.intersection(*(set(node_at) for _, node_at in spans))

    sites = {}
    for span in sorted(common, key=lambda span: span[1] - span[0]):
        nodes = [node_at[span] for _, node_at in spans]
        signatures = {_signature(node, span_of, sites)
                      for node, (span_of, _) in zip(nodes, spans)}
        if len(signatures) > 1:
            choices = [_choice(node, span_of) for node, (span_of, _) in zip(nodes, spans)]
            prefix = os.path.commonprefix(choices)
            choices = [choice[len(prefix):] for choice in choices]
            # without a rule telling the readings apart, the site is a kind of its own
            kind = frozenset(choices) if len(set(choices)) == len(signatures) else span
            sites[span] = (kind, choices)

    kinds = {}
    for kind, choices in sites.values():
        kinds.setdefault(kind, []).append(choices)

    parallel = [tree for i, tree in enumerate(trees)
                if all(len({choices[i] for choices in same_kind}) == 1
                       for same_kind in kinds.values())]
    return parallel or trees


if _lark is not None:
    _lark_latex_parser = LarkLaTeXParser()


@doctest_depends_on(modules=('lark',))
def parse_latex_lark(s: str, locals=None):
    r"""
    Experimental LaTeX parser using Lark.

    This function is still under development and its API may change with the
    next releases of SymPy.

    Parameters
    ==========

    s : str
        The `\mathrm{\LaTeX}` string to parse.

    locals : dict, optional
        The readings of constants and functions to use instead of the default
        ones. The keys are the commands as they are written in ``s``: the
        constants ``\pi``, ``\mathrm{e}``, ``\infty`` and ``\imaginaryunit``,
        the trigonometric and hyperbolic functions like ``\sin``, the functions
        ``\exp``, ``\ln``, ``\log`` and ``\lg``, and any function written as
        ``\operatorname{name}``. The value is an expression for a constant,
        and for a function it is what is called with the arguments.

    Examples
    ========

    >>> from sympy.parsing.latex.lark import parse_latex_lark
    >>> from sympy import Function, Symbol, pi
    >>> parse_latex_lark(r"
2\pi").has(pi)
    True
    >>> parse_latex_lark(r"
2\pi", locals={r"\pi": Symbol("pi")}).has(pi)
    False
    >>> f = Function("
erf")
    >>> parse_latex_lark(r"
\operatorname{erf}(x)", locals={r"\operatorname{erf}": f}).func == f
    True

    "
""
    if _lark is None:
        raise ImportError("Lark is probably not installed")
    return _lark_latex_parser.doparse(s, locals=locals)


@doctest_depends_on(modules=('lark',))
def parse_latex_lark_all(s: str, locals=None):
    r"""
    Experimental LaTeX parser using Lark, returning all the readings of an
    ambiguous input.

    This function is still under development and its API may change with the
    next releases of SymPy.

    It takes the same arguments as :func:`parse_latex_lark` and returns a list
    of the expressions ``s`` may mean, with a single element when ``s`` is not
    ambiguous. When the same ambiguity occurs several times, the readings choose
    the same way at every place where it occurs, instead of giving all the
    combinations of the choices.

    Examples
    ========

    >>> from sympy.parsing.latex.lark import parse_latex_lark_all
    >>> parse_latex_lark_all(r"
x + y")
    [x + y]
    >>> parse_latex_lark_all(r"
\sin xy")
    [sin(x*y), y*sin(x)]
    >>> parse_latex_lark_all(r"
\cos ab + \sin xy")
    [sin(x*y) + cos(a*b), b*cos(a) + y*sin(x)]

    "
""
    if _lark is None:
        raise ImportError("Lark is probably not installed")
    return _lark_latex_parser.doparse_all(s, locals=locals)


def _pretty_print_lark_trees(tree, indent=0, show_expr=True):
    if isinstance(tree, _lark.Token):
        return tree.value

    data = str(tree.data)

    is_expr = data.startswith("expression")

    if is_expr:
        data = re.sub(r"^expression", "E", data)

    is_ambig = (data == "_ambig")

    if is_ambig:
        new_indent = indent + 2
    else:
        new_indent = indent

    output = ""
    show_node = not is_expr or show_expr

    if show_node:
        output += str(data) + "("

    if is_ambig:
        output += "\n" + "\n".join([" " * new_indent + _pretty_print_lark_trees(i, new_indent, show_expr) for i in tree.children])
    else:
        output += ",".join([_pretty_print_lark_trees(i, new_indent, show_expr) for i in tree.children])

    if show_node:
        output += ")"

    return output

Messung
CHZG
859810094

¤ Dauer der Verarbeitung: 0.1 Sekunden  (vorverarbeitet am  2026-11-24) ¤

*© Formatika GbR, Deutschland







                                                                                                                                                                                                                                                                                                                                                                                                     

 

Neuigkeiten

Aktuelles
Motto des Tages

Open Source Software


Gedichte
Musik
Bilder

Jenseits des Üblichen

Besucherstatistik

Besucherstatistik

Statistik
#Sources=1,188,316
#Domains=919,464