Skip to content

Commit 514c22e

Browse files
committed
ruff clean examples
1 parent e2d5fef commit 514c22e

35 files changed

+78
-94
lines changed

examples/acopf3/ACtree.py

-2
Original file line numberDiff line numberDiff line change
@@ -149,11 +149,9 @@ def __init__(self, Parent, TreeInfo, ScenarioList, Name, CondProb, acstream):
149149
self.kids = []
150150
if self.stage < TreeInfo.NumStages:
151151
bf = TreeInfo.BFs[self.stage-1]
152-
snstr = "_sn"+str(self.sn)
153152
self.sn += 1 # serial number for non-leaf, non-ROOT nodes
154153
else:
155154
bf = 1 # leaf node
156-
snstr = ""
157155
for b in range(bf):
158156
# divide up the scenario list
159157
plist = self.ScenarioList # typing aid

examples/acopf3/ccopf_multistage.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,10 @@ def FixGaussian(minutes, acstream, mu, sigma):
5454
#======= end repair functions =====
5555

5656
def _md_dict(epath):
57-
p = str(egret.__path__)
58-
l = p.find("'")
59-
r = p.find("'", l+1)
60-
egretrootpath = p[l+1:r]
57+
path = str(egret.__path__)
58+
left = path.find("'")
59+
right = path.find("'", left+1)
60+
egretrootpath = path[left+1:right]
6161
if epath[0] != os.sep:
6262
test_case = os.path.join(egretrootpath, epath)
6363
else:
@@ -259,9 +259,10 @@ def scenario_denouement(rank, scenario_name, scenario):
259259

260260
print("GEN: %4s PG:" % gen, end="")
261261

262+
previous_val = None
262263
for stage in stages:
263264
current_val = pyo.value(getattr(scenario, "stage_models_"+str(stage)).pg[gen])
264-
if stage == stages[0]:
265+
if previous_val is None:
265266
print("%6.2f -->> " % current_val, end=" ")
266267
else:
267268
print("%6.2f" % (current_val-previous_val), end=" ")
@@ -270,9 +271,10 @@ def scenario_denouement(rank, scenario_name, scenario):
270271

271272
print("GEN: %4s QG:" % gen, end="")
272273

274+
previous_val = None
273275
for stage in stages:
274276
current_val = pyo.value(getattr(scenario, "stage_models_"+str(stage)).qg[gen])
275-
if stage == stages[0]:
277+
if previous_val is None:
276278
print("%6.2f -->> " % current_val, end=" ")
277279
else:
278280
print("%6.2f" % (current_val-previous_val), end=" ")

examples/aircond/aircond_cylinders.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def make_nodenames_balanced(BFs, leaf_nodes=False, root = True):
9898
0, 1, 2, ..., BFs[0], 0_0, 0_1, ..., 0_BFs[1], 1_0, 1_1, ... ,
9999
1_BFs[1], ... , BFs[0]_BFs[1], ... , BFs[0]...BFs[-2]
100100
"""
101-
if leaf_nodes == False:
101+
if not leaf_nodes:
102102
BFs = BFs[:-1] # exclude leaf nodes
103103

104104
# Constructs all nodenames
@@ -153,7 +153,7 @@ def _parse_args():
153153
domain=bool,
154154
default=False)
155155
# special "proper" bundle arguments
156-
parser = pickle_bundle.pickle_bundle_parser(cfg)
156+
pickle_bundle.pickle_bundle_config(cfg)
157157

158158
cfg.add_to_config("EF_directly",
159159
description="Solve the EF directly instead of using cylinders (default False)",
@@ -208,15 +208,13 @@ def main():
208208
all_scenario_names = [f"Bundle_{bn*bsize}_{(bn+1)*bsize-1}" for bn in range(numbuns)]
209209
refmodule = aircondB
210210
primal_rho_setter = None
211-
dual_rho_setter = None
212211
global_toc("WARNING: not using rho setters with proper bundles")
213212

214213
else:
215214
ScenCount = np.prod(BFs)
216215
all_scenario_names = [f"scen{i}" for i in range(ScenCount)] #Scens are 0-based
217216
refmodule = aircond
218217
primal_rho_setter = refmodule.primal_rho_setter
219-
dual_rho_setter = refmodule.dual_rho_setter
220218

221219
xhat_scenario_dict = make_node_scenario_dict_balanced(BFs)
222220
all_nodenames = list(xhat_scenario_dict.keys())

examples/aircond/aircond_seqsampling.py

+1-10
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,10 @@ def main(cfg):
2323
results (dict): the solution, gap confidence interval and T
2424
"""
2525
refmodelname = "mpisppy.tests.examples.aircond"
26-
scenario_creator = aircond.scenario_creator
2726

2827
BFs = cfg.branching_factors
2928
num_scens = np.prod(BFs)
3029

31-
scenario_creator_kwargs = {"num_scens" : num_scens,
32-
"branching_factors": BFs,
33-
"mu_dev": cfg.mu_dev,
34-
"sigma_dev": cfg.sigma_dev,
35-
"start_ups": cfg.start_ups,
36-
"start_seed": cfg.seed,
37-
}
38-
3930
scenario_names = ['Scenario' + str(i) for i in range(num_scens)]
4031

4132
xhat_gen_kwargs = {"scenario_names": scenario_names,
@@ -108,7 +99,7 @@ def _parse_args():
10899
if cfg.BM_vs_BPL is None:
109100
raise RuntimeError("--BM-vs-BPL must be given.")
110101
if cfg.BM_vs_BPL != "BM" and cfg.BM_vs_BPL != "BPL":
111-
raise RuntimeError(f"--BM-vs-BPL must be BM or BPL (you gave {args.BM_vs_BMPL})")
102+
raise RuntimeError(f"--BM-vs-BPL must be BM or BPL (you gave {cfg.BM_vs_BPL})")
112103

113104
return cfg
114105

examples/aircond/bundle_pickler.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
def _parse_args():
2828
cfg = config.Config()
2929
cfg.multistage()
30-
pickle_bundle.pickle_bundle_parser(cfg)
30+
pickle_bundle.pickle_bundle_config(cfg)
3131
aircondB.inparser_adder(cfg)
3232
cfg.parse_command_line("bundle_pickler for aircond")
3333

@@ -51,8 +51,6 @@ def main():
5151

5252
bsize = int(cfg.scenarios_per_bundle)
5353
numbuns = ScenCount // bsize
54-
# we won't actually use all names
55-
all_bundle_names = [f"Bundle_{bn*bsize}_{(bn+1)*bsize-1}" for bn in range(numbuns)]
5654

5755
if numbuns < n_proc:
5856
raise RuntimeError(

examples/battery/battery.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import mpisppy.scenario_tree as stree
2424

2525
def scenario_creator(
26-
scenario_name, solar_filname=None, use_LP=False, lam=None,
26+
scenario_name, solar_filename=None, use_LP=False, lam=None,
2727
):
2828
"""
2929
Args:
@@ -80,7 +80,8 @@ def big_M_constraint_rule(model, t):
8080
+ data['disc'] * pyo.quicksum(model.q) + lam * model.z[0],
8181
sense=pyo.minimize)
8282

83-
fscr = lambda model: pyo.dot_product(data['rev'], model.y)
83+
def fscr(model):
84+
return pyo.dot_product(data["rev"], model.y)
8485
model.first_stage_cost = pyo.Expression(rule=fscr)
8586

8687
model._mpisppy_node_list = [

examples/distr/distr_admm_cylinders.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,10 @@
1616
from mpisppy.utils import config
1717
import mpisppy.utils.cfg_vanilla as vanilla
1818
from mpisppy import MPI
19-
global_rank = MPI.COMM_WORLD.Get_rank()
20-
2119
import time
2220

21+
global_rank = MPI.COMM_WORLD.Get_rank()
22+
2323
write_solution = False
2424

2525
def _parse_args():
@@ -169,4 +169,4 @@ def main():
169169

170170

171171
if __name__ == "__main__":
172-
main()
172+
main()

examples/distr/distr_data.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@
1414
# First there is a hard wired data_set, then there is a scalable dataset
1515

1616
# Hardwired data sets
17+
import json
18+
import re
19+
import numpy as np
20+
1721

1822
def inter_region_dict_creator(num_scens):
1923
"""Creates the oriented arcs between the regions, with their capacities and costs. \n
@@ -184,7 +188,6 @@ def _is_partition(L, *lists):
184188

185189
return region_dict
186190

187-
import json
188191
if __name__ == "__main__":
189192
#creating the json files
190193
for num_scens in range(2,5):
@@ -206,9 +209,6 @@ def _is_partition(L, *lists):
206209
########################################################################################################################
207210
# Scalable datasets
208211

209-
import re
210-
import numpy as np
211-
212212
def parse_node_name(name):
213213
""" decomposes the name, for example "DC1_2 gives" "DC",1,2
214214
Args:
@@ -413,4 +413,4 @@ def scalable_region_dict_creator(scenario_name, all_nodes_dict=None, cfg=None, d
413413
arc = (node_1, node_2)
414414
_intra_arc_creator(region_dict, node_1, node_2, cfg, arc, arc_params, my_seed=count, intra=True)
415415
count += 1
416-
return region_dict
416+
return region_dict

examples/farmer/farmer_cylinders.py

-1
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,6 @@ def main():
9191
"crops_multiplier": crops_multiplier,
9292
'sense': pyo.minimize
9393
}
94-
scenario_names = [f"Scenario{i+1}" for i in range(num_scen)]
9594

9695
# Things needed for vanilla cylinders
9796
beans = (cfg, scenario_creator, scenario_denouement, all_scenario_names)

examples/farmer/farmer_ef.py

+2
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ def main_with_cfg():
8080
results = solver.solve(tee=True)
8181
else:
8282
results = solver.solve(ef, tee=True, symbolic_solver_labels=True,)
83+
if not pyo.check_optimal_termination(results):
84+
print("Warning: solver reported non-optimal termination status")
8385

8486
return ef
8587

examples/farmer/farmer_lshapedhub.py

-4
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,6 @@ def main():
9595
# FWPH spoke
9696
if fwph:
9797
fw_spoke = vanilla.fwph_spoke(*beans, scenario_creator_kwargs=scenario_creator_kwargs)
98-
99-
# xhat looper bound spoke -- any scenario will do for
100-
# lshaped (they're all the same)
101-
xhat_scenario_dict = {"ROOT": all_scenario_names[0]}
10298

10399
if xhatlshaped:
104100
xhatlshaped_spoke = vanilla.xhatlshaped_spoke(*beans, scenario_creator_kwargs=scenario_creator_kwargs)

examples/farmer/farmer_rho_demo.py

-2
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,6 @@ def main():
7575

7676
cfg = _parse_args()
7777

78-
num_scen = cfg.num_scens
7978
crops_multiplier = cfg.crops_mult
8079
rho_setter = None # non-grad rho setter?
8180

@@ -99,7 +98,6 @@ def main():
9998
'use_integer': False,
10099
"crops_multiplier": crops_multiplier,
101100
}
102-
scenario_names = [f"Scenario{i+1}" for i in range(num_scen)]
103101

104102
# Things needed for vanilla cylinders
105103
beans = (cfg, scenario_creator, scenario_denouement, all_scenario_names)

examples/farmer/farmer_seqsampling.py

-1
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,6 @@ def main(cfg):
8888
results (dict): the solution, gap confidence interval and T
8989
"""
9090
refmodelname = "farmer"
91-
scenario_creator = farmer.scenario_creator
9291

9392
scen_count = cfg.num_scens
9493
assert cfg.EF_solver_name is not None

examples/farmer/from_pysp/abstract.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def _print_usage():
2929
if not solver_avail:
3030
print(f"Cannot find solver {solver_name}")
3131
sys.exit()
32-
except:
32+
except Exception:
3333
print(f"Cannot find solver {solver_name}")
3434
_print_usage()
3535
sys.exit()

examples/farmer/from_pysp/concrete_ampl.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def _print_usage():
2525
if not solver_avail:
2626
print(f"Cannot find solver {sys.argv[1]}")
2727
sys.exit()
28-
except:
28+
except Exception:
2929
print(f"Cannot find solver {sys.argv[1]}")
3030
_print_usage()
3131
sys.exit()

examples/farmer/schur_complement.py

+5
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import logging
1212
from mpisppy import MPI
1313
import sys
14+
import pyomo.environ as pyo
1415

1516

1617
if MPI.COMM_WORLD.Get_rank() == 0:
@@ -36,6 +37,8 @@ def solve_with_extensive_form(scen_count):
3637
scenario_creator=farmer.scenario_creator,
3738
scenario_creator_kwargs=scenario_kwargs)
3839
results = opt.solve_extensive_form()
40+
if not pyo.check_optimal_termination(results):
41+
print("Warning: solver reported non-optimal termination status")
3942
opt.report_var_values_at_rank0()
4043
return opt
4144

@@ -53,6 +56,8 @@ def solve_with_sc(scen_count, linear_solver=None):
5356
scenario_creator=farmer.scenario_creator,
5457
scenario_creator_kwargs=scenario_kwargs)
5558
results = opt.solve()
59+
if not pyo.check_optimal_termination(results):
60+
print("Warning: solver reported non-optimal termination status")
5661
opt.report_var_values_at_rank0()
5762
return opt
5863

examples/generic_tester.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -54,13 +54,13 @@
5454
def egret_avail():
5555
try:
5656
import egret
57-
except:
57+
except Exception:
5858
return False
5959

60-
p = str(egret.__path__)
61-
l = p.find("'")
62-
r = p.find("'", l+1)
63-
egretrootpath = p[l+1:r]
60+
path = str(egret.__path__)
61+
left = path.find("'")
62+
right = path.find("'", left+1)
63+
egretrootpath = path[left+1:right]
6464

6565
egret_thirdparty_path = os.path.join(egretrootpath, "thirdparty")
6666
if os.path.exists(os.path.join(egret_thirdparty_path, "pglib-opf-master")):

examples/netdes/netdes_ef.py

+2
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ def main():
3434
scenario_creator_kwargs={"path": path},
3535
)
3636
results = ef.solve_extensive_form(tee=True)
37+
if not pyo.check_optimal_termination(results):
38+
print("Warning: solver reported non-optimal termination status")
3739
print("Netdes objective value:", pyo.value(ef.ef.EF_Obj))
3840

3941
if __name__=="__main__":

examples/run_all.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,13 @@
4545
def egret_avail():
4646
try:
4747
import egret
48-
except:
48+
except Exception:
4949
return False
5050

51-
p = str(egret.__path__)
52-
l = p.find("'")
53-
r = p.find("'", l+1)
54-
egretrootpath = p[l+1:r]
51+
path = str(egret.__path__)
52+
left = path.find("'")
53+
right = path.find("'", left+1)
54+
egretrootpath = path[left+1:right]
5555

5656
egret_thirdparty_path = os.path.join(egretrootpath, "thirdparty")
5757
if os.path.exists(os.path.join(egret_thirdparty_path, "pglib-opf-master")):
@@ -106,6 +106,8 @@ def time_one(ID, dirname, progname, np, argstring):
106106
if (i % 2) == 0:
107107
foo = i * i
108108
bar = str(i)+"!"
109+
del foo
110+
del bar
109111
finish = dt.now()
110112
refsecs = (finish-start).total_seconds()
111113

examples/sizes/sizes.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def scenario_creator(scenario_name, scenario_count=None):
2020
datadir = os.sep.join((sizes_dir, f"SIZES{scenario_count}"))
2121
try:
2222
fname = datadir + os.sep + scenario_name + ".dat"
23-
except:
23+
except Exception:
2424
print("FAIL: datadir=", datadir, " scenario_name=", scenario_name)
2525

2626
model = ref.model.create_instance(fname)
@@ -57,7 +57,7 @@ def inparser_adder(cfg):
5757
def kw_creator(cfg):
5858
# (for Amalgamator): linked to the scenario_creator and inparser_adder
5959
if cfg.num_scens not in (3, 10):
60-
raise RuntimeError(f"num_scen must the 3 or 10; was {num_scen}")
60+
raise RuntimeError(f"num_scen must the 3 or 10; was {cfg.num_scen}")
6161
kwargs = {"scenario_count": cfg.num_scens}
6262
return kwargs
6363

examples/sizes/sizes_demo.py

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from mpisppy.extensions.extension import MultiExtension
1717
from mpisppy.extensions.fixer import Fixer
1818
from mpisppy.extensions.mipgapper import Gapper
19+
from mpisppy.extensions.avgminmaxer import MinMaxAvg
1920
from mpisppy.extensions.wtracker_extension import Wtracker_extension
2021
from sizes import scenario_creator, \
2122
scenario_denouement, \

examples/sizes/sizes_ef.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@
2525
scenario_creator,
2626
scenario_creator_kwargs={"scenario_count": ScenCount},
2727
)
28-
if 'persistent' in options["solver_name"]:
28+
if 'persistent' in solver.name:
2929
solver.set_instance(ef, symbolic_solver_labels=True)
3030
solver.options["mipgap"] = 0.0001
31-
results = solver.solve(ef, tee=options["verbose"])
32-
print('EF objective value:', pyo.value(ef.EF_Obj))
31+
results = solver.solve(ef, tee=True)
32+
print('EF objective value:', pyo.value(ef.EF_Obj))

0 commit comments

Comments
 (0)