<commit_before>"""
Octave/Matlab code printer
"""

from __future__ import print_function, division
from sympy.core import S, C
from sympy.core.compatibility import string_types
from sympy.printing.codeprinter import CodePrinter, Assignment
from sympy.printing.str import StrPrinter
from sympy.printing.precedence import precedence

# dictionary mapping sympy function to (argument_conditions, C_function).
# Used in OctaveCodePrinter._print_Function(self)
# FIXME: almost certainly incomplete, perhaps better to default yet!
known_functions = {
    "sin": "sin",
    "cos": "cos",
    "tan": "tan",
    "asin": "asin",
    "acos": "acos",
    "atan": "atan",
    "atan2": "atan2",
    "sinh": "sinh",
    "cosh": "cosh",
    "tanh": "tanh",
    "asinh": "asinh",
    "acosh": "acosh",
    "atanh": "atanh",
    "log": "log",
    "exp": "exp",
    "erf": "erf",
    "gamma": "gamma",
    "sign": "sign",
    "floor": "floor",
    "Abs": "abs",       # different names after this point
    "ceiling": "ceil",
    "conjugate": "conj",
}
# FIXME: test and/or merge these in
# csc
# sec
# cot
# coth
# acot
# acoth
# factorial
# erfc
# erfinv
# erfcinv
# erfi
# heaviside|Heaviside
# dirac|DiracDelta


class OctaveCodePrinter(CodePrinter):
    """
    A printer to convert expressions to strings of Octave/Matlab code.
    """
    printmethod = "_octave"
    language = "Octave"

    _operators = {
        'and': '&&',
        'or': '||',
        'not': '~',
    }

    # StrPrinter's _print_Pow is fine, except for ** instead of ^
    _exponentsymbol = "^"

    _default_settings = {
        'order': None,
        'full_prec': 'auto',
        'precision': 15,
        'user_functions': {},
        'human': True,
        'contract': False
    }
    # FIXME: contract is for expressing tensors as loops (if True), or
    # just assignment (if False).  Needs tests for tensors, borrow
    # some from C?

    def __init__(self, settings={}):
        CodePrinter.__init__(self, settings)
        self.known_functions = dict(known_functions)
        userfuncs = settings.get('user_functions', {})
        self.known_functions.update(userfuncs)

    def _rate_index_position(self, p):
        return p*5

    def _get_statement(self, codestring):
        return "%s;" % codestring

    def _get_comment(self, text):
        return "% {0}".format(text)

    def _declare_number_const(self, name, value):
        return "{0} = {1};".format(name, value)

    def _format_code(self, lines):
        return self.indent_code(lines)

    def _traverse_matrix_indices(self, mat):
        # Octave uses Fortran order (column-major)
        # FIXME: need tests for matrix traverse stuff
        rows, cols = mat.shape
        return ((i, j) for j in range(cols) for i in range(rows))

    def _get_loop_opening_ending(self, indices):
        open_lines = []
        close_lines = []
        for i in indices:
            # Octave arrays start at 1 and end at dimension
            var, start, stop = map(self._print,
                    [i.label, i.lower + 1, i.upper + 1])
            open_lines.append("for %s = %s:%s" % (var, start, stop))
            close_lines.append("end")
        return open_lines, close_lines

    def _print_Mul(self, expr):
        # print complex numbers nicely in Octave
        if expr.is_number and expr.is_imaginary and \
           expr.as_coeff_Mul()[0].is_integer:
            return "%si" % (
                self._print(-S.ImaginaryUnit*expr)
            )
        else:
            return CodePrinter._print_Mul(self, expr)

    def _print_Pi(self, expr):
        return 'pi'

    def _print_ImaginaryUnit(self, expr):
        return "1i"

    def _print_Exp1(self, expr):
        return "exp(1)"

    def _print_GoldenRatio(self, expr):
        # FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)?
        return "(1+sqrt(5))/2"

    def _print_NumberSymbol(self, expr):
        # FIXME: perhaps this should be based on Assignment?  Like in
        # Piecewise.  This form is better for inline code, but the
        # CodePrinter implementation is nicer for longer programs.
        return "%.18g" % float(expr)

    def _print_Infinity(self, expr):
        return 'inf'

    def _print_NegativeInfinity(self, expr):
        return '-inf'

    def _print_NaN(self, expr):<commit_msg>OctaveCodePrinter: Use ".^" for Pow and "^" for MatPow<commit_after>"""
Octave/Matlab code printer
"""

from __future__ import print_function, division
from sympy.core import S, C
from sympy.core.compatibility import string_types
from sympy.printing.codeprinter import CodePrinter, Assignment
from sympy.printing.str import StrPrinter
from sympy.printing.precedence import precedence

# dictionary mapping sympy function to (argument_conditions, C_function).
# Used in OctaveCodePrinter._print_Function(self)
# FIXME: almost certainly incomplete, perhaps better to default yet!
known_functions = {
    "sin": "sin",
    "cos": "cos",
    "tan": "tan",
    "asin": "asin",
    "acos": "acos",
    "atan": "atan",
    "atan2": "atan2",
    "sinh": "sinh",
    "cosh": "cosh",
    "tanh": "tanh",
    "asinh": "asinh",
    "acosh": "acosh",
    "atanh": "atanh",
    "log": "log",
    "exp": "exp",
    "erf": "erf",
    "gamma": "gamma",
    "sign": "sign",
    "floor": "floor",
    "Abs": "abs",       # different names after this point
    "ceiling": "ceil",
    "conjugate": "conj",
}
# FIXME: test and/or merge these in
# csc
# sec
# cot
# coth
# acot
# acoth
# factorial
# erfc
# erfinv
# erfcinv
# erfi
# heaviside|Heaviside
# dirac|DiracDelta


class OctaveCodePrinter(CodePrinter):
    """
    A printer to convert expressions to strings of Octave/Matlab code.
    """
    printmethod = "_octave"
    language = "Octave"

    _operators = {
        'and': '&&',
        'or': '||',
        'not': '~',
    }

    _default_settings = {
        'order': None,
        'full_prec': 'auto',
        'precision': 15,
        'user_functions': {},
        'human': True,
        'contract': False
    }
    # FIXME: contract is for expressing tensors as loops (if True), or
    # just assignment (if False).  Needs tests for tensors, borrow
    # some from C?

    def __init__(self, settings={}):
        CodePrinter.__init__(self, settings)
        self.known_functions = dict(known_functions)
        userfuncs = settings.get('user_functions', {})
        self.known_functions.update(userfuncs)

    def _rate_index_position(self, p):
        return p*5

    def _get_statement(self, codestring):
        return "%s;" % codestring

    def _get_comment(self, text):
        return "% {0}".format(text)

    def _declare_number_const(self, name, value):
        return "{0} = {1};".format(name, value)

    def _format_code(self, lines):
        return self.indent_code(lines)

    def _traverse_matrix_indices(self, mat):
        # Octave uses Fortran order (column-major)
        # FIXME: need tests for matrix traverse stuff
        rows, cols = mat.shape
        return ((i, j) for j in range(cols) for i in range(rows))

    def _get_loop_opening_ending(self, indices):
        open_lines = []
        close_lines = []
        for i in indices:
            # Octave arrays start at 1 and end at dimension
            var, start, stop = map(self._print,
                    [i.label, i.lower + 1, i.upper + 1])
            open_lines.append("for %s = %s:%s" % (var, start, stop))
            close_lines.append("end")
        return open_lines, close_lines

    def _print_Mul(self, expr):
        # print complex numbers nicely in Octave
        if expr.is_number and expr.is_imaginary and \
           expr.as_coeff_Mul()[0].is_integer:
            return "%si" % (
                self._print(-S.ImaginaryUnit*expr)
            )
        else:
            return CodePrinter._print_Mul(self, expr)

    def _print_Pow(self, expr):
        return super(OctaveCodePrinter, self)._print_Pow(expr, powsymbol='.^')

    def _print_MatPow(self, expr):
        return super(OctaveCodePrinter, self)._print_MatPow(expr, powsymbol='^')

    def _print_Pi(self, expr):
        return 'pi'

    def _print_ImaginaryUnit(self, expr):
        return "1i"

    def _print_Exp1(self, expr):
        return "exp(1)"

    def _print_GoldenRatio(self, expr):
        # FIXME: how to do better, e.g., for octave_code(2*GoldenRatio)?
        return "(1+sqrt(5))/2"

    def _print_NumberSymbol(self, expr):
        # FIXME: perhaps this should be based on Assignment?  Like in
        # Piecewise.  This form is better for inline code, but the
        # CodePrinter implementation is nicer for longer programs.
        return "%.18g" % float(expr)

    def _print_Infinity(self, expr):
        return 'inf'

    def _print_NegativeInfinity(self, expr):
        return '-inf'

    def _print_NaN(self, expr):
{'fraction_non_alphanumeric': 0.1264602472496314, 'fraction_numerical': 0.004763525008506295, 'mean_word_length': 2.62880658436214, 'pattern_counts': {'":': 44, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6854147', 'n_tokens_mistral': 2924, 'n_tokens_neox': 2833, 'n_words': 778}