Coverage for docs/source/examples/model_var_access.py: 100%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

25 statements  

1"Demo of accessing variables in models" 

2from gpkit import Model, Variable 

3 

4 

5class Battery(Model): 

6 """A simple battery 

7 

8 Upper Unbounded 

9 --------------- 

10 m 

11 

12 Lower Unbounded 

13 --------------- 

14 E 

15 

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] 

22 

23 

24class Motor(Model): 

25 """Electric motor 

26 

27 Upper Unbounded 

28 --------------- 

29 m 

30 

31 Lower Unbounded 

32 --------------- 

33 Pmax 

34 

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] 

41 

42 

43class PowerSystem(Model): 

44 """A battery powering a motor 

45 

46 Upper Unbounded 

47 --------------- 

48 m 

49 

50 Lower Unbounded 

51 --------------- 

52 E, Pmax 

53 

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 

61 

62 return [components, 

63 m >= sum(comp.m for comp in components)] 

64 

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"))