File: pretty.py

package info (click to toggle)
python-escript 5.6-10
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 144,304 kB
  • sloc: python: 592,074; cpp: 136,909; ansic: 18,675; javascript: 9,411; xml: 3,384; sh: 738; makefile: 207
file content (130 lines) | stat: -rw-r--r-- 4,267 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

##############################################################################
#
# Copyright (c) 2003-2018 by The University of Queensland
# http://www.uq.edu.au
#
# Primary Business: Queensland, Australia
# Licensed under the Apache License, version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
# Development until 2012 by Earth Systems Science Computational Center (ESSCC)
# Development 2012-2013 by School of Earth Sciences
# Development from 2014 by Centre for Geoscience Computing (GeoComp)
#
##############################################################################

from __future__ import print_function, division

__copyright__="""Copyright (c) 2003-2018 by The University of Queensland
http://www.uq.edu.au
Primary Business: Queensland, Australia"""
__license__="""Licensed under the Apache License, version 2.0
http://www.apache.org/licenses/LICENSE-2.0"""
__url__="https://launchpad.net/escript-finley"

import numpy
import sympy
from sympy.printing.pretty.pretty import PrettyPrinter,prettyForm,pretty_symbol
from .symbol import Symbol

__author__="Cihan Altinay"

class ValueMatrix(object):
    def __init__(self, content):
        self._items=numpy.array(content)
        if self._items.ndim>2:
            raise TypeError("ValueMatrix only supports 1-D and 2-D arrays")
        elif self._items.ndim==1:
            self._items=self._items.reshape((1,)+self._items.shape)
        self.rows,self.cols=self._items.shape

    def __getitem__(self, key):
        return self._items[key]

class EscriptPrettyPrinter(PrettyPrinter):
    """
    """
    def __init__(self, profile=None):
        PrettyPrinter.__init__(self, profile)
        try:
            self.__ppMatrix = self._print_Matrix
        except AttributeError:
            # renamed in 0.7.2
            self.__ppMatrix = self._print_MatrixBase

    def _print_Symbol(self, e):
        # handle escript symbols
        if isinstance(e, Symbol):
            if e.getRank()<=4:
                return self._print(e.__array__())
            return PrettyPrinter._print_Symbol(self,e)

        # e is a sympy Symbol. Remove any brackets from the name in case e is
        # a component
        n,c=Symbol._symComp(e)
        if len(c)==0:
            return PrettyPrinter._print_Symbol(self,e)
        s=sympy.Symbol(n+'_'.join([str(i) for i in c]))
        return PrettyPrinter._print_Symbol(self, s)

    def _print_ndarray(self, e):
        if e.ndim==0:
            return self._print(e.item())
        elif e.ndim==1:
            m=sympy.Matrix(1,e.shape[0],lambda i,j:e[j])
            return self.__ppMatrix(m)
        elif e.ndim==2:
            i,j=e.shape
            m=sympy.Matrix(i,j,lambda i,j:e[i,j])
            return self.__ppMatrix(m)
        else: #ndim==3 or 4:
            arr=numpy.empty(e.shape[2:],dtype=object)
            for idx in numpy.ndindex(e.shape[2:]):
                arr[idx]=Symbol(e[idx])
            m=ValueMatrix(arr)
            return self.__ppMatrix(m)

    def _print_grad_n(self, e):
        s=prettyForm(*self._print(e.args[0]).parens())
        i=pretty_symbol(",_"+str(e.args[1]))
        return prettyForm(*s.right(i))

def pretty(expr, profile=None, **kargs):
    """
    Returns a string containing the prettified form of expr.

    Supported arguments:
        ``expr``
            the expression to print
        ``wrap_line``
            line wrapping enabled/disabled, should be a boolean value
            (default to True)
        ``use_unicode``
            use unicode characters, such as the Greek letter pi instead of
            the string pi. Values should be boolean or None
        ``full_prec``
            use full precision. Default to "auto"
    """
    from sympy.printing.pretty.pretty import pretty_use_unicode
    if profile is not None:
        profile.update(kargs)
    else:
        profile = kargs
    uflag = pretty_use_unicode(kargs.get("use_unicode", None))
    try:
        pp = EscriptPrettyPrinter(profile)
        return pp.doprint(expr)
    finally:
        pretty_use_unicode(uflag)

def pretty_print(expr, use_unicode=None):
    """
    Prints expr in pretty form.

    pprint is just a shortcut for this function
    """
    print(pretty(expr, use_unicode = use_unicode))

pprint = pretty_print