Skip to content

Commit

Permalink
numpy array formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
idanpa committed Jun 24, 2024
1 parent 54cf8fa commit 98851e3
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
13 changes: 11 additions & 2 deletions calcpy/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
import shutil
import datetime
import IPython
import IPython.lib.pretty
import numpy
import sympy
import sympy.combinatorics
from sympy.printing.pretty.pretty import PrettyPrinter
from sympy.printing.pretty.stringpict import stringPict, prettyForm
from sympy.concrete.expr_with_limits import ExprWithLimits
import IPython.lib.pretty

MAX_SEQ_LENGTH = 100

Expand Down Expand Up @@ -248,10 +249,17 @@ def sympy_pretty_formatter(obj, printer, cycle):
n_col, n_row = shutil.get_terminal_size()
printer.text(sympy.printing.pretty(obj, num_columns=n_col))

def numpy_array_formatter(obj, printer, cycle):
return sympy_expr_formatter(sympy.Matrix(obj), printer, cycle)

def previewer_formatter(obj):
try:
if isinstance(obj, sympy.Expr):
obj_str = IPython.lib.pretty.pretty(evalf(obj))
obj_str = IPython.lib.pretty.pretty(obj)
if not isinstance(obj, (sympy.Integer, sympy.Float)):
evalu_obj = IPython.lib.pretty.pretty(evalf(obj))
if obj_str != evalu_obj:
obj_str += " ≈ " + evalu_obj
elif isinstance(obj, sympy.combinatorics.Cycle):
obj_str = IPython.lib.pretty.pretty(obj)
elif isinstance(obj, (list, tuple)):
Expand Down Expand Up @@ -301,6 +309,7 @@ def init(ip: IPython.InteractiveShell):
formatter.for_type(sympy.core.function.FunctionClass, IPython.lib.pretty._function_pprint)
formatter.for_type(sympy.combinatorics.Permutation, sympy_pretty_formatter)
formatter.for_type(sympy.combinatorics.Cycle, sympy_pretty_formatter)
formatter.for_type(numpy.ndarray, numpy_array_formatter)

# use IPython's float precision
def print_float(self, e):
Expand Down
16 changes: 16 additions & 0 deletions calcpy/tests/output.txt
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,19 @@ e
2 = series(_)

[] = solve(_)
In [1]: np.arange(4)
Out[1]:
[0]
[ ]
[1]
[ ]
[2]
[ ]
[3]
In [1]: np.zeros((2,2))
Out[1]:
[0 0]
[ ]
[0 0]
In [1]: np.array([[alpha, gamma, x_1]])
Out[1]: [alpha gamma x_1]
3 changes: 3 additions & 0 deletions calcpy/tests/test_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ def run_cell(raw_cell):
sleep(1)
run_cell('e**(-x**2)?')
sleep(2)
run_cell('np.arange(4)')
run_cell('np.zeros((2,2))')
run_cell('np.array([[alpha, gamma, x_1]])')

def test_output(ip, capsys):
run_flow(ip)
Expand Down

0 comments on commit 98851e3

Please sign in to comment.