Ejemplo n.º 1
0
 def __init__(self, settings=None):
     StrPrinter.__init__(self, settings)
     self._init_leading_padding()
     assign_to = self._settings['assign_to']
     if isinstance(assign_to, basestring):
         self._settings['assign_to'] = Symbol(assign_to)
     elif not isinstance(assign_to, (Basic, type(None))):
         raise TypeError("FCodePrinter cannot assign to object of type %s"%
                 type(assign_to))
Ejemplo n.º 2
0
    def __init__(self, settings=None):
        ReprPrinter.__init__(self)
        StrPrinter.__init__(self, settings)
        self.symbols = []
        self.functions = []

        # Create print methods for classes that should use StrPrinter instead
        # of ReprPrinter.
        for name in STRPRINT:
            f_name = "_print_%s"%name
            f = getattr(StrPrinter, f_name)
            setattr(PythonPrinter, f_name, f)
Ejemplo n.º 3
0
    def __init__(self, settings=None):
        ReprPrinter.__init__(self)
        StrPrinter.__init__(self, settings)
        self.symbols = []
        self.functions = []

        # Create print methods for classes that should use StrPrinter instead
        # of ReprPrinter.
        for name in STRPRINT:
            f_name = "_print_%s" % name
            f = getattr(StrPrinter, f_name)
            setattr(PythonPrinter, f_name, f)
Ejemplo n.º 4
0
 def _print_Function(self, expr):
     if expr.func.__name__ == "ceiling":
         return "ceil(%s)" % self.stringify(expr.args, ", ")
     elif expr.func.__name__ == "abs" and not expr.args[0].is_integer:
         return "fabs(%s)" % self.stringify(expr.args, ", ")
     else:
         return StrPrinter._print_Function(self, expr)
Ejemplo n.º 5
0
    def doprint(self, expr):
        """Returns Fortran code for expr (as a string)"""
        # keep a set of expressions that are not strictly translatable to
        # Fortran.
        self.not_fortran = set([])

        lines = []
        if isinstance(expr, Piecewise):
            # support for top-level Piecewise function
            for i, (e, c) in enumerate(expr.args):
                if i == 0:
                    lines.append("      if (%s) then" % self._print(c))
                elif i == len(expr.args)-1 and c == True:
                    lines.append("      else")
                else:
                    lines.append("      else if (%s) then" % self._print(c))
                if self._settings["assign_to"] is None:
                    lines.append("        %s" % self._print(e))
                else:
                    lines.append("        %s = %s" % (self._settings["assign_to"], self._print(e)))
            lines.append("      end if")
            return "\n".join(lines)
        else:
            line = StrPrinter.doprint(self, expr)
            if self._settings["assign_to"] is None:
                return "      %s" % line
            else:
                return "      %s = %s" % (self._settings["assign_to"], line)
Ejemplo n.º 6
0
 def _print_Function(self, expr):
     if expr.func.__name__ == "ceiling":
         return "ceil(%s)" % self.stringify(expr.args, ", ")
     elif expr.func.__name__ == "abs" and not expr.args[0].is_integer:
         return "fabs(%s)" % self.stringify(expr.args, ", ")
     else:
         return StrPrinter._print_Function(self, expr)
Ejemplo n.º 7
0
 def _print_Pow(self, expr):
     PREC = precedence(expr)
     if expr.exp is S.NegativeOne:
         return '1.0/%s' % (self.parenthesize(expr.base, PREC))
     elif expr.exp == 0.5:
         return 'sqrt(%s)' % self._print(expr.base)
     else:
         return StrPrinter._print_Pow(self, expr)
Ejemplo n.º 8
0
 def _print_Pow(self, expr):
     PREC = precedence(expr)
     if expr.exp is S.NegativeOne:
         return '1.0/%s'%(self.parenthesize(expr.base, PREC))
     elif expr.exp == 0.5:
         return 'sqrt(%s)' % self._print(expr.base)
     else:
         return StrPrinter._print_Pow(self, expr)
Ejemplo n.º 9
0
 def _print_Mul(self, expr):
     # purpose: print complex numbers nicely in Fortran.
     if expr.is_imaginary and expr.is_number:
         return "cmplx(0,%s)" % (
             self._print(-I*expr)
         )
     else:
         return StrPrinter._print_Mul(self, expr)
Ejemplo n.º 10
0
    def doprint(self, expr):
        """Returns Fortran code for expr (as a string)"""
        # find all number symbols
        number_symbols = set([])
        for sub in postorder_traversal(expr):
            if isinstance(sub, NumberSymbol):
                number_symbols.add(sub)
        number_symbols = [(str(ns), ns.evalf(self._settings["precision"]))
                          for ns in sorted(number_symbols)]

        # keep a set of expressions that are not strictly translatable to
        # Fortran.
        self._not_fortran = set([])

        lines = []
        if isinstance(expr, Piecewise):
            # support for top-level Piecewise function
            for i, (e, c) in enumerate(expr.args):
                if i == 0:
                    lines.append("      if (%s) then" % self._print(c))
                elif i == len(expr.args) - 1 and c == True:
                    lines.append("      else")
                else:
                    lines.append("      else if (%s) then" % self._print(c))
                if self._settings["assign_to"] is None:
                    lines.append("        %s" % self._print(e))
                else:
                    lines.append("        %s = %s" %
                                 (self._settings["assign_to"], self._print(e)))
            lines.append("      end if")
            text = "\n".join(lines)
        else:
            line = StrPrinter.doprint(self, expr)
            if self._settings["assign_to"] is None:
                text = "      %s" % line
            else:
                text = "      %s = %s" % (self._settings["assign_to"], line)

        # format the output
        if self._settings["human"]:
            lines = []
            if len(self._not_fortran) > 0:
                lines.append("C     Not Fortran 77:")
                for expr in sorted(self._not_fortran):
                    lines.append("C     %s" % expr)
            for name, value in number_symbols:
                lines.append("      parameter (%s = %s)" % (name, value))
            lines.extend(text.split("\n"))
            lines = wrap_fortran(lines)
            result = "\n".join(lines)
        else:
            result = number_symbols, self._not_fortran, text

        del self._not_fortran
        return result
Ejemplo n.º 11
0
    def doprint(self, expr):
        """Returns Fortran code for expr (as a string)"""
        # find all number symbols
        number_symbols = set([])
        for sub in postorder_traversal(expr):
            if isinstance(sub, NumberSymbol):
                number_symbols.add(sub)
        number_symbols = [(str(ns), ns.evalf(self._settings["precision"]))
                          for ns in sorted(number_symbols)]

        # keep a set of expressions that are not strictly translatable to
        # Fortran.
        self._not_fortran = set([])

        lines = []
        if isinstance(expr, Piecewise):
            # support for top-level Piecewise function
            for i, (e, c) in enumerate(expr.args):
                if i == 0:
                    lines.append("      if (%s) then" % self._print(c))
                elif i == len(expr.args)-1 and c == True:
                    lines.append("      else")
                else:
                    lines.append("      else if (%s) then" % self._print(c))
                if self._settings["assign_to"] is None:
                    lines.append("        %s" % self._print(e))
                else:
                    lines.append("        %s = %s" % (self._settings["assign_to"], self._print(e)))
            lines.append("      end if")
            text = "\n".join(lines)
        else:
            line = StrPrinter.doprint(self, expr)
            if self._settings["assign_to"] is None:
                text = "      %s" % line
            else:
                text = "      %s = %s" % (self._settings["assign_to"], line)

        # format the output
        if self._settings["human"]:
            lines = []
            if len(self._not_fortran) > 0:
                lines.append("C     Not Fortran 77:")
                for expr in sorted(self._not_fortran):
                    lines.append("C     %s" % expr)
            for name, value in number_symbols:
                lines.append("      parameter (%s = %s)" % (name, value))
            lines.extend(text.split("\n"))
            lines = wrap_fortran(lines)
            result = "\n".join(lines)
        else:
            result = number_symbols, self._not_fortran, text

        del self._not_fortran
        return result
Ejemplo n.º 12
0
    def _print_Add(self, expr):
        # purpose: print complex numbers nicely in Fortran.
        # collect the purely real and purely imaginary parts:
        pure_real = []
        pure_imaginary = []
        mixed = []
        for arg in expr.args:
            if arg.is_real and arg.is_number:
                pure_real.append(arg)
            elif arg.is_imaginary and arg.is_number:
                pure_imaginary.append(arg)
            else:
                mixed.append(arg)
        if len(pure_imaginary) > 0:
            if len(mixed) > 0:
                PREC = precedence(expr)
                term = Add(*mixed)
                t = self._print(term)
                if t.startswith('-'):
                    sign = "-"
                    t = t[1:]
                else:
                    sign = "+"
                if precedence(term) < PREC:
                    t = "(%s)" % t

                return "cmplx(%s,%s) %s %s" % (
                    self._print(Add(*pure_real)),
                    self._print(-I * Add(*pure_imaginary)),
                    sign,
                    t,
                )
            else:
                return "cmplx(%s,%s)" % (
                    self._print(Add(*pure_real)),
                    self._print(-I * Add(*pure_imaginary)),
                )
        else:
            return StrPrinter._print_Add(self, expr)
Ejemplo n.º 13
0
    def _print_Add(self, expr):
        # purpose: print complex numbers nicely in Fortran.
        # collect the purely real and purely imaginary parts:
        pure_real = []
        pure_imaginary = []
        mixed = []
        for arg in expr.args:
            if arg.is_real and arg.is_number:
                pure_real.append(arg)
            elif arg.is_imaginary and arg.is_number:
                pure_imaginary.append(arg)
            else:
                mixed.append(arg)
        if len(pure_imaginary) > 0:
            if len(mixed) > 0:
                PREC = precedence(expr)
                term = Add(*mixed)
                t = self._print(term)
                if t.startswith('-'):
                    sign = "-"
                    t = t[1:]
                else:
                    sign = "+"
                if precedence(term) < PREC:
                    t = "(%s)" % t

                return "cmplx(%s,%s) %s %s" % (
                    self._print(Add(*pure_real)),
                    self._print(-I*Add(*pure_imaginary)),
                    sign, t,
                )
            else:
                return "cmplx(%s,%s)" % (
                    self._print(Add(*pure_real)),
                    self._print(-I*Add(*pure_imaginary)),
                )
        else:
            return StrPrinter._print_Add(self, expr)
Ejemplo n.º 14
0
 def _print_Function(self, expr):
     func = expr.func.__name__
     if not hasattr(sympy, func) and not func in self.functions:
         self.functions.append(func)
     return StrPrinter._print_Function(self, expr)
Ejemplo n.º 15
0
    def doprint(self, expr):
        """Returns Fortran code for expr (as a string)"""
        # find all number symbols
        number_symbols = set([])
        for sub in postorder_traversal(expr):
            if isinstance(sub, NumberSymbol):
                number_symbols.add(sub)
        number_symbols = [(str(ns), ns.evalf(self._settings["precision"]))
                          for ns in sorted(number_symbols)]

        # keep a set of expressions that are not strictly translatable to
        # Fortran.
        self._not_fortran = set([])


        # Setup loops if expression contain Indexed objects
        openloop, closeloop, local_ints = self._get_loop_opening_ending_ints(expr)

        self._not_fortran |= set(local_ints)

        # the lhs may contain loops that are not in the rhs
        lhs = self._settings['assign_to']
        if lhs:
            open_lhs, close_lhs, lhs_ints = self._get_loop_opening_ending_ints(lhs)
            for n,ind in enumerate(lhs_ints):
                if ind not in self._not_fortran:
                    self._not_fortran.add(ind)
                    openloop.insert(0,open_lhs[n])
                    closeloop.append(close_lhs[n])
            lhs_printed = self._print(lhs)

        lines = []
        if isinstance(expr, Piecewise):
            # support for top-level Piecewise function
            for i, (e, c) in enumerate(expr.args):
                if i == 0:
                    lines.append("if (%s) then" % self._print(c))
                elif i == len(expr.args)-1 and c == True:
                    lines.append("else")
                else:
                    lines.append("else if (%s) then" % self._print(c))
                if self._settings["assign_to"] is None:
                    lines.extend(openloop)
                    lines.append("  %s" % self._print(e))
                    lines.extend(closeloop)
                else:
                    lines.extend(openloop)
                    lines.append("  %s = %s" % (lhs_printed, self._print(e)))
                    lines.extend(closeloop)
            lines.append("end if")
        else:
            lines.extend(openloop)
            line = StrPrinter.doprint(self, expr)
            if self._settings["assign_to"] is None:
                text = "%s" % line
            else:
                text = "%s = %s" % (lhs_printed, line)
            lines.append(text)
            lines.extend(closeloop)

        # format the output
        if self._settings["human"]:
            frontlines = []
            if len(self._not_fortran) > 0:
                frontlines.append("! Not Fortran:")
                for expr in sorted(self._not_fortran, key=self._print):
                    frontlines.append("! %s" % expr)
            for name, value in number_symbols:
                frontlines.append("parameter (%s = %s)" % (name, value))
            frontlines.extend(lines)
            lines = frontlines
            lines = self._pad_leading_columns(lines)
            lines = self._wrap_fortran(lines)
            lines = self.indent_code(lines)
            result = "\n".join(lines)
        else:
            lines = self._pad_leading_columns(lines)
            lines = self._wrap_fortran(lines)
            lines = self.indent_code(lines)
            result = number_symbols, self._not_fortran, "\n".join(lines)

        del self._not_fortran
        return result
Ejemplo n.º 16
0
 def _print_Symbol(self, expr):
     symbol = self._str(expr)
     if symbol not in self.symbols:
         self.symbols.append(symbol)
     return StrPrinter._print_Symbol(self, expr)
Ejemplo n.º 17
0
 def _print_Function(self, expr):
     func = expr.func.__name__
     if not hasattr(sympy, func) and not func in self.functions:
         self.functions.append(func)
     return StrPrinter._print_Function(self, expr)
Ejemplo n.º 18
0
 def _print_Symbol(self, expr):
     symbol = self._str(expr)
     if symbol not in self.symbols:
         self.symbols.append(symbol)
     return StrPrinter._print_Symbol(self, expr)
Ejemplo n.º 19
0
 def _print_Mul(self, expr):
     # purpose: print complex numbers nicely in Fortran.
     if expr.is_imaginary and expr.is_number:
         return "cmplx(0,%s)" % (self._print(-I * expr))
     else:
         return StrPrinter._print_Mul(self, expr)
Ejemplo n.º 20
0
"""Printing subsystem"""

from pretty import *
from latex import latex, print_latex
from mathml import mathml, print_mathml
from python import python, print_python
from ccode import ccode, print_ccode
from gtk import *

from preview import preview, view, pngview, pdfview, dviview

from str import StrPrinter, sstr, sstrrepr
_StrPrinter = StrPrinter()


from repr import srepr

# /cyclic/
from sympy.core import basic
from sympy.matrices import matrices
basic.StrPrinter = _StrPrinter
matrices.StrPrinter = _StrPrinter
del basic, matrices

from tree import print_tree
Ejemplo n.º 21
0
 def _print_not_fortran(self, expr):
     self.not_fortran.add(expr)
     return StrPrinter.emptyPrinter(self, expr)