Пример #1
0
def _determine_indices(symbol: Union[sp.Indexed, sp.Symbol]) -> List[int]:
    r"""Extract any indices if available from a `~sympy.core.symbol.Symbol`.

    >>> _determine_indices(sp.Symbol("m1"))
    [1]
    >>> _determine_indices(sp.Symbol("m_a2"))
    [2]
    >>> _determine_indices(sp.Symbol(R"\alpha_{i2, 5}"))
    [2, 5]
    >>> _determine_indices(sp.Symbol("m"))
    []

    `~sympy.tensor.indexed.Indexed` instances can also be handled:
    >>> m_a = sp.IndexedBase("m_a")
    >>> _determine_indices(m_a[0])
    [0]
    """
    _, _, subscripts = split_super_sub(sp.latex(symbol))
    if not subscripts:
        return []
    subscript: str = subscripts[-1]
    subscript = re.sub(r"[^0-9^\,]", "", subscript)
    subscript = f"[{subscript}]"
    try:
        indices = eval(subscript)  # pylint: disable=eval-used
    except SyntaxError:
        return []
    return list(indices)
Пример #2
0
def pretty_symbol(symb_name, bold_name=False):
    """return pretty representation of a symbol"""
    # let's split symb_name into symbol + index
    # UC: beta1
    # UC: f_beta

    if not _use_unicode:
        return symb_name

    name, sups, subs = split_super_sub(symb_name)

    def translate(s, bold_name) :
        if bold_name:
            gG = greek_bold_unicode.get(s)
        else:
            gG = greek_unicode.get(s)
        if gG is not None:
            return gG
        for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True) :
            if s.lower().endswith(key) and len(s)>len(key):
                return modifier_dict[key](translate(s[:-len(key)], bold_name))
        if bold_name:
            return ''.join([bold_unicode[c] for c in s])
        return s

    name = translate(name, bold_name)

    # Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are
    # not used at all.
    def pretty_list(l, mapping):
        result = []
        for s in l:
            pretty = mapping.get(s)
            if pretty is None:
                try:  # match by separate characters
                    pretty = ''.join([mapping[c] for c in s])
                except (TypeError, KeyError):
                    return None
            result.append(pretty)
        return result

    pretty_sups = pretty_list(sups, sup)
    if pretty_sups is not None:
        pretty_subs = pretty_list(subs, sub)
    else:
        pretty_subs = None

    # glue the results into one string
    if pretty_subs is None:  # nice formatting of sups/subs did not work
        if subs:
            name += '_'+'_'.join([translate(s, bold_name) for s in subs])
        if sups:
            name += '__'+'__'.join([translate(s, bold_name) for s in sups])
        return name
    else:
        sups_result = ' '.join(pretty_sups)
        subs_result = ' '.join(pretty_subs)

    return ''.join([name, sups_result, subs_result])
Пример #3
0
def pretty_symbol(symb_name, bold_name=False):
    """return pretty representation of a symbol"""
    # let's split symb_name into symbol + index
    # UC: beta1
    # UC: f_beta

    if not _use_unicode:
        return symb_name

    name, sups, subs = split_super_sub(symb_name)

    def translate(s, bold_name) :
        if bold_name:
            gG = greek_bold_unicode.get(s)
        else:
            gG = greek_unicode.get(s)
        if gG is not None:
            return gG
        for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True) :
            if s.lower().endswith(key) and len(s)>len(key):
                return modifier_dict[key](translate(s[:-len(key)], bold_name))
        if bold_name:
            return ''.join([bold_unicode[c] for c in s])
        return s

    name = translate(name, bold_name)

    # Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are
    # not used at all.
    def pretty_list(l, mapping):
        result = []
        for s in l:
            pretty = mapping.get(s)
            if pretty is None:
                try:  # match by separate characters
                    pretty = ''.join([mapping[c] for c in s])
                except (TypeError, KeyError):
                    return None
            result.append(pretty)
        return result

    pretty_sups = pretty_list(sups, sup)
    if pretty_sups is not None:
        pretty_subs = pretty_list(subs, sub)
    else:
        pretty_subs = None

    # glue the results into one string
    if pretty_subs is None:  # nice formatting of sups/subs did not work
        if subs:
            name += '_'+'_'.join([translate(s, bold_name) for s in subs])
        if sups:
            name += '__'+'__'.join([translate(s, bold_name) for s in sups])
        return name
    else:
        sups_result = ' '.join(pretty_sups)
        subs_result = ' '.join(pretty_subs)

    return ''.join([name, sups_result, subs_result])
Пример #4
0
def pretty_symbol(symb_name):
    """return pretty representation of a symbol"""
    # let's split symb_name into symbol + index
    # UC: beta1
    # UC: f_beta

    if not _use_unicode:
        return symb_name

    name, sups, subs = split_super_sub(symb_name)

    # let's prettify name
    gG = greek.get(name.lower())
    if gG is not None:
        if name.islower():
            greek_name = greek.get(name.lower())[0]
        else:
            greek_name = greek.get(name.lower())[1]
        # some letters may not be available
        if greek_name is not None:
            name = greek_name

    # Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are
    # not used at all.
    def pretty_list(l, mapping):
        result = []
        for s in l:
            pretty = mapping.get(s)
            if pretty is None:
                try: # match by separate characters
                    pretty = ''.join([mapping[c] for c in s])
                except KeyError:
                    return None
            result.append(pretty)
        return result

    pretty_sups = pretty_list(sups, sup)
    if pretty_sups is not None:
        pretty_subs = pretty_list(subs, sub)
    else:
        pretty_subs = None

    # glue the results into one string
    if pretty_subs is None: # nice formatting of sups/subs did not work
        if len(sups) > 0:
            sups_result = '^' + '^'.join(sups)
        else:
            sups_result = ''
        if len(subs) > 0:
            subs_result = '_' + '_'.join(subs)
        else:
            subs_result = ''
    else:
        sups_result = ' '.join(pretty_sups)
        subs_result = ' '.join(pretty_subs)


    return ''.join([name, sups_result, subs_result])
Пример #5
0
    def _print_Symbol(self, sym, style='plain'):
        x = self.dom.createElement('mi')

        if style == 'bold':
            x.setAttribute('mathvariant', 'bold')

        def join(items):
            if len(items) > 1:
                mrow = self.dom.createElement('mrow')
                for i, item in enumerate(items):
                    if i > 0:
                        mo = self.dom.createElement('mo')
                        mo.appendChild(self.dom.createTextNode(" "))
                        mrow.appendChild(mo)
                    mi = self.dom.createElement('mi')
                    mi.appendChild(self.dom.createTextNode(item))
                    mrow.appendChild(mi)
                return mrow
            else:
                mi = self.dom.createElement('mi')
                mi.appendChild(self.dom.createTextNode(items[0]))
                return mi

        # translate name, supers and subs to unicode characters
        def translate(s):
            if s in greek_unicode:
                return greek_unicode.get(s)
            else:
                return s

        name, supers, subs = split_super_sub(sym.name)
        name = translate(name)
        supers = [translate(sup) for sup in supers]
        subs = [translate(sub) for sub in subs]

        mname = self.dom.createElement('mi')
        mname.appendChild(self.dom.createTextNode(name))
        if len(supers) == 0:
            if len(subs) == 0:
                x.appendChild(self.dom.createTextNode(name))
            else:
                msub = self.dom.createElement('msub')
                msub.appendChild(mname)
                msub.appendChild(join(subs))
                x.appendChild(msub)
        else:
            if len(subs) == 0:
                msup = self.dom.createElement('msup')
                msup.appendChild(mname)
                msup.appendChild(join(supers))
                x.appendChild(msup)
            else:
                msubsup = self.dom.createElement('msubsup')
                msubsup.appendChild(mname)
                msubsup.appendChild(join(subs))
                msubsup.appendChild(join(supers))
                x.appendChild(msubsup)
        return x
Пример #6
0
def pretty_symbol(symb_name):
    """return pretty representation of a symbol"""
    # let's split symb_name into symbol + index
    # UC: beta1
    # UC: f_beta

    if not _use_unicode:
        return symb_name

    name, sups, subs = split_super_sub(symb_name)

    # let's prettify name
    gG = greek.get(name.lower())
    if gG is not None:
        if name.islower():
            greek_name = greek.get(name.lower())[0]
        else:
            greek_name = greek.get(name.lower())[1]
        # some letters may not be available
        if greek_name is not None:
            name = greek_name

    # Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are
    # not used at all.
    def pretty_list(l, mapping):
        result = []
        for s in l:
            pretty = mapping.get(s)
            if pretty is None:
                try: # match by separate characters
                    pretty = ''.join([mapping[c] for c in s])
                except KeyError:
                    return None
            result.append(pretty)
        return result

    pretty_sups = pretty_list(sups, sup)
    if pretty_sups is not None:
        pretty_subs = pretty_list(subs, sub)
    else:
        pretty_subs = None

    # glue the results into one string
    if pretty_subs is None: # nice formatting of sups/subs did not work
        if len(sups) > 0:
            sups_result = '^' + '^'.join(sups)
        else:
            sups_result = ''
        if len(subs) > 0:
            subs_result = '_' + '_'.join(subs)
        else:
            subs_result = ''
    else:
        sups_result = ' '.join(pretty_sups)
        subs_result = ' '.join(pretty_subs)


    return ''.join([name, sups_result, subs_result])
Пример #7
0
    def _print_Symbol(self, sym):
        ci = self.dom.createElement(self.mathml_tag(sym))

        def join(items):
            if len(items) > 1:
                mrow = self.dom.createElement('mml:mrow')
                for i, item in enumerate(items):
                    if i > 0:
                        mo = self.dom.createElement('mml:mo')
                        mo.appendChild(self.dom.createTextNode(" "))
                        mrow.appendChild(mo)
                    mi = self.dom.createElement('mml:mi')
                    mi.appendChild(self.dom.createTextNode(item))
                    mrow.appendChild(mi)
                return mrow
            else:
                mi = self.dom.createElement('mml:mi')
                mi.appendChild(self.dom.createTextNode(items[0]))
                return mi

        # translate name, supers and subs to unicode characters
        def translate(s):
            if s in greek_unicode:
                return greek_unicode.get(s)
            else:
                return s

        name, supers, subs = split_super_sub(sym.name)
        name = translate(name)
        supers = [translate(sup) for sup in supers]
        subs = [translate(sub) for sub in subs]

        mname = self.dom.createElement('mml:mi')
        mname.appendChild(self.dom.createTextNode(name))
        if not supers:
            if not subs:
                ci.appendChild(self.dom.createTextNode(name))
            else:
                msub = self.dom.createElement('mml:msub')
                msub.appendChild(mname)
                msub.appendChild(join(subs))
                ci.appendChild(msub)
        else:
            if not subs:
                msup = self.dom.createElement('mml:msup')
                msup.appendChild(mname)
                msup.appendChild(join(supers))
                ci.appendChild(msup)
            else:
                msubsup = self.dom.createElement('mml:msubsup')
                msubsup.appendChild(mname)
                msubsup.appendChild(join(subs))
                msubsup.appendChild(join(supers))
                ci.appendChild(msubsup)
        return ci
Пример #8
0
    def _print_Symbol(self, sym):
        x = self.dom.createElement('mi')

        def join(items):
            if len(items) > 1:
                mrow = self.dom.createElement('mrow')
                for i, item in enumerate(items):
                    if i > 0:
                        mo = self.dom.createElement('mo')
                        mo.appendChild(self.dom.createTextNode(" "))
                        mrow.appendChild(mo)
                    mi = self.dom.createElement('mi')
                    mi.appendChild(self.dom.createTextNode(item))
                    mrow.appendChild(mi)
                return mrow
            else:
                mi = self.dom.createElement('mi')
                mi.appendChild(self.dom.createTextNode(items[0]))
                return mi

        # translate name, supers and subs to unicode characters
        def translate(s):
            if s in greek_unicode:
                return greek_unicode.get(s)
            else:
                return s

        name, supers, subs = split_super_sub(sym.name)
        name = translate(name)
        supers = [translate(sup) for sup in supers]
        subs = [translate(sub) for sub in subs]

        mname = self.dom.createElement('mi')
        mname.appendChild(self.dom.createTextNode(name))
        if len(supers) == 0:
            if len(subs) == 0:
                x.appendChild(self.dom.createTextNode(name))
            else:
                msub = self.dom.createElement('msub')
                msub.appendChild(mname)
                msub.appendChild(join(subs))
                x.appendChild(msub)
        else:
            if len(subs) == 0:
                msup = self.dom.createElement('msup')
                msup.appendChild(mname)
                msup.appendChild(join(supers))
                x.appendChild(msup)
            else:
                msubsup = self.dom.createElement('msubsup')
                msubsup.appendChild(mname)
                msubsup.appendChild(join(subs))
                msubsup.appendChild(join(supers))
                x.appendChild(msubsup)
        return x
Пример #9
0
 def _print_Symbol(self, expr):
     name, sup, sub = split_super_sub(expr.name)
     if name == 'lamda':
         name = 'lambda'
     if name.lower() in greeks:
         if not name.islower():
             name = name.upper()
         name = '%' + name
     if sub:
         name += '_{%s}' % sub[0]
     return name
Пример #10
0
    def _print_Symbol(self, sym, style='plain'):
        def join(items):
            if len(items) > 1:
                mrow = self.dom.createElement('mrow')
                for i, item in enumerate(items):
                    if i > 0:
                        mo = self.dom.createElement('mo')
                        mo.appendChild(self.dom.createTextNode(" "))
                        mrow.appendChild(mo)
                    mi = self.dom.createElement('mi')
                    mi.appendChild(self.dom.createTextNode(item))
                    mrow.appendChild(mi)
                return mrow
            else:
                mi = self.dom.createElement('mi')
                mi.appendChild(self.dom.createTextNode(items[0]))
                return mi

        # translate name, supers and subs to unicode characters
        def translate(s):
            if s in greek_unicode:
                return greek_unicode.get(s)
            else:
                return s

        name, supers, subs = split_super_sub(sym.name)
        name = translate(name)
        supers = [translate(sup) for sup in supers]
        subs = [translate(sub) for sub in subs]

        mname = self.dom.createElement('mi')
        mname.appendChild(self.dom.createTextNode(name))
        if len(supers) == 0:
            if len(subs) == 0:
                x = mname
            else:
                x = self.dom.createElement('msub')
                x.appendChild(mname)
                x.appendChild(join(subs))
        else:
            if len(subs) == 0:
                x = self.dom.createElement('msup')
                x.appendChild(mname)
                x.appendChild(join(supers))
            else:
                x = self.dom.createElement('msubsup')
                x.appendChild(mname)
                x.appendChild(join(subs))
                x.appendChild(join(supers))
        # Set bold font?
        if style == 'bold':
            x.setAttribute('mathvariant', 'bold')
        return x
Пример #11
0
 def _render_str(self, string):
     """Returned a texified version of the string"""
     if isinstance(string, StrLabel):
         string = string._render(string.expr)
     string = str(string)
     if len(string) == 0:
         return ''
     name, supers, subs = split_super_sub(string)
     return render_latex_sub_super(name,
                                   subs,
                                   supers,
                                   translate_symbols=True)
Пример #12
0
def _strip_subscript_superscript(symbol: sp.Symbol) -> str:
    """Collect subscripts from a `sympy.core.symbol.Symbol`.

    >>> _strip_subscript_superscript(sp.Symbol("p1"))
    'p'
    >>> _strip_subscript_superscript(sp.Symbol("p^2_{0,0}"))
    'p'
    """
    if isinstance(symbol, sp.Basic):
        text = sp.latex(symbol)
    else:
        text = symbol
    name, _, _ = split_super_sub(text)
    return name
Пример #13
0
 def _render_str(self, string):
     """Returned a unicodified version of the string."""
     if isinstance(string, StrLabel):
         string = string._render(string.expr)
     string = str(string)
     if len(string) == 0:
         return ''
     name, supers, subs = split_super_sub(string)
     return render_unicode_sub_super(
         name,
         subs,
         supers,
         sub_first=True,
         translate_symbols=True,
         unicode_sub_super=self._settings['unicode_sub_super'],
     )
Пример #14
0
        def str_symbol(name_str):
            def translate(s):
                tmp = s

                parse_dict = {}
                i_sub = 1

                for glyph in GaLatexPrinter.special_alphabet:
                    escaped_glyph = '\\' + glyph
                    if glyph in tmp:
                        parse_sym = '????' + str(i_sub)
                        i_sub += 1
                        # If this glyph is already escaped, avoid escaping again
                        translated_glyph = (
                            escaped_glyph +
                            ' ') if escaped_glyph not in tmp else glyph
                        parse_dict[parse_sym] = translated_glyph
                        tmp = tmp.replace(glyph, parse_sym)

                for parse_sym in parse_dict:
                    tmp = tmp.replace(parse_sym, parse_dict[parse_sym])

                for glyph in GaLatexPrinter.greek_translated:
                    if glyph in tmp:
                        tmp = tmp.replace(
                            glyph, GaLatexPrinter.greek_translated[glyph])

                return tmp

            name, supers, subs = split_super_sub(name_str)

            name = translate(name)

            if style == 'bold':
                name = '\\boldsymbol{' + name + '}'

            supers = list(map(translate, supers))
            subs = list(map(translate, subs))

            # glue all items together:
            if len(supers) > 0:
                name += "^{%s}" % " ".join(supers)
            if len(subs) > 0:
                name += "_{%s}" % " ".join(subs)

            return name
Пример #15
0
def _get_subscript(symbol: sp.Symbol) -> str:
    """Collect subscripts from a `sympy.core.symbol.Symbol`.

    >>> _get_subscript(sp.Symbol("p1"))
    '1'
    >>> _get_subscript(sp.Symbol("p^2_{0,0}"))
    '0,0'
    """
    if isinstance(symbol, sp.Basic):
        text = sp.latex(symbol)
    else:
        text = symbol
    _, _, subscripts = split_super_sub(text)
    stripped_subscripts: Iterable[str] = map(
        lambda s: s.strip("{").strip("}"), subscripts
    )
    return " ".join(stripped_subscripts)
Пример #16
0
        def str_symbol(name_str):
            (name, supers, subs) = split_super_sub(name_str)

            # translate name, supers and subs to tex keywords
            greek = set([
                'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta',
                'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi',
                'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon', 'phi',
                'chi', 'psi', 'omega'
            ])

            greek_translated = {'lamda': 'lambda', 'Lamda': 'Lambda'}

            other = set([
                'aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth', 'hbar',
                'hslash', 'mho'
            ])

            def translate(s):
                tmp = s.lower()
                if tmp in greek or tmp in other:
                    return "\\" + s
                if s in greek_translated:
                    return "\\" + greek_translated[s]
                else:
                    return s

            name = translate(name)

            if supers != []:
                supers = list(map(translate, supers))

            if subs != []:
                subs = list(map(translate, subs))

            # glue all items together:
            if len(supers) > 0:
                name += "^{%s}" % " ".join(supers)
            if len(subs) > 0:
                name += "_{%s}" % " ".join(subs)

            return name
    def _print_VectorSymbol(self, expr, vec_symbol=None):
        # print("_print_VecSymbol", type(expr), expr)

        # this method is used to print:
        # 1. VectorSymbol instances, that uses the vec_symbol provided in the settings.
        # 2. The unit vector symbol (normalized vector), that uses uni_vec_symbol. In this
        #    case, the expression in a string representing the expression given into 
        #    _print_Normalize()
        if expr in self._settings['symbol_names']:
            return self._settings['symbol_names'][expr]
        if hasattr(expr, "name"):
            # this has been adapted from _deal_with_super_sub
            string = expr.name
            result = expr.name
            if not '{' in string and string != r"\nabla":
                name, supers, subs = split_super_sub(string)

                name = translate(name)
                supers = [translate(sup) for sup in supers]
                subs = [translate(sub) for sub in subs]
                if vec_symbol is None:
                    if expr._vec_symbol == "":
                        vec_symbol = self._settings["vec_symbol"]
                    else:
                        vec_symbol = expr._vec_symbol

                result = vec_symbol % name
                # glue all items together:
                if supers:
                    result += "^{%s}" % " ".join(supers)
                if subs:
                    result += "_{%s}" % " ".join(subs)

            if expr._bold:
                result = r"\mathbf{{{}}}".format(result)
            if expr._italic:
                result = r"\mathit{%s}" % result

            return result
        return vec_symbol % expr
Пример #18
0
        def str_symbol(name_str):
            (name, supers, subs) = split_super_sub(name_str)

            # translate name, supers and subs to tex keywords
            greek = set(['alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
                         'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu',
                         'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon',
                         'phi', 'chi', 'psi', 'omega'])

            greek_translated = {'lamda': 'lambda', 'Lamda': 'Lambda'}

            other = set(['aleph', 'beth', 'daleth', 'gimel', 'ell', 'eth',
                        'hbar', 'hslash', 'mho'])

            def translate(s):
                tmp = s.lower()
                if tmp in greek or tmp in other:
                    return "\\" + s
                if s in greek_translated:
                    return "\\" + greek_translated[s]
                else:
                    return s

            name = translate(name)

            if supers != []:
                supers = list(map(translate, supers))

            if subs != []:
                subs = list(map(translate, subs))

            # glue all items together:
            if len(supers) > 0:
                name += "^{%s}" % " ".join(supers)
            if len(subs) > 0:
                name += "_{%s}" % " ".join(subs)

            return name
Пример #19
0
def test_super_sub():
    assert split_super_sub("beta_13_2") == ("beta", [], ["13","2"])
    assert split_super_sub("beta_132_20") == ("beta", [], ["132","20"])
    assert split_super_sub("beta_13") == ("beta", [], ["13"])
    assert split_super_sub("x_a_b") == ("x", [], ["a","b"])
    assert split_super_sub("x_1_2_3") == ("x", [], ["1","2","3"])
    assert split_super_sub("x_a_b1") == ("x", [], ["a","b1"])
    assert split_super_sub("x_a_1") == ("x", [], ["a","1"])
    assert split_super_sub("x_1_a") == ("x", [], ["1","a"])
    assert split_super_sub("x_1^aa") == ("x", ["aa"], ["1"])
    assert split_super_sub("x_1__aa") == ("x", ["aa"], ["1"])
    assert split_super_sub("x_11^a") == ("x", ["a"], ["11"])
    assert split_super_sub("x_11__a") == ("x", ["a"], ["11"])
    assert split_super_sub("x_a_b_c_d") == ("x", [], ["a","b","c","d"])
    assert split_super_sub("x_a_b^c^d") == ("x", ["c","d"], ["a","b"])
    assert split_super_sub("x_a_b__c__d") == ("x", ["c","d"], ["a","b"])
    assert split_super_sub("x_a^b_c^d") == ("x", ["b","d"], ["a","c"])
    assert split_super_sub("x_a__b_c__d") == ("x", ["b","d"], ["a","c"])
    assert split_super_sub("x^a^b_c_d") == ("x", ["a","b"], ["c","d"])
    assert split_super_sub("x__a__b_c_d") == ("x", ["a","b"], ["c","d"])
    assert split_super_sub("x^a^b^c^d") == ("x", ["a","b","c","d"], [])
    assert split_super_sub("x__a__b__c__d") == ("x", ["a","b","c","d"], [])
    assert split_super_sub("alpha_11") == ("alpha", [], ["11"])
    assert split_super_sub("alpha_11_11") == ("alpha", [], ["11","11"])
Пример #20
0
    def _print_Function(self, expr, exp=None):
        from sympy.physics.vector.functions import dynamicsymbols
        func = expr.func.__name__
        t = dynamicsymbols._t

        if hasattr(self, '_print_' + func):
            return getattr(self, '_print_' + func)(expr, exp)
        elif isinstance(type(expr), UndefinedFunction) and (expr.args
                                                            == (t, )):

            name, supers, subs = split_super_sub(func)
            name = translate(name)
            supers = [translate(sup) for sup in supers]
            subs = [translate(sub) for sub in subs]

            if len(supers) != 0:
                supers = r"^{%s}" % "".join(supers)
            else:
                supers = r""

            if len(subs) != 0:
                subs = r"_{%s}" % "".join(subs)
            else:
                subs = r""

            if exp:
                supers += r"^{%s}" % self._print(exp)

            return r"%s" % (name + supers + subs)
        else:
            args = [str(self._print(arg)) for arg in expr.args]
            # How inverse trig functions should be displayed, formats are:
            # abbreviated: asin, full: arcsin, power: sin^-1
            inv_trig_style = self._settings['inv_trig_style']
            # If we are dealing with a power-style inverse trig function
            inv_trig_power_case = False
            # If it is applicable to fold the argument brackets
            can_fold_brackets = self._settings['fold_func_brackets'] and \
                len(args) == 1 and \
                not self._needs_function_brackets(expr.args[0])

            inv_trig_table = ["asin", "acos", "atan", "acot"]

            # If the function is an inverse trig function, handle the style
            if func in inv_trig_table:
                if inv_trig_style == "abbreviated":
                    func = func
                elif inv_trig_style == "full":
                    func = "arc" + func[1:]
                elif inv_trig_style == "power":
                    func = func[1:]
                    inv_trig_power_case = True

                    # Can never fold brackets if we're raised to a power
                    if exp is not None:
                        can_fold_brackets = False

            if inv_trig_power_case:
                name = r"\operatorname{%s}^{-1}" % func
            elif exp is not None:
                name = r"\operatorname{%s}^{%s}" % (func, exp)
            else:
                name = r"\operatorname{%s}" % func

            if can_fold_brackets:
                name += r"%s"
            else:
                name += r"\left(%s\right)"

            if inv_trig_power_case and exp is not None:
                name += r"^{%s}" % exp

            return name % ",".join(args)
Пример #21
0
        def str_symbol(name_str):
            (name, supers, subs) = split_super_sub(name_str)

            # translate name, supers and subs to tex keywords
            greek = set(
                [
                    "alpha",
                    "beta",
                    "gamma",
                    "delta",
                    "epsilon",
                    "zeta",
                    "eta",
                    "theta",
                    "iota",
                    "kappa",
                    "lambda",
                    "mu",
                    "nu",
                    "xi",
                    "omicron",
                    "pi",
                    "rho",
                    "sigma",
                    "tau",
                    "upsilon",
                    "phi",
                    "chi",
                    "psi",
                    "omega",
                ]
            )

            greek_translated = {"lamda": "lambda", "Lamda": "Lambda"}

            other = set(["aleph", "beth", "daleth", "gimel", "ell", "eth", "hbar", "hslash", "mho"])

            def translate(s):
                tmp = s.lower()
                if tmp in greek or tmp in other:
                    return "\\" + s
                if s in greek_translated:
                    return "\\" + greek_translated[s]
                else:
                    return s

            name = translate(name)

            if supers != []:
                supers = list(map(translate, supers))

            if subs != []:
                subs = list(map(translate, subs))

            # glue all items together:
            if len(supers) > 0:
                name += "^{%s}" % " ".join(supers)
            if len(subs) > 0:
                name += "_{%s}" % " ".join(subs)

            return name
Пример #22
0
    def _print_Function(self, expr, exp=None):
        from sympy.physics.vector.functions import dynamicsymbols
        func = expr.func.__name__
        t = dynamicsymbols._t

        if hasattr(self, '_print_' + func):
            return getattr(self, '_print_' + func)(expr, exp)
        elif isinstance(type(expr), UndefinedFunction) and (expr.args == (t,)):

            name, supers, subs = split_super_sub(func)
            name = translate(name)
            supers = [translate(sup) for sup in supers]
            subs = [translate(sub) for sub in subs]

            if len(supers) != 0:
                supers = r"^{%s}" % "".join(supers)
            else:
                supers = r""

            if len(subs) != 0:
                subs = r"_{%s}" % "".join(subs)
            else:
                subs = r""

            if exp:
                supers += r"^{%s}" % self._print(exp)

            return r"%s" % (name + supers + subs)
        else:
            args = [str(self._print(arg)) for arg in expr.args]
            # How inverse trig functions should be displayed, formats are:
            # abbreviated: asin, full: arcsin, power: sin^-1
            inv_trig_style = self._settings['inv_trig_style']
            # If we are dealing with a power-style inverse trig function
            inv_trig_power_case = False
            # If it is applicable to fold the argument brackets
            can_fold_brackets = self._settings['fold_func_brackets'] and \
                len(args) == 1 and \
                not self._needs_function_brackets(expr.args[0])

            inv_trig_table = ["asin", "acos", "atan", "acot"]

            # If the function is an inverse trig function, handle the style
            if func in inv_trig_table:
                if inv_trig_style == "abbreviated":
                    func = func
                elif inv_trig_style == "full":
                    func = "arc" + func[1:]
                elif inv_trig_style == "power":
                    func = func[1:]
                    inv_trig_power_case = True

                    # Can never fold brackets if we're raised to a power
                    if exp is not None:
                        can_fold_brackets = False

            if inv_trig_power_case:
                name = r"\operatorname{%s}^{-1}" % func
            elif exp is not None:
                name = r"\operatorname{%s}^{%s}" % (func, exp)
            else:
                name = r"\operatorname{%s}" % func

            if can_fold_brackets:
                name += r"%s"
            else:
                name += r"\left(%s\right)"

            if inv_trig_power_case and exp is not None:
                name += r"^{%s}" % exp

            return name % ",".join(args)
Пример #23
0
def test_super_sub():
    assert split_super_sub("beta_13_2") == ("beta", [], ["13", "2"])
    assert split_super_sub("beta_132_20") == ("beta", [], ["132", "20"])
    assert split_super_sub("beta_13") == ("beta", [], ["13"])
    assert split_super_sub("x_a_b") == ("x", [], ["a", "b"])
    assert split_super_sub("x_1_2_3") == ("x", [], ["1", "2", "3"])
    assert split_super_sub("x_a_b1") == ("x", [], ["a", "b1"])
    assert split_super_sub("x_a_1") == ("x", [], ["a", "1"])
    assert split_super_sub("x_1_a") == ("x", [], ["1", "a"])
    assert split_super_sub("x_1^aa") == ("x", ["aa"], ["1"])
    assert split_super_sub("x_1__aa") == ("x", ["aa"], ["1"])
    assert split_super_sub("x_11^a") == ("x", ["a"], ["11"])
    assert split_super_sub("x_11__a") == ("x", ["a"], ["11"])
    assert split_super_sub("x_a_b_c_d") == ("x", [], ["a", "b", "c", "d"])
    assert split_super_sub("x_a_b^c^d") == ("x", ["c", "d"], ["a", "b"])
    assert split_super_sub("x_a_b__c__d") == ("x", ["c", "d"], ["a", "b"])
    assert split_super_sub("x_a^b_c^d") == ("x", ["b", "d"], ["a", "c"])
    assert split_super_sub("x_a__b_c__d") == ("x", ["b", "d"], ["a", "c"])
    assert split_super_sub("x^a^b_c_d") == ("x", ["a", "b"], ["c", "d"])
    assert split_super_sub("x__a__b_c_d") == ("x", ["a", "b"], ["c", "d"])
    assert split_super_sub("x^a^b^c^d") == ("x", ["a", "b", "c", "d"], [])
    assert split_super_sub("x__a__b__c__d") == ("x", ["a", "b", "c", "d"], [])
    assert split_super_sub("alpha_11") == ("alpha", [], ["11"])
    assert split_super_sub("alpha_11_11") == ("alpha", [], ["11", "11"])
    assert split_super_sub("w1") == ("w", [], ["1"])
    assert split_super_sub("w𝟙") == ("w", [], ["𝟙"])
    assert split_super_sub("w11") == ("w", [], ["11"])
    assert split_super_sub("w𝟙𝟙") == ("w", [], ["𝟙𝟙"])
    assert split_super_sub("w𝟙2𝟙") == ("w", [], ["𝟙2𝟙"])
    assert split_super_sub("w1^a") == ("w", ["a"], ["1"])
    assert split_super_sub("ω1") == ("ω", [], ["1"])
    assert split_super_sub("ω11") == ("ω", [], ["11"])
    assert split_super_sub("ω1^a") == ("ω", ["a"], ["1"])
    assert split_super_sub("ω𝟙^α") == ("ω", ["α"], ["𝟙"])
    assert split_super_sub("ω𝟙2^3α") == ("ω", ["3α"], ["𝟙2"])
    assert split_super_sub("") == ("", [], [])
Пример #24
0
def test_super_sub():
    assert split_super_sub("beta_13_2") == ("beta", [], ["13", "2"])
    assert split_super_sub("beta_132_20") == ("beta", [], ["132", "20"])
    assert split_super_sub("beta_13") == ("beta", [], ["13"])
    assert split_super_sub("x_a_b") == ("x", [], ["a", "b"])
    assert split_super_sub("x_1_2_3") == ("x", [], ["1", "2", "3"])
    assert split_super_sub("x_a_b1") == ("x", [], ["a", "b1"])
    assert split_super_sub("x_a_1") == ("x", [], ["a", "1"])
    assert split_super_sub("x_1_a") == ("x", [], ["1", "a"])
    assert split_super_sub("x_1^aa") == ("x", ["aa"], ["1"])
    assert split_super_sub("x_1__aa") == ("x", ["aa"], ["1"])
    assert split_super_sub("x_11^a") == ("x", ["a"], ["11"])
    assert split_super_sub("x_11__a") == ("x", ["a"], ["11"])
    assert split_super_sub("x_a_b_c_d") == ("x", [], ["a", "b", "c", "d"])
    assert split_super_sub("x_a_b^c^d") == ("x", ["c", "d"], ["a", "b"])
    assert split_super_sub("x_a_b__c__d") == ("x", ["c", "d"], ["a", "b"])
    assert split_super_sub("x_a^b_c^d") == ("x", ["b", "d"], ["a", "c"])
    assert split_super_sub("x_a__b_c__d") == ("x", ["b", "d"], ["a", "c"])
    assert split_super_sub("x^a^b_c_d") == ("x", ["a", "b"], ["c", "d"])
    assert split_super_sub("x__a__b_c_d") == ("x", ["a", "b"], ["c", "d"])
    assert split_super_sub("x^a^b^c^d") == ("x", ["a", "b", "c", "d"], [])
    assert split_super_sub("x__a__b__c__d") == ("x", ["a", "b", "c", "d"], [])
    assert split_super_sub("alpha_11") == ("alpha", [], ["11"])
    assert split_super_sub("alpha_11_11") == ("alpha", [], ["11", "11"])
Пример #25
0
 def _print_Symbol(self, expr):
    name, sup, sub = split_super_sub(expr.name)
    return '__'.join([name] + sub)
Пример #26
0
 def _print_Symbol(self, expr):
     name, sup, sub = split_super_sub(expr.name)
     return '_'.join((greek_to_latin.get(name, name), *sub))