def test_init(self): """Make sure HashVector acts like a dict""" # args and kwargs hv = HashVector([(2, 3), (1, 10)], dog='woof') self.assertTrue(isinstance(hv, dict)) self.assertEqual(hv, {2: 3, 1: 10, 'dog': 'woof'}) # no args self.assertEqual(HashVector(), {}) # creation from dict self.assertEqual(HashVector({'x': 7}), {'x': 7})
def test_init(self): "Test Posynomial construction" x = Variable('x') y = Variable('y') ms = [ Monomial({ 'x': 1, 'y': 2 }, 3.14), 0.5 * Variable('y'), Monomial({ 'x': 3, 'y': 1 }, 6), Monomial(2) ] exps, cs = [], [] for m in ms: cs += m.cs.tolist() exps += m.exps hmap = NomialMap(zip(exps, cs)) hmap.units_of_product(None) p = Posynomial(hmap) # check arithmetic p2 = 3.14 * x * y**2 + y / 2 + x**3 * 6 * y + 2 self.assertEqual(p, p2) self.assertEqual(p, sum(ms)) _ = hash(p2) hmap = NomialMap({ HashVector({ 'm': 1, 'v': 2 }): 0.5, HashVector({ 'm': 1, 'g': 1, 'h': 1 }): 1 }) hmap.units_of_product(None) p = Posynomial(hmap) m, = p.varkeys["m"] g, = p.varkeys["g"] h, = p.varkeys["h"] v, = p.varkeys["v"] self.assertTrue(all(isinstance(x, float) for x in p.cs)) self.assertEqual(len(p.exps), 2) self.assertEqual(set(p.varlocs), set([m, g, h, v])) self.assertEqual(p.varlocs[g], p.varlocs[h]) self.assertNotEqual(p.varlocs[g], p.varlocs[v]) self.assertEqual(len(p.varlocs[m]), 2) self.assertTrue(all(len(p.varlocs[key]) == 1 for key in [g, h, v]))
def test_pow(self): """Test exponentiation""" hv = HashVector(x=4, y=0, z=1) self.assertEqual(hv**0.5, {'x': 2, 'y': 0, 'z': 1}) with self.assertRaises(TypeError): _ = hv**hv with self.assertRaises(TypeError): _ = hv**"a"
def test_mul_add(self): """Test multiplication and addition""" a = HashVector(x=1, y=7) b = HashVector() c = HashVector(x=3, z=4) # multiplication and addition by scalars r = a * 0 self.assertEqual(r, HashVector(x=0, y=0)) self.assertTrue(isinstance(r, HashVector)) r = a - 2 self.assertEqual(r, HashVector(x=-1, y=5)) self.assertTrue(isinstance(r, HashVector)) # multiplication and addition by dicts self.assertEqual(a + b, a) self.assertEqual(a + b + c, HashVector(x=4, y=7, z=4)) self.assertEqual(a * b * c, HashVector()) self.assertEqual(a * {'x': 6, 'k': 4}, HashVector(x=6))
def test_mul_add(self): """Test multiplication and addition""" a = HashVector(x=1, y=7) b = HashVector() c = HashVector(x=3, z=4) # multiplication and addition by scalars r = a * 0 self.assertEqual(r, HashVector(x=0, y=0)) self.assertTrue(isinstance(r, HashVector)) r = a - 2 self.assertEqual(r, HashVector(x=-1, y=5)) self.assertTrue(isinstance(r, HashVector)) with self.assertRaises(TypeError): _ = r + "a" # multiplication and addition by dicts self.assertEqual(a + b, a) self.assertEqual(a + b + c, HashVector(x=4, y=7, z=4))
def test_pow(self): """Test exponentiation""" hv = HashVector(x=4, y=0, z=1) self.assertEqual(hv**0.5, {'x': 2, 'y': 0, 'z': 1})
def test_neg(self): """Test negation""" hv = HashVector(x=7, y=0, z=-1) self.assertEqual(-hv, {'x': -7, 'y': 0, 'z': 1})