def test_numerical_precision(self): "not sure what to test here, placeholder for now" c1, c2 = 1/700., 123e8 m1 = Monomial({'x': 2, 'y': 1}, c1) m2 = Monomial({'y': -1, 'z': 3/2.}, c2) self.assertEqual(math.log((m1**4 * m2**3).c), # pylint: disable=no-member 4*math.log(c1) + 3*math.log(c2))
def linearize_two_term_posynomial(self, m, r): """ Approximates a two term posynomial constraint by upper and lower piecewise-linear constraints :param m: the index of the constraint :param r: the number of piecewise-linear sections :return: the deprived of data upper and lower constraints and the common data containing constraints """ if r < 2: raise Exception('The number of piece-wise sections should be two or larger') if len(self.p.exps) > 2: raise Exception('The posynomial is larger than a two term posynomial') if len(self.p.exps) < 2: return [], [], [self.p <= 1] a, b, _, _, eps = LinearizeTwoTermPosynomials.two_term_posynomial_linearization_coeff(r) data_constraints = [] w = Variable('w_%s' % m) no_data_constraints_upper = [w * np.exp(eps) <= 1] no_data_constraints_lower = [w <= 1] first_monomial = Monomial(self.p.exps[0], self.p.cs[0]) second_monomial = Monomial(self.p.exps[1], self.p.cs[1]) data_constraints += [first_monomial <= w] for i in xrange(r - 2): data_constraints += [first_monomial ** a[r - 3 - i] * second_monomial ** a[i] * np.exp(b[i]) <= w] data_constraints += [second_monomial <= w] return no_data_constraints_upper, no_data_constraints_lower, data_constraints
def test_init(self): """Test VectorVariable initialization""" # test 1 n = 3 v = VectorVariable(n, 'v', label='dummy variable') self.assertTrue(isinstance(v, NomialArray)) v_mult = 3 * v for i in range(n): self.assertTrue(isinstance(v[i], PlainVariable)) self.assertTrue(isinstance(v[i], Monomial)) # test that operations on Variable cast to Monomial self.assertTrue(isinstance(v_mult[i], Monomial)) self.assertFalse(isinstance(v_mult[i], PlainVariable)) # test 2 x = VectorVariable(3, 'x', label='dummy variable') x_0 = Monomial('x', idx=(0, ), shape=(3, ), label='dummy variable') x_1 = Monomial('x', idx=(1, ), shape=(3, ), label='dummy variable') x_2 = Monomial('x', idx=(2, ), shape=(3, ), label='dummy variable') x2 = NomialArray([x_0, x_1, x_2]) self.assertEqual(x, x2) # test inspired by issue 137 N = 20 x_arr = np.arange(0, 5., 5. / N) + 1e-6 x = VectorVariable(N, 'x', x_arr, 'm', "Beam Location")
def test_init(self): # pylint:disable=too-many-locals "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) exp1 = Monomial({"m": 1, "v": 2}).exp exp2 = Monomial({"m": 1, "g": 1, "h": 1}).exp hmap = NomialMap({exp1 : 0.5, exp2: 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.vks), set([m, g, h, v]))
def test_constraint_gen(self): "Test creation of Constraints via operator overloading" x = Monomial('x') y = Monomial('y') p = x**2 + 2 * y * x + y**2 self.assertEqual(p <= 1, p) self.assertEqual(p <= x, p / x)
def test_constraint_gen(self): "Test creation of Constraints via operator overloading" x = Monomial('x') y = Monomial('y') p = x**2 + 2*y*x + y**2 self.assertEqual((p <= 1).as_posyslt1(), [p]) self.assertEqual((p <= x).as_posyslt1(), [p/x])
def test_constraint_gen(self): x = VectorVariable(3, 'x', label='dummy variable') x_0 = Monomial('x', idx=(0, ), shape=(3, ), label='dummy variable') x_1 = Monomial('x', idx=(1, ), shape=(3, ), label='dummy variable') x_2 = Monomial('x', idx=(2, ), shape=(3, ), label='dummy variable') v = NomialArray([1, 2, 3]).T p = [x_0, x_1 / 2, x_2 / 3] self.assertEqual((x <= v).as_posyslt1(), p)
def test_init(self): "Test Signomial construction" x = Monomial('x') y = Monomial('y') with SignomialsEnabled(): self.assertEqual(str(1 - x - y**2 - 1), "-x + -y**2") self.assertEqual((1 - x/y**2).latex(), "-\\frac{x}{y^{2}} + 1") self.assertRaises(TypeError, lambda: x-y)
def test_str_with_units(self): "Make sure __str__() works when units are involved" S = Monomial('S', units='m^2') rho = Monomial('rho', units='kg/m^3') x = rho*S xstr = str(x) self.assertEqual(type(xstr), str) self.assertTrue('S' in xstr and 'rho' in xstr)
def test_substition(self): x = VectorVariable(3, 'x', label='dummy variable') c = {x: [1, 2, 3]} self.assertEqual(x.sub(c), [Monomial({}, e) for e in [1, 2, 3]]) p = x**2 self.assertEqual(p.sub(c), [Monomial({}, e) for e in [1, 4, 9]]) d = p.sum() self.assertEqual(d.sub(c), Monomial({}, 14))
def test_integer_division(self): "Make sure division by integer doesn't use Python integer division" x = Monomial('x') y = Monomial('y') p = 4*x + y self.assertEqual(p/3, p/3.) equiv1 = all((p/3).cs == [1./3., 4./3.]) equiv2 = all((p/3).cs == [4./3., 1./3.]) self.assertTrue(equiv1 or equiv2)
def test_simplification(self): "Make sure like monomial terms get automatically combined" x = Monomial('x') y = Monomial('y') p1 = x + y + y + (x+y) + (y+x**2) + 3*x p2 = 4*y + x**2 + 5*x # ps1 = [list(exp.keys())for exp in p1.exps] # ps2 = [list(exp.keys())for exp in p2.exps] # print("%s, %s" % (ps1, ps2)) # python 3 dict reordering self.assertEqual(p1, p2)
def test_array_mult(self): x = VectorVariable(3, 'x', label='dummy variable') x_0 = Monomial('x', idx=(0, ), shape=(3, ), label='dummy variable') x_1 = Monomial('x', idx=(1, ), shape=(3, ), label='dummy variable') x_2 = Monomial('x', idx=(2, ), shape=(3, ), label='dummy variable') p = x_0**2 + x_1**2 + x_2**2 self.assertEqual(x.dot(x), p) m = NomialArray([[x_0**2, x_0 * x_1, x_0 * x_2], [x_0 * x_1, x_1**2, x_1 * x_2], [x_0 * x_2, x_1 * x_2, x_2**2]]) self.assertEqual(x.outer(x), m)
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 Monomial exponentiation" x = Monomial({'x': 1, 'y': -1}, 4) self.assertEqual(x, Monomial({'x': 1, 'y': -1}, 4)) # identity self.assertEqual(x / x, Monomial({}, 1)) # square self.assertEqual(x * x, x**2) # divide y = Monomial({'x': 2, 'y': 3}, 5) self.assertEqual(x / y, x * y**-1) # make sure x unchanged self.assertEqual(x, Monomial({'x': 1, 'y': -1}, 4))
def test_init(self): "Test multiple ways to create a Monomial" m = Monomial({'x': 2, 'y': -1}, 5) m2 = Monomial({'x': 2, 'y': -1}, 5) x, = m.varkeys["x"] y, = m.varkeys["y"] self.assertEqual(m.varlocs, {x: [0], y: [0]}) self.assertEqual(m.exp, {x: 2, y: -1}) self.assertEqual(m.c, 5) self.assertEqual(m, m2) # default c and a m = Variable('x') x, = m.varkeys["x"] self.assertEqual(m.varlocs, {x: [0]}) self.assertEqual(m.exp, {x: 1}) self.assertEqual(m.c, 1) # single (string) var with non-default c m = 0.1 * Variable('tau') tau, = m.varkeys["tau"] self.assertEqual(m.varlocs, {tau: [0]}) self.assertEqual(m.exp, {tau: 1}) # pylint: disable=no-member self.assertEqual(m.c, .1) # pylint: disable=no-member # variable names not compatible with python namespaces crazy_varstr = 'what the !!!/$**?' m = Monomial({'x': 1, crazy_varstr: .5}, 25) crazy_varkey, = m.varkeys[crazy_varstr] self.assertTrue(crazy_varkey in m.exp) # non-positive c raises self.assertRaises(InvalidPosynomial, Monomial, -2) self.assertRaises(InvalidPosynomial, Monomial, -1.) self.assertRaises(InvalidPosynomial, Monomial, 0) self.assertRaises(InvalidPosynomial, Monomial, 0.0) # can create nameless Variables x1 = Variable() x2 = Variable() V = Variable('V') vel = Variable('V') self.assertNotEqual(x1, x2) self.assertEqual(V, vel) # test label kwarg x = Variable('x', label='dummy variable') self.assertEqual(list(x.exp)[0].descr['label'], 'dummy variable') _ = hash(m) _ = hash(x) _ = hash(Monomial(x))
def test_init(self): "Test multiple ways to create a Monomial" m = Monomial({"x": 2, "y": -1}, 5) m2 = Monomial({"x": 2, "y": -1}, 5) x, = m.varkeys["x"] y, = m.varkeys["y"] self.assertEqual(m.exp, {x: 2, y: -1}) self.assertEqual(m.c, 5) self.assertEqual(m, m2) # default c and a v = Variable("x") x, = v.varkeys["x"] self.assertEqual(v.exp, {x: 1}) self.assertEqual(v.c, 1) # single (string) var with non-default c v = 0.1 * Variable("tau") tau, = v.varkeys["tau"] # pylint: disable=no-member self.assertEqual(v.exp, {tau: 1}) # pylint: disable=no-member self.assertEqual(v.c, .1) # pylint: disable=no-member # variable names not compatible with python namespaces crazy_varstr = "what the !!!/$**?" m = Monomial({"x": 1, crazy_varstr: .5}, 25) crazy_varkey, = m.varkeys[crazy_varstr] self.assertTrue(crazy_varkey in m.exp) # non-positive c raises self.assertRaises(InvalidPosynomial, Monomial, -2) self.assertRaises(InvalidPosynomial, Monomial, -1) self.assertRaises(InvalidPosynomial, Monomial, 0) self.assertRaises(InvalidPosynomial, Monomial, 0.0) # can create nameless Variables x1 = Variable() x2 = Variable() V = Variable("V") vel = Variable("V") self.assertNotEqual(x1, x2) self.assertEqual(V, vel) # test label kwarg x = Variable("x", label="dummy variable") self.assertEqual(list(x.exp)[0].descr["label"], "dummy variable") _ = hash(m) _ = hash(x) _ = hash(Monomial(x))
def test_init(self): "Test multiple ways to create a Monomial" m = Monomial({'x': 2, 'y': -1}, 5) m2 = Monomial({'x': 2, 'y': -1}, 5) x, = m.varkeys["x"] y, = m.varkeys["y"] self.assertEqual(m.varlocs, {x: [0], y: [0]}) self.assertEqual(m.exp, {x: 2, y: -1}) self.assertEqual(m.c, 5) self.assertEqual(m, m2) # default c and a m = Monomial('x') x, = m.varkeys["x"] self.assertEqual(m.varlocs, {x: [0]}) self.assertEqual(m.exp, {x: 1}) self.assertEqual(m.c, 1) # single (string) var with non-default c m = Monomial('tau', .1) tau, = m.varkeys["tau"] self.assertEqual(m.varlocs, {tau: [0]}) self.assertEqual(m.exp, {tau: 1}) self.assertEqual(m.c, .1) # variable names not compatible with python namespaces crazy_varstr = 'what the !!!/$**?' m = Monomial({'x': 1, crazy_varstr: .5}, 25) crazy_varkey, = m.varkeys[crazy_varstr] self.assertTrue(crazy_varkey in m.exp) # non-positive c raises self.assertRaises(ValueError, Monomial, 'x', -2) self.assertRaises(ValueError, Monomial, {'x': 2}, -1.) self.assertRaises(ValueError, Monomial, 'x', 0) self.assertRaises(ValueError, Monomial, 'x', 0.0) # can create nameless Monomials x1 = Monomial() x2 = Monomial() V = Monomial('V') vel = Monomial('V') self.assertNotEqual(x1, x2) self.assertEqual(V, vel) # test label kwarg x = Monomial('x', label='dummy variable') self.assertEqual(list(x.exp)[0].descr['label'], 'dummy variable')
def test_posyposy_mult(self): "Test multiplication of Posynomial with Posynomial" x = Monomial('x') y = Monomial('y') p1 = x**2 + 2*y*x + y**2 p2 = (x+y)**2 # ps1 = [list(exp.keys())for exp in p1.exps] # ps2 = [list(exp.keys())for exp in p2.exps] # print("%s, %s" % (ps1, ps2)) # python 3 dict reordering self.assertEqual(p1, p2) p1 = (x+y)*(2*x+y**2) p2 = 2*x**2 + 2*y*x + y**2*x + y**3 # ps1 = [list(exp.keys())for exp in p1.exps] # ps2 = [list(exp.keys())for exp in p2.exps] # print("%s, %s" % (ps1, ps2)) # python 3 dict reordering self.assertEqual(p1, p2)
def test_mul(self): "Test monomial multiplication" x = Monomial({'x': 1, 'y': -1}, 4) # test integer division self.assertEqual(x / 5, Monomial({'x': 1, 'y': -1}, 0.8)) # divide by scalar self.assertEqual(x * 9, Monomial({'x': 1, 'y': -1}, 36)) # divide by Monomial y = x * Variable('z') self.assertEqual(y, Monomial({'x': 1, 'y': -1, 'z': 1}, 4)) # make sure x unchanged self.assertEqual(x, Monomial({'x': 1, 'y': -1}, 4)) # mixed new and old vars z = x * Monomial({'x': -1, 't': 2}, .5) self.assertEqual(z, Monomial({'x': 0, 'y': -1, 't': 2}, 2)) x0 = Variable('x0') self.assertEqual(0.0, 0.0 * x0) x1 = Variable('x1') n_hat = [1, 0] p = n_hat[0] * x0 + n_hat[1] * x1 self.assertEqual(p, x0) if gpkit.units: self.assertNotEqual((x + 1), (x + 1) * gpkit.units("m"))
def no_coefficient_monomials(self): """ separates the monomials in a posynomial into a list of monomials :return: The list of monomials """ monomials = [] for i in xrange(len(self.p.exps)): monomials.append(Monomial(self.p.exps[i], self.p.cs[i])) return monomials
def test_div(self): "Test Monomial division" x = Variable('x') y = Variable('y') z = Variable('z') t = Variable('t') a = 36 * x / y # sanity check self.assertEqual(a, Monomial({'x': 1, 'y': -1}, 36)) # divide by scalar self.assertEqual(a / 9, 4 * x / y) # divide by Monomial b = a / z self.assertEqual(b, 36 * x / y / z) # make sure x unchanged self.assertEqual(a, Monomial({'x': 1, 'y': -1}, 36)) # mixed new and old vars c = a / (0.5 * t**2 / x) self.assertEqual(c, Monomial({'x': 2, 'y': -1, 't': -2}, 72))
def test_div(self): "Test Monomial division" x = Variable("x") y = Variable("y") z = Variable("z") t = Variable("t") a = 36 * x / y # sanity check self.assertEqual(a, Monomial({"x": 1, "y": -1}, 36)) # divide by scalar self.assertEqual(a / 9, 4 * x / y) # divide by Monomial b = a / z self.assertEqual(b, 36 * x / y / z) # make sure x unchanged self.assertEqual(a, Monomial({"x": 1, "y": -1}, 36)) # mixed new and old vars c = a / (0.5 * t**2 / x) self.assertEqual(c, Monomial({"x": 2, "y": -1, "t": -2}, 72))
def test_trivial_gp(self): """ Create and solve a trivial GP: minimize x + 2y subject to xy >= 1 The global optimum is (x, y) = (sqrt(2), 1/sqrt(2)). """ x = Monomial('x') y = Monomial('y') prob = Model(cost=(x + 2 * y), constraints=[x * y >= 1]) sol = prob.solve(solver=self.solver, verbosity=0) self.assertEqual(type(prob.latex()), str) self.assertEqual(type(prob._repr_latex_()), str) self.assertAlmostEqual(sol("x"), math.sqrt(2.), self.ndig) self.assertAlmostEqual(sol("y"), 1 / math.sqrt(2.), self.ndig) self.assertAlmostEqual( sol("x") + 2 * sol("y"), 2 * math.sqrt(2), self.ndig) self.assertAlmostEqual(sol["cost"], 2 * math.sqrt(2), self.ndig)
def test_init(self): "Test Posynomial construction" x = Monomial('x') y = Monomial('y') ms = [Monomial({'x': 1, 'y': 2}, 3.14), Monomial('y', 0.5), Monomial({'x': 3, 'y': 1}, 6), Monomial({}, 2)] exps, cs = [], [] for m in ms: cs += m.cs.tolist() exps += m.exps p = Posynomial(exps, cs) # check arithmetic p2 = 3.14*x*y**2 + y/2 + x**3*6*y + 2 self.assertEqual(p, p2) p = Posynomial(({'m': 1, 'v': 2}, {'m': 1, 'g': 1, 'h': 1}), (0.5, 1)) 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 calculate_value_of_two_term_approximated_posynomial(self, two_term_approximation, index_of_permutation, solution): permutation = two_term_approximation.list_of_permutations[index_of_permutation] number_of_two_terms = int(len(permutation) / 2) num_of_linear_sections = self.robust_solve_properties['numoflinearsections'] slopes = self.robust_solve_properties['slopes'] intercepts = self.robust_solve_properties['intercepts'] values = [] for i in xrange(number_of_two_terms): monomials = [] first_monomial = Monomial(two_term_approximation.p.exps[permutation[2 * i]], two_term_approximation.p.cs[permutation[2 * i]]) second_monomial = Monomial(two_term_approximation.p.exps[permutation[2 * i + 1]], two_term_approximation.p.cs[permutation[2 * i + 1]]) monomials += [first_monomial] for j in xrange(num_of_linear_sections - 2): monomials += [first_monomial ** slopes[num_of_linear_sections - 3 - j] * second_monomial ** slopes[j] * np.exp(intercepts[j])] monomials += [second_monomial] subs_monomials = [] for j in xrange(len(monomials)): # st3 = time() monomials[j] = self.robustify_monomial(monomials[j]) monomials[j] = monomials[j].sub(solution['variables']) # print "subs for a monomial is taking too much time", time()-st3 subs_monomials.append(monomials[j].cs[0]) values.append(max(subs_monomials)) if number_of_two_terms % 2 != 0: the_monomial = Monomial(two_term_approximation.p.exps[permutation[len(permutation) - 1]], two_term_approximation.p.cs[permutation[len(permutation) - 1]]) the_monomial = self.robustify_monomial(the_monomial) # the_monomial = the_monomial.sub(self.substitutions) the_monomial = the_monomial.sub(solution['variables']) values.append(the_monomial.cs[0]) return sum(values)
def test_init(self): "Test Posynomial construction" x = Monomial('x') y = Monomial('y') ms = [ Monomial({ 'x': 1, 'y': 2 }, 3.14), Monomial('y', 0.5), Monomial({ 'x': 3, 'y': 1 }, 6), Monomial({}, 2) ] exps, cs = [], [] for m in ms: cs += m.cs.tolist() exps += m.exps p = Posynomial(exps, cs) # check arithmetic p2 = 3.14 * x * y**2 + y / 2 + x**3 * 6 * y + 2 self.assertEqual(p, p2) p = Posynomial(({'m': 1, 'v': 2}, {'m': 1, 'g': 1, 'h': 1}), (0.5, 1)) 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 'ghv'))
def test_elementwise_mult(self): m = Monomial('m') x = VectorVariable(3, 'x', label='dummy variable') x_0 = Monomial('x', idx=(0, ), shape=(3, ), label='dummy variable') x_1 = Monomial('x', idx=(1, ), shape=(3, ), label='dummy variable') x_2 = Monomial('x', idx=(2, ), shape=(3, ), label='dummy variable') # multiplication with numbers v = NomialArray([2, 2, 3]).T p = NomialArray([2 * x_0, 2 * x_1, 3 * x_2]).T self.assertEqual(x * v, p) # division with numbers p2 = NomialArray([x_0 / 2, x_1 / 2, x_2 / 3]).T self.assertEqual(x / v, p2) # power p3 = NomialArray([x_0**2, x_1**2, x_2**2]).T self.assertEqual(x**2, p3) # multiplication with monomials p = NomialArray([m * x_0, m * x_1, m * x_2]).T self.assertEqual(x * m, p) # division with monomials p2 = NomialArray([x_0 / m, x_1 / m, x_2 / m]).T self.assertEqual(x / m, p2)
def two_term_equivalent_posynomial(p, m, permutation, boyd): """ returns a two term posynomial equivalent to the original large posynomial :param p: the posynomial :param m: the index of the posynomial :param boyd: whether or not a boyd two term approximation is preferred :param permutation: the permutation to be used for two term approximation :return: the no data constraints and the data constraints """ number_of_monomials = len(p.exps) if number_of_monomials <= 2: return [[]], [[p <= 1]] data_constraints, no_data_constraints = [], [] if boyd: z_1 = Variable("z^1_(%s)" % m) data_constraints += [Monomial(p.exps[0], p.cs[0]) + z_1 <= 1] for i in xrange(number_of_monomials - 3): if i > 0: z_1 = Variable("z^%s_(%s)" % (i + 1, m)) z_2 = Variable("z^%s_(%s)" % (i + 2, m)) data_constraints += [Monomial(p.exps[i + 1], p.cs[i + 1])/z_1 + z_2 / z_1 <= 1] z_2 = Variable("z^%s_(%s)" % (number_of_monomials - 2, m)) data_constraints += [ Monomial(p.exps[number_of_monomials - 2], p.cs[number_of_monomials - 2]) / z_2 + Monomial(p.exps[number_of_monomials - 1], p.cs[number_of_monomials - 1]) / z_2 <= 1] return [], data_constraints length_of_permutation = len(permutation) number_of_iterations = int(np.floor(length_of_permutation / 2.0)) zs = [] for j in xrange(number_of_iterations): z = Variable("z^%s_%s" % (j, m)) zs.append(z) data_constraints += [Monomial(p.exps[permutation[2 * j]], p.cs[permutation[2 * j]]) + Monomial(p.exps[permutation[2 * j + 1]], p.cs[permutation[2 * j + 1]]) <= z] if length_of_permutation % 2 == 1: z = Variable("z^%s_%s" % (number_of_iterations, m)) zs.append(z) data_constraints += [Monomial(p.exps[permutation[length_of_permutation - 1]], p.cs[permutation[length_of_permutation - 1]]) <= z] no_data_constraints.append([sum(zs) <= 1]) return no_data_constraints, data_constraints
def test_mul(self): "Test monomial multiplication" x = Monomial({"x": 1, "y": -1}, 4) # test integer division self.assertEqual(x / 5, Monomial({"x": 1, "y": -1}, 0.8)) # divide by scalar self.assertEqual(x * 9, Monomial({"x": 1, "y": -1}, 36)) # divide by Monomial y = x * Variable("z") self.assertEqual(y, Monomial({"x": 1, "y": -1, "z": 1}, 4)) # make sure x unchanged self.assertEqual(x, Monomial({"x": 1, "y": -1}, 4)) # mixed new and old vars z = x * Monomial({"x": -1, "t": 2}, .5) self.assertEqual(z, Monomial({"x": 0, "y": -1, "t": 2}, 2)) x0 = Variable("x0") self.assertEqual(0.0, 0.0 * x0) x1 = Variable("x1") n_hat = [1, 0] p = n_hat[0] * x0 + n_hat[1] * x1 self.assertEqual(p, x0) self.assertNotEqual((x + 1), (x + 1) * gpkit.units("m"))
def test_repr(self): "Simple tests for __repr__, which prints more than str" m = Monomial({'x': 2, 'y': -1}, 5) r = m.__repr__() self.assertEqual(type(r), str) self.assertEqual(Monomial('x').__repr__(), 'gpkit.Monomial(x)')