stringpict.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. """Prettyprinter by Jurjen Bos.
  2. (I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay).
  3. All objects have a method that create a "stringPict",
  4. that can be used in the str method for pretty printing.
  5. Updates by Jason Gedge (email <my last name> at cs mun ca)
  6. - terminal_string() method
  7. - minor fixes and changes (mostly to prettyForm)
  8. TODO:
  9. - Allow left/center/right alignment options for above/below and
  10. top/center/bottom alignment options for left/right
  11. """
  12. from .pretty_symbology import hobj, vobj, xsym, xobj, pretty_use_unicode, line_width
  13. from sympy.utilities.exceptions import sympy_deprecation_warning
  14. class stringPict:
  15. """An ASCII picture.
  16. The pictures are represented as a list of equal length strings.
  17. """
  18. #special value for stringPict.below
  19. LINE = 'line'
  20. def __init__(self, s, baseline=0):
  21. """Initialize from string.
  22. Multiline strings are centered.
  23. """
  24. self.s = s
  25. #picture is a string that just can be printed
  26. self.picture = stringPict.equalLengths(s.splitlines())
  27. #baseline is the line number of the "base line"
  28. self.baseline = baseline
  29. self.binding = None
  30. @staticmethod
  31. def equalLengths(lines):
  32. # empty lines
  33. if not lines:
  34. return ['']
  35. width = max(line_width(line) for line in lines)
  36. return [line.center(width) for line in lines]
  37. def height(self):
  38. """The height of the picture in characters."""
  39. return len(self.picture)
  40. def width(self):
  41. """The width of the picture in characters."""
  42. return line_width(self.picture[0])
  43. @staticmethod
  44. def next(*args):
  45. """Put a string of stringPicts next to each other.
  46. Returns string, baseline arguments for stringPict.
  47. """
  48. #convert everything to stringPicts
  49. objects = []
  50. for arg in args:
  51. if isinstance(arg, str):
  52. arg = stringPict(arg)
  53. objects.append(arg)
  54. #make a list of pictures, with equal height and baseline
  55. newBaseline = max(obj.baseline for obj in objects)
  56. newHeightBelowBaseline = max(
  57. obj.height() - obj.baseline
  58. for obj in objects)
  59. newHeight = newBaseline + newHeightBelowBaseline
  60. pictures = []
  61. for obj in objects:
  62. oneEmptyLine = [' '*obj.width()]
  63. basePadding = newBaseline - obj.baseline
  64. totalPadding = newHeight - obj.height()
  65. pictures.append(
  66. oneEmptyLine * basePadding +
  67. obj.picture +
  68. oneEmptyLine * (totalPadding - basePadding))
  69. result = [''.join(lines) for lines in zip(*pictures)]
  70. return '\n'.join(result), newBaseline
  71. def right(self, *args):
  72. r"""Put pictures next to this one.
  73. Returns string, baseline arguments for stringPict.
  74. (Multiline) strings are allowed, and are given a baseline of 0.
  75. Examples
  76. ========
  77. >>> from sympy.printing.pretty.stringpict import stringPict
  78. >>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0])
  79. 1
  80. 10 + -
  81. 2
  82. """
  83. return stringPict.next(self, *args)
  84. def left(self, *args):
  85. """Put pictures (left to right) at left.
  86. Returns string, baseline arguments for stringPict.
  87. """
  88. return stringPict.next(*(args + (self,)))
  89. @staticmethod
  90. def stack(*args):
  91. """Put pictures on top of each other,
  92. from top to bottom.
  93. Returns string, baseline arguments for stringPict.
  94. The baseline is the baseline of the second picture.
  95. Everything is centered.
  96. Baseline is the baseline of the second picture.
  97. Strings are allowed.
  98. The special value stringPict.LINE is a row of '-' extended to the width.
  99. """
  100. #convert everything to stringPicts; keep LINE
  101. objects = []
  102. for arg in args:
  103. if arg is not stringPict.LINE and isinstance(arg, str):
  104. arg = stringPict(arg)
  105. objects.append(arg)
  106. #compute new width
  107. newWidth = max(
  108. obj.width()
  109. for obj in objects
  110. if obj is not stringPict.LINE)
  111. lineObj = stringPict(hobj('-', newWidth))
  112. #replace LINE with proper lines
  113. for i, obj in enumerate(objects):
  114. if obj is stringPict.LINE:
  115. objects[i] = lineObj
  116. #stack the pictures, and center the result
  117. newPicture = []
  118. for obj in objects:
  119. newPicture.extend(obj.picture)
  120. newPicture = [line.center(newWidth) for line in newPicture]
  121. newBaseline = objects[0].height() + objects[1].baseline
  122. return '\n'.join(newPicture), newBaseline
  123. def below(self, *args):
  124. """Put pictures under this picture.
  125. Returns string, baseline arguments for stringPict.
  126. Baseline is baseline of top picture
  127. Examples
  128. ========
  129. >>> from sympy.printing.pretty.stringpict import stringPict
  130. >>> print(stringPict("x+3").below(
  131. ... stringPict.LINE, '3')[0]) #doctest: +NORMALIZE_WHITESPACE
  132. x+3
  133. ---
  134. 3
  135. """
  136. s, baseline = stringPict.stack(self, *args)
  137. return s, self.baseline
  138. def above(self, *args):
  139. """Put pictures above this picture.
  140. Returns string, baseline arguments for stringPict.
  141. Baseline is baseline of bottom picture.
  142. """
  143. string, baseline = stringPict.stack(*(args + (self,)))
  144. baseline = len(string.splitlines()) - self.height() + self.baseline
  145. return string, baseline
  146. def parens(self, left='(', right=')', ifascii_nougly=False):
  147. """Put parentheses around self.
  148. Returns string, baseline arguments for stringPict.
  149. left or right can be None or empty string which means 'no paren from
  150. that side'
  151. """
  152. h = self.height()
  153. b = self.baseline
  154. # XXX this is a hack -- ascii parens are ugly!
  155. if ifascii_nougly and not pretty_use_unicode():
  156. h = 1
  157. b = 0
  158. res = self
  159. if left:
  160. lparen = stringPict(vobj(left, h), baseline=b)
  161. res = stringPict(*lparen.right(self))
  162. if right:
  163. rparen = stringPict(vobj(right, h), baseline=b)
  164. res = stringPict(*res.right(rparen))
  165. return ('\n'.join(res.picture), res.baseline)
  166. def leftslash(self):
  167. """Precede object by a slash of the proper size.
  168. """
  169. # XXX not used anywhere ?
  170. height = max(
  171. self.baseline,
  172. self.height() - 1 - self.baseline)*2 + 1
  173. slash = '\n'.join(
  174. ' '*(height - i - 1) + xobj('/', 1) + ' '*i
  175. for i in range(height)
  176. )
  177. return self.left(stringPict(slash, height//2))
  178. def root(self, n=None):
  179. """Produce a nice root symbol.
  180. Produces ugly results for big n inserts.
  181. """
  182. # XXX not used anywhere
  183. # XXX duplicate of root drawing in pretty.py
  184. #put line over expression
  185. result = self.above('_'*self.width())
  186. #construct right half of root symbol
  187. height = self.height()
  188. slash = '\n'.join(
  189. ' ' * (height - i - 1) + '/' + ' ' * i
  190. for i in range(height)
  191. )
  192. slash = stringPict(slash, height - 1)
  193. #left half of root symbol
  194. if height > 2:
  195. downline = stringPict('\\ \n \\', 1)
  196. else:
  197. downline = stringPict('\\')
  198. #put n on top, as low as possible
  199. if n is not None and n.width() > downline.width():
  200. downline = downline.left(' '*(n.width() - downline.width()))
  201. downline = downline.above(n)
  202. #build root symbol
  203. root = downline.right(slash)
  204. #glue it on at the proper height
  205. #normally, the root symbel is as high as self
  206. #which is one less than result
  207. #this moves the root symbol one down
  208. #if the root became higher, the baseline has to grow too
  209. root.baseline = result.baseline - result.height() + root.height()
  210. return result.left(root)
  211. def render(self, * args, **kwargs):
  212. """Return the string form of self.
  213. Unless the argument line_break is set to False, it will
  214. break the expression in a form that can be printed
  215. on the terminal without being broken up.
  216. """
  217. if kwargs["wrap_line"] is False:
  218. return "\n".join(self.picture)
  219. if kwargs["num_columns"] is not None:
  220. # Read the argument num_columns if it is not None
  221. ncols = kwargs["num_columns"]
  222. else:
  223. # Attempt to get a terminal width
  224. ncols = self.terminal_width()
  225. ncols -= 2
  226. if ncols <= 0:
  227. ncols = 78
  228. # If smaller than the terminal width, no need to correct
  229. if self.width() <= ncols:
  230. return type(self.picture[0])(self)
  231. # for one-line pictures we don't need v-spacers. on the other hand, for
  232. # multiline-pictures, we need v-spacers between blocks, compare:
  233. #
  234. # 2 2 3 | a*c*e + a*c*f + a*d | a*c*e + a*c*f + a*d | 3.14159265358979323
  235. # 6*x *y + 4*x*y + | | *e + a*d*f + b*c*e | 84626433832795
  236. # | *e + a*d*f + b*c*e | + b*c*f + b*d*e + b |
  237. # 3 4 4 | | *d*f |
  238. # 4*y*x + x + y | + b*c*f + b*d*e + b | |
  239. # | | |
  240. # | *d*f
  241. i = 0
  242. svals = []
  243. do_vspacers = (self.height() > 1)
  244. while i < self.width():
  245. svals.extend([ sval[i:i + ncols] for sval in self.picture ])
  246. if do_vspacers:
  247. svals.append("") # a vertical spacer
  248. i += ncols
  249. if svals[-1] == '':
  250. del svals[-1] # Get rid of the last spacer
  251. return "\n".join(svals)
  252. def terminal_width(self):
  253. """Return the terminal width if possible, otherwise return 0.
  254. """
  255. ncols = 0
  256. try:
  257. import curses
  258. import io
  259. try:
  260. curses.setupterm()
  261. ncols = curses.tigetnum('cols')
  262. except AttributeError:
  263. # windows curses doesn't implement setupterm or tigetnum
  264. # code below from
  265. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440694
  266. from ctypes import windll, create_string_buffer
  267. # stdin handle is -10
  268. # stdout handle is -11
  269. # stderr handle is -12
  270. h = windll.kernel32.GetStdHandle(-12)
  271. csbi = create_string_buffer(22)
  272. res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
  273. if res:
  274. import struct
  275. (bufx, bufy, curx, cury, wattr,
  276. left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
  277. ncols = right - left + 1
  278. except curses.error:
  279. pass
  280. except io.UnsupportedOperation:
  281. pass
  282. except (ImportError, TypeError):
  283. pass
  284. return ncols
  285. def __eq__(self, o):
  286. if isinstance(o, str):
  287. return '\n'.join(self.picture) == o
  288. elif isinstance(o, stringPict):
  289. return o.picture == self.picture
  290. return False
  291. def __hash__(self):
  292. return super().__hash__()
  293. def __str__(self):
  294. return '\n'.join(self.picture)
  295. def __repr__(self):
  296. return "stringPict(%r,%d)" % ('\n'.join(self.picture), self.baseline)
  297. def __getitem__(self, index):
  298. return self.picture[index]
  299. def __len__(self):
  300. return len(self.s)
  301. class prettyForm(stringPict):
  302. """
  303. Extension of the stringPict class that knows about basic math applications,
  304. optimizing double minus signs.
  305. "Binding" is interpreted as follows::
  306. ATOM this is an atom: never needs to be parenthesized
  307. FUNC this is a function application: parenthesize if added (?)
  308. DIV this is a division: make wider division if divided
  309. POW this is a power: only parenthesize if exponent
  310. MUL this is a multiplication: parenthesize if powered
  311. ADD this is an addition: parenthesize if multiplied or powered
  312. NEG this is a negative number: optimize if added, parenthesize if
  313. multiplied or powered
  314. OPEN this is an open object: parenthesize if added, multiplied, or
  315. powered (example: Piecewise)
  316. """
  317. ATOM, FUNC, DIV, POW, MUL, ADD, NEG, OPEN = range(8)
  318. def __init__(self, s, baseline=0, binding=0, unicode=None):
  319. """Initialize from stringPict and binding power."""
  320. stringPict.__init__(self, s, baseline)
  321. self.binding = binding
  322. if unicode is not None:
  323. sympy_deprecation_warning(
  324. """
  325. The unicode argument to prettyForm is deprecated. Only the s
  326. argument (the first positional argument) should be passed.
  327. """,
  328. deprecated_since_version="1.7",
  329. active_deprecations_target="deprecated-pretty-printing-functions")
  330. self._unicode = unicode or s
  331. @property
  332. def unicode(self):
  333. sympy_deprecation_warning(
  334. """
  335. The prettyForm.unicode attribute is deprecated. Use the
  336. prettyForm.s attribute instead.
  337. """,
  338. deprecated_since_version="1.7",
  339. active_deprecations_target="deprecated-pretty-printing-functions")
  340. return self._unicode
  341. # Note: code to handle subtraction is in _print_Add
  342. def __add__(self, *others):
  343. """Make a pretty addition.
  344. Addition of negative numbers is simplified.
  345. """
  346. arg = self
  347. if arg.binding > prettyForm.NEG:
  348. arg = stringPict(*arg.parens())
  349. result = [arg]
  350. for arg in others:
  351. #add parentheses for weak binders
  352. if arg.binding > prettyForm.NEG:
  353. arg = stringPict(*arg.parens())
  354. #use existing minus sign if available
  355. if arg.binding != prettyForm.NEG:
  356. result.append(' + ')
  357. result.append(arg)
  358. return prettyForm(binding=prettyForm.ADD, *stringPict.next(*result))
  359. def __truediv__(self, den, slashed=False):
  360. """Make a pretty division; stacked or slashed.
  361. """
  362. if slashed:
  363. raise NotImplementedError("Can't do slashed fraction yet")
  364. num = self
  365. if num.binding == prettyForm.DIV:
  366. num = stringPict(*num.parens())
  367. if den.binding == prettyForm.DIV:
  368. den = stringPict(*den.parens())
  369. if num.binding==prettyForm.NEG:
  370. num = num.right(" ")[0]
  371. return prettyForm(binding=prettyForm.DIV, *stringPict.stack(
  372. num,
  373. stringPict.LINE,
  374. den))
  375. def __mul__(self, *others):
  376. """Make a pretty multiplication.
  377. Parentheses are needed around +, - and neg.
  378. """
  379. quantity = {
  380. 'degree': "\N{DEGREE SIGN}"
  381. }
  382. if len(others) == 0:
  383. return self # We aren't actually multiplying... So nothing to do here.
  384. # add parens on args that need them
  385. arg = self
  386. if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG:
  387. arg = stringPict(*arg.parens())
  388. result = [arg]
  389. for arg in others:
  390. if arg.picture[0] not in quantity.values():
  391. result.append(xsym('*'))
  392. #add parentheses for weak binders
  393. if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG:
  394. arg = stringPict(*arg.parens())
  395. result.append(arg)
  396. len_res = len(result)
  397. for i in range(len_res):
  398. if i < len_res - 1 and result[i] == '-1' and result[i + 1] == xsym('*'):
  399. # substitute -1 by -, like in -1*x -> -x
  400. result.pop(i)
  401. result.pop(i)
  402. result.insert(i, '-')
  403. if result[0][0] == '-':
  404. # if there is a - sign in front of all
  405. # This test was failing to catch a prettyForm.__mul__(prettyForm("-1", 0, 6)) being negative
  406. bin = prettyForm.NEG
  407. if result[0] == '-':
  408. right = result[1]
  409. if right.picture[right.baseline][0] == '-':
  410. result[0] = '- '
  411. else:
  412. bin = prettyForm.MUL
  413. return prettyForm(binding=bin, *stringPict.next(*result))
  414. def __repr__(self):
  415. return "prettyForm(%r,%d,%d)" % (
  416. '\n'.join(self.picture),
  417. self.baseline,
  418. self.binding)
  419. def __pow__(self, b):
  420. """Make a pretty power.
  421. """
  422. a = self
  423. use_inline_func_form = False
  424. if b.binding == prettyForm.POW:
  425. b = stringPict(*b.parens())
  426. if a.binding > prettyForm.FUNC:
  427. a = stringPict(*a.parens())
  428. elif a.binding == prettyForm.FUNC:
  429. # heuristic for when to use inline power
  430. if b.height() > 1:
  431. a = stringPict(*a.parens())
  432. else:
  433. use_inline_func_form = True
  434. if use_inline_func_form:
  435. # 2
  436. # sin + + (x)
  437. b.baseline = a.prettyFunc.baseline + b.height()
  438. func = stringPict(*a.prettyFunc.right(b))
  439. return prettyForm(*func.right(a.prettyArgs))
  440. else:
  441. # 2 <-- top
  442. # (x+y) <-- bot
  443. top = stringPict(*b.left(' '*a.width()))
  444. bot = stringPict(*a.right(' '*b.width()))
  445. return prettyForm(binding=prettyForm.POW, *bot.above(top))
  446. simpleFunctions = ["sin", "cos", "tan"]
  447. @staticmethod
  448. def apply(function, *args):
  449. """Functions of one or more variables.
  450. """
  451. if function in prettyForm.simpleFunctions:
  452. #simple function: use only space if possible
  453. assert len(
  454. args) == 1, "Simple function %s must have 1 argument" % function
  455. arg = args[0].__pretty__()
  456. if arg.binding <= prettyForm.DIV:
  457. #optimization: no parentheses necessary
  458. return prettyForm(binding=prettyForm.FUNC, *arg.left(function + ' '))
  459. argumentList = []
  460. for arg in args:
  461. argumentList.append(',')
  462. argumentList.append(arg.__pretty__())
  463. argumentList = stringPict(*stringPict.next(*argumentList[1:]))
  464. argumentList = stringPict(*argumentList.parens())
  465. return prettyForm(binding=prettyForm.ATOM, *argumentList.left(function))