Skip to content

Commit

Permalink
lint
Browse files Browse the repository at this point in the history
  • Loading branch information
bqpd committed Oct 8, 2021
1 parent f8ce8c5 commit 4907943
Show file tree
Hide file tree
Showing 10 changed files with 194 additions and 74 deletions.
5 changes: 3 additions & 2 deletions docs/source/examples/beam.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
Euler-Bernoulli beam equations for a constant distributed load
"""
import numpy as np
from gpkit import parse_variables, Model, ureg
from gpkit.small_scripts import mag
from gpkit import parse_variables, Model
# from gpkit import parse_variables, Model, ureg
# from gpkit.small_scripts import mag

eps = 2e-4 # has to be quite large for consistent cvxopt printouts;
# normally you'd set this to something more like 1e-20
Expand Down
14 changes: 9 additions & 5 deletions docs/source/examples/breakdowns.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"An example to show off Breakdowns"
import pickle
from gpkit.breakdown import Breakdowns
from gpkit.breakdowns import Breakdowns

# the code to create solar.p is in ./breakdowns/solartest.py
sol = pickle.load(open("solar.p", "rb"))
Expand All @@ -11,7 +12,8 @@

print("Variable breakdowns (note the two methods of access)")
print("===================")
varkey, = sol["variables"].keymap["Mission.FlightSegment.AircraftPerf.AircraftDrag.Poper"]
varkey, = sol["variables"].keymap[("Mission.FlightSegment.AircraftPerf"
".AircraftDrag.Poper")]
bds.plot(varkey)
bds.plot("AircraftPerf.AircraftDrag.MotorPerf.Q")

Expand All @@ -26,11 +28,13 @@

print("Exhaustive variable breakdown traces (and configuration arguments)")
print("====================================")
bds.plot("AircraftPerf.AircraftDrag.Poper", height=12) # often useful as a reference point when reading the below
bds.plot("AircraftPerf.AircraftDrag.Poper", showlegend=True) # includes factors, can be useful as well
# often useful as a reference point when reading traces
bds.plot("AircraftPerf.AircraftDrag.Poper", height=12)
# includes factors, can be useful for reading traces as well
bds.plot("AircraftPerf.AircraftDrag.Poper", showlegend=True)
print("\nPermissivity = 2 (the default)")
print("----------------")
bds.trace("AircraftPerf.AircraftDrag.Poper")
print("\nPermissivity = 1 (stops at Pelec = v·i)") # showing different values for permissivity
print("\nPermissivity = 1 (stops at Pelec = v·i)")
print("----------------")
bds.trace("AircraftPerf.AircraftDrag.Poper", permissivity=1)
2 changes: 1 addition & 1 deletion docs/source/examples/docstringparsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,6 @@ def setup(self):
c = Cube()
c.cost = c.A
sol = c.solve(verbosity=0)
from gpkit.breakdown import Breakdowns
from gpkit.breakdowns import Breakdowns
bds = Breakdowns(sol)
bds.plot("cost", showlegend=True)
64 changes: 32 additions & 32 deletions docs/source/examples/performance_modeling.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,38 +219,38 @@ def setup(self):
AC = Aircraft()
MISSION = Mission(AC)
M = Model(MISSION.takeoff_fuel, [MISSION, AC])
# print(M)
print(M)
sol = M.solve(verbosity=0)
# save solution to some files
# sol.savemat()
# sol.savecsv()
# sol.savetxt()
# sol.save("solution.pkl")
# # retrieve solution from a file
# sol_loaded = pickle.load(open("solution.pkl", "rb"))
#
# vars_of_interest = set(AC.varkeys)
# # note that there's two ways to access submodels
# assert (MISSION["flight segment"]["aircraft performance"]
# is MISSION.fs.aircraftp)
# vars_of_interest.update(MISSION.fs.aircraftp.unique_varkeys)
# vars_of_interest.add(M["D"])
# print(sol.summary(vars_of_interest))
sol.savemat()
sol.savecsv()
sol.savetxt()
sol.save("solution.pkl")
# retrieve solution from a file
sol_loaded = pickle.load(open("solution.pkl", "rb"))

vars_of_interest = set(AC.varkeys)
# note that there's two ways to access submodels
assert (MISSION["flight segment"]["aircraft performance"]
is MISSION.fs.aircraftp)
vars_of_interest.update(MISSION.fs.aircraftp.unique_varkeys)
vars_of_interest.add(M["D"])
print(sol.summary(vars_of_interest))
print(sol.table(tables=["cost breakdown"]))
# print(sol.table(tables=["loose constraints"]))
#
# M.append(MISSION.fs.aircraftp.Wburn >= 0.2*MISSION.fs.aircraftp.wing_aero.D)
# sol = M.solve(verbosity=0)
# print(sol.diff("solution.pkl", showvars=vars_of_interest, sortbymodel=False))
#
# try:
# from gpkit.interactive.sankey import Sankey
# variablesankey = Sankey(sol, M).diagram(AC.wing.A)
# sankey = Sankey(sol, M).diagram(width=1200, height=400, maxlinks=30)
# # the line below shows an interactive graph if run in jupyter notebook
# sankey # pylint: disable=pointless-statement
# except (ImportError, ModuleNotFoundError):
# print("Making Sankey diagrams requires the ipysankeywidget package")
#
# from gpkit.interactive.references import referencesplot
# referencesplot(M, openimmediately=False)
print(sol.table(tables=["loose constraints"]))

M.append(MISSION.fs.aircraftp.Wburn >= 0.2*MISSION.fs.aircraftp.wing_aero.D)
sol = M.solve(verbosity=0)
print(sol.diff("solution.pkl", showvars=vars_of_interest, sortbymodel=False))

try:
from gpkit.interactive.sankey import Sankey
variablesankey = Sankey(sol, M).diagram(AC.wing.A)
sankey = Sankey(sol, M).diagram(width=1200, height=400, maxlinks=30)
# the line below shows an interactive graph if run in jupyter notebook
sankey # pylint: disable=pointless-statement
except (ImportError, ModuleNotFoundError):
print("Making Sankey diagrams requires the ipysankeywidget package")

from gpkit.interactive.references import referencesplot
referencesplot(M, openimmediately=False)
122 changes: 122 additions & 0 deletions docs/source/examples/performance_modeling_output.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,37 @@

Cost Function
-------------
Wfuel[0]

Constraints
-----------
Mission
"fuel constraints":
Wfuel[:-1] ≥ Wfuel[1:] + Wburn[:-1]
Wfuel[3] ≥ Wburn[3]

FlightSegment
AircraftP
Wburn[:] ≥ 0.1·D[:]
Aircraft.W + Wfuel[:] ≤ 0.5·rho[:]·CL[:]·S·V[:]²
"performance":
WingAero
D[:] ≥ 0.5·rho[:]·V[:]²·CD[:]·S
Re[:] = rho[:]·V[:]·c/mu[:]
CD[:] ≥ 0.074/Re[:]^0.2 + CL[:]²/π/A/e[:]

FlightState
(no constraints)

Aircraft
Aircraft.W ≥ Fuselage.W + Wing.W
Fuselage
(no constraints)

Wing
c = (S/A)^0.5
Wing.W ≥ S·Wing.rho

┃┓ ┓ ┓ ┓ ┓
┃┃ ┃ ┃ ┃ ┃
┃┃ ┃ ┃ ┣╸Wburn[2] ┣╸CD[2]╶⎨
Expand All @@ -21,3 +54,92 @@
┃┛ ┛ ┛ ┛ (0.0772)


Mission 1.0 [(0, 0.25, 4), (1, 0.5, 3), (1, 0.75, 2), (2, 1.0, 1), (8, 4.5, 0)]
AircraftP -3 [(1, -0.35, 1), (1, -0.35, 2), (1, -0.35, 3), (1, -0.35, 4), (1, -0.25, 5), (1, -0.25, 6), (1, -0.25, 7), (1, -0.25, 8), (4, -2.1, 0)]

┃┓ ┓ ┓
┃┃ ┃ ┃
┃┃ ┃ ┃
┃┃ ┃ ┃
┃┃ ┣╸FlightSegment ┣╸AircraftP╶⎨
┃┃ ┃ ┃
┃┣╸Mission ┃ ┃
┃┃ ┃ ┃
┃┃ ┛ ┛
Model╺┫┃ ┣╸Wfuel[0] ≥ Wfuel[1] + Wburn[0]
┃┃ ┛
┃┃ ┣╸Wfuel[1] ≥ Wfuel[2] + Wburn[1]
┃┛ ┣╸Wfuel[2] ≥ Wfuel[3] + Wburn[2]
┃┓ ┓
┃┃ ┣╸Wing╶⎨
┃┃ ┛
┃┣╸Aircraft ┣╸W ≥ Fuselage.W + Wing.W
┃┃ ┛
┃┃ ┣╸Fuselage ┣╸W = 100lbf
┃┛ ┛ ┛


Free Variables
--------------
| Aircraft
W : 144.1 [lbf] weight

| Aircraft.Wing
S : 44.14 [ft²] surface area
W : 44.14 [lbf] weight
c : 1.279 [ft] mean chord

| Mission.FlightSegment.AircraftP
Wburn : [ 0.274 0.273 0.272 0.272 ] [lbf] segment fuel burn
Wfuel : [ 1.09 0.817 0.544 0.272 ] [lbf] fuel weight

| Mission.FlightSegment.AircraftP.WingAero
D : [ 2.74 2.73 2.72 2.72 ] [lbf] drag force


┃┓ ┓ ┓ ┓ ┓
┃┃ ┃ ┃ ┃ ┃
┃┃ ┃ ┃ ┣╸Wburn[2] ┣╸CD[2]╶⎨
┃┃ ┃ ┃ ┃ (0.272lbf) ┃ (0.0189)
┃┃ ┃ ┃ ┛ ┛
┃┃ ┃ ┣╸Wfuel[2] ┓ ┓
┃┃ ┃ ┃ (0.544lbf) ┃ ┃
┃┃ ┣╸Wfuel[1] ┃ ┣╸Wfuel[3] ┣╸CD[3]╶⎨
┃┃ ┃ (0.817lbf) ┃ ┃ (0.272lbf) ┃ (0.0188)
Cost╺┫┃ ┃ ┛ ┛ ┛
(1.09lbf) ┃┣╸Wfuel[0] ┃ ┓ ┓ ┓
┃┃ (1.09lbf) ┃ ┃ ┃ ┣╸CL[1]²
┃┃ ┃ ┣╸Wburn[1] ┣╸CD[1] ┛ (1.01)
┃┃ ┃ ┃ (0.273lbf) ┃ (0.0189) ┣╸1/Re[1]^0.2
┃┃ ┛ ┛ ┛ ┛ (0.0772)
┃┃ ┓ ┓ ┓
┃┃ ┃ ┃ ┣╸CL[0]²
┃┃ ┣╸Wburn[0] ┣╸CD[0] ┛ (1.01)
┃┃ ┃ (0.274lbf) ┃ (0.019) ┣╸1/Re[0]^0.2
┃┛ ┛ ┛ ┛ (0.0772)


Insensitive Constraints |below +1e-05|
--------------------------------------
(none)

Solution Diff (for selected variables)
======================================
(argument is the baseline solution)

Constraint Differences
**********************
@@ -31,3 +31,4 @@
Wing
c = (S/A)^0.5
Wing.W ≥ S·Wing.rho
+ Wburn[:] ≥ 0.2·D[:]

**********************

Relative Differences |above 1%|
-------------------------------
Wburn : [ +102.1% +101.6% +101.1% +100.5% ] segment fuel burn
Wfuel : [ +101.3% +101.1% +100.8% +100.5% ] fuel weight
D : [ +1.1% - - - ] drag force

2 changes: 1 addition & 1 deletion docs/source/examples/relaxation.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
constraintsrelaxed)
print(mr2)
print(mr2.solve(verbosity=0).table()) # solves with an x of 1.0
from gpkit.breakdown import Breakdowns
from gpkit.breakdowns import Breakdowns
bds = Breakdowns(mr2.solution)
bds.plot("cost")
bds.trace("cost")
Expand Down
File renamed without changes.
5 changes: 3 additions & 2 deletions gpkit/small_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def dot(self, arg):
return self.tocsr().dot(arg)


class SolverLog(object):
class SolverLog:
"Adds a `write` method to list so it's file-like and can replace stdout."
def __init__(self, output=None, *, verbosity=0):
self.written = ""
Expand All @@ -81,10 +81,11 @@ def write(self, writ):
self.output.write(writ)

def lines(self):
"Returns the lines presently written."
return self.written.split("\n")

def flush(self):
pass
"Dummy function for I/O api compatibility"


class DictOfLists(dict):
Expand Down
52 changes: 22 additions & 30 deletions gpkit/solution_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from .small_classes import DictOfLists, Strings, SolverLog
from .small_scripts import mag, try_str_without
from .repr_conventions import unitstr, lineagestr
from .breakdown import Breakdowns
from .breakdowns import Breakdowns


CONSTRSPLITPATTERN = re.compile(r"([^*]\*[^*])|( \+ )|( >= )|( <= )|( = )")
Expand Down Expand Up @@ -284,32 +284,24 @@ def warnings_table(self, _, **kwargs):
lines[-1] = "~~~~~~~~"
return lines + [""]

def costbd(self, _, **kwargs):
bds = Breakdowns(self)
original_stdout = sys.stdout
try:
sys.stdout = SolverLog(original_stdout, verbosity=0)
bds.plot("cost")
except:
raise
finally:
lines = sys.stdout.lines()
sys.stdout = original_stdout
return lines
# TODO: deduplicate these two functions
def bdtable_gen(key):
"Generator for breakdown tablefns"

def bdtable(self, _showvars, **_):
"Cost breakdown plot"
bds = Breakdowns(self)
original_stdout = sys.stdout
try:
sys.stdout = SolverLog(original_stdout, verbosity=0)
bds.plot(key)
finally:
lines = sys.stdout.lines()
sys.stdout = original_stdout
return lines

return bdtable

def msenssbd(self, _, **kwargs):
bds = Breakdowns(self)
original_stdout = sys.stdout
try:
sys.stdout = SolverLog(original_stdout, verbosity=0)
bds.plot("model sensitivities")
except:
raise
finally:
lines = sys.stdout.lines()
sys.stdout = original_stdout
return lines

TABLEFNS = {"sensitivities": senss_table,
"top sensitivities": topsenss_table,
Expand All @@ -318,8 +310,8 @@ def msenssbd(self, _, **kwargs):
"tightest constraints": tight_table,
"loose constraints": loose_table,
"warnings": warnings_table,
"model sensitivities breakdown": msenssbd,
"cost breakdown": costbd
"model sensitivities breakdown": bdtable_gen("model sensitivities"),
"cost breakdown": bdtable_gen("cost")
}

def unrolled_absmax(values):
Expand Down Expand Up @@ -717,9 +709,9 @@ def _parse_showvars(self, showvars):
def summary(self, showvars=(), **kwargs):
"Print summary table, showing no sensitivities or constants"
return self.table(showvars,
["cost breakdown", "model sensitivities breakdown",
"warnings", "sweepvariables", "freevariables"],
**kwargs)
["cost breakdown", "model sensitivities breakdown",
"warnings", "sweepvariables", "freevariables"],
**kwargs)

def table(self, showvars=(),
tables=("cost breakdown", "model sensitivities breakdown",
Expand Down
2 changes: 1 addition & 1 deletion gpkit/tests/t_keydict.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def test_vector(self):
v = VectorVariable(3, "v")
kd = KeyDict()
kd[v] = np.array([2, 3, 4])
self.assertTrue(all(kd[v] == kd[v.key]))
self.assertTrue(all(kd[v] == kd[v.key])) # pylint:disable=no-member
self.assertTrue(all(kd["v"] == np.array([2, 3, 4])))
self.assertEqual(v[0].key.idx, (0,))
self.assertEqual(kd[v][0], kd[v[0]])
Expand Down

0 comments on commit 4907943

Please sign in to comment.