Skip to content

Commit 6c877b4

Browse files
ewu63marcomanganokanekosh
authored
Cleanup error class (#436)
* use builtin Error classes * finish removing Error * format? --------- Co-authored-by: Marco Mangano <[email protected]> Co-authored-by: Shugo Kaneko <[email protected]>
1 parent 6fc5a16 commit 6c877b4

File tree

14 files changed

+87
-121
lines changed

14 files changed

+87
-121
lines changed

pyoptsparse/pyALPSO/pyALPSO.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212

1313
# Local modules
1414
from . import alpso
15-
from ..pyOpt_error import Error
1615
from ..pyOpt_optimizer import Optimizer
1716

1817
# isort: off
@@ -161,10 +160,10 @@ def objconfunc(x):
161160
self.setOption("minInnerIter", opt("maxInnerIter"))
162161

163162
if opt("stopCriteria") not in [0, 1]:
164-
raise Error("Incorrect Stopping Criteria Setting")
163+
raise ValueError("Incorrect Stopping Criteria Setting")
165164

166165
if opt("fileout") not in [0, 1, 2, 3]:
167-
raise Error("Incorrect fileout Setting")
166+
raise ValueError("Incorrect fileout Setting")
168167

169168
# Run ALPSO
170169
t0 = time.time()

pyoptsparse/pyCONMIN/pyCONMIN.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import numpy as np
1313

1414
# Local modules
15-
from ..pyOpt_error import Error
1615
from ..pyOpt_optimizer import Optimizer
1716
from ..pyOpt_utils import try_import_compiled_module_from_path
1817

@@ -194,7 +193,7 @@ def cnmngrad(n1, n2, x, f, g, ct, df, a, ic, nac):
194193
if self.getOption("IPRINT") >= 0 and self.getOption("IPRINT") <= 4:
195194
iprint = self.getOption("IPRINT")
196195
else:
197-
raise Error("IPRINT option must be >= 0 and <= 4")
196+
raise ValueError("IPRINT option must be >= 0 and <= 4")
198197

199198
iout = self.getOption("IOUT")
200199
ifile = self.getOption("IFILE")

pyoptsparse/pyNLPQLP/pyNLPQLP.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
pyNLPQLP - A pyOptSparse wrapper for Schittkowski's NLPQLP
33
optimization algorithm.
44
"""
5+
56
# Standard Python modules
67
import datetime
78
import os
@@ -11,7 +12,6 @@
1112
import numpy as np
1213

1314
# Local modules
14-
from ..pyOpt_error import Error
1515
from ..pyOpt_optimizer import Optimizer
1616
from ..pyOpt_utils import try_import_compiled_module_from_path
1717

@@ -225,10 +225,10 @@ def nlgrad(m, me, mmax, n, f, g, df, dg, x, active, wa):
225225
d = np.zeros(nmax)
226226
go = self.getOption
227227
if go("iPrint") < 0 or go("iPrint") > 4:
228-
raise Error("Incorrect iPrint option. Must be >=0 and <= 4")
228+
raise ValueError("Incorrect iPrint option. Must be >=0 and <= 4")
229229

230230
if not (go("mode") >= 0 and go("mode") <= 18):
231-
raise Error("Incorrect mode option. Must be >= 0 and <= 18.")
231+
raise ValueError("Incorrect mode option. Must be >= 0 and <= 18.")
232232

233233
if os.path.isfile(go("iFile")):
234234
os.remove(go("iFile"))

pyoptsparse/pyNSGA2/pyNSGA2.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import numpy as np
1212

1313
# Local modules
14-
from ..pyOpt_error import Error
1514
from ..pyOpt_optimizer import Optimizer
1615
from ..pyOpt_utils import try_import_compiled_module_from_path
1716

@@ -161,7 +160,7 @@ def objconfunc(nreal, nobj, ncon, x, f, g):
161160
if self.getOption("PrintOut") >= 0 and self.getOption("PrintOut") <= 2:
162161
printout = self.getOption("PrintOut")
163162
else:
164-
raise Error("Incorrect option PrintOut")
163+
raise ValueError("Incorrect option PrintOut")
165164

166165
seed = self.getOption("seed")
167166
if seed == 0:

pyoptsparse/pyOpt_constraint.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import numpy as np
88

99
# Local modules
10-
from .pyOpt_error import Error, pyOptSparseWarning
10+
from .pyOpt_error import pyOptSparseWarning
1111
from .pyOpt_types import Dict1DType
1212
from .pyOpt_utils import INFINITY, _broadcast_to_array, convertToCOO
1313

@@ -204,7 +204,7 @@ def finalize(self, variables: OrderedDict, dvOffset, index: int):
204204
try:
205205
self.wrt = list(self.wrt)
206206
except Exception:
207-
raise Error(f"The 'wrt' argument to constraint '{self.name}' must be an iterable list")
207+
raise TypeError(f"The 'wrt' argument to constraint '{self.name}' must be an iterable list")
208208

209209
# We allow 'None' to be in the list...they are null so
210210
# just pop them out:
@@ -214,7 +214,7 @@ def finalize(self, variables: OrderedDict, dvOffset, index: int):
214214
# *actually* are variables
215215
for dvGroup in self.wrt:
216216
if dvGroup not in variables:
217-
raise Error(
217+
raise KeyError(
218218
f"The supplied dvGroup '{dvGroup}' in 'wrt' for the {self.name} constraint, does not exist. "
219219
+ "It must be added with a call to addVar() or addVarGroup()."
220220
)
@@ -254,7 +254,7 @@ def finalize(self, variables: OrderedDict, dvOffset, index: int):
254254
# sparse constraints.
255255

256256
if self.linear:
257-
raise Error(
257+
raise ValueError(
258258
"The 'jac' keyword to argument to addConGroup() must be supplied for a linear constraint. "
259259
+ f"The constraint in error is {self.name}."
260260
)
@@ -274,7 +274,7 @@ def finalize(self, variables: OrderedDict, dvOffset, index: int):
274274
else:
275275
# First sanitize input:
276276
if not isinstance(self.jac, dict):
277-
raise Error(
277+
raise TypeError(
278278
"The 'jac' keyword argument to addConGroup() must be a dictionary. "
279279
+ f"The constraint in error is {self.name}."
280280
)
@@ -301,7 +301,7 @@ def finalize(self, variables: OrderedDict, dvOffset, index: int):
301301

302302
# Generically check the shape:
303303
if self.jac[dvGroup]["shape"][0] != self.ncon or self.jac[dvGroup]["shape"][1] != ndvs:
304-
raise Error(
304+
raise ValueError(
305305
f"The supplied Jacobian for dvGroup {dvGroup}' in constraint {self.name}, was the incorrect size. "
306306
+ f"Expecting a Jacobian of size ({self.ncon}, {ndvs}) but received a Jacobian of size "
307307
+ f"({self.jac[dvGroup]['shape'][0]}, {self.jac[dvGroup]['shape'][1]})."

pyoptsparse/pyOpt_error.py

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,6 @@
55
"""
66

77

8-
class Error(Exception):
9-
"""
10-
Format the error message in a box to make it clear this
11-
was a expliclty raised exception.
12-
"""
13-
14-
def __init__(self, message):
15-
msg = "\n+" + "-" * 78 + "+" + "\n" + "| pyOptSparse Error: "
16-
i = 21
17-
for word in message.split():
18-
if len(word) + i + 1 > 78: # Finish line and start new one
19-
msg += " " * (79 - i) + "|\n| " + word + " "
20-
i = 2 + len(word) + 1
21-
else:
22-
msg += word + " "
23-
i += len(word) + 1
24-
msg += " " * (79 - i) + "|\n" + "+" + "-" * 78 + "+" + "\n"
25-
print(msg)
26-
self.message = message
27-
super().__init__(message)
28-
29-
def __str__(self):
30-
return self.message
31-
32-
338
class pyOptSparseWarning:
349
"""
3510
Format a warning message

pyoptsparse/pyOpt_history.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from sqlitedict import SqliteDict
99

1010
# Local modules
11-
from .pyOpt_error import Error, pyOptSparseWarning
11+
from .pyOpt_error import pyOptSparseWarning
1212
from .pyOpt_utils import EPS
1313

1414

@@ -53,7 +53,7 @@ def __init__(self, fileName, optProb=None, temp=False, flag="r"):
5353
)
5454
self._processDB()
5555
else:
56-
raise Error("The flag argument to History must be 'r' or 'n'.")
56+
raise ValueError("The flag argument to History must be 'r' or 'n'.")
5757
self.temp = temp
5858
self.fileName = fileName
5959

@@ -578,7 +578,7 @@ def getValues(self, names=None, callCounters=None, major=True, scale=False, stac
578578
allNames.add("xuser")
579579
# error if names isn't either a DV, con or obj
580580
if not names.issubset(allNames):
581-
raise Error(
581+
raise KeyError(
582582
"The names provided are not one of DVNames, conNames or objNames.\n"
583583
+ f"The names must be a subset of {allNames}"
584584
)

pyoptsparse/pyOpt_optimization.py

Lines changed: 31 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@
1313
# Local modules
1414
from .pyOpt_MPI import MPI
1515
from .pyOpt_constraint import Constraint
16-
from .pyOpt_error import Error
1716
from .pyOpt_objective import Objective
1817
from .pyOpt_types import Dict1DType, Dict2DType, NumpyType
1918
from .pyOpt_utils import (
@@ -232,13 +231,13 @@ def addVarGroup(
232231
self.finalized = False
233232
# Check that the nVars is > 0.
234233
if nVars < 1:
235-
raise Error(
234+
raise ValueError(
236235
f"The 'nVars' argument to addVarGroup must be greater than or equal to 1. The bad DV is {name}."
237236
)
238237

239238
# Check that the type is ok
240239
if varType not in ["c", "i", "d"]:
241-
raise Error("Type must be one of 'c' for continuous, 'i' for integer or 'd' for discrete.")
240+
raise ValueError("Type must be one of 'c' for continuous, 'i' for integer or 'd' for discrete.")
242241

243242
value = _broadcast_to_array("value", value, nVars)
244243
lower = _broadcast_to_array("lower", lower, nVars, allow_none=True)
@@ -270,10 +269,10 @@ def addVarGroup(
270269
if name in self.variables:
271270
# Check that the variables happen to be the same
272271
if not len(self.variables[name]) == len(varList):
273-
raise Error(f"The supplied name '{name}' for a variable group has already been used!")
272+
raise KeyError(f"The supplied name '{name}' for a variable group has already been used!")
274273
for i in range(len(varList)):
275274
if not varList[i] == self.variables[name][i]:
276-
raise Error(f"The supplied name '{name}' for a variable group has already been used!")
275+
raise KeyError(f"The supplied name '{name}' for a variable group has already been used!")
277276
# We we got here, we know that the variables we wanted to
278277
# add are **EXACTLY** the same so that's cool. We'll just
279278
# overwrite with the varList below.
@@ -459,7 +458,7 @@ def addConGroup(
459458
"""
460459
self.finalized = False
461460
if name in self.constraints:
462-
raise Error(f"The supplied name '{name}' for a constraint group has already been used.")
461+
raise KeyError(f"The supplied name '{name}' for a constraint group has already been used.")
463462

464463
# Simply add constraint object
465464
self.constraints[name] = Constraint(name, nCon, linear, wrt, jac, lower, upper, scale)
@@ -550,7 +549,7 @@ def setDVsFromHistory(self, histFile, key=None):
550549
self.setDVs(hist[key]["xuser"])
551550
hist.close()
552551
else:
553-
raise Error(f"History file '{histFile}' not found!.")
552+
raise FileNotFoundError(f"History file '{histFile}' not found!.")
554553

555554
def printSparsity(self, verticalPrint=False):
556555
"""
@@ -1016,10 +1015,10 @@ def processXtoDict(self, x: ndarray) -> OrderedDict:
10161015
xg[dvGroup] = x[..., istart]
10171016
else:
10181017
xg[dvGroup] = x[..., istart:iend].copy()
1019-
except IndexError:
1020-
raise Error("Error processing x. There is a mismatch in the number of variables.")
1018+
except IndexError as e:
1019+
raise ValueError("Error processing x. There is a mismatch in the number of variables.") from e
10211020
if imax != self.ndvs:
1022-
raise Error("Error processing x. There is a mismatch in the number of variables.")
1021+
raise ValueError("Error processing x. There is a mismatch in the number of variables.")
10231022
return xg
10241023

10251024
def processXtoVec(self, x: dict) -> ndarray:
@@ -1053,10 +1052,10 @@ def processXtoVec(self, x: dict) -> ndarray:
10531052
x_array[..., istart] = x[dvGroup]
10541053
else:
10551054
x_array[..., istart:iend] = x[dvGroup]
1056-
except IndexError:
1057-
raise Error("Error deprocessing x. There is a mismatch in the number of variables.")
1055+
except IndexError as e:
1056+
raise ValueError("Error deprocessing x. There is a mismatch in the number of variables.") from e
10581057
if imax != self.ndvs:
1059-
raise Error("Error deprocessing x. There is a mismatch in the number of variables.")
1058+
raise ValueError("Error deprocessing x. There is a mismatch in the number of variables.")
10601059

10611060
return x_array
10621061

@@ -1084,13 +1083,13 @@ def processObjtoVec(self, funcs: Dict1DType, scaled: bool = True) -> NumpyType:
10841083
if objKey in funcs:
10851084
try:
10861085
f = np.squeeze(funcs[objKey]).item()
1087-
except ValueError:
1088-
raise Error(f"The objective return value, '{objKey}' must be a scalar!")
1086+
except ValueError as e:
1087+
raise ValueError(f"The objective return value, '{objKey}' must be a scalar!") from e
10891088
# Store objective for printing later
10901089
self.objectives[objKey].value = np.real(f)
10911090
fobj.append(f)
10921091
else:
1093-
raise Error(f"The key for the objective, '{objKey}' was not found.")
1092+
raise KeyError(f"The key for the objective, '{objKey}' was not found.")
10941093

10951094
# scale the objective
10961095
if scaled:
@@ -1124,8 +1123,8 @@ def processObjtoDict(self, fobj_in: NumpyType, scaled: bool = True) -> Dict1DTyp
11241123
iObj = self.objectiveIdx[objKey]
11251124
try:
11261125
fobj[objKey] = fobj_in[iObj]
1127-
except IndexError:
1128-
raise Error("The input array shape is incorrect!")
1126+
except IndexError as e:
1127+
raise ValueError("The input array shape is incorrect!") from e
11291128
if scaled:
11301129
fobj = self._mapObjtoOpt(fobj)
11311130
return fobj
@@ -1177,15 +1176,15 @@ def processContoVec(
11771176
if c.shape[-1] == self.constraints[iCon].ncon:
11781177
fcon[..., con.rs : con.re] = c
11791178
else:
1180-
raise Error(
1179+
raise ValueError(
11811180
f"{len(fcon_in[iCon])} constraint values were returned in {iCon}, "
11821181
+ f"but expected {self.constraints[iCon].ncon}."
11831182
)
11841183

11851184
# Store constraint values for printing later
11861185
con.value = np.real(copy.copy(c))
11871186
else:
1188-
raise Error(f"No constraint values were found for the constraint '{iCon}'.")
1187+
raise KeyError(f"No constraint values were found for the constraint '{iCon}'.")
11891188

11901189
# Perform scaling on the original Jacobian:
11911190
if scaled:
@@ -1330,14 +1329,14 @@ def processObjectiveGradient(self, funcsSens: Dict2DType) -> NumpyType:
13301329
# Everything checks out so set:
13311330
gobj[iObj, ss[0] : ss[1]] = tmp
13321331
else:
1333-
raise Error(
1332+
raise ValueError(
13341333
f"The shape of the objective derivative for dvGroup '{dvGroup}' is the incorrect length. "
13351334
+ f"Expecting a shape of {(ss[1] - ss[0],)} but received a shape of {funcsSens[objKey][dvGroup].shape}."
13361335
)
13371336
else:
1338-
raise Error(f"The dvGroup key '{dvGroup}' is not valid")
1337+
raise KeyError(f"The dvGroup key '{dvGroup}' is not valid")
13391338
else:
1340-
raise Error(f"The key for the objective gradient, '{objKey}', was not found.")
1339+
raise KeyError(f"The key for the objective gradient, '{objKey}', was not found.")
13411340
iObj += 1
13421341

13431342
# Note that we looped over the keys in funcsSens[objKey]
@@ -1420,21 +1419,20 @@ def processConstraintJacobian(self, gcon):
14201419
ndvs = ss[1] - ss[0]
14211420

14221421
gotDerivative = False
1423-
try:
1424-
if dvGroup in gcon[iCon]:
1425-
tmp = convertToCOO(gcon[iCon][dvGroup])
1426-
gotDerivative = True
1427-
except KeyError:
1428-
raise Error(
1422+
if dvGroup in gcon[iCon]:
1423+
tmp = convertToCOO(gcon[iCon][dvGroup])
1424+
gotDerivative = True
1425+
else:
1426+
raise KeyError(
14291427
f"The constraint Jacobian entry for '{con.name}' with respect to '{dvGroup}', "
14301428
+ "as was defined in addConGroup(), was not found in constraint Jacobian dictionary provided."
14311429
)
14321430
if not gotDerivative:
14331431
# All keys for this constraint must be returned
14341432
# since the user has explicitly specified the wrt.
14351433
if not con.partialReturnOk:
1436-
raise Error(
1437-
f"Constraint '{con.name}' was expecting a jacobain with respect to dvGroup "
1434+
raise ValueError(
1435+
f"Constraint '{con.name}' was expecting a Jacobian with respect to dvGroup "
14381436
+ f"'{dvGroup}' as was supplied in addConGroup(). "
14391437
+ "This was not found in the constraint Jacobian dictionary"
14401438
)
@@ -1445,15 +1443,15 @@ def processConstraintJacobian(self, gcon):
14451443

14461444
# Now check that the Jacobian is the correct shape
14471445
if not (tmp["shape"][0] == con.ncon and tmp["shape"][1] == ndvs):
1448-
raise Error(
1446+
raise ValueError(
14491447
f"The shape of the supplied constraint Jacobian for constraint {con.name} with respect to {dvGroup} is incorrect. "
14501448
+ f"Expected an array of shape ({con.ncon}, {ndvs}), but received an array of shape ({tmp['shape'][0]}, {tmp['shape'][1]})."
14511449
)
14521450

14531451
# Now check that supplied coo matrix has same length
14541452
# of data array
14551453
if len(tmp["coo"][2]) != len(con.jac[dvGroup]["coo"][2]):
1456-
raise Error(
1454+
raise ValueError(
14571455
f"The number of nonzero elements for constraint group '{con.name}' with respect to {dvGroup} was not the correct size. "
14581456
+ f"The supplied Jacobian has {len(tmp['coo'][2])} nonzero entries, but must contain {len(con.jac[dvGroup]['coo'][2])} nonzero entries."
14591457
)

0 commit comments

Comments
 (0)