Coverage for docs\source\examples\issue_1513.py: 0%
56 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 16:57 -0500
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 16:57 -0500
1"Tests non-array linked functions & subs in a vectorization environment"
2import numpy as np
3from gpkit import Variable, Model, ConstraintSet, Vectorize
5class Vehicle(Model):
6 "Vehicle model"
7 def setup(self):
8 self.a = a = Variable("a")
9 constraints = [a >= 1]
10 return constraints
12class System(Model):
13 "System model"
14 def setup(self):
15 with Vectorize(1):
16 self.Fleet2 = Fleet2()
17 constraints = [self.Fleet2]
18 self.cost = sum(self.Fleet2.z)
19 return constraints
21class Fleet2(Model):
22 "Fleet model (composed of multiple Vehicles)"
23 def setup(self):
24 x = Variable("x")
25 lambdafun = lambda c: [c[x]-1, np.ones(x.shape)]
26 with Vectorize(2):
27 y = Variable("y", lambdafun)
28 self.Vehicle = Vehicle()
30 self.z = z = Variable("z")
31 substitutions = {"x": 4}
32 constraints = [
33 z >= sum(y/x*self.Vehicle.a),
34 self.Vehicle,
35 ]
36 return constraints, substitutions
38m = System()
39sol = m.solve(verbosity=0)
40print(sol.table())
42# now with more fleets per system
43class System2(Model):
44 "System model"
45 def setup(self):
46 with Vectorize(3):
47 self.Fleet2 = Fleet2()
48 constraints = [self.Fleet2]
49 self.cost = sum(self.Fleet2.z)
50 return constraints
52m = System2()
53sol = m.solve(verbosity=0)
54print(sol.table())
57# now testing substitutions
59class Simple(Model):
60 "Simple model"
61 def setup(self):
62 self.x = x = Variable("x")
63 y = Variable("y", 1)
64 z = Variable("z", 2)
65 constraints = [
66 x >= y + z,
67 ]
68 return constraints
70class Cake(Model):
71 "Cake model"
72 def setup(self):
73 with Vectorize(3):
74 s = Simple()
75 c = ConstraintSet([s])
76 self.cost = sum(s.x)
77 return c
79m = Cake()
80m.substitutions.update({
81 "y": ("sweep", [1, 2, 3]),
82 "z": lambda v: v("y")**2,
83})
84sol = m.solve(verbosity=0)
85print(sol.table())