Skip to content

Update tabular_writer to include option to not sort rows #3578

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions pyomo/common/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def tostr(value, quote_str=False):
}


def tabular_writer(ostream, prefix, data, header, row_generator):
def tabular_writer(ostream, prefix, data, header, row_generator, sort_rows=True):
"""Output data in tabular form

Parameters
Expand All @@ -121,7 +121,8 @@ def tabular_writer(ostream, prefix, data, header, row_generator):
returns either a tuple defining the entries for a single row, or
a generator that returns a sequence of table rows to be output
for the specified `key`

sort_rows: bool
sets if rows should be sorted using robust_sort, default (True)
"""

prefix = tostr(prefix)
Expand Down Expand Up @@ -186,7 +187,11 @@ def tabular_writer(ostream, prefix, data, header, row_generator):

if any(' ' in r[-1] for x in _rows.values() if x is not None for r in x):
_width[-1] = '%s'
for _key in sorted_robust(_rows):
if sort_rows:
_sorted_rows = sorted_robust(_rows)
else:
_sorted_rows = _rows
for _key in _sorted_rows:
_rowSet = _rows[_key]
if not _rowSet:
_rowSet = [[_key] + [None] * (len(_width) - 1)]
Expand Down
19 changes: 19 additions & 0 deletions pyomo/common/tests/test_formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,25 @@ def _data_gen(i, j):
"""
self.assertEqual(ref.strip(), os.getvalue().strip())

def test_multiline_generator_user_sorted(self):
os = StringIO()
data = {"b": 0, "a": 1, "c": 3}

def _data_gen(i, j):
for n in range(j):
yield (n, chr(ord("a") + n) * j)

tabular_writer(os, "", data.items(), ["i", "j"], _data_gen, sort_rows=False)
ref = """
Key : i : j
b : None : None
a : 0 : a
c : 0 : aaa
: 1 : bbb
: 2 : ccc
"""
self.assertEqual(ref.strip(), os.getvalue().strip())

def test_multiline_generator_exception(self):
os = StringIO()
data = {'a': 0, 'b': 1, 'c': 3}
Expand Down