Example #1
0
    def display(self, prefix="", ostream=None):
        """
        Print component state information

        This duplicates logic in Component.pprint()
        """
        if not self.active:
            return
        if ostream is None:
            ostream = sys.stdout
        tab = "    "
        ostream.write(prefix + self.local_name + " : ")
        ostream.write("Size=" + str(len(self)))

        ostream.write("\n")

        def _line_generator(k, v):
            for _k, _v in sorted(v.vars.items()):
                if _v is None:
                    _val = '-'
                elif not hasattr(_v, 'is_indexed') or not _v.is_indexed():
                    _val = str(value(_v))
                else:
                    _val = "{%s}" % (', '.join('%r: %r' % (x, value(_v[x]))
                                               for x in sorted(_v._data)), )
                yield _k, _val

        tabular_writer(ostream, prefix + tab,
                       ((k, v) for k, v in self._data.items()),
                       ("Name", "Value"), _line_generator)
Example #2
0
    def _pprint_base_impl(self, ostream, verbose, prefix, _name, _doc,
                          _constructed, _attr, _data, _header, _fcn):
        if ostream is None:
            ostream = sys.stdout
        if prefix:
            ostream = StreamIndenter(ostream, prefix)

        # FIXME: HACK for backwards compatability with suppressing the
        # header for the top block
        if not _attr and self.parent_block() is None:
            _name = ''

        # We only indent everything if we printed the header
        if _attr or _name or _doc:
            ostream = StreamIndenter(ostream, self._PPRINT_INDENT)
            # The first line should be a hanging indent (i.e., not indented)
            ostream.newline = False

        if self.is_reference():
            _attr = list(_attr) if _attr else []
            _attr.append(('ReferenceTo', self.referent))

        if _name:
            ostream.write(_name + " : ")
        if _doc:
            ostream.write(_doc + '\n')
        if _attr:
            ostream.write(", ".join("%s=%s" % (k, v) for k, v in _attr))
        if _attr or _name or _doc:
            ostream.write("\n")

        if not _constructed:
            # HACK: for backwards compatability, Abstract blocks will
            # still print their assigned components.  Should we instead
            # always pprint unconstructed components (possibly
            # suppressing the table header if the table is empty)?
            if self.parent_block() is not None:
                ostream.write("Not constructed\n")
                return

        if type(_fcn) is tuple:
            _fcn, _fcn2 = _fcn
        else:
            _fcn2 = None

        if _header is not None:
            if _fcn2 is not None:
                _data_dict = dict(_data)
                _data = _data_dict.items()
            tabular_writer(ostream, '', _data, _header, _fcn)
            if _fcn2 is not None:
                for _key in sorted_robust(_data_dict):
                    _fcn2(ostream, _key, _data_dict[_key])
        elif _fcn is not None:
            _data_dict = dict(_data)
            for _key in sorted_robust(_data_dict):
                _fcn(ostream, _key, _data_dict[_key])
        elif _data is not None:
            ostream.write(_data)
Example #3
0
    def test_no_data(self):
        os = StringIO()
        data = {}
        tabular_writer(os, "", data.items(), ['s', 'val'], lambda k, v: v)
        ref = u"""
Key : s : val
"""
        self.assertEqual(ref.strip(), os.getvalue().strip())
Example #4
0
    def test_no_header(self):
        os = StringIO()
        data = {(2, ): (["a", 1], 1), (1, 3): ({1: 'a', 2: '2'}, '2')}
        tabular_writer(os, "", data.items(), [], lambda k, v: v)
        ref = u"""
{1: 'a', 2: '2'} : 2
        ['a', 1] : 1
"""
        self.assertEqual(ref.strip(), os.getvalue().strip())
Example #5
0
    def test_tuple_list_dict(self):
        os = StringIO()
        data = {(1, ): (["a", 1], 1), ('2', 3): ({1: 'a', 2: '2'}, '2')}
        tabular_writer(os, "", data.items(), ["s", "val"], lambda k, v: v)
        ref = u"""
Key      : s                : val
    (1,) :         ['a', 1] :   1
('2', 3) : {1: 'a', 2: '2'} :   2
"""
        self.assertEqual(ref.strip(), os.getvalue().strip())
Example #6
0
    def test_unicode_table(self):
        # Test that an embedded unicode character does not foul up the
        # table alignment
        os = StringIO()
        data = {1: ("a", 1), (2, 3): ("∧", 2)}
        tabular_writer(os, "", data.items(), ["s", "val"], lambda k, v: v)
        ref = u"""
Key    : s : val
     1 : a :   1
(2, 3) : ∧ :   2
"""
        self.assertEqual(ref.strip(), os.getvalue().strip())
Example #7
0
    def test_data_exception(self):
        os = StringIO()
        data = {'a': 0, 'b': 1, 'c': 3}

        def _data_gen(i, j):
            if i == 'b':
                raise ValueError("invalid")
            return (j, i * (j + 1))

        tabular_writer(os, "", data.items(), ['i', 'j'], _data_gen)
        ref = u"""
Key : i    : j
  a :    0 :    a
  b : None : None
  c :    3 : cccc
"""
        self.assertEqual(ref.strip(), os.getvalue().strip())
Example #8
0
    def test_multiline_generator(self):
        os = StringIO()
        data = {'a': 0, 'b': 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)
        ref = u"""
Key : i    : j
  a : None : None
  b :    0 :    a
  c :    0 :  aaa
    :    1 :  bbb
    :    2 :  ccc
"""
        self.assertEqual(ref.strip(), os.getvalue().strip())
Example #9
0
    def display(self, prefix="", ostream=None):
        """TODO"""
        if not self.active:
            return
        if ostream is None:
            ostream = sys.stdout
        tab = "    "
        ostream.write(prefix + self.local_name + " : ")
        ostream.write("Size=" + str(len(self)))

        ostream.write("\n")
        tabular_writer(
            ostream,
            prefix+tab,
            ((k,v) for k,v in self._data.items()),
            ( "Value", ),
            lambda k, v: \
               ["Undefined" if v.expr is None else v()])
Example #10
0
    def display(self, prefix="", ostream=None):
        """
        Print component state information

        This duplicates logic in Component.pprint()
        """
        if not self.active:
            return
        if ostream is None:
            ostream = sys.stdout
        tab = "    "
        ostream.write(prefix + self.local_name + " : ")
        ostream.write("Size=" + str(len(self)))

        ostream.write("\n")
        tabular_writer(ostream, prefix + tab,
                       ((k, v) for k, v in self._data.items() if v.active),
                       ("Body",),
                       lambda k, v: [v.body(), ])
Example #11
0
    def display(self, prefix="", ostream=None):
        """Provide a verbose display of this object"""
        if not self.active:
            return
        tab = "    "
        if ostream is None:
            ostream = sys.stdout
        ostream.write(prefix+self.local_name+" : ")
        ostream.write(", ".join("%s=%s" % (k,v) for k,v in [
                    ("Size", len(self)),
                    ("Index", self._index_set if self.is_indexed() else None),
                    ("Active", self.active),
                    ] ))

        ostream.write("\n")
        tabular_writer( ostream, prefix+tab,
                        ((k,v) for k,v in self._data.items() if v.active),
                        ( "Active","Value" ),
                        lambda k, v: [ v.active, value(v), ] )
Example #12
0
    def test_multiline_alignment(self):
        os = StringIO()
        data = {'a': 1, 'b': 2, 'c': 3}

        def _data_gen(i, j):
            for n in range(j):
                _str = chr(ord('a') + n) * (j + 1)
                if n % 2:
                    _str = list(_str)
                    _str[1] = ' '
                    _str = ''.join(_str)
                yield (n, _str)

        tabular_writer(os, "", data.items(), ['i', 'j'], _data_gen)
        ref = u"""
Key : i : j
  a : 0 : aa
  b : 0 : aaa
    : 1 : b b
  c : 0 : aaaa
    : 1 : b bb
    : 2 : cccc
"""
        self.assertEqual(ref.strip(), os.getvalue().strip())
Example #13
0
    def report(self,
               index=(0),
               true_state=False,
               dof=False,
               ostream=None,
               prefix=""):
        """
        Default report method for StateBlocks. Returns a Block report populated
        with either the display or state variables defined in the
        StateBlockData class.

        Args:
            index : tuple of Block indices indicating which point in time (and
                    space if applicable) to report state at.
            true_state : whether to report the display variables (False
                    default) or the actual state variables (True)
            dof : whether to show local degrees of freedom in the report
                    (default=False)
            ostream : output stream to write report to
            prefix : string to append to the beginning of all output lines

        Returns:
            Printed output to ostream
        """

        if ostream is None:
            ostream = sys.stdout

        # Get DoF and model stats
        if dof:
            dof_stat = degrees_of_freedom(self[index])
            nv = number_variables(self[index])
            nc = number_activated_constraints(self[index])
            nb = number_activated_blocks(self[index])

        # Create stream table
        if true_state:
            disp_dict = self[index].define_state_vars()
        else:
            disp_dict = self[index].define_display_vars()

        stream_attributes = {}

        for k in disp_dict:
            for i in disp_dict[k]:
                if i is None:
                    stream_attributes[k] = disp_dict[k][i]
                else:
                    stream_attributes[k + " " + i] = disp_dict[k][i]

        # Write output
        max_str_length = 84
        tab = " " * 4
        ostream.write("\n" + "=" * max_str_length + "\n")

        lead_str = f"{prefix}State : {self.name}"
        trail_str = f"Index: {index}"
        mid_str = " " * (max_str_length - len(lead_str) - len(trail_str))
        ostream.write(lead_str + mid_str + trail_str)

        if dof:
            ostream.write("\n" + "=" * max_str_length + "\n")
            ostream.write(f"{prefix}{tab}Local Degrees of Freedom: {dof_stat}")
            ostream.write('\n')
            ostream.write(f"{prefix}{tab}Total Variables: {nv}{tab}"
                          f"Activated Constraints: {nc}{tab}"
                          f"Activated Blocks: {nb}")

        ostream.write("\n" + "-" * max_str_length + "\n")
        ostream.write(f"{prefix}{tab}State Report")

        if any(isinstance(v, _VarData) for k, v in stream_attributes.items()):
            ostream.write("\n" * 2)
            ostream.write(f"{prefix}{tab}Variables: \n\n")
            tabular_writer(
                ostream, prefix + tab,
                ((k, v) for k, v in stream_attributes.items()
                 if isinstance(v, _VarData)), ("Value", "Fixed", "Bounds"),
                lambda k, v: ["{:#.5g}".format(value(v)), v.fixed, v.bounds])

        if any(
                isinstance(v, _ExpressionData)
                for k, v in stream_attributes.items()):
            ostream.write("\n" * 2)
            ostream.write(f"{prefix}{tab}Expressions: \n\n")
            tabular_writer(ostream, prefix + tab,
                           ((k, v) for k, v in stream_attributes.items()
                            if isinstance(v, _ExpressionData)), ("Value", ),
                           lambda k, v: ["{:#.5g}".format(value(v))])

        ostream.write("\n" + "=" * max_str_length + "\n")