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

56 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-23 21:28 -0400

1"Tests non-array linked functions & subs in a vectorization environment" 

2import numpy as np 

3from gpkit import Variable, Model, ConstraintSet, Vectorize 

4 

5class Vehicle(Model): 

6 "Vehicle model" 

7 def setup(self): 

8 self.a = a = Variable("a") 

9 constraints = [a >= 1] 

10 return constraints 

11 

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 

20 

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

29 

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 

37 

38m = System() 

39sol = m.solve(verbosity=0) 

40print(sol.table()) 

41 

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 

51 

52m = System2() 

53sol = m.solve(verbosity=0) 

54print(sol.table()) 

55 

56 

57# now testing substitutions 

58 

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 

69 

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 

78 

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