Coverage for docs/source/examples/model_var_access.py: 100%
25 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 16:49 -0500
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 16:49 -0500
1"Demo of accessing variables in models"
2from gpkit import Model, Variable
5class Battery(Model):
6 """A simple battery
8 Upper Unbounded
9 ---------------
10 m
12 Lower Unbounded
13 ---------------
14 E
16 """
17 def setup(self):
18 h = Variable("h", 200, "Wh/kg", "specific energy")
19 E = self.E = Variable("E", "MJ", "stored energy")
20 m = self.m = Variable("m", "lb", "battery mass")
21 return [E <= m*h]
24class Motor(Model):
25 """Electric motor
27 Upper Unbounded
28 ---------------
29 m
31 Lower Unbounded
32 ---------------
33 Pmax
35 """
36 def setup(self):
37 m = self.m = Variable("m", "lb", "motor mass")
38 f = Variable("f", 20, "lb/hp", "mass per unit power")
39 Pmax = self.Pmax = Variable("P_{max}", "hp", "max output power")
40 return [m >= f*Pmax]
43class PowerSystem(Model):
44 """A battery powering a motor
46 Upper Unbounded
47 ---------------
48 m
50 Lower Unbounded
51 ---------------
52 E, Pmax
54 """
55 def setup(self):
56 battery, motor = Battery(), Motor()
57 components = [battery, motor]
58 m = self.m = Variable("m", "lb", "mass")
59 self.E = battery.E
60 self.Pmax = motor.Pmax
62 return [components,
63 m >= sum(comp.m for comp in components)]
65PS = PowerSystem()
66print("Getting the only var 'E': %s" % PS["E"])
67print("The top-level var 'm': %s" % PS.m)
68print("All the variables 'm': %s" % PS.variables_byname("m"))