Exemple #1
0
    def test_cuid_from_slice_with_call(self):
        m = self._slice_model()

        _slice = m.b.component('b2')[:, 'a'].v2[1, :]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[*,a].v2[1,*]')
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        # This works as find_component is not in the
        # _call_stack of the slice.
        _slice = m.b.find_component('b2')[:, 'a'].v2[1, :]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[*,a].v2[1,*]')
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b[:].component('b2')
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b[*].b2')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b[:].component('b2', 'b1')
        with self.assertRaisesRegex(ValueError, '.*multiple arguments.*'):
            cuid = ComponentUID(_slice)

        # call of something other than component
        _slice = IndexedComponent_slice(m.b[:].fix,
                                        (IndexedComponent_slice.call,
                                         ('fix', ), {}))
        with self.assertRaisesRegex(
                ValueError,
                "Cannot create a CUID from a slice with a call to any "
                r"method other than 'component': got 'fix'\."):
            cuid = ComponentUID(_slice)

        _slice = IndexedComponent_slice(m.b[:].component('v'),
                                        (IndexedComponent_slice.call,
                                         ('fix', ), {}))
        with self.assertRaisesRegex(
                ValueError, "Cannot create a CUID with a __call__ of anything "
                "other than a 'component' attribute"):
            cuid = ComponentUID(_slice)

        _slice = m.b[:].component('b2', kwd=None)
        with self.assertRaisesRegex(ValueError,
                                    '.*call that contains keywords.*'):
            cuid = ComponentUID(_slice)

        _slice = m.b.b2[:, 'a'].component('vn')[:, 'c', 3, :, :]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[*,a].vn[*,c,3,*,*]')
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[1, 'a'].component('vn')[:, 'c', 3, :, :]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[1,a].vn[*,c,3,*,*]')
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[...].component('vn')[:, 'c', 3, :, :]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[**].vn[*,c,3,*,*]')
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[:, 'a'].component('vn')[...]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[*,a].vn[**]')
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)
Exemple #2
0
    def test_cuid_from_slice_1(self):
        """
        These are slices over a single level of the hierarchy.
        """
        m = self._slice_model()

        _slice = m.b[:]
        cuid_str = ComponentUID('b[*]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)

        _slice = m.b.b1[:]
        cuid_str = ComponentUID('b.b1[*]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)

        _slice = m.b.b1[...]
        cuid_str = ComponentUID('b.b1[**]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)

        _slice = m.b.b2[:, 'a']
        cuid_str = ComponentUID('b.b2[*,a]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[...]
        cuid_str = ComponentUID('b.b2[**]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)

        _slice = m.b.b3[1.1, :, 2]
        cuid_str = ComponentUID('b.b3[1.1,*,2]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b3[:, :, 'b']
        cuid_str = ComponentUID('b.b3[*,*,b]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b3[1.1, ...]
        cuid_str = ComponentUID('b.b3[1.1,**]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b3[...]
        cuid_str = ComponentUID('b.b3[**]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))

        _slice = m.b.bn['a', :, :, 'a', 1]
        cuid_str = ComponentUID('b.bn[a,*,*,a,1]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.bn['a', 'c', 3, :, :]
        cuid_str = ComponentUID('b.bn[a,c,3,*,*]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.bn[...]
        cuid_str = ComponentUID('b.bn[**]')
        cuid = ComponentUID(_slice)
        self.assertEqual(cuid, cuid_str)
Exemple #3
0
    def test_cuid_from_slice_2(self):
        """
        These are slices that describe a component
        at a "deeper level" than the original slice.
        """
        m = self._slice_model()

        _slice = m.b[:].b
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b[*].b')
        self.assertEqual(cuid, cuid_str)

        _slice = m.b[:].b1[:].v
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b[*].b1[*].v')
        self.assertEqual(cuid, cuid_str)

        _slice = m.b.b2[2, :].v
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[2,*].v')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[2, :].v1[:]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[2,*].v1[*]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[2, :].v1[1.1]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[2,*].v1[1.1]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertEqual(cuid, cuid_str)
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[2, :].vn[1, ..., :, 'b']
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[2,*].vn[1,**,*,b]')
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[2, :].vn[..., 'b']
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[2,*].vn[**,b]')
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[2, :].vn[..., ...]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[2,*].vn[**,**]')
        self.assertEqual(cuid, cuid_str)
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[2, :].vn[...]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[2,*].vn[**]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b2[...].v2[:, 'a']
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b2[**].v2[*,a]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b3[:, 'a', :].v1
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b3[*,a,*].v1')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b3[:, 'a', :].v2[1, 'a']
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b3[*,a,*].v2[1,a]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b3[:, 'a', :].v2[1, :]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b3[*,a,*].v2[1,*]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.b3[:, 'a', :].vn[1, :, :, 'a', 1]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.b3[*,a,*].vn[1,*,*,a,1]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.bn['a', 'c', 3, :, :].vn[1, :, 3, 'a', :]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.bn[a,c,3,*,*].vn[1,*,3,a,*]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.bn[...].vn[1, :, 3, 'a', :]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.bn[**].vn[1,*,3,a,*]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.bn[...].vn
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.bn[**].vn')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)

        _slice = m.b.bn[...].vn[...]
        cuid = ComponentUID(_slice)
        cuid_str = ComponentUID('b.bn[**].vn[**]')
        self.assertEqual(str(cuid), str(cuid_str))
        self.assertListSameComponents(m, cuid, cuid_str)
Exemple #4
0
    def test_generate_cuid_string_map(self):
        model = Block(concrete=True)
        model.x = Var()
        model.y = Var([1, 2])
        model.V = Var([('a', 'b'), (1, '2'), (3, 4)])
        model.b = Block(concrete=True)
        model.b.z = Var([1, '2'])
        setattr(model.b, '.H', Var(['a', 2]))
        model.B = Block(['a', 2], concrete=True)
        setattr(model.B['a'], '.k', Var())
        model.B[2].b = Block()
        model.B[2].b.x = Var()
        model.add_component('c tuple', Constraint(Any))
        model.component('c tuple')[(1, )] = model.x >= 0

        cuids = (
            ComponentUID.generate_cuid_string_map(model, repr_version=1),
            ComponentUID.generate_cuid_string_map(model),
        )
        self.assertEqual(len(cuids[0]), 29)
        self.assertEqual(len(cuids[1]), 29)
        for obj in [
                model, model.x, model.y, model.y_index, model.y[1], model.y[2],
                model.V, model.V_index, model.V['a', 'b'], model.V[1, '2'],
                model.V[3, 4], model.b, model.b.z, model.b.z_index,
                model.b.z[1], model.b.z['2'],
                getattr(model.b, '.H'),
                getattr(model.b, '.H_index'),
                getattr(model.b, '.H')['a'],
                getattr(model.b,
                        '.H')[2], model.B, model.B_index, model.B['a'],
                getattr(model.B['a'],
                        '.k'), model.B[2], model.B[2].b, model.B[2].b.x,
                model.component('c tuple')[(1, )]
        ]:
            self.assertEqual(ComponentUID(obj).get_repr(1), cuids[0][obj])
            self.assertEqual(repr(ComponentUID(obj)), cuids[1][obj])

        cuids = (
            ComponentUID.generate_cuid_string_map(model,
                                                  descend_into=False,
                                                  repr_version=1),
            ComponentUID.generate_cuid_string_map(model, descend_into=False),
        )
        self.assertEqual(len(cuids[0]), 18)
        self.assertEqual(len(cuids[1]), 18)
        for obj in [
                model, model.x, model.y, model.y_index, model.y[1], model.y[2],
                model.V, model.V_index, model.V['a', 'b'], model.V[1, '2'],
                model.V[3, 4], model.b, model.B, model.B_index, model.B['a'],
                model.B[2],
                model.component('c tuple')[(1, )]
        ]:
            self.assertEqual(ComponentUID(obj).get_repr(1), cuids[0][obj])
            self.assertEqual(repr(ComponentUID(obj)), cuids[1][obj])

        cuids = (
            ComponentUID.generate_cuid_string_map(model,
                                                  ctype=Var,
                                                  repr_version=1),
            ComponentUID.generate_cuid_string_map(model, ctype=Var),
        )
        self.assertEqual(len(cuids[0]), 22)
        self.assertEqual(len(cuids[1]), 22)
        for obj in [
                model, model.x, model.y, model.y[1], model.y[2], model.V,
                model.V['a', 'b'], model.V[1, '2'], model.V[3, 4], model.b,
                model.b.z, model.b.z[1], model.b.z['2'],
                getattr(model.b, '.H'),
                getattr(model.b, '.H')['a'],
                getattr(model.b, '.H')[2], model.B, model.B['a'],
                getattr(model.B['a'],
                        '.k'), model.B[2], model.B[2].b, model.B[2].b.x
        ]:
            self.assertEqual(ComponentUID(obj).get_repr(1), cuids[0][obj])
            self.assertEqual(repr(ComponentUID(obj)), cuids[1][obj])

        cuids = (
            ComponentUID.generate_cuid_string_map(model,
                                                  ctype=Var,
                                                  descend_into=False,
                                                  repr_version=1),
            ComponentUID.generate_cuid_string_map(model,
                                                  ctype=Var,
                                                  descend_into=False),
        )
        self.assertEqual(len(cuids[0]), 9)
        self.assertEqual(len(cuids[1]), 9)
        for obj in [
                model, model.x, model.y, model.y[1], model.y[2], model.V,
                model.V['a', 'b'], model.V[1, '2'], model.V[3, 4]
        ]:
            self.assertEqual(ComponentUID(obj).get_repr(1), cuids[0][obj])
            self.assertEqual(repr(ComponentUID(obj)), cuids[1][obj])
Exemple #5
0
    def test_findComponentOn_nestedTuples(self):
        # Tests for #1069
        m = ConcreteModel()
        m.x = Var()
        m.c = Constraint(Any)
        m.c[0] = m.x >= 0
        m.c[(1, )] = m.x >= 1
        m.c[(2, )] = m.x >= 2
        m.c[2] = m.x >= 3
        self.assertIs(ComponentUID(m.c[0]).find_component_on(m), m.c[0])
        self.assertIs(ComponentUID('c[0]').find_component_on(m), m.c[0])
        self.assertIsNone(ComponentUID('c[(0,)]').find_component_on(m))
        self.assertIs(
            ComponentUID(m.c[(1, )]).find_component_on(m), m.c[(1, )])
        self.assertIs(ComponentUID('c[(1,)]').find_component_on(m), m.c[(1, )])
        self.assertIsNone(ComponentUID('c[1]').find_component_on(m))
        self.assertIs(ComponentUID('c[(2,)]').find_component_on(m), m.c[(2, )])
        self.assertIs(ComponentUID('c[2]').find_component_on(m), m.c[2])
        self.assertEqual(len(m.c), 4)

        self.assertEqual(repr(ComponentUID(m.c[0])), "c[0]")
        self.assertEqual(repr(ComponentUID(m.c[(1, )])), "c[(1,)]")
        self.assertEqual(str(ComponentUID(m.c[0])), "c[0]")
        self.assertEqual(str(ComponentUID(m.c[(1, )])), "c[(1,)]")

        m = ConcreteModel()
        m.x = Var()
        m.c = Constraint([0, 1])
        m.c[0] = m.x >= 0
        m.c[(1, )] = m.x >= 1
        self.assertIs(ComponentUID(m.c[0]).find_component_on(m), m.c[0])
        self.assertIs(ComponentUID(m.c[(0, )]).find_component_on(m), m.c[0])
        self.assertIs(ComponentUID('c[0]').find_component_on(m), m.c[0])
        self.assertIs(ComponentUID('c[(0,)]').find_component_on(m), m.c[0])
        self.assertIs(ComponentUID(m.c[1]).find_component_on(m), m.c[1])
        self.assertIs(ComponentUID(m.c[(1, )]).find_component_on(m), m.c[1])
        self.assertIs(ComponentUID('c[(1,)]').find_component_on(m), m.c[1])
        self.assertIs(ComponentUID('c[1]').find_component_on(m), m.c[1])
        self.assertEqual(len(m.c), 2)

        m = ConcreteModel()
        m.b = Block(Any)
        m.b[0].c = Block(Any)
        m.b[0].c[0].x = Var()
        m.b[(1, )].c = Block(Any)
        m.b[(1, )].c[(1, )].x = Var()
        ref = m.b[0].c[0].x
        self.assertIs(ComponentUID(ref).find_component_on(m), ref)
        ref = 'm.b[0].c[(0,)].x'
        self.assertIsNone(ComponentUID(ref).find_component_on(m))
        ref = m.b[(1, )].c[(1, )].x
        self.assertIs(ComponentUID(ref).find_component_on(m), ref)
        ref = 'm.b[(1,)].c[1].x'
        self.assertIsNone(ComponentUID(ref).find_component_on(m))

        buf = {}
        ref = m.b[0].c[0].x
        self.assertIs(
            ComponentUID(ref, cuid_buffer=buf).find_component_on(m), ref)
        self.assertEqual(len(buf), 3)
        ref = 'm.b[0].c[(0,)].x'
        self.assertIsNone(
            ComponentUID(ref, cuid_buffer=buf).find_component_on(m))
        self.assertEqual(len(buf), 3)
        ref = m.b[(1, )].c[(1, )].x
        self.assertIs(
            ComponentUID(ref, cuid_buffer=buf).find_component_on(m), ref)
        self.assertEqual(len(buf), 4)
        ref = 'm.b[(1,)].c[1].x'
        self.assertIsNone(
            ComponentUID(ref, cuid_buffer=buf).find_component_on(m))
        self.assertEqual(len(buf), 4)
Exemple #6
0
 def test_list_components_dne_2(self):
     cuid = ComponentUID('b:*,*.c:#1.a:*')
     ref = []
     cList = [str(ComponentUID(x)) for x in cuid.list_components(self.m)]
     self.assertEqual(sorted(cList), sorted(ref))
Exemple #7
0
    def test_comparisons(self):
        a = ComponentUID('foo.x[*]')
        b = ComponentUID('baz')

        self.assertFalse(a < b)
        self.assertFalse(a <= b)
        self.assertTrue(a > b)
        self.assertTrue(a >= b)
        self.assertFalse(a == b)
        self.assertTrue(a != b)

        self.assertTrue(b < a)
        self.assertTrue(b <= a)
        self.assertFalse(b > a)
        self.assertFalse(b >= a)
        self.assertFalse(b == a)
        self.assertTrue(b != a)

        self.assertFalse(a < ComponentUID('baz'))
        self.assertFalse(a <= ComponentUID('baz'))
        self.assertTrue(a > ComponentUID('baz'))
        self.assertTrue(a >= ComponentUID('baz'))
        self.assertFalse(a == ComponentUID('baz'))
        self.assertTrue(a != ComponentUID('baz'))

        self.assertTrue(ComponentUID('baz') < a)
        self.assertTrue(ComponentUID('baz') <= a)
        self.assertFalse(ComponentUID('baz') > a)
        self.assertFalse(ComponentUID('baz') >= a)
        self.assertFalse(ComponentUID('baz') == a)
        self.assertTrue(ComponentUID('baz') != a)

        self.assertFalse(b < b)
        self.assertTrue(b <= b)
        self.assertFalse(b > b)
        self.assertTrue(b >= b)
        self.assertTrue(b == b)
        self.assertFalse(b != b)

        self.assertFalse(ComponentUID('baz') < b)
        self.assertTrue(ComponentUID('baz') <= b)
        self.assertFalse(ComponentUID('baz') > b)
        self.assertTrue(ComponentUID('baz') >= b)
        self.assertTrue(ComponentUID('baz') == b)
        self.assertFalse(ComponentUID('baz') != b)
Exemple #8
0
 def test_find_component_exists_1(self):
     ref = self.m.b[1, '2'].c.a
     cuid = ComponentUID(ref)
     self.assertTrue(cuid.find_component_on(self.m) is ref)
Exemple #9
0
 def test_find_wildcard_not_exists(self):
     cuid = ComponentUID('b[*,*].c.x')
     self.assertIsNone(cuid.find_component_on(self.m))
Exemple #10
0
 def test_parseFromRepr1_wildcard_2(self):
     cuid = ComponentUID('b:*,*.c.a:*')
     self.assertEqual(cuid._cids, (('b', (_star, _star)), ('c', tuple()),
                                   ('a', (_star, ))))
Exemple #11
0
    def test_nonIntNumber(self):
        inf = float('inf')
        m = ConcreteModel()
        m.b = Block([inf, 'inf'])

        m.b[inf].x = x = Var()
        ref = r"b[inf].x"

        cuid = ComponentUID(x)
        self.assertEqual(cuid._cids, (('b', (inf, )), ('x', tuple())))

        self.assertTrue(cuid.matches(x))
        self.assertEqual(repr(ComponentUID(x)), ref)
        self.assertEqual(str(ComponentUID(x)), ref)

        cuid = ComponentUID(ref)
        self.assertEqual(cuid._cids, (('b', (inf, )), ('x', tuple())))

        self.assertTrue(cuid.matches(x))
        self.assertEqual(repr(ComponentUID(x)), ref)
        self.assertEqual(str(ComponentUID(x)), ref)

        ref = r"b:#inf.x"
        cuid = ComponentUID(ref)
        self.assertEqual(cuid._cids, (('b', (inf, )), ('x', tuple())))

        self.assertTrue(cuid.matches(x))
        self.assertEqual(ComponentUID(x).get_repr(1), ref)
        self.assertEqual(str(ComponentUID(x)), r"b[inf].x")

        #
        m.b['inf'].x = x = Var()
        ref = r"b['inf'].x"
        #

        cuid = ComponentUID(x)
        self.assertEqual(cuid._cids, (('b', ('inf', )), ('x', tuple())))

        self.assertTrue(cuid.matches(x))
        self.assertEqual(repr(ComponentUID(x)), ref)
        self.assertEqual(str(ComponentUID(x)), ref)

        cuid = ComponentUID(ref)
        self.assertEqual(cuid._cids, (('b', ('inf', )), ('x', tuple())))

        self.assertTrue(cuid.matches(x))
        self.assertEqual(repr(ComponentUID(x)), ref)
        self.assertEqual(str(ComponentUID(x)), ref)

        ref = r"b:$inf.x"
        cuid = ComponentUID(ref)
        self.assertEqual(cuid._cids, (('b', ('inf', )), ('x', tuple())))

        self.assertTrue(cuid.matches(x))
        self.assertEqual(ComponentUID(x).get_repr(1), ref)
        self.assertEqual(str(ComponentUID(x)), r"b['inf'].x")
Exemple #12
0
 def test_parseFromRepr1_typeID(self):
     cuid = ComponentUID('b:#1,$2.c.a:2')
     self.assertEqual(cuid._cids,
                      (('b', (1, '2')), ('c', tuple()), ('a', (2, ))))
Exemple #13
0
 def test_parseFromRepr1_doubleQuote(self):
     cuid = ComponentUID('b:1,\"2\".c.a:2')
     self.assertEqual(cuid._cids,
                      (('b', (1, '2')), ('c', tuple()), ('a', (2, ))))
Exemple #14
0
 def test_parseFromString_wildcard_2(self):
     cuid = ComponentUID('b[*,*].c.a[*]')
     self.assertEqual(cuid._cids, (('b', (_star, _star)), ('c', tuple()),
                                   ('a', (_star, ))))
Exemple #15
0
 def test_matches_ellipsis3(self):
     cuid = ComponentUID('b[**,1,1,3].c')
     self.assertFalse(cuid.matches(self.m.b[1, 1].c))
     self.assertFalse(cuid.matches(self.m.b[1, '2'].c))
Exemple #16
0
 def test_find_implicit_notExists_1(self):
     cuid = ComponentUID('b:1,2.c.a:4')
     self.assertTrue(cuid.find_component_on(self.m) is None)
Exemple #17
0
 def test_matches_ellipsis4(self):
     cuid = ComponentUID('b[**,1,*].c')
     self.assertTrue(cuid.matches(self.m.b[1, 1].c))
     self.assertTrue(cuid.matches(self.m.b[1, '2'].c))
Exemple #18
0
 def test_find_explicit_notExists_2(self):
     cuid = ComponentUID('b:$1,2.c.a:3')
     self.assertTrue(cuid.find_component_on(self.m) is None)
Exemple #19
0
 def test_list_components_wildcard_1(self):
     cuid = ComponentUID('b:**.c.a:3')
     ref = [str(ComponentUID(self.m.b[1, '2'].c.a[3]))]
     cList = [str(ComponentUID(x)) for x in cuid.list_components(self.m)]
     self.assertEqual(sorted(cList), sorted(ref))
Exemple #20
0
 def test_matches_explicit(self):
     cuid = ComponentUID(self.m.b[1, '2'].c.a[3])
     self.assertTrue(cuid.matches(self.m.b[1, '2'].c.a[3]))
     self.assertFalse(cuid.matches(self.m.b[1, '2'].c.a['2']))
Exemple #21
0
 def test_genFromComponent_simple(self):
     cuid = ComponentUID(self.m.a)
     self.assertEqual(cuid._cids, (('a', tuple()), ))
Exemple #22
0
 def test_matches_explicit_2(self):
     cuid = ComponentUID('b:#1,#2.c.a:#3')
     self.assertFalse(cuid.matches(self.m.b[1, '2'].c.a[3]))
     self.assertFalse(cuid.matches(self.m.b[1, '2'].c.a['2']))
Exemple #23
0
 def test_genFromComponent_indexed(self):
     cuid = ComponentUID(self.m.b[1, '2'].c.a)
     self.assertEqual(cuid._cids,
                      (('b', (1, '2')), ('c', tuple()), ('a', ())))
Exemple #24
0
 def test_matches_wildcard_2(self):
     cuid = ComponentUID('b:*,*.c.a:**')
     self.assertTrue(cuid.matches(self.m.b[1, '2'].c.a[3]))
     self.assertTrue(cuid.matches(self.m.b[1, '2'].c.a['2']))
Exemple #25
0
    def test_pickle_index(self):
        m = ConcreteModel()
        m.b = Block(Any)

        idx = "|b'foo'"
        m.b[idx].x = Var()
        cuid = ComponentUID(m.b[idx].x)
        self.assertEqual(str(cuid), 'b["|b\'foo\'"].x')
        self.assertIs(cuid.find_component_on(m), m.b[idx].x)
        tmp = ComponentUID(str(cuid))
        self.assertIsNot(cuid, tmp)
        self.assertEqual(cuid, tmp)
        self.assertIs(tmp.find_component_on(m), m.b[idx].x)
        tmp = pickle.loads(pickle.dumps(cuid))
        self.assertIsNot(cuid, tmp)
        self.assertEqual(cuid, tmp)
        self.assertIs(tmp.find_component_on(m), m.b[idx].x)

        idx = _Foo(1, 'a')
        m.b[idx].x = Var()
        cuid = ComponentUID(m.b[idx].x)
        # Note that the pickle string for namedtuple changes between
        # Python 2, 3, and pypy, so we will just check the non-pickle
        # data part
        self.assertRegex(str(cuid), r"^b\[\|b?(['\"]).*\.\1\]\.x$")

        self.assertIs(cuid.find_component_on(m), m.b[idx].x)
        tmp = ComponentUID(str(cuid))
        self.assertIsNot(cuid, tmp)
        self.assertEqual(cuid, tmp)
        self.assertIs(tmp.find_component_on(m), m.b[idx].x)
        tmp = pickle.loads(pickle.dumps(cuid))
        self.assertIsNot(cuid, tmp)
        self.assertEqual(cuid, tmp)
        self.assertIs(tmp.find_component_on(m), m.b[idx].x)

        idx = datetime(1, 2, 3)
        m.b[idx].x = Var()
        cuid = ComponentUID(m.b[idx].x)
        # Note that the pickle string for namedtuple changes between
        # Python 2, 3, and pypy, so we will just check the non-pickle
        # data part
        self.assertRegex(str(cuid), r"^b\[\|b?(['\"]).*\.\1\]\.x$")
        self.assertIs(cuid.find_component_on(m), m.b[idx].x)
        tmp = ComponentUID(str(cuid))
        self.assertIsNot(cuid, tmp)
        self.assertEqual(cuid, tmp)
        self.assertIs(tmp.find_component_on(m), m.b[idx].x)
        tmp = pickle.loads(pickle.dumps(cuid))
        self.assertIsNot(cuid, tmp)
        self.assertEqual(cuid, tmp)
        self.assertIs(tmp.find_component_on(m), m.b[idx].x)

        self.assertEqual(len(m.b), 3)
Exemple #26
0
 def test_matches_mismatch_name(self):
     cuid = ComponentUID('b:*,*.d')
     self.assertFalse(cuid.matches(self.m.b[1, '2'].c))
     self.assertFalse(cuid.matches(self.m.b[1, '2'].c))
Exemple #27
0
 def test_parseFromString(self):
     cuid = ComponentUID('b[1,2].c.a[2]')
     self.assertEqual(cuid._cids,
                      (('b', (1, 2)), ('c', tuple()), ('a', (2, ))))
Exemple #28
0
 def test_matches_mismatch_3(self):
     cuid = ComponentUID('b:*,*,*.c.a:*')
     self.assertFalse(cuid.matches(self.m.b[1, '2'].c.a[3]))
     self.assertFalse(cuid.matches(self.m.b[1, '2'].c.a['2']))
Exemple #29
0
 def test_parseFromString_doubleQuote(self):
     cuid = ComponentUID('b[1,\"2\"].c.a[2]')
     self.assertEqual(cuid._cids,
                      (('b', (1, '2')), ('c', tuple()), ('a', (2, ))))
Exemple #30
0
def get_dsdp(model,
             theta_names,
             theta,
             var_dic={},
             tee=False,
             solver_options=None):
    """This function calculates gradient vector of the (decision variables, 
    parameters) with respect to the paramerters (theta_names). 

    e.g) min f:  p1*x1+ p2*(x2^2) + p1*p2
         s.t  c1: x1 + x2 = p1
              c2: x2 + x3 = p2
              0 <= x1, x2, x3 <= 10
              p1 = 10
              p2 = 5
    the function retuns dx/dp and dp/dp, and colum orders.
    
    The following terms are used to define the output dimensions:
    Ncon   = number of constraints
    Nvar   = number of variables (Nx + Ntheta)
    Nx     = the numer of decision (primal) variables
    Ntheta = number of uncertain parameters.

    Parameters
    ----------
    model: Pyomo ConcreteModel
        model should includes an objective function
    theta_names: list of strings
        List of Var names
    theta: dict
        Estimated parameters e.g) from parmest
    tee: bool, optional
        Indicates that ef solver output should be teed
    solver_options: dict, optional
        Provides options to the solver (also the name of an attribute)
    var_dic: dictionary
        If any original variable contains "'", need an auxiliary dictionary 
        with keys theta_names without "'", values with "'".
        e.g) var_dic= 
        {'fs.properties.tau[benzene,toluene]': 
        "fs.properties.tau['benzene','toluene']",
        'fs.properties.tau[toluene,benzene]': 
        "fs.properties.tau['toluene','benzene']"}

    Returns
    -------
    dsdp: scipy.sparse.csr.csr_matrix
        Ntheta by Nvar size sparse matrix. A Jacobian matrix of the 
        (decision variables, parameters) with respect to paramerters 
        (=theta_name). number of rows = len(theta_name), 
        number of columns= len(col)
    col: list
        List of variable names
    """
    m = model.clone()
    original_Param = []
    perturbed_Param = []
    m.extra = ConstraintList()
    kk = 0
    if var_dic == {}:
        for i in theta_names:
            var_dic[i] = i
    '''
    for v in theta_names:
        v_tmp = str(kk)
        original_param_object = Param(initialize=theta[v], mutable=True)
        perturbed_param_object = Param(initialize=theta[v])
        m.add_component("original_"+v_tmp, original_param_object)
        m.add_component("perturbed_"+v_tmp, perturbed_param_object)
        m.extra.add(eval('m.'+var_dic[v]) - eval('m.original_'+v_tmp) == 0 )
        original_Param.append(original_param_object)
        perturbed_Param.append(perturbed_param_object)
        kk = kk + 1
    m_kaug_dsdp = sensitivity_calculation('kaug',m,original_Param,
                                          perturbed_Param, tee)

    '''
    for i, name in enumerate(theta_names):
        orig_param = Param(initialize=theta[name], mutable=True)
        ptb_param = Param(initialize=theta[name])
        m.add_component("original_%s" % i, orig_param)
        m.add_component("perturbed_%s" % i, ptb_param)
        cuid = ComponentUID(name)
        var = cuid.find_component_on(m)
        m.extra.add(var - orig_param == 0)
        original_Param.append(orig_param)
        perturbed_Param.append(ptb_param)

    m_kaug_dsdp = sensitivity_calculation('kaug', m, original_Param,
                                          perturbed_Param, tee)
    try:
        with open("./dsdp/col_row.col", "r") as myfile:
            col = myfile.read().splitlines()
        with open("./dsdp/col_row.row", "r") as myfile:
            row = myfile.read().splitlines()
        dsdp = np.loadtxt("./dsdp/dsdp_in_.in")
    except Exception as e:
        print('File not found.')
    dsdp = dsdp.reshape((len(theta_names), int(len(dsdp) / len(theta_names))))
    dsdp = dsdp[:len(theta_names), :len(col)]
    try:
        shutil.rmtree('dsdp', ignore_errors=True)
    except OSError:
        pass
    col = [
        i for i in col
        if SensitivityInterface.get_default_block_name() not in i
    ]
    dsdp_out = np.zeros((len(theta_names), len(col)))
    # e.g) k_aug dsdp returns -dx1/dx1 = -1.0
    for i in range(len(theta_names)):
        for j in range(len(col)):
            if SensitivityInterface.get_default_block_name() not in col[j]:
                dsdp_out[i, j] = -dsdp[i, j]

    return sparse.csr_matrix(dsdp_out), col