Skip to content

Commit

Permalink
fix pylint errors
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelbynum committed Apr 24, 2024
1 parent 23061a1 commit 3d56508
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 14 deletions.
3 changes: 3 additions & 0 deletions idaes/apps/flexibility_analysis/decision_rules/dr_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
# All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md
# for full copyright and license information.
#################################################################################
"""
This module defines a config for specifying options related to decision rules
"""
from pyomo.common.config import ConfigDict


Expand Down
8 changes: 8 additions & 0 deletions idaes/apps/flexibility_analysis/decision_rules/dr_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@
# All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md
# for full copyright and license information.
#################################################################################
"""
This module defines an enum for specifying the type of decision rule when a
decision rule is used.
"""
import enum


class DecisionRuleTypes(enum.Enum):
"""
An enum to specify the type of decision rule to use.
"""

linear = enum.auto()
relu_nn = enum.auto()
34 changes: 28 additions & 6 deletions idaes/apps/flexibility_analysis/decision_rules/linear_dr.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,17 @@
# All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md
# for full copyright and license information.
#################################################################################
import pyomo.environ as pe
"""
This module contains a function for constructing a linear decision rule for
the inner problem of the flexibility test.
"""
from typing import MutableMapping, Sequence
from pyomo.core.base.var import _GeneralVarData
import pyomo.environ as pe
from pyomo.core.base.var import _GeneralVarData, ScalarVar, IndexedVar
from pyomo.core.base.block import _BlockData
from pyomo.core.expr.numeric_expr import LinearExpression
from .dr_config import DRConfig
from pyomo.common.config import ConfigValue
from .dr_config import DRConfig
from ..check_optimal import assert_optimal_termination


Expand Down Expand Up @@ -56,6 +60,24 @@ def construct_linear_decision_rule(
output_vals: MutableMapping[_GeneralVarData, Sequence[float]],
config: LinearDRConfig,
) -> _BlockData:
"""
Construct a linear decision rule from the data provided for the inputs
and outputs.
Parameters
----------
input_vals: input_vals: MutableMapping[_GeneralVarData, Sequence[float]]
Data for the variables that are inputs to the decision rule
output_vals: input_vals: MutableMapping[_GeneralVarData, Sequence[float]]
Data for the variables that are outputs to the decision rule
config: LinearDRConfig
A config object to specify options for the decision rule
Returns
-------
res: _BlockData
A pyomo model containing the linear decision rule
"""
n_inputs = len(input_vals)
n_outputs = len(output_vals)

Expand All @@ -70,9 +92,9 @@ def construct_linear_decision_rule(
trainer.input_set = pe.Set(initialize=list(range(n_inputs)))
trainer.sample_set = pe.Set(initialize=list(range(n_samples)))

trainer.const = pe.Var()
trainer.coefs = pe.Var(trainer.input_set)
trainer.out_est = pe.Var(trainer.sample_set)
trainer.const = ScalarVar()
trainer.coefs = IndexedVar(trainer.input_set)
trainer.out_est = IndexedVar(trainer.sample_set)

obj_expr = sum(
(trainer.out_est[i] - out_samples[i]) ** 2 for i in trainer.sample_set
Expand Down
33 changes: 27 additions & 6 deletions idaes/apps/flexibility_analysis/decision_rules/relu_dr.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,16 @@
# All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md
# for full copyright and license information.
#################################################################################
"""
This module contains a function for constructing a neural network-based decision
rule for the inner problem of the flexibility test.
"""
from typing import MutableMapping, Sequence
import numpy as np
from pyomo.common.dependencies import attempt_import
import pyomo.environ as pe
from pyomo.core.base.var import _GeneralVarData
from pyomo.core.base.block import _BlockData
from typing import MutableMapping, Sequence
from idaes.apps.flexibility_analysis.indices import _VarIndex
from .relu_dr_config import ReluDRConfig

Expand All @@ -24,13 +28,32 @@
omlt, omlt_available = attempt_import("omlt")
omlt_nn, _ = attempt_import("omlt.neuralnet")
omlt_io, _ = attempt_import("omlt.io")
plt, _ = attempt_import("matplotlib.pyplot")


def construct_relu_decision_rule(
input_vals: MutableMapping[_GeneralVarData, Sequence[float]],
output_vals: MutableMapping[_GeneralVarData, Sequence[float]],
config: ReluDRConfig,
) -> _BlockData:
"""
Construct a neural network-based decision rule with ReLU activation functions
from the data provided for the inputs and outputs.
Parameters
----------
input_vals: input_vals: MutableMapping[_GeneralVarData, Sequence[float]]
Data for the variables that are inputs to the decision rule
output_vals: input_vals: MutableMapping[_GeneralVarData, Sequence[float]]
Data for the variables that are outputs to the decision rule
config: ReluDRConfig
A config object to specify options for the decision rule
Returns
-------
res: _BlockData
A pyomo model containing the linear decision rule
"""
tf.random.set_seed(config.tensorflow_seed)
inputs = list(input_vals.keys())
outputs = list(output_vals.keys())
Expand Down Expand Up @@ -76,7 +99,7 @@ def construct_relu_decision_rule(
units=config.n_nodes_per_layer, input_dim=len(inputs), activation="relu"
)
)
for layer_ndx in range(config.n_layers - 1):
for _ in range(config.n_layers - 1):
nn.add(keras.layers.Dense(config.n_nodes_per_layer, activation="relu"))
nn.add(keras.layers.Dense(len(outputs)))
if config.learning_rate is None:
Expand All @@ -93,8 +116,6 @@ def construct_relu_decision_rule(
)

if config.plot_history:
import matplotlib.pyplot as plt

plt.scatter(history.epoch, history.history["loss"])
plt.xlabel("Epoch")
plt.ylabel("Loss")
Expand Down Expand Up @@ -126,14 +147,14 @@ def construct_relu_decision_rule(
res.input_links = pe.Constraint(res.input_set)
for ndx, v in enumerate(inputs):
key = _VarIndex(v, None)
res.input_set.add(key)
res.input_set.add(key) # pylint: disable=no-member
res.input_links[key] = v == res.nn.inputs[ndx]

res.output_set = pe.Set()
res.output_links = pe.Constraint(res.output_set)
for ndx, v in enumerate(outputs):
key = _VarIndex(v, None)
res.output_set.add(key)
res.output_set.add(key) # pylint: disable=no-member
res.output_links[key] = v == res.nn.outputs[ndx]

return res
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@
# All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md
# for full copyright and license information.
#################################################################################
from .dr_config import DRConfig
"""
This module defines a config for specifying options related to neural network-based
decision rules
"""
from pyomo.common.config import ConfigValue
from .dr_config import DRConfig


class ReluDRConfig(DRConfig):
Expand Down
21 changes: 20 additions & 1 deletion idaes/apps/flexibility_analysis/examples/nonlin_hx_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,18 @@
# All rights reserved. Please see the files COPYRIGHT.md and LICENSE.md
# for full copyright and license information.
#################################################################################
"""
A flexibility analysis example from
Grossmann, I. E., & Floudas, C. A. (1987). Active constraint strategy for
flexibility analysis in chemical processes. Computers & Chemical Engineering,
11(6), 675-693.
"""
from typing import Tuple, MutableMapping
import pyomo.environ as pe
from pyomo.core.base.block import _BlockData
from pyomo.core.base.param import _ParamData
import idaes.apps.flexibility_analysis as flexibility
from typing import Tuple, MutableMapping


def create_model() -> Tuple[
Expand Down Expand Up @@ -57,12 +64,24 @@ def create_model() -> Tuple[


def get_var_bounds(m):
"""
Generate a map with valid variable bounds for
any possible realization of the uncertain parameters
"""
res = pe.ComponentMap()
res[m.qc] = (-1000, 1000)
return res


def main(method):
"""
Run the example
Parameters
----------
method: flexibility.FlexTestMethod
The method to use for the flexibility test
"""
m, nominal_values, param_bounds = create_model()
var_bounds = get_var_bounds(m)
config = flexibility.FlexTestConfig()
Expand Down

0 comments on commit 3d56508

Please sign in to comment.