Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1"Scripts for generating, solving and sweeping programs" 

2from time import time 

3import warnings as pywarnings 

4import numpy as np 

5from ad import adnumber 

6from ..nomials import parse_subs 

7from ..solution_array import SolutionArray 

8from ..keydict import KeyDict 

9from ..small_scripts import maybe_flatten 

10from ..small_classes import FixedScalar 

11from ..exceptions import Infeasible 

12from ..globals import SignomialsEnabled 

13 

14 

15def evaluate_linked(constants, linked): 

16 "Evaluates the values and gradients of linked variables." 

17 kdc = KeyDict({k: adnumber(maybe_flatten(v), k) 

18 for k, v in constants.items()}) 

19 kdc_plain = None 

20 array_calulated = {} 

21 for key in constants: # remove gradients from constants 

22 if key.gradients: 

23 del key.descr["gradients"] 

24 for v, f in linked.items(): 

25 try: 

26 if v.veckey and v.veckey.vecfn: 

27 if v.veckey not in array_calulated: 

28 with SignomialsEnabled(): # to allow use of gpkit.units 

29 vecout = v.veckey.vecfn(kdc) 

30 if not hasattr(vecout, "shape"): 

31 vecout = np.array(vecout) 

32 array_calulated[v.veckey] = vecout 

33 out = array_calulated[v.veckey][v.idx] 

34 else: 

35 with SignomialsEnabled(): # to allow use of gpkit.units 

36 out = f(kdc) 

37 if isinstance(out, FixedScalar): # to allow use of gpkit.units 

38 out = out.value 

39 if hasattr(out, "units"): 

40 out = out.to(v.units or "dimensionless").magnitude 

41 elif out != 0 and v.units: 

42 pywarnings.warn( 

43 "Linked function for %s did not return a united value." 

44 "Modifying it to do so (e.g. by using `()` instead of `[]`" 

45 " to access variables) will reduce errors." % v) 

46 if not hasattr(out, "x"): 

47 constants[v] = out 

48 continue # a new fixed variable, not a calculated one 

49 constants[v] = out.x 

50 gradients = {adn.tag: 

51 grad for adn, grad in out.d().items() if adn.tag} 

52 if gradients: 

53 v.descr["gradients"] = gradients 

54 except Exception as exception: # pylint: disable=broad-except 

55 from .. import settings 

56 if settings.get("ad_errors_raise", None): 

57 raise 

58 print("Warning: skipped auto-differentiation of linked variable" 

59 " %s because %s was raised. Set `gpkit.settings" 

60 "[\"ad_errors_raise\"] = True` to raise such Exceptions" 

61 " directly.\n" % (v, repr(exception))) 

62 if kdc_plain is None: 

63 kdc_plain = KeyDict(constants) 

64 constants[v] = f(kdc_plain) 

65 v.descr.pop("gradients", None) 

66 

67 

68def progify(program, return_attr=None): 

69 """Generates function that returns a program() and optionally an attribute. 

70 

71 Arguments 

72 --------- 

73 program: NomialData 

74 Class to return, e.g. GeometricProgram or SequentialGeometricProgram 

75 return_attr: string 

76 attribute to return in addition to the program 

77 """ 

78 def programfn(self, constants=None, **initargs): 

79 "Return program version of self" 

80 if not constants: 

81 constants, _, linked = parse_subs(self.varkeys, self.substitutions) 

82 if linked: 

83 evaluate_linked(constants, linked) 

84 prog = program(self.cost, self, constants, **initargs) 

85 prog.model = self # NOTE SIDE EFFECTS 

86 if return_attr: 

87 return prog, getattr(prog, return_attr) 

88 return prog 

89 return programfn 

90 

91 

92def solvify(genfunction): 

93 "Returns function for making/solving/sweeping a program." 

94 def solvefn(self, solver=None, *, verbosity=1, skipsweepfailures=False, 

95 **solveargs): 

96 """Forms a mathematical program and attempts to solve it. 

97 

98 Arguments 

99 --------- 

100 solver : string or function (default None) 

101 If None, uses the default solver found in installation. 

102 verbosity : int (default 1) 

103 If greater than 0 prints runtime messages. 

104 Is decremented by one and then passed to programs. 

105 skipsweepfailures : bool (default False) 

106 If True, when a solve errors during a sweep, skip it. 

107 **solveargs : Passed to solve() call 

108 

109 Returns 

110 ------- 

111 sol : SolutionArray 

112 See the SolutionArray documentation for details. 

113 

114 Raises 

115 ------ 

116 ValueError if the program is invalid. 

117 RuntimeWarning if an error occurs in solving or parsing the solution. 

118 """ 

119 constants, sweep, linked = parse_subs(self.varkeys, self.substitutions) 

120 solution = SolutionArray() 

121 solution.modelstr = str(self) 

122 

123 # NOTE SIDE EFFECTS: self.program and self.solution set below 

124 if sweep: 

125 run_sweep(genfunction, self, solution, skipsweepfailures, 

126 constants, sweep, linked, solver, verbosity, **solveargs) 

127 else: 

128 self.program, progsolve = genfunction(self) 

129 result = progsolve(solver, verbosity=verbosity, **solveargs) 

130 if solveargs.get("process_result", True): 

131 self.process_result(result) 

132 solution.append(result) 

133 solution.to_arrays() 

134 self.solution = solution 

135 return solution 

136 return solvefn 

137 

138 

139# pylint: disable=too-many-locals,too-many-arguments,too-many-branches 

140def run_sweep(genfunction, self, solution, skipsweepfailures, 

141 constants, sweep, linked, solver, verbosity, **solveargs): 

142 "Runs through a sweep." 

143 # sort sweeps by the eqstr of their varkey 

144 sweepvars, sweepvals = zip(*sorted(list(sweep.items()), 

145 key=lambda vkval: vkval[0].eqstr)) 

146 if len(sweep) == 1: 

147 sweep_grids = np.array(list(sweepvals)) 

148 else: 

149 sweep_grids = np.meshgrid(*list(sweepvals)) 

150 

151 N_passes = sweep_grids[0].size 

152 sweep_vects = {var: grid.reshape(N_passes) 

153 for (var, grid) in zip(sweepvars, sweep_grids)} 

154 

155 if verbosity > 0: 

156 print("Sweeping with %i solves:" % N_passes) 

157 tic = time() 

158 

159 self.program = [] 

160 last_error = None 

161 for i in range(N_passes): 

162 constants.update({var: sweep_vect[i] 

163 for (var, sweep_vect) in sweep_vects.items()}) 

164 if linked: 

165 evaluate_linked(constants, linked) 

166 program, solvefn = genfunction(self, constants) 

167 self.program.append(program) # NOTE: SIDE EFFECTS 

168 try: 

169 if verbosity > 1: 

170 print("\nSolve %i:" % i) 

171 result = solvefn(solver, verbosity=verbosity-1, **solveargs) 

172 if solveargs.get("process_result", True): 

173 self.process_result(result) 

174 solution.append(result) 

175 except Infeasible as e: 

176 last_error = e 

177 if not skipsweepfailures: 

178 raise RuntimeWarning( 

179 "Solve %i was infeasible; progress saved to m.program." 

180 " To continue sweeping after failures, solve with" 

181 " skipsweepfailures=True." % i) from e 

182 if verbosity > 0: 

183 print("Solve %i was %s." % (i, e.__class__.__name__)) 

184 if not solution: 

185 raise RuntimeWarning("All solves were infeasible.") from last_error 

186 

187 solution["sweepvariables"] = KeyDict() 

188 ksweep = KeyDict(sweep) 

189 for var, val in list(solution["constants"].items()): 

190 if var in ksweep: 

191 solution["sweepvariables"][var] = val 

192 del solution["constants"][var] 

193 elif linked: # if any variables are linked, we check all of them 

194 if hasattr(val[0], "shape"): 

195 differences = ((l != val[0]).any() for l in val[1:]) 

196 else: 

197 differences = (l != val[0] for l in val[1:]) 

198 if not any(differences): 

199 solution["constants"][var] = [val[0]] 

200 else: 

201 solution["constants"][var] = [val[0]] 

202 

203 if verbosity > 0: 

204 soltime = time() - tic 

205 print("Sweeping took %.3g seconds." % (soltime,))