Modify an existing constraintΒΆ

This notebook demonstrates how to edit an existing constraint, in this case to add subsidies to the cost function. All constraints in the base model can be found on ReadTheDocs.

[ ]:
from pyehub.energy_hub.ehub_model import EHubModel
from pyehub.energy_hub.utils import constraint
from pyehub.outputter import pretty_print

calc_total_cost(self) is an existing constraint in the base Energy Hub model. We show how to incorporate a subsidy in this calculation.

First we define a new class MyModel which extends the parent class EHubModel and: + Gets the original cost function to get the total cost. + Calculates the subsidy based on the different technologies. + Adds the subsidy to the previously estabilished total cost.

[ ]:
class MyModel(
    EHubModel
):  # inherit the `EHubModel` model class which defines all the governing constraints of the base Energy Hub model
    @constraint()  # @ is important while defining the constraint.
    def calc_total_cost(self):
        """Calculate a new total cost that allows for subsidies."""
        # This gets the constraint object from the parent class's
        # `calc_total_cost`. If this function has arguments, you should
        # pass in the arguments from the arguments of this new function.
        parent_constraint = super().calc_total_cost()

        # Now that we have the constraint, we also need to know how the
        # constraint is structured. Is the LHS of the constraint the calculated
        # total cost or is it the RHS? The only way to know is to look at the
        # parent class's source code for `calc_total_cost`.
        #
        # In our case, the RHS is the calculated total cost.
        old_total_cost = parent_constraint.rhs

        # Now we calculate the total income we get from the subsidies. In this
        # case we assume that we get $1000 for each converter we use.
        # We slice the technologies list starting from index 1 since index 0 is 'Grid' which isn't subsidized
        total_subsidy = sum(
            1000 * self.is_installed[tech] for tech in self.technologies[1:]
        )

        # Now we return the new calculated total cost
        return self.total_cost == old_total_cost - total_subsidy

Now we load and run a model.

[ ]:
excel_file = "test_file_all_constraints_work.xlsx"  # name of the excel file. [This must be in the current directory]
my_model = MyModel(
    excel=excel_file
)  # instantiate our model. Nothing is solved at this point.
results = my_model.solve()  # solve the model and get back our results
pretty_print(results)  # print the results to the console
[ ]: