How to run models in a Python script

In most circumstances, code involving WaterTAP models should run without issues in any way Python code can normally be run (assuming that the installation procedure has been completed successfully).

However, when writing a script, it is recommended (and in some cases, required; see below for details) to structure the script in the following way:

  1. Start from an empty Python source file, e.g.

  2. At the beginning of the file, in the global scope, define the imports for external modules (and, if applicable, other externally defined objects). In this context, defining something at the global scope means that it is written at the leftmost level of the Python file, i.e. without any indentation.

    import pyomo.environ as pyo
    import idaes
    from pyomo.contrib.pynumero.interfaces.pyomo_nlp import PyomoNLP
  3. Next, also in the global scope, add any constants, functions, and/or classes:

    def my_function():
        return 42
  4. Next, define a function (typically called main()), where all other code (creating a model, variable, model initialization, solve, …) will be defined.

    def main():
        m = pyo.ConcreteModel()
        m.x = pyo.Var()
        m.c = pyo.Constraint(expr=(0, m.x, 1))
        m.o = pyo.Objective(expr=m.x)
        nlp = PyomoNLP(m)
  5. At the end of the file, add the following code snippet. This will cause the main() function to be called only when the Python file is invoked directly:

    if __name__ == "__main__":
  6. Finally, save and run the Python file: