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_vector_sub(self): x = VectorVariable(3, "x") y = VectorVariable(3, "y") ymax = VectorVariable(3, "ymax") with SignomialsEnabled(): # issue1077 links to a case that failed for SPs only m = Model(x.prod(), [x + y >= 1, y <= ymax]) m.substitutions["ymax"] = [0.3, 0.5, 0.8] m.localsolve(verbosity=0)
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_vector(self): x = Variable("x") y = Variable("y") z = VectorVariable(2, "z") p = x*y*z self.assertTrue(all(p.sub({x: 1, "y": 2}) == 2*z)) self.assertTrue(all(p.sub({x: 1, y: 2, "z": [1, 2]}) == z.sub(z, [2, 4]))) x = VectorVariable(3, "x", "m") xs = x[:2].sum() for x_ in ["x", x]: self.assertAlmostEqual(mag(xs.sub(x_, [1, 2, 3]).c), 3.0)
def test_vector_sweep(self): x = Variable("x") y = VectorVariable(2, "y") m = Model(x, [x >= y.prod()]) m.substitutions.update({y: ('sweep', [[2, 3], [5, 7, 11]])}) a = m.solve(verbosity=0)["cost"] b = [10, 14, 22, 15, 21, 33] # below line fails with changing dictionary keys in py3 # self.assertTrue(all(abs(a-b)/(a+b) < 1e-7)) m = Model(x, [x >= y.prod()]) m.substitutions.update({y: ('sweep', [[2, 3], [5, 7], [9, 11], [13, 15]])}) self.assertRaises(ValueError, m.solve)
def test_phantoms(self): x = Variable("x") x_ = Variable("x", 1, models=["test"]) xv = VectorVariable(2, "x", [1, 1], models=["vec"]) m = Model(x, [x >= x_, x_ == xv.prod()]) m.solve(verbosity=0) with self.assertRaises(ValueError): _ = m.substitutions["x"] with self.assertRaises(KeyError): _ = m.substitutions["y"] with self.assertRaises(ValueError): _ = m["x"] self.assertIn(x, m.variables_byname("x")) self.assertIn(x_, m.variables_byname("x"))
def test_sum(self): x = VectorVariable(5, 'x') p = x.sum() self.assertTrue(isinstance(p, Posynomial)) self.assertEqual(p, sum(x)) x = VectorVariable((2, 3), 'x') rowsum = x.sum(axis=1) colsum = x.sum(axis=0) self.assertTrue(isinstance(rowsum, NomialArray)) self.assertTrue(isinstance(colsum, NomialArray)) self.assertEqual(rowsum[0], sum(x[0])) self.assertEqual(colsum[0], sum(x[:, 0])) self.assertEqual(len(rowsum), 2) self.assertEqual(len(colsum), 3)
def test_constraintget(self): x = Variable("x") x_ = Variable("x", models=["_"]) xv = VectorVariable(2, "x") xv_ = VectorVariable(2, "x", models=["_"]) self.assertEqual(Model(x, [x >= 1])["x"], x) with self.assertRaises(ValueError): _ = Model(x, [x >= 1, x_ >= 1])["x"] with self.assertRaises(ValueError): _ = Model(x, [x >= 1, xv >= 1])["x"] self.assertTrue(all(Model(xv.prod(), [xv >= 1])["x"] == xv)) with self.assertRaises(ValueError): _ = Model(xv.prod(), [xv >= 1, xv_ >= 1])["x"] with self.assertRaises(ValueError): _ = Model(xv.prod(), [xv >= 1, x_ >= 1])["x"]
def test_vector_init(self): N = 6 Weight = 50000 xi_dist = 6*Weight/float(N)*( (np.array(range(1, N+1)) - .5/float(N))/float(N) - (np.array(range(1, N+1)) - .5/float(N))**2/float(N)**2) xi = VectorVariable(N, "xi", xi_dist, "N", "Constant Thrust per Bin") P = Variable("P", "N", "Total Power") phys_constraints = [P >= xi.sum()] objective = P eqns = phys_constraints m = Model(objective, eqns) sol = m.solve(verbosity=0) a, b = sol("xi"), xi_dist*gpkit.ureg.N self.assertTrue(all(abs(a-b)/(a+b) < 1e-7))
def test_check_result(self): """issue 361""" N = 5 L = 5. dx = L/(N-1) EI = Variable("EI",10) p = VectorVariable(N, "p") p = p.sub(p, 100*np.ones(N)) V = VectorVariable(N, "V") M = VectorVariable(N, "M") th = VectorVariable(N, "th") w = VectorVariable(N, "w") eps = 1E-6 substitutions = {var: eps for var in [V[-1], M[-1], th[0], w[0]]} objective = w[-1] constraints = [EI*V.left[1:N] >= EI*V[1:N] + 0.5*dx*p.left[1:N] + 0.5*dx*p[1:N], EI*M.left[1:N] >= EI*M[1:N] + 0.5*dx*V.left[1:N] + 0.5*dx*V[1:N], EI*th.right[0:N-1] >= EI*th[0:N-1] + 0.5*dx*M.right[0:N-1] + 0.5*dx*M[0:N-1], EI*w.right[0:N-1] >= EI*w[0:N-1] + 0.5*dx*th.right[0:N-1] + 0.5*dx*th[0:N-1]] m = Model(objective, constraints, substitutions) sol = m.solve(verbosity=0)
def test_quantity_sub(self): if gpkit.units: x = Variable("x", 1, "cm") y = Variable("y", 1) self.assertEqual(x.sub({x: 1*gpkit.units.m}).c.magnitude, 100) # NOTE: uncomment the below if requiring Quantity substitutions # self.assertRaises(ValueError, x.sub, x, 1) self.assertRaises(ValueError, x.sub, {x: 1*gpkit.ureg.N}) self.assertRaises(ValueError, y.sub, {y: 1*gpkit.ureg.N}) v = gpkit.VectorVariable(3, "v", "cm") subbed = v.sub({v: [1, 2, 3]*gpkit.ureg.m}) self.assertEqual([z.c.magnitude for z in subbed], [100, 200, 300]) v = VectorVariable(1, "v", "km") v_min = VectorVariable(1, "v_min", "km") m = Model(v.prod(), [v >= v_min], {v_min: [2*gpkit.units("nmi")]}) cost = m.solve(verbosity=0)["cost"] self.assertAlmostEqual(cost/(3.704*gpkit.ureg("km")), 1.0) m = Model(v.prod(), [v >= v_min], {v_min: np.array([2])*gpkit.units("nmi")}) cost = m.solve(verbosity=0)["cost"] self.assertAlmostEqual(cost/(3.704*gpkit.ureg("km")), 1.0)
def test_constraintget(self): x = Variable("x") x_ = Variable("x", lineage=[("_", 0)]) xv = VectorVariable(2, "x") xv_ = VectorVariable(2, "x", lineage=[("_", 0)]) self.assertEqual(Model(x, [x >= 1])["x"], x) with self.assertRaises(ValueError): _ = Model(x, [x >= 1, x_ >= 1])["x"] with self.assertRaises(ValueError): _ = Model(x, [x >= 1, xv >= 1])["x"] self.assertTrue(all(Model(xv.prod(), [xv >= 1])["x"] == xv)) with self.assertRaises(ValueError): _ = Model(xv.prod(), [xv >= 1, xv_ >= 1])["x"] with self.assertRaises(ValueError): _ = Model(xv.prod(), [xv >= 1, x_ >= 1])["x"]
def test_call_time(self): N = 20 x = VectorVariable(N, 'x', 'm') y = VectorVariable(N, 'y', 'm') z1 = VectorVariable(N, 'z1', 'm') z2 = VectorVariable(N, 'z2', 'm') z3 = VectorVariable(N, 'z3', 'm') z4 = VectorVariable(N, 'z4', 'm') L = Variable('L', 5, 'm') prob = Model(sum(x), [x >= y, y >= z1, z1 >= z2, z2 >= z3, z3 >= z4, z4 >= L]) sol = prob.solve(verbosity=0) t1 = time.time() _ = sol(z1) self.assertLess(time.time() - t1, 0.05)
def test_simple_united_gp(self): R = Variable("R", "nautical_miles") if not R.units: return a0 = Variable("a0", 340.29, "m/s") theta = Variable("\\theta", 0.7598) t = Variable("t", 10, "hr") T_loiter = Variable("T_{loiter}", 1, "hr") T_reserve = Variable("T_{reserve}", 45, "min") M = VectorVariable(2, "M") prob = Model(1 / R, [ t >= sum(R / a0 / M / theta**0.5) + T_loiter + T_reserve, M <= 0.76 ]) sol = prob.solve(solver=self.solver, verbosity=0) almostequal = self.assertAlmostEqual almostequal(0.000553226 / R.units / sol["cost"], 1, self.ndig) almostequal(340.29 * a0.units / sol["constants"]["a0"], 1, self.ndig) almostequal(340.29 * a0.units / sol["variables"]["a0"], 1, self.ndig) almostequal(1807.58 * R.units / sol["freevariables"]["R"], 1, self.ndig)
def test_bad_elements(self): x = Variable("x") with self.assertRaises(ValueError): _ = Model(x, [x == "A"]) with self.assertRaises(ValueError): _ = Model(x, [x >= 1, x == "A"]) with self.assertRaises(ValueError): _ = Model(x, [ x >= 1, x == "A", x >= 1, ]) with self.assertRaises(ValueError): _ = Model(x, [x == "A", x >= 1]) v = VectorVariable(2, "v") with self.assertRaises(ValueError): _ = Model(x, [v == "A"]) with self.assertRaises(ValueError): _ = Model(x, [v <= ["A", "B"]]) with self.assertRaises(ValueError): _ = Model(x, [v >= ["A", "B"]])
def setup(self, N): edgeCost = VectorVariable([N, N], 'edgeCost') edgeMaxFlow = VectorVariable([N, N], 'edgeMaxFlow') slackCost = Variable('slackCost', 1000) connect = VectorVariable([N, N], 'connectivity') flow = VectorVariable([N, N], 'flow') source = VectorVariable(N, 'source') sink = VectorVariable(N, 'sink') slack_one = VectorVariable(N, 'slackOne') slack_two = VectorVariable(N, 'slackTwo') constraints = [] with SignomialsEnabled(): for i in range(0, N): constraints.extend([ Tight([ sink[i] + sum(flow[i, :]) <= slack_one[i] * (source[i] + sum(flow[:, i])) ]), Tight([slack_one[i] >= 1]), Tight([ source[i] + sum(flow[:, i]) <= slack_two[i] * (sink[i] + sum(flow[i, :])) ]), Tight([slack_two[i] >= 1]), ]) for j in range(0, N): constraints += [ flow[i, j] <= connect[i, j] * edgeMaxFlow[i, j], connect[i, j] <= 1., flow[i, j] >= 1e-20 ] for i in range(0, N): for j in range(i + 1, N): constraints.extend( [connect[i, j] * connect[j, i] <= 1e-20]) return constraints
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 test_bad_elements(self): x = Variable("x") with self.assertRaises(ValueError): _ = Model(x, [x == "A"]) with self.assertRaises(ValueError): _ = Model(x, [x >= 1, x == "A"]) with self.assertRaises(ValueError): _ = Model(x, [ x >= 1, x == "A", x >= 1, ]) with self.assertRaises(ValueError): _ = Model(x, [x == "A", x >= 1]) v = VectorVariable(2, "v") with self.assertRaises(ValueError): _ = Model(x, [v == "A"]) err = TypeError if sys.version_info >= (3, 0) else ValueError with self.assertRaises(err): _ = Model(x, [v <= ["A", "B"]]) with self.assertRaises(err): _ = Model(x, [v >= ["A", "B"]])
def test_shape(self): x = VectorVariable((2, 3), 'x') self.assertEqual(x.shape, (2, 3)) self.assertIsInstance(x.str_without(), str) self.assertIsInstance(x.latex(), str)
def setup(self, N, topology_list=None): H = VectorVariable(N, "H", "m", "Head") H_min = VectorVariable(N, "H_{min}", "m", "Minimal Head Required") H_s = Variable("H_{s}", "m", "Head Source") source = VectorVariable(N, "Sr", "m^3/s", "Source") sink = VectorVariable(N, "Sk", "m^3/s", "Sink") rough = VectorVariable([N, N], "\\epsilon", "m", "Pipe Roughness") relRough = VectorVariable([N, N], "\\epsilon/D", "-", "Relative Pipe Roughness") pipeCost = VectorVariable([N, N], "C_f", "s/m^3", "Pipe Flow Cost") L = VectorVariable([N, N], "L", "m", "Pipe Length") D = VectorVariable([N, N], "D", "m", "Pipe Diameter") maxFlow = VectorVariable([N, N], "F_{max}", "m^3/s", 'Maximum Flow Rate') connect = VectorVariable([N, N], "x", "-", "connectivity") # Integer Variable flow = VectorVariable([N, N], "q", "m^3/s", "Flow Rate") V = VectorVariable([N, N], "v_f", "m/s", "Flow Velocity") H_loss = VectorVariable([N, N], "H_L", "m", "Head Loss") Re = VectorVariable([N, N], "Re", "-", "Reynold's Number") f = VectorVariable([N, N], "f", "-", "Friction Factor") slack_1 = VectorVariable(N, "S_1", "-", "First Slack") slack_2 = VectorVariable(N, "S_2", "-", "Second Slack") slack_h = VectorVariable([N, N], "S_h", "-", "Head Slack") udr = Variable("Udr", "-", "Undirected Topology") slackCost = Variable("C_s", "-", "Slack Cost") totalCost = Variable("C", "-", "Total Cost") D_max = Variable("D_{max}", "m", "Maximum Diameter") D_min = Variable("D_{min}", "m", "Minimum Diameter") rho = Variable("\\rho", "kg/m^3", "Density") mu = Variable("\\mu", "kg/m/s", "Viscosity") g = Variable("g", "m/s^2", "Gravity") constraints = [] # Allowing for solution of known topologies as well if topology_list: for i in range(N): for j in range(N): if [i, j] in topology_list: constraints += [connect[i, j] == 1] else: constraints += [connect[i, j] == 1e-20] with SignomialsEnabled(): for i in range(0, N): # conservation of mass constraints constraints.extend([ Tight([ sink[i] + sum(flow[i, :]) <= slack_1[i] * (source[i] + sum(flow[:, i])) ]), Tight([ source[i] + sum(flow[:, i]) <= slack_2[i] * (sink[i] + sum(flow[i, :])) ]), Tight([slack_2[i] >= 1]), Tight([slack_1[i] >= 1]), ]) # head constraints constraints.extend([ H[i] >= H_min[i], ]) for j in range(0, N): if i != j: constraints.extend([ Tight([ H[i] * slack_h[i, j] >= (H_loss[i, j] + H[j]) * connect[i, j] ]), Tight([ H[i] * connect[i, j] <= slack_h[i, j] * (H_loss[i, j] + H[j]) ]), Tight([slack_h[i, j] >= 1]), ]) # topology constraints constraints += [ connect[i, j] <= 1, connect[i, j] >= udr, connect[i, j] * connect[j, i] <= udr, flow[i, j] <= maxFlow[i, j], D[i, j] <= D_max, D[i, j] >= D_min * (connect[i, j] + connect[j, i]), # flow cost pipeCost[i, j] == 1.1 * D[i, j]**1.5 * L[i, j] * units.s / units.m**5.5, # Darcy-Weisbach Equations H_loss[i, j] == f[i, j] * L[i, j] * V[i, j]**2 / (2 * D[i, j] * g), V[i, j] == 4 * flow[i, j] / (np.pi * D[i, j]**2), relRough[i, j] == rough[i, j] / D[i, j], Re[i, j] == rho * V[i, j] * D[i, j] / mu, # friction factor posynomial approximation f[i, j]**2.39794 >= 3.26853e-06 * Re[i, j]**0.0574443 * relRough[i, j]**0.364794 + 0.0001773 * Re[i, j]**-0.529499 * relRough[i, j]**-0.0810121 + 0.00301918 * Re[i, j]**-0.0220498 * relRough[i, j]**1.73526 + 0.0734922 * Re[i, j]**-1.13629 * relRough[i, j]**0.0574655 + 0.000214297 * Re[i, j]**0.00035242 * relRough[i, j]**0.823896, f[i, j] <= 1, ] else: constraints.extend([ slack_h[i, j] == 1, connect[i, j] == udr, D[i, j] == udr * D[i, j].units, pipeCost[i, j] == udr * pipeCost[i, j].units, H_loss[i, j] == udr * H_loss[i, j].units, f[i, j] == udr, ]) for j in range(i + 1, N): constraints.extend([ D[i, j] == D[j, i], ]) constraints += [ totalCost >= np.sum(flow * pipeCost) * (1 + slackCost * np.prod(slack_1) * np.prod(slack_2) * np.prod(slack_h)) ] return constraints
def test_vector(self): "Monomial Equalities with VectorVariables" x = VectorVariable(3, "x") self.assertFalse(x == 3) self.assertTrue(x == x) # pylint: disable=comparison-with-itself
def setup(self, length): a = VectorVariable(length, "a", "g/m") b = VectorVariable(length, "b", "m") c = Variable("c", 17 / 4., "g") return [a >= c / b]
def test_outer(self): x = VectorVariable(3, 'x') y = VectorVariable(3, 'y') self.assertEqual(np.outer(x, y), x.outer(y)) self.assertEqual(np.outer(y, x), y.outer(x)) self.assertTrue(isinstance(x.outer(y), NomialArray))
def test_getitem(self): x = VectorVariable((2, 4), 'x') self.assertTrue(isinstance(x[0][0], Monomial)) self.assertTrue(isinstance(x[0, 0], Monomial))
def test_vector_cost(self): x = VectorVariable(2, "x") self.assertRaises(ValueError, CostedConstraintSet, x, []) _ = CostedConstraintSet(np.array(x[0]), [])
"Example Vectorize usage, from gpkit/tests/t_vars.py" from gpkit import Variable, Vectorize, VectorVariable with Vectorize(3): with Vectorize(5): y = Variable("y") x = VectorVariable(2, "x") z = VectorVariable(7, "z") assert (y.shape == (5, 3)) assert (x.shape == (2, 5, 3)) assert (z.shape == (7, 3))
def test_prod(self): x = VectorVariable(3, 'x') m = x.prod() self.assertTrue(isinstance(m, Monomial)) self.assertEqual(m, x[0]*x[1]*x[2]) self.assertEqual(m, np.prod(x))
def test_ast(self): # pylint: disable=too-many-statements if sys.platform[:3] == "win": # pragma: no cover return t = Variable("t") u = Variable("u") v = Variable("v") w = Variable("w") x = VectorVariable(3, "x") y = VectorVariable(3, "y") z = VectorVariable(3, "z") a = VectorVariable((3, 2), "a") # print(w >= x) # TODO: this always prints the vector on the left self.assertEqual(str(3*(x + y)*z), "3·(x[:] + y[:])·z[:]") nni = 3 ii = np.tile(np.arange(1, nni+1), a.shape[1:]+(1,)).T self.assertEqual(str(w*NomialArray(ii)/nni)[:4], "w·[[") self.assertEqual(str(w*NomialArray(ii)/nni)[-4:], "]]/3") self.assertEqual(str(NomialArray(ii)*w/nni)[:2], "[[") self.assertEqual(str(NomialArray(ii)*w/nni)[-6:], "]]·w/3") self.assertEqual(str(w*ii/nni)[:4], "w·[[") self.assertEqual(str(w*ii/nni)[-4:], "]]/3") self.assertEqual(str(w*(ii/nni))[:4], "w·[[") self.assertEqual(str(w*(ii/nni))[-2:], "]]") self.assertEqual(str(w >= (x[0]*t + x[1]*u)/v), "w ≥ (x[0]·t + x[1]·u)/v") self.assertEqual(str(x), "x[:]") self.assertEqual(str(x*2), "x[:]·2") self.assertEqual(str(2*x), "2·x[:]") self.assertEqual(str(x + 2), "x[:] + 2") self.assertEqual(str(2 + x), "2 + x[:]") self.assertEqual(str(x/2), "x[:]/2") self.assertEqual(str(2/x), "2/x[:]") self.assertEqual(str(x**3), "x[:]³") self.assertEqual(str(-x), "-x[:]") self.assertEqual(str(x/y/z), "x[:]/y[:]/z[:]") self.assertEqual(str(x/(y/z)), "x[:]/(y[:]/z[:])") self.assertEqual(str(x <= y), "x[:] ≤ y[:]") self.assertEqual(str(x >= y + z), "x[:] ≥ y[:] + z[:]") self.assertEqual(str(x[:2]), "x[:2]") self.assertEqual(str(x[:]), "x[:]") self.assertEqual(str(x[1:]), "x[1:]") self.assertEqual(str(y * [1, 2, 3]), "y[:]·[1, 2, 3]") self.assertEqual(str(x[:2] == (y*[1, 2, 3])[:2]), "x[:2] = (y[:]·[1, 2, 3])[:2]") self.assertEqual(str(y + [1, 2, 3]), "y[:] + [1, 2, 3]") self.assertEqual(str(x == y + [1, 2, 3]), "x[:] = y[:] + [1, 2, 3]") self.assertEqual(str(x >= y + [1, 2, 3]), "x[:] ≥ y[:] + [1, 2, 3]") self.assertEqual(str(a[:, 0]), "a[:,0]") self.assertEqual(str(a[2, :]), "a[2,:]") g = 1 + 3*a[2, 0]**2 gstrbefore = str(g) g.ast = None gstrafter = str(g) self.assertEqual(gstrbefore, gstrafter) cstr = str(2*a >= a + np.ones((3, 2))/2) self.assertEqual(cstr, """2·a[:] ≥ a[:] + [[0.5 0.5] [0.5 0.5] [0.5 0.5]]""")
import gpkit from gpkit import Variable, VectorVariable, Model from gpkit.tools import te_exp_minus1 from gpkit.feasibility import feasibility_model n_stages = 2 dV_total = Variable("dV_requirement","m/s") dV = VectorVariable(n_stages,"dV","m/s") Isp = VectorVariable(n_stages,"Isp",[282,348],"s") #Values from F9 wiki theta_fuel = VectorVariable(n_stages,"theta_fuel",[0.97,0.95],"-") #Super optimistic values z = VectorVariable(n_stages,"z","-") m_fuel = VectorVariable(n_stages,"m_fuel","kg") m_payload = Variable("m_payload",100,"kg") m_structures = VectorVariable(n_stages,"m_structures","kg") m_dot = VectorVariable(n_stages,"m_dot","kg/s") v_exhaust_effective = VectorVariable(n_stages,"v_exhaust_effective","m/s") F_thrust = VectorVariable(n_stages,"F_thrust","N") total_mass = VectorVariable(n_stages,"total_mass","kg") m_total = Variable("m_total","kg") g = Variable("g",9.8,"m/s/s") constraints = [] for stage in range(n_stages): constraints += [ Isp[stage] == v_exhaust_effective[stage]/g, m_dot[stage] == F_thrust[stage]/(g*Isp[stage]), z[stage] >= (dV[stage]+g*(m_fuel[stage]/m_dot[stage]))/v_exhaust_effective[stage], theta_fuel[stage] >= te_exp_minus1(z[stage],5) ]
def test_shape(self): x = VectorVariable((2, 3), 'x') self.assertEqual(x.shape, (2, 3))
def test_vector(self): "Monomial Equalities with VectorVariables" x = VectorVariable(3, "x") self.assertFalse(x == 3) self.assertTrue(x == x)
def test_prod(self): x = VectorVariable(3, 'x') m = x.prod() self.assertTrue(isinstance(m, Monomial)) self.assertEqual(m, x[0] * x[1] * x[2]) self.assertEqual(m, np.prod(x))
"Example substitution; adapted from t_sub.py/t_NomialSubs/test_Vector" from gpkit import Variable, VectorVariable x = Variable("x") y = Variable("y") z = VectorVariable(2, "z") p = x * y * z assert all(p.sub({x: 1, "y": 2}) == 2 * z) assert all(p.sub({x: 1, y: 2, "z": [1, 2]}) == z.sub({z: [2, 4]}))
def test_ndim(self): x = VectorVariable((3, 4), 'x') self.assertEqual(x.ndim, 2)
"Minimizes cylindrical tank surface area for a particular volume." from gpkit import Variable, VectorVariable, Model M = Variable("M", 100, "kg", "Mass of Water in the Tank") rho = Variable("\\rho", 1000, "kg/m^3", "Density of Water in the Tank") A = Variable("A", "m^2", "Surface Area of the Tank") V = Variable("V", "m^3", "Volume of the Tank") d = VectorVariable(3, "d", "m", "Dimension Vector") constraints = (A >= 2 * (d[0] * d[1] + d[0] * d[2] + d[1] * d[2]), V == d[0] * d[1] * d[2], M == V * rho) m = Model(A, constraints) sol = m.solve(verbosity=0) print sol.summary()
# Declare a variable, y, with units of meters y = Variable("y", "m") # Declare a variable, z, with units of meters, and a description z = Variable("z", "m", "A variable called z with units of meters") ### Example Fixed Variables 1 rho = Variable("rho", 1.225, "kg/m^3", "Density of air at sea level") ### Example Fixed Variables 2 #Declare pi equal to 3.14 pi = Variable("pi", 3.14159, "-", constant=True) ### Example Vector Variables # Declare a 3-element vector variable "x" with units of "m" x = VectorVariable(3, "x", "m", "Cube corner coordinates") x_min = VectorVariable(3, "x", [1, 2, 3], "m", "Cube corner minimum") ### Example Creating Monomials and Posynomials 1 # create a Monomial term xy^2/z x = Variable("x") y = Variable("y") z = Variable("z") m = x * y**2 / z assert isinstance(m, Monomial) ### Example Creating Monomials and Posynomials 2 # create a Posynomial expression x + xy^2 x = Variable("x") y = Variable("y") p = x + x * y**2
def setup(self, N, topology_dict, friction='DW', penalty=10.): n_p = len(topology_dict) # number of pipes H = VectorVariable(N, "H", "m", "Head") H_min = VectorVariable(N, "H_{min}", "m", "Minimal Head Required") source = VectorVariable(N, "\dot{V}_+", "m^3/s", "Source", pr=20) sink = VectorVariable(N, "\dot{V}_-", "m^3/s", "Sink", pr=20) rough = VectorVariable(n_p, "\\epsilon", "m", "Pipe Roughness") pipeCost = VectorVariable(n_p, "c_p", "-", "Pipe Cost") L = VectorVariable(n_p, "L", "m", "Pipe Length") D = VectorVariable(n_p, "D", "m", "Pipe Diameter") flow = VectorVariable(n_p, "q", "m^3/s", "Flow Rate") V = VectorVariable(n_p, "v_f", "m/s", "Flow Velocity") maxV = VectorVariable(n_p, "v_{max}", 1e20 * np.ones(n_p), "m/s", 'Maximum Flow Velocity') H_loss = VectorVariable(n_p, "H_L", "m", "Head Loss") slack_out = VectorVariable(N, "S_{out}", "-", "Outflow Slack") slack_in = VectorVariable(N, "S_{in}", "-", "Inflow Slack") slack_h = VectorVariable(n_p, "S_h", "-", "Head Slack") totalCost = Variable("C", "-", "Total Cost") D_max = Variable("D_{max}", "m", "Maximum Diameter") D_min = Variable("D_{min}", "m", "Minimum Diameter") rho = Variable("\\rho", 1000, "kg/m^3", "Density") mu = Variable("\\mu", 8.9e-4, "kg/m/s", "Viscosity") g = Variable("g", 9.81, "m/s^2", "Gravity") if friction == 'DW': relRough = VectorVariable(n_p, "\\bar{\\epsilon}", "-", "Relative Pipe Roughness") Re = VectorVariable(n_p, "Re", "-", "Reynold's Number") f = VectorVariable(n_p, "f", "-", "Friction Factor") constraints = [] with SignomialsEnabled(): for i in range(0, N): flow_in = sink[i] flow_out = source[i] for pipe_index, node in list(topology_dict.items()): if node[0] == i: flow_in += flow[pipe_index] if node[1] == i: flow_out += flow[pipe_index] constraints.extend([ Tight([flow_in <= slack_out[i] * flow_out]), Tight([flow_out <= slack_in[i] * flow_in]), Tight([slack_in[i] >= 1]), Tight([slack_out[i] >= 1]), H[i] >= H_min[i] ]) # Head loss constraints for pipe_index, node in list(topology_dict.items()): if node[0] == i: constraints.extend([ Tight([ H[node[0]] >= H_loss[pipe_index] + H[node[1]] ]), Tight([ H[node[0]] <= slack_h[pipe_index] * (H_loss[pipe_index] + H[node[1]]) ]), Tight([slack_h[pipe_index] >= 1]), ]) for pipe_index in range(n_p): constraints += [ V[pipe_index] <= maxV, pipeCost[pipe_index] == 1.1 * D[pipe_index]**1.5 * L[pipe_index] / units.m**2.5, V[pipe_index] == 4 * flow[pipe_index] / (np.pi * D[pipe_index]**2), D[pipe_index] <= D_max, D[pipe_index] >= D_min ] if friction == "HW": constraints += [ H_loss[pipe_index] == 10.67 * L[pipe_index] * (flow[pipe_index] / units('m^3/s'))**1.852 / ((rough[pipe_index] / units('m'))**1.852 * (D[pipe_index] / units('m'))**4.8704) ] # S (hydraulic slope H/L) = 10.67*Q^1.852 (volumetric flow rate) / # C^1.852 (pipe roughness) /d^4.8704 (pipe diameter) if friction == 'DW': constraints += [ H_loss[pipe_index] == f[pipe_index] * L[pipe_index] * V[pipe_index]**2 / (2 * D[pipe_index] * g), relRough[pipe_index] == rough[pipe_index] / D[pipe_index], Re[pipe_index] == rho * V[pipe_index] * D[pipe_index] / mu, # From frictionFactorFitting.py f[pipe_index]**2.39794 >= 3.26853e-06 * Re[pipe_index]**0.0574443 * relRough[pipe_index]**0.364794 + 0.0001773 * Re[pipe_index]**-0.529499 * relRough[pipe_index]**-0.0810121 + 0.00301918 * Re[pipe_index]**-0.0220498 * relRough[pipe_index]**1.73526 + 0.0734922 * Re[pipe_index]**-1.13629 * relRough[pipe_index]**0.0574655 + 0.000214297 * Re[pipe_index]**0.00035242 * relRough[pipe_index]**0.823896, f[pipe_index] <= 1 ] constraints += [ totalCost >= np.sum(pipeCost) * (np.prod(slack_out) * np.prod(slack_in) * np.prod(slack_h)**penalty) ] return constraints
def setup(self): self.y = y = Variable("y", 1) self.x = x = VectorVariable( 3, "x", lambda c: c[y] + np.array([1, 2, 3]))