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

34 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-01-07 22:56 -0500

1"Show autosweep_1d functionality" 

2import pickle 

3import numpy as np 

4import gpkit 

5from gpkit import units, Variable, Model 

6from gpkit.tools.autosweep import autosweep_1d 

7from gpkit.small_scripts import mag 

8 

9A = Variable("A", "m**2") 

10l = Variable("l", "m") 

11 

12m1 = Model(A**2, [A >= l**2 + units.m**2]) 

13tol1 = 1e-3 

14bst1 = autosweep_1d(m1, tol1, l, [1, 10], verbosity=0) 

15print(f"Solved after {bst1.nsols:2} passes, cost logtol +/-{bst1.tol:.3g}") 

16# autosweep solution accessing 

17l_vals = np.linspace(1, 10, 10) 

18sol1 = bst1.sample_at(l_vals) 

19print(f"values of l: {l_vals}") 

20print("values of A: [" + 

21 " ".join(f"{n: .1f}" for n in sol1("A").magnitude) + "] " + 

22 str(sol1("A").units)) 

23cost_estimate = sol1["cost"] 

24cost_lb, cost_ub = sol1.cost_lb(), sol1.cost_ub() 

25print(f"cost lower bound:\n{cost_lb}\n") 

26print(f"cost estimate:\n{cost_estimate}\n") 

27print(f"cost upper bound:\n{cost_ub}\n") 

28# you can evaluate arbitrary posynomials 

29np.testing.assert_allclose(mag(2*sol1(A)), mag(sol1(2*A))) 

30assert (sol1["cost"] == sol1(A**2)).all() 

31# the cost estimate is the logspace mean of its upper and lower bounds 

32np.testing.assert_allclose((np.log(mag(cost_lb)) + np.log(mag(cost_ub)))/2, 

33 np.log(mag(cost_estimate))) 

34# save autosweep to a file and retrieve it 

35bst1.save("autosweep.pkl") 

36with open ("autosweep.pkl", "rb") as f: 

37 bst1_loaded = pickle.load(f) 

38 

39# this problem is two intersecting lines in logspace 

40m2 = Model(A**2, [A >= (l/3)**2, A >= (l/3)**0.5 * units.m**1.5]) 

41tol2 = {"mosek_cli": 1e-6, "mosek_conif": 1e-6, 

42 "cvxopt": 1e-7}[gpkit.settings["default_solver"]] 

43# test Model method 

44sol2 = m2.autosweep({l: [1, 10]}, tol2, verbosity=0) 

45bst2 = sol2.bst 

46print(f"Solved after {bst2.nsols:2} passes, cost logtol +/-{bst2.tol:.3g}") 

47print("Table of solutions used in the autosweep:") 

48print(bst2.solarray.table())