iesopt 1.0.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- iesopt-1.0.0/LICENSE +21 -0
- iesopt-1.0.0/PKG-INFO +55 -0
- iesopt-1.0.0/README.md +23 -0
- iesopt-1.0.0/pyproject.toml +78 -0
- iesopt-1.0.0/src/iesopt/__init__.py +74 -0
- iesopt-1.0.0/src/iesopt/general.py +0 -0
- iesopt-1.0.0/src/iesopt/iesopt.py +109 -0
- iesopt-1.0.0/src/iesopt/julia/__init__.py +2 -0
- iesopt-1.0.0/src/iesopt/julia/general.py +53 -0
- iesopt-1.0.0/src/iesopt/julia/setup.py +41 -0
- iesopt-1.0.0/src/iesopt/julia/util.py +59 -0
- iesopt-1.0.0/src/iesopt/juliapkg.json +21 -0
- iesopt-1.0.0/src/iesopt/model.py +202 -0
- iesopt-1.0.0/src/iesopt/results.py +364 -0
- iesopt-1.0.0/src/iesopt/util/__init__.py +5 -0
- iesopt-1.0.0/src/iesopt/util/constants.py +0 -0
- iesopt-1.0.0/src/iesopt/util/logging.py +11 -0
- iesopt-1.0.0/src/iesopt/util/util.py +11 -0
iesopt-1.0.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) AIT Austrian Institute of Technology GmbH
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
iesopt-1.0.0/PKG-INFO
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: iesopt
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: IESopt -- an Integrated Energy System Optimization framework.
|
|
5
|
+
Home-page: https://github.com/ait-energy/iesopt
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: integrated energy systems,optimization,energy model,modelling
|
|
8
|
+
Author: Stefan Strömer
|
|
9
|
+
Author-email: 8915976+sstroemer@users.noreply.github.com
|
|
10
|
+
Maintainer: Stefan Strömer
|
|
11
|
+
Maintainer-email: 8915976+sstroemer@users.noreply.github.com
|
|
12
|
+
Requires-Python: >=3.11,<4.0
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Science/Research
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Requires-Dist: juliacall (>=0.9.20,<0.10.0)
|
|
21
|
+
Requires-Dist: juliapkg (>=0.1.13,<0.2.0)
|
|
22
|
+
Requires-Dist: pandas (>=2.0.0,<3.0.0)
|
|
23
|
+
Requires-Dist: pathlib (>=1.0.0,<2.0.0)
|
|
24
|
+
Requires-Dist: pydantic (>=2.7.4,<3.0.0)
|
|
25
|
+
Requires-Dist: pytest-ruff (>=0.3.2,<0.4.0)
|
|
26
|
+
Project-URL: Changelog, https://github.com/ait-energy/iesopt/blob/main/CHANGELOG.md
|
|
27
|
+
Project-URL: Documentation, https://ait-energy.github.io/iesopt
|
|
28
|
+
Project-URL: Issues, https://github.com/ait-energy/iesopt/issues
|
|
29
|
+
Project-URL: Repository, https://github.com/ait-energy/iesopt
|
|
30
|
+
Description-Content-Type: text/markdown
|
|
31
|
+
|
|
32
|
+
# IESopt: Integrated Energy System Optimization
|
|
33
|
+
|
|
34
|
+
[](https://pypi.org/project/iesopt/)
|
|
35
|
+
[](https://ait-energy.github.io/iesopt/)
|
|
36
|
+
[](LICENSE)
|
|
37
|
+
|
|
38
|
+
[](https://github.com/ait-energy/iesopt/actions/workflows/pytest.yml?query=branch%3Amain)
|
|
39
|
+
[](https://codecov.io/gh/ait-energy/iesopt)
|
|
40
|
+
[](https://github.com/psf/black)
|
|
41
|
+
|
|
42
|
+
**IESopt** (_Integrated Energy System Optimization_) is a modeling and optimization framework for integrated energy
|
|
43
|
+
systems.
|
|
44
|
+
|
|
45
|
+
> Note: We are currently moving from our internal version control to GitHub. Missing contents will be added during the
|
|
46
|
+
> upcoming days ...
|
|
47
|
+
|
|
48
|
+
It is developed and maintained at the **Center for Energy** at
|
|
49
|
+
[AIT Austrian Institute of Technology GmbH](https://www.ait.ac.at/). The framework is designed to support the
|
|
50
|
+
optimization of energy systems that are characterized by a high degree of integration between different energy carriers
|
|
51
|
+
and sectors. It focuses on offering a modular and adaptable tool for modelers, that does not compromise on performance,
|
|
52
|
+
while still being user-friendly. This is enabled by reducing energy system assets to abstract building blocks, that are
|
|
53
|
+
supported by specialized implementation, and can be combined into complex systems without the need of a detailed
|
|
54
|
+
understanding of mathematical modeling or proficiency in any coding-language.
|
|
55
|
+
|
iesopt-1.0.0/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# IESopt: Integrated Energy System Optimization
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/iesopt/)
|
|
4
|
+
[](https://ait-energy.github.io/iesopt/)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
[](https://github.com/ait-energy/iesopt/actions/workflows/pytest.yml?query=branch%3Amain)
|
|
8
|
+
[](https://codecov.io/gh/ait-energy/iesopt)
|
|
9
|
+
[](https://github.com/psf/black)
|
|
10
|
+
|
|
11
|
+
**IESopt** (_Integrated Energy System Optimization_) is a modeling and optimization framework for integrated energy
|
|
12
|
+
systems.
|
|
13
|
+
|
|
14
|
+
> Note: We are currently moving from our internal version control to GitHub. Missing contents will be added during the
|
|
15
|
+
> upcoming days ...
|
|
16
|
+
|
|
17
|
+
It is developed and maintained at the **Center for Energy** at
|
|
18
|
+
[AIT Austrian Institute of Technology GmbH](https://www.ait.ac.at/). The framework is designed to support the
|
|
19
|
+
optimization of energy systems that are characterized by a high degree of integration between different energy carriers
|
|
20
|
+
and sectors. It focuses on offering a modular and adaptable tool for modelers, that does not compromise on performance,
|
|
21
|
+
while still being user-friendly. This is enabled by reducing energy system assets to abstract building blocks, that are
|
|
22
|
+
supported by specialized implementation, and can be combined into complex systems without the need of a detailed
|
|
23
|
+
understanding of mathematical modeling or proficiency in any coding-language.
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["poetry-core"]
|
|
3
|
+
build-backend = "poetry.core.masonry.api"
|
|
4
|
+
|
|
5
|
+
[tool.poetry]
|
|
6
|
+
name = "iesopt"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "IESopt -- an Integrated Energy System Optimization framework."
|
|
9
|
+
keywords = ["integrated energy systems", "optimization", "energy model", "modelling"]
|
|
10
|
+
authors = [
|
|
11
|
+
"Stefan Strömer <8915976+sstroemer@users.noreply.github.com>",
|
|
12
|
+
]
|
|
13
|
+
maintainers = [
|
|
14
|
+
"Stefan Strömer <8915976+sstroemer@users.noreply.github.com>",
|
|
15
|
+
]
|
|
16
|
+
readme = "README.md"
|
|
17
|
+
license = "MIT"
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 4 - Beta",
|
|
20
|
+
"Intended Audience :: Science/Research",
|
|
21
|
+
"License :: OSI Approved :: MIT License",
|
|
22
|
+
"Programming Language :: Python :: 3.10",
|
|
23
|
+
"Programming Language :: Python :: 3.11",
|
|
24
|
+
"Programming Language :: Python :: 3.12",
|
|
25
|
+
]
|
|
26
|
+
homepage = "https://github.com/ait-energy/iesopt"
|
|
27
|
+
documentation = "https://ait-energy.github.io/iesopt"
|
|
28
|
+
repository = "https://github.com/ait-energy/iesopt"
|
|
29
|
+
|
|
30
|
+
[tool.poetry.urls]
|
|
31
|
+
"Issues" = "https://github.com/ait-energy/iesopt/issues"
|
|
32
|
+
"Changelog" = "https://github.com/ait-energy/iesopt/blob/main/CHANGELOG.md"
|
|
33
|
+
|
|
34
|
+
[tool.poetry.dependencies]
|
|
35
|
+
python = "^3.11"
|
|
36
|
+
pathlib = "^1.0.0"
|
|
37
|
+
juliacall = "^0.9.20"
|
|
38
|
+
pandas = "^2.0.0"
|
|
39
|
+
juliapkg = "^0.1.13"
|
|
40
|
+
pytest-ruff = "^0.3.2"
|
|
41
|
+
pydantic = "^2.7.4"
|
|
42
|
+
|
|
43
|
+
[tool.poetry.group.dev.dependencies]
|
|
44
|
+
ruff = "^0.4.7"
|
|
45
|
+
black = {extras = ["jupyter"], version = "^24.4.2"}
|
|
46
|
+
codespell = "^2.3.0"
|
|
47
|
+
myst-nb = "^1.1.0"
|
|
48
|
+
|
|
49
|
+
[tool.poetry.group.docs.dependencies]
|
|
50
|
+
myst-parser = "^3.0.1"
|
|
51
|
+
sphinx = "^7.3.7"
|
|
52
|
+
sphinxawesome-theme = "^5.2.0"
|
|
53
|
+
sphinx-togglebutton = "^0.3.2"
|
|
54
|
+
ipywidgets = "^8.1.3"
|
|
55
|
+
myst-nb = "^1.1.0"
|
|
56
|
+
|
|
57
|
+
[tool.poetry.group.test.dependencies]
|
|
58
|
+
pytest = "^8.2.2"
|
|
59
|
+
pytest-cov = "^5.0.0"
|
|
60
|
+
|
|
61
|
+
[tool.black]
|
|
62
|
+
line-length = 120
|
|
63
|
+
target-version = ["py311", "py312"]
|
|
64
|
+
|
|
65
|
+
[tool.ruff]
|
|
66
|
+
line-length = 120
|
|
67
|
+
extend-exclude = ["*.jl"]
|
|
68
|
+
target-version = "py311"
|
|
69
|
+
|
|
70
|
+
[tool.pytest.ini_options]
|
|
71
|
+
addopts = [
|
|
72
|
+
"--import-mode=importlib",
|
|
73
|
+
"--ruff",
|
|
74
|
+
"--ruff-format",
|
|
75
|
+
"--cov-report=term",
|
|
76
|
+
"--cov-report=xml:coverage.xml",
|
|
77
|
+
"--cov=iesopt",
|
|
78
|
+
]
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import importlib.metadata
|
|
3
|
+
|
|
4
|
+
# Set version.
|
|
5
|
+
__version__ = importlib.metadata.version("iesopt")
|
|
6
|
+
|
|
7
|
+
# =======================================================================
|
|
8
|
+
# Setup "module globals" that will be overwritten internally.
|
|
9
|
+
julia = None
|
|
10
|
+
"""
|
|
11
|
+
The Julia object, if setup was successful.
|
|
12
|
+
|
|
13
|
+
.. code-block:: python
|
|
14
|
+
:caption: Usage
|
|
15
|
+
|
|
16
|
+
import iesopt
|
|
17
|
+
iesopt.julia.println("Hello, from Julia's world!")
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
Symbol = None
|
|
21
|
+
|
|
22
|
+
IESopt = None
|
|
23
|
+
"""IESopt.jl module from Julia."""
|
|
24
|
+
|
|
25
|
+
JuMP = None
|
|
26
|
+
"""JuMP.jl module from Julia."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def jump_value(item):
|
|
30
|
+
"""Calls `JuMP.value.(item)`."""
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def jump_dual(item):
|
|
35
|
+
"""Calls `JuMP.dual.(item)`."""
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def jump_reduced_cost(item):
|
|
40
|
+
"""Calls `JuMP.reduced_cost.(item)`."""
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def jump_shadow_price(item):
|
|
45
|
+
"""Calls `JuMP.shadow_price.(item)`."""
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# =======================================================================
|
|
50
|
+
|
|
51
|
+
# Setup Julia.
|
|
52
|
+
from .julia import initialize as _initialize_everything # noqa: E402
|
|
53
|
+
from .util import get_iesopt_module_attr as _get_iesopt_module_attr # noqa: E402
|
|
54
|
+
|
|
55
|
+
julia = _initialize_everything()
|
|
56
|
+
|
|
57
|
+
# Export everything.
|
|
58
|
+
from iesopt.model import Model as Model, ModelStatus as ModelStatus # noqa: E402
|
|
59
|
+
from iesopt.results import Results as Results # noqa: E402
|
|
60
|
+
from iesopt.iesopt import run as run, examples as examples, make_example as make_example # noqa: E402
|
|
61
|
+
|
|
62
|
+
from .julia.util import jl_symbol # noqa: E402
|
|
63
|
+
from .julia import jl_isa as jl_isa # noqa: E402
|
|
64
|
+
|
|
65
|
+
Symbol = jl_symbol
|
|
66
|
+
|
|
67
|
+
if not os.getenv("IESOPT_DOCS_NOEXEC"):
|
|
68
|
+
IESopt = _get_iesopt_module_attr("IESopt")
|
|
69
|
+
JuMP = _get_iesopt_module_attr("JuMP")
|
|
70
|
+
|
|
71
|
+
jump_value = _get_iesopt_module_attr("jump_value")
|
|
72
|
+
jump_dual = _get_iesopt_module_attr("jump_dual")
|
|
73
|
+
jump_reduced_cost = _get_iesopt_module_attr("jump_reduced_cost")
|
|
74
|
+
jump_shadow_price = _get_iesopt_module_attr("jump_shadow_price")
|
|
File without changes
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
from .util import logger, get_iesopt_module_attr
|
|
4
|
+
from .julia.util import jl_symbol
|
|
5
|
+
from .model import Model, ModelStatus
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def run(filename: str | Path, verbosity: bool | str = True, **kwargs) -> Model:
|
|
9
|
+
r"""
|
|
10
|
+
Generate and optimize an IESopt model.
|
|
11
|
+
|
|
12
|
+
Results can be accessed (after a successful optimization) using `model.results`.
|
|
13
|
+
|
|
14
|
+
Arguments:
|
|
15
|
+
filename (str): Path to the IESopt model file to load.
|
|
16
|
+
verbosity (bool or str, optional): Verbosity level for the IESopt model, defaults to `True`. If `True`, the core
|
|
17
|
+
model will be run in verbose mode, `"warning"` will show warnings (and errors), setting it to `False` will
|
|
18
|
+
only show errors. If `verbosity_solve` is not set in the top-level YAML config, `verbosity = True` will
|
|
19
|
+
enable solver verbose mode, otherwise the solver will be run in silent mode.
|
|
20
|
+
|
|
21
|
+
Keyword Arguments:
|
|
22
|
+
**kwargs: Additional keyword arguments to pass to the `Model` constructor.
|
|
23
|
+
|
|
24
|
+
Returns:
|
|
25
|
+
Model: The generated and optimized IESopt model.
|
|
26
|
+
|
|
27
|
+
Example:
|
|
28
|
+
.. code-block:: python
|
|
29
|
+
:caption: Run an IESopt model
|
|
30
|
+
|
|
31
|
+
import iesopt
|
|
32
|
+
iesopt.run("opt/config.iesopt.yaml")
|
|
33
|
+
"""
|
|
34
|
+
model = Model(filename, verbosity=verbosity, **kwargs)
|
|
35
|
+
model.generate()
|
|
36
|
+
|
|
37
|
+
if model.status == ModelStatus.GENERATED:
|
|
38
|
+
model.optimize()
|
|
39
|
+
else:
|
|
40
|
+
logger.error("Model could not be generated; skipping optimization.")
|
|
41
|
+
|
|
42
|
+
return model
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def examples() -> list[str]:
|
|
46
|
+
"""
|
|
47
|
+
Return a list of all available examples.
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
list[str]: List of available examples. This contains the names of the examples, not the full filenames (so,
|
|
51
|
+
e.g., `"some_example"` instead of `"some_example.iesopt.yaml"`)
|
|
52
|
+
"""
|
|
53
|
+
import os
|
|
54
|
+
|
|
55
|
+
julia = get_iesopt_module_attr("julia")
|
|
56
|
+
folder = Path(julia.IESoptLib.get_path(jl_symbol("examples")))
|
|
57
|
+
return sorted([fn.split(".iesopt.yaml")[0] for fn in os.listdir(folder) if fn.endswith(".iesopt.yaml")])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def make_example(example: str, dst_dir: str | Path = "./", dst_name: str | None = None) -> Path:
|
|
61
|
+
"""
|
|
62
|
+
Generate a local copy of a specific example.
|
|
63
|
+
|
|
64
|
+
A list of examples, and their exact names, can be obtained using :py:func:`iesopt.examples()`.
|
|
65
|
+
|
|
66
|
+
Arguments:
|
|
67
|
+
example (str): Name of the example to generate.
|
|
68
|
+
dst_dir (str, optional): Directory to generate the example in, defaults to `"./"`.
|
|
69
|
+
dst_name (str, optional): Name of the generated example file (without the ".iesopt.yaml" extension), e.g.,
|
|
70
|
+
`"config"`, will create `dst_dir/config.iesopt.yaml`. Will default to the original name of the example.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
Path: Path to the generated example file.
|
|
74
|
+
"""
|
|
75
|
+
import shutil
|
|
76
|
+
import os
|
|
77
|
+
import stat
|
|
78
|
+
|
|
79
|
+
julia = get_iesopt_module_attr("julia")
|
|
80
|
+
folder = Path(julia.IESoptLib.get_path(jl_symbol("examples")))
|
|
81
|
+
|
|
82
|
+
filename = folder / f"{example}.iesopt.yaml"
|
|
83
|
+
datafolder = folder / "files"
|
|
84
|
+
target_filename = Path(dst_dir) / ((example if dst_name is None else dst_name) + ".iesopt.yaml")
|
|
85
|
+
target_datafolder = Path(dst_dir) / "files"
|
|
86
|
+
|
|
87
|
+
# Check if data folder already exists.
|
|
88
|
+
if not os.path.exists(target_datafolder):
|
|
89
|
+
logger.info("Data folder for examples does not exist; creating it, and copying contents")
|
|
90
|
+
shutil.copytree(datafolder, target_datafolder)
|
|
91
|
+
else:
|
|
92
|
+
logger.info("Data folder for examples already exists; NOT copying ANY contents")
|
|
93
|
+
|
|
94
|
+
# Copy the config file.
|
|
95
|
+
logger.info("Creating example ('%s') at: '%s'" % (example, target_filename))
|
|
96
|
+
shutil.copy(filename, target_filename)
|
|
97
|
+
|
|
98
|
+
# Make everything editable.
|
|
99
|
+
logger.info(
|
|
100
|
+
"Set write permissions for example ('%s'), and data folder ('%s')" % (target_filename, target_datafolder)
|
|
101
|
+
)
|
|
102
|
+
os.chmod(target_filename, os.stat(target_filename).st_mode & ~stat.S_IWRITE | stat.S_IWUSR)
|
|
103
|
+
for dirpath, _, filenames in os.walk(target_datafolder):
|
|
104
|
+
os.chmod(dirpath, os.stat(dirpath).st_mode & ~stat.S_IWRITE | stat.S_IWUSR)
|
|
105
|
+
for filename in filenames:
|
|
106
|
+
filepath = os.path.join(dirpath, filename)
|
|
107
|
+
os.chmod(filepath, os.stat(filepath).st_mode & ~stat.S_IWRITE | stat.S_IWUSR)
|
|
108
|
+
|
|
109
|
+
return target_filename
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import importlib.metadata
|
|
3
|
+
|
|
4
|
+
from ..util import logger, set_iesopt_module_attr, get_iesopt_module_attr
|
|
5
|
+
from .setup import setup_julia, import_modules
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def log_welcome_msg():
|
|
9
|
+
julia = get_iesopt_module_attr("julia")
|
|
10
|
+
version_core = str(julia.pkgversion(julia.IESopt))
|
|
11
|
+
version_py = importlib.metadata.version("iesopt")
|
|
12
|
+
version_lib = str(julia.pkgversion(julia.IESoptLib))
|
|
13
|
+
n_v = max(len(version_core), len(version_py), len(version_lib))
|
|
14
|
+
url_docs = "https://ait-energy.github.io/iesopt"
|
|
15
|
+
|
|
16
|
+
def _fill(_s: str, n: int):
|
|
17
|
+
return " " * (n - len(_s))
|
|
18
|
+
|
|
19
|
+
logger.info("╔════════════════════════════════════════════════════════════════════════╗")
|
|
20
|
+
logger.info("║ IESopt «Integrated Energy System Optimization» ║")
|
|
21
|
+
logger.info("╟────────────────────────────────────────────────────────────────────────╢")
|
|
22
|
+
logger.info("║ ╭────────────────────────────────────────────────────────────────╮ ║")
|
|
23
|
+
logger.info("║ ├ authors: Stefan Strömer, Daniel Schwabeneder, and contributors │ ║")
|
|
24
|
+
logger.info("║ ├ © 2021: AIT Austrian Institute of Technology GmbH │ ║")
|
|
25
|
+
logger.info(f"║ ├ docs: {url_docs}{_fill(url_docs, 53)} │ ║")
|
|
26
|
+
logger.info("║ ├ version: ┐ │ ║")
|
|
27
|
+
logger.info(f"║ │ ├─{{ py :: {version_py}{_fill(version_py, n_v)} }} {' ' * 32} │ ║")
|
|
28
|
+
logger.info(f"║ │ ├─{{ jl :: {version_core}{_fill(version_core, n_v)} }} {' ' * 32} │ ║")
|
|
29
|
+
logger.info(f"║ │ └─{{ lib :: {version_lib}{_fill(version_lib, n_v)} }} {' ' * 32} │ ║")
|
|
30
|
+
logger.info("║ ╰────────────────────────────────────────────────────────────────╯ ║")
|
|
31
|
+
logger.info("╚════════════════════════════════════════════════════════════════════════╝")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def initialize():
|
|
35
|
+
if os.getenv("IESOPT_DOCS_NOEXEC"):
|
|
36
|
+
logger.warn("Detected docs environment (env. var. `IESOPT_DOCS_NOEXEC` is set), skip loading Julia.")
|
|
37
|
+
return
|
|
38
|
+
|
|
39
|
+
julia = setup_julia()
|
|
40
|
+
set_iesopt_module_attr("julia", julia)
|
|
41
|
+
|
|
42
|
+
import_modules()
|
|
43
|
+
log_welcome_msg()
|
|
44
|
+
|
|
45
|
+
set_iesopt_module_attr("IESopt", julia.IESopt)
|
|
46
|
+
set_iesopt_module_attr("JuMP", julia.JuMP)
|
|
47
|
+
|
|
48
|
+
set_iesopt_module_attr("jump_value", julia.seval("(x) -> JuMP.value.(x)"))
|
|
49
|
+
set_iesopt_module_attr("jump_dual", julia.seval("(x) -> JuMP.dual.(x)"))
|
|
50
|
+
set_iesopt_module_attr("jump_reduced_cost", julia.seval("(x) -> JuMP.reduced_cost.(x)"))
|
|
51
|
+
set_iesopt_module_attr("jump_shadow_price", julia.seval("(x) -> JuMP.reduced_cost.(x)"))
|
|
52
|
+
|
|
53
|
+
return julia
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# import os
|
|
2
|
+
# import ssl
|
|
3
|
+
|
|
4
|
+
from ..util import logger
|
|
5
|
+
from .util import jl_import
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def setup_julia():
|
|
9
|
+
logger.info("Setting up Julia ...")
|
|
10
|
+
|
|
11
|
+
# # Check for local SSL certificate file, that can interfere with Julia setup.
|
|
12
|
+
# _ssl = None
|
|
13
|
+
# if "SSL_CERT_FILE" in os.environ:
|
|
14
|
+
# logger.info("Detected local `SSL_CERT_FILE`; disabling it during Julia setup")
|
|
15
|
+
# _ssl = os.environ.pop("SSL_CERT_FILE")
|
|
16
|
+
|
|
17
|
+
# ssl._create_default_https_context = ssl._create_unverified_context
|
|
18
|
+
# logger.warn("Disabling SSL verification to prevent problems; this may be unsafe")
|
|
19
|
+
|
|
20
|
+
# Setup Julia (checking if it "looks" valid).
|
|
21
|
+
import juliapkg
|
|
22
|
+
|
|
23
|
+
if not juliapkg.resolve():
|
|
24
|
+
raise Exception("Julia setup is not valid")
|
|
25
|
+
|
|
26
|
+
import juliacall
|
|
27
|
+
|
|
28
|
+
logger.info("Julia setup successful")
|
|
29
|
+
|
|
30
|
+
# # Restoring potential SSL certificate.
|
|
31
|
+
# if _ssl is not None:
|
|
32
|
+
# logger.info("Restoring local `SSL_CERT_FILE`")
|
|
33
|
+
# os.environ["SSL_CERT_FILE"] = _ssl
|
|
34
|
+
|
|
35
|
+
return juliacall.Main
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def import_modules():
|
|
39
|
+
jl_import("IESoptLib")
|
|
40
|
+
jl_import("IESopt")
|
|
41
|
+
jl_import("JuMP")
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
from ..util import logger, get_iesopt_module_attr
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def jl_safe_seval(code: str):
|
|
5
|
+
"""Safely evaluate Julia code."""
|
|
6
|
+
try:
|
|
7
|
+
return get_iesopt_module_attr("julia").seval(code)
|
|
8
|
+
except Exception as e:
|
|
9
|
+
logger.error("Exception while trying to execute Julia code: `%s`" % code)
|
|
10
|
+
raise e
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def jl_import(module: str):
|
|
14
|
+
"""Import a Julia module."""
|
|
15
|
+
logger.info("Importing Julia module `%s`" % module)
|
|
16
|
+
jl_safe_seval(f"import {module}")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def jl_symbol(string: str):
|
|
20
|
+
"""Create a Julia `Symbol` from `string`.
|
|
21
|
+
|
|
22
|
+
This function can be called as: :py:func:`iesopt.Symbol`, or :py:func:`iesopt.jl_symbol`.
|
|
23
|
+
|
|
24
|
+
Arguments:
|
|
25
|
+
string (str): The string to convert to a Julia `Symbol`.
|
|
26
|
+
|
|
27
|
+
Returns:
|
|
28
|
+
The Julia `Symbol` object.
|
|
29
|
+
|
|
30
|
+
Examples:
|
|
31
|
+
.. code-block:: python
|
|
32
|
+
:caption: Convert a string to a Julia `Symbol`
|
|
33
|
+
|
|
34
|
+
import iesopt
|
|
35
|
+
iesopt.jl_symbol(":iesopt") # => `Julia: :iesopt`
|
|
36
|
+
|
|
37
|
+
.. code-block:: python
|
|
38
|
+
:caption: Directly import and use the `Symbol` alias
|
|
39
|
+
|
|
40
|
+
from iesopt import Symbol
|
|
41
|
+
Symbol(":iesopt") # => `Julia: :iesopt`
|
|
42
|
+
|
|
43
|
+
"""
|
|
44
|
+
return get_iesopt_module_attr("julia").Symbol(string)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def jl_isa(obj, julia_type: str):
|
|
48
|
+
julia = get_iesopt_module_attr("julia")
|
|
49
|
+
|
|
50
|
+
if julia_type == "AbstractVector":
|
|
51
|
+
return julia.isa(obj, julia.AbstractVector)
|
|
52
|
+
|
|
53
|
+
if julia_type == "AbstractSet":
|
|
54
|
+
return julia.isa(obj, julia.AbstractSet)
|
|
55
|
+
|
|
56
|
+
if julia_type == "AbstractDict":
|
|
57
|
+
return julia.isa(obj, julia.AbstractDict)
|
|
58
|
+
|
|
59
|
+
return julia.seval(f"(x) -> (x isa {julia_type})")(obj)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"julia": "=1.10.4",
|
|
3
|
+
"packages": {
|
|
4
|
+
"JuMP": {
|
|
5
|
+
"uuid": "4076af6c-e467-56ae-b986-b466b2749572",
|
|
6
|
+
"version": "=1.22.2"
|
|
7
|
+
},
|
|
8
|
+
"HiGHS": {
|
|
9
|
+
"uuid": "87dc4568-4c63-4d18-b0c0-bb2238e4078b",
|
|
10
|
+
"version": "=1.9.0"
|
|
11
|
+
},
|
|
12
|
+
"IESopt": {
|
|
13
|
+
"uuid": "ed3f0a38-8ad9-4cf8-877e-929e8d190fe9",
|
|
14
|
+
"version": "=1.0.3"
|
|
15
|
+
},
|
|
16
|
+
"IESoptLib": {
|
|
17
|
+
"uuid": "b98f706d-40ec-4ce6-a66c-1c6e71d3cef6",
|
|
18
|
+
"version": "=0.2.0"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from .util import logger, get_iesopt_module_attr
|
|
5
|
+
from .julia.util import jl_symbol
|
|
6
|
+
from .results import Results
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ModelStatus(Enum):
|
|
10
|
+
"""Status of an :py:class:`iesopt.Model`."""
|
|
11
|
+
|
|
12
|
+
EMPTY = "empty"
|
|
13
|
+
GENERATED = "generated"
|
|
14
|
+
FAILED_GENERATE = "failed_generate"
|
|
15
|
+
FAILED_OPTIMIZE = "failed_optimize"
|
|
16
|
+
OPTIMAL = "optimal"
|
|
17
|
+
OPTIMAL_LOCALLY = "local_optimum"
|
|
18
|
+
INFEASIBLE = "infeasible"
|
|
19
|
+
INFEASIBLE_OR_UNBOUNDED = "infeasible_unbounded"
|
|
20
|
+
OTHER = "other"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Model:
|
|
24
|
+
"""An IESopt model, based on an :jl:module:`IESopt.jl <IESopt.IESopt>` core model."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, filename: str | Path, **kwargs) -> None:
|
|
27
|
+
self._filename = filename
|
|
28
|
+
self._kwargs = kwargs
|
|
29
|
+
|
|
30
|
+
self._model = None
|
|
31
|
+
self._verbosity = kwargs.get("verbosity", True)
|
|
32
|
+
|
|
33
|
+
self._status = ModelStatus.EMPTY
|
|
34
|
+
self._status_details = None
|
|
35
|
+
|
|
36
|
+
self._results = None
|
|
37
|
+
|
|
38
|
+
self._IESopt = get_iesopt_module_attr("IESopt")
|
|
39
|
+
self._JuMP = get_iesopt_module_attr("JuMP")
|
|
40
|
+
self._jump_value = get_iesopt_module_attr("jump_value")
|
|
41
|
+
self._jump_dual = get_iesopt_module_attr("jump_dual")
|
|
42
|
+
|
|
43
|
+
def __repr__(self) -> str:
|
|
44
|
+
if self._model is None:
|
|
45
|
+
return "An IESopt model (not yet generated)"
|
|
46
|
+
|
|
47
|
+
n_var = self._JuMP.num_variables(self.core)
|
|
48
|
+
n_con = self._JuMP.num_constraints(self.core, count_variable_in_set_constraints=False)
|
|
49
|
+
solver = self._JuMP.solver_name(self.core)
|
|
50
|
+
termination_status = self._JuMP.termination_status(self.core)
|
|
51
|
+
|
|
52
|
+
return (
|
|
53
|
+
f"An IESopt model:"
|
|
54
|
+
f"\n\tname: {self.data.input.config.names.model}"
|
|
55
|
+
f"\n\tsolver: {solver}"
|
|
56
|
+
f"\n\t"
|
|
57
|
+
f"\n\t{n_var} variables, {n_con} constraints"
|
|
58
|
+
f"\n\tstatus: {termination_status}"
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def core(self):
|
|
63
|
+
"""Access the core `JuMP` model that is used internally."""
|
|
64
|
+
if self._model is None:
|
|
65
|
+
raise Exception("Model was not properly set up; call `generate` first")
|
|
66
|
+
return self._model
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def data(self):
|
|
70
|
+
"""Access the IESopt data object of the model."""
|
|
71
|
+
return self.core.ext[jl_symbol("iesopt")]
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def status(self) -> ModelStatus:
|
|
75
|
+
"""Get the current status of this model. See `ModelStatus` for possible values."""
|
|
76
|
+
return self._status
|
|
77
|
+
|
|
78
|
+
@property
|
|
79
|
+
def objective_value(self) -> float:
|
|
80
|
+
"""Get the objective value of the model. Only available if the model was solved beforehand."""
|
|
81
|
+
if self._status == ModelStatus.OPTIMAL_LOCALLY:
|
|
82
|
+
logger.warning("Model is only locally optimal; objective value may not be accurate")
|
|
83
|
+
elif self._status != ModelStatus.OPTIMAL:
|
|
84
|
+
raise Exception("Model is not optimal; no objective value available")
|
|
85
|
+
return self._JuMP.objective_value(self.core)
|
|
86
|
+
|
|
87
|
+
def generate(self) -> None:
|
|
88
|
+
"""Generate a IESopt model from the attached top-level YAML config."""
|
|
89
|
+
try:
|
|
90
|
+
self._model = self._IESopt.generate_b(str(self._filename), **self._kwargs)
|
|
91
|
+
self._status = ModelStatus.GENERATED
|
|
92
|
+
except Exception as e:
|
|
93
|
+
self._status = ModelStatus.FAILED_GENERATE
|
|
94
|
+
logger.error(f"Exception during `generate`: {e}")
|
|
95
|
+
try:
|
|
96
|
+
logger.error(f"Current debugging info: {self.data.debug}")
|
|
97
|
+
except Exception as e:
|
|
98
|
+
logger.error("Failed to extract debugging info")
|
|
99
|
+
|
|
100
|
+
def optimize(self) -> None:
|
|
101
|
+
"""Optimize the model."""
|
|
102
|
+
try:
|
|
103
|
+
self._IESopt.optimize_b(self.core)
|
|
104
|
+
|
|
105
|
+
if self._JuMP.is_solved_and_feasible(self.core, allow_local=False):
|
|
106
|
+
self._status = ModelStatus.OPTIMAL
|
|
107
|
+
self._results = Results(model=self)
|
|
108
|
+
elif self._JuMP.is_solved_and_feasible(self.core, allow_local=True):
|
|
109
|
+
self._status = ModelStatus.OPTIMAL_LOCALLY
|
|
110
|
+
self._results = Results(model=self)
|
|
111
|
+
else:
|
|
112
|
+
_term_status = self._JuMP.termination_status(self.core)
|
|
113
|
+
if str(_term_status) == "INFEASIBLE":
|
|
114
|
+
self._status = ModelStatus.INFEASIBLE
|
|
115
|
+
elif str(_term_status) == "INFEASIBLE_OR_UNBOUNDED":
|
|
116
|
+
self._status = ModelStatus.INFEASIBLE_OR_UNBOUNDED
|
|
117
|
+
else:
|
|
118
|
+
self._status = ModelStatus.OTHER
|
|
119
|
+
self._status_details = _term_status
|
|
120
|
+
except Exception as e:
|
|
121
|
+
self._status = ModelStatus.FAILED_OPTIMIZE
|
|
122
|
+
logger.error(f"Exception during `optimize`: {e}")
|
|
123
|
+
try:
|
|
124
|
+
logger.error(f"Current debugging info: {self.data.debug}")
|
|
125
|
+
except Exception as e:
|
|
126
|
+
logger.error("Failed to extract debugging info")
|
|
127
|
+
|
|
128
|
+
@property
|
|
129
|
+
def results(self) -> Results:
|
|
130
|
+
"""Get the results of the model."""
|
|
131
|
+
if self._results is None:
|
|
132
|
+
raise Exception("No results available; have you successfully called `optimize`?")
|
|
133
|
+
return self._results
|
|
134
|
+
|
|
135
|
+
def extract_result(self, component: str, field: str, mode: str = "value"):
|
|
136
|
+
"""Manually extract a specific result from the model."""
|
|
137
|
+
try:
|
|
138
|
+
c = self._IESopt.component(self.core, "node2")
|
|
139
|
+
except Exception:
|
|
140
|
+
raise Exception(f"Exception during `extract_result({component}, {field}, mode={mode})`")
|
|
141
|
+
|
|
142
|
+
f = None
|
|
143
|
+
for fieldtype in ["var", "exp", "con", "obj"]:
|
|
144
|
+
try:
|
|
145
|
+
t = getattr(c, fieldtype)
|
|
146
|
+
f = getattr(t, field)
|
|
147
|
+
break
|
|
148
|
+
except Exception:
|
|
149
|
+
pass
|
|
150
|
+
|
|
151
|
+
if f is None:
|
|
152
|
+
raise Exception(f"Field `{field}` not found in component `{component}`")
|
|
153
|
+
|
|
154
|
+
try:
|
|
155
|
+
if mode == "value":
|
|
156
|
+
return self._jump_values(f)
|
|
157
|
+
elif mode == "dual":
|
|
158
|
+
return self._jump_duals(f)
|
|
159
|
+
else:
|
|
160
|
+
raise Exception(f"Mode `{mode}` not supported, use `value` or `dual`")
|
|
161
|
+
except Exception:
|
|
162
|
+
raise Exception(f"Error during extraction of result `{field}` from component `{component}`")
|
|
163
|
+
|
|
164
|
+
def get_component(self, component: str):
|
|
165
|
+
"""Get a core component based on its full name."""
|
|
166
|
+
try:
|
|
167
|
+
return self._IESopt.component(self.core, component)
|
|
168
|
+
except Exception:
|
|
169
|
+
raise Exception(f"Error while retrieving component `{component}` from model")
|
|
170
|
+
|
|
171
|
+
def get_variable(self, component: str, variable: str):
|
|
172
|
+
"""Get a specific variable from a core component."""
|
|
173
|
+
raise DeprecationWarning(
|
|
174
|
+
f"`get_variable(...)` is deprecated; you can instead access the variable directly using "
|
|
175
|
+
f"`model.get_component('{component}').var.{variable}`. Conversion to Python lists, if not done "
|
|
176
|
+
f"automatically, can be done using `list(...)`."
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
def get_constraint(self, component: str, constraint: str):
|
|
180
|
+
"""Get a specific constraint from a core component."""
|
|
181
|
+
raise DeprecationWarning(
|
|
182
|
+
f"`get_constraint(...)` is deprecated; you can instead access the constraint directly using "
|
|
183
|
+
f"`model.get_component('{component}').con.{constraint}`. Conversion to Python lists, if not done "
|
|
184
|
+
f"automatically, can be done using `list(...)`."
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
def nvar(self, var: str):
|
|
188
|
+
"""Extract a named variable, from `model`.
|
|
189
|
+
|
|
190
|
+
If your variable is called `:myvar`, and you would access it in Julia using `model[:myvar]`, you can call
|
|
191
|
+
`model.nvar("myvar")`.
|
|
192
|
+
"""
|
|
193
|
+
try:
|
|
194
|
+
return self.core[jl_symbol(var)]
|
|
195
|
+
except Exception:
|
|
196
|
+
raise Exception(f"Error while retrieving variable `{var}` from model")
|
|
197
|
+
|
|
198
|
+
@staticmethod
|
|
199
|
+
def _to_pylist(obj):
|
|
200
|
+
# if isinstance(obj, jl.VectorValue):
|
|
201
|
+
# return jl.PythonCall.pylist(obj)
|
|
202
|
+
return obj
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import warnings
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
from pydantic import validate_call
|
|
5
|
+
|
|
6
|
+
from .util import get_iesopt_module_attr
|
|
7
|
+
from .julia import jl_isa
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ddict(dict):
|
|
11
|
+
"""Wrapper to enable dot.notation access to dictionary attributes."""
|
|
12
|
+
|
|
13
|
+
__getattr__ = dict.get
|
|
14
|
+
__setattr__ = dict.__setitem__
|
|
15
|
+
__delattr__ = dict.__delitem__
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class JuliaCallPyConvertReadWrapper:
|
|
19
|
+
def __init__(self, obj):
|
|
20
|
+
import juliacall
|
|
21
|
+
|
|
22
|
+
self._juliacall = juliacall
|
|
23
|
+
self._obj = obj
|
|
24
|
+
|
|
25
|
+
def _rewrap_return(self, value):
|
|
26
|
+
if isinstance(value, self._juliacall.ArrayValue):
|
|
27
|
+
return value.to_numpy(copy=False)
|
|
28
|
+
if isinstance(value, self._juliacall.DictValue):
|
|
29
|
+
return JuliaCallPyConvertReadWrapper(value)
|
|
30
|
+
return JuliaCallPyConvertReadWrapper(value)
|
|
31
|
+
|
|
32
|
+
def __getattr__(self, name: str):
|
|
33
|
+
return self._rewrap_return(getattr(self._obj, name))
|
|
34
|
+
|
|
35
|
+
def __getitem__(self, key):
|
|
36
|
+
return self._rewrap_return(self._obj.get(key))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class Results:
|
|
40
|
+
_valid_attrs = ["attributes", "model", "custom", "input", "info", "snapshots", "components"]
|
|
41
|
+
|
|
42
|
+
@validate_call
|
|
43
|
+
def __init__(self, *, file: str = None, model=None):
|
|
44
|
+
"""
|
|
45
|
+
Create a new `Results` object, either from a file or from an IESopt model. Make sure to pass either a file or a
|
|
46
|
+
model explicitly using a keyword argument.
|
|
47
|
+
|
|
48
|
+
:param file: Path to the results file to load, by default None
|
|
49
|
+
:param model: IESopt model to extract results from, by default None
|
|
50
|
+
|
|
51
|
+
:type file: str, optional
|
|
52
|
+
:type model: IESopt.Model, optional
|
|
53
|
+
"""
|
|
54
|
+
self._attributes = None
|
|
55
|
+
self._model = None
|
|
56
|
+
self._snapshots = None
|
|
57
|
+
self._components = None
|
|
58
|
+
self._custom = None
|
|
59
|
+
self._input = None
|
|
60
|
+
self._info = None
|
|
61
|
+
self._source = None
|
|
62
|
+
|
|
63
|
+
self._cache = None
|
|
64
|
+
|
|
65
|
+
self._IESopt = get_iesopt_module_attr("IESopt")
|
|
66
|
+
self._julia = get_iesopt_module_attr("julia")
|
|
67
|
+
|
|
68
|
+
if (int(file is None) + int(model is None)) != 1:
|
|
69
|
+
raise Exception("Either file or model must be set, not both and not none of them.")
|
|
70
|
+
elif file is not None:
|
|
71
|
+
if not isinstance(file, str):
|
|
72
|
+
raise Exception("File must be a `str`, did you try passing a model without `model=your_model`?")
|
|
73
|
+
self._from_file(file)
|
|
74
|
+
elif model is not None:
|
|
75
|
+
self._from_model(model)
|
|
76
|
+
|
|
77
|
+
# Allow dot access to attributes of "model" results, to align with access to the models structure.
|
|
78
|
+
self._model = ddict(self._model)
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def components(self):
|
|
82
|
+
return JuliaCallPyConvertReadWrapper(self._model["components"])
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def objectives(self):
|
|
86
|
+
return JuliaCallPyConvertReadWrapper(self._model["objectives"])
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def customs(self):
|
|
90
|
+
return JuliaCallPyConvertReadWrapper(self._model["customs"])
|
|
91
|
+
|
|
92
|
+
@validate_call
|
|
93
|
+
def get(
|
|
94
|
+
self,
|
|
95
|
+
result: str,
|
|
96
|
+
component: str,
|
|
97
|
+
fieldtype: str,
|
|
98
|
+
field: str,
|
|
99
|
+
*,
|
|
100
|
+
mode: str = "primal",
|
|
101
|
+
build_cache: bool = False,
|
|
102
|
+
):
|
|
103
|
+
if result not in ["component", "objective", "custom"]:
|
|
104
|
+
raise ValueError(f"`result` must be 'component', 'objective', or 'custom', got '{result}'")
|
|
105
|
+
|
|
106
|
+
if result in ["objective", "custom"]:
|
|
107
|
+
# TODO: Implement and remove this
|
|
108
|
+
raise NotImplementedError("Accessing objectives and custom results is not yet supported using `get(...)`")
|
|
109
|
+
|
|
110
|
+
if mode == "dual":
|
|
111
|
+
field = field + "__dual"
|
|
112
|
+
elif mode != "primal":
|
|
113
|
+
raise ValueError(f"`mode` must be 'primal' or 'dual', got '{mode}'")
|
|
114
|
+
|
|
115
|
+
if build_cache:
|
|
116
|
+
self._build_cache()
|
|
117
|
+
|
|
118
|
+
if self._has_cache():
|
|
119
|
+
t = (component, fieldtype, field)
|
|
120
|
+
if t in self._cache:
|
|
121
|
+
return self._cache[t]
|
|
122
|
+
raise ValueError(f"Failed to access result '{fieldtype}.{field}' in component '{component}'")
|
|
123
|
+
|
|
124
|
+
return self._get_safe(component, fieldtype, field, mode)
|
|
125
|
+
|
|
126
|
+
@validate_call
|
|
127
|
+
def entries(self, field: str = None):
|
|
128
|
+
"""
|
|
129
|
+
Get all available entries for a specific field, or all fields if `field` is `None`.
|
|
130
|
+
|
|
131
|
+
Parameters
|
|
132
|
+
----------
|
|
133
|
+
field : str, optional
|
|
134
|
+
Field to get entries for, by default None which returns all fields
|
|
135
|
+
"""
|
|
136
|
+
if field is None:
|
|
137
|
+
return [it for it in Results._valid_attrs if getattr(self, f"_{it}") is not None]
|
|
138
|
+
return sorted(getattr(self, field).keys())
|
|
139
|
+
|
|
140
|
+
@validate_call
|
|
141
|
+
def to_dict(self, filter=None, field_types=None, build_cache: bool = True):
|
|
142
|
+
"""
|
|
143
|
+
Extract results from the `Results` object and return them as a dictionary.
|
|
144
|
+
|
|
145
|
+
Parameters
|
|
146
|
+
----------
|
|
147
|
+
filter : callable, optional
|
|
148
|
+
Filter function to apply to the results, by default None, must take three arguments: (c, t, f) where `c` is
|
|
149
|
+
the component's name, `t` is the field type ("var", "exp", "con", or "obj"), and `f` is the field name
|
|
150
|
+
field_types : list[str], optional
|
|
151
|
+
Field types to extract, by default None, which extracts all field types
|
|
152
|
+
build_cache : bool, optional
|
|
153
|
+
Whether to build a cache of the results, by default True
|
|
154
|
+
"""
|
|
155
|
+
if build_cache:
|
|
156
|
+
self._build_cache()
|
|
157
|
+
|
|
158
|
+
if field_types is None:
|
|
159
|
+
field_types = ["var", "exp", "con", "obj", "res"]
|
|
160
|
+
|
|
161
|
+
entries = {}
|
|
162
|
+
if self._cache is None:
|
|
163
|
+
for c in self._model["components"].keys():
|
|
164
|
+
for t in field_types:
|
|
165
|
+
container = getattr(self._model["components"][c], t)
|
|
166
|
+
for f in [str(it) for it in self._julia.Main.keys(container)]:
|
|
167
|
+
if (filter is None) or filter(c, t, f):
|
|
168
|
+
entries[(c, t, f)] = Results._safe_convert(getattr(container, f))
|
|
169
|
+
else:
|
|
170
|
+
for c, t, f in self._cache.keys():
|
|
171
|
+
if (t in field_types) and ((filter is None) or filter(c, t, f)):
|
|
172
|
+
entries[(c, t, f)] = self._cache[(c, t, f)]
|
|
173
|
+
|
|
174
|
+
return entries
|
|
175
|
+
|
|
176
|
+
@validate_call
|
|
177
|
+
def to_pandas(self, filter=None, field_types=None, orientation: str = "long", build_cache: bool = True):
|
|
178
|
+
"""
|
|
179
|
+
Extract results from the `Results` object and return them as `pd.DataFrame` or `pd.Series` (depending on the
|
|
180
|
+
shape of the included results).
|
|
181
|
+
|
|
182
|
+
Parameters
|
|
183
|
+
----------
|
|
184
|
+
filter : callable, optional
|
|
185
|
+
Filter function to apply to the results, by default None, must take three arguments: (c, t, f) where `c` is
|
|
186
|
+
the component's name, `t` is the field type ("var", "exp", "con", or "obj"), and `f` is the field name
|
|
187
|
+
field_types : list[str], optional
|
|
188
|
+
Field types to extract, by default None, which extracts all field types
|
|
189
|
+
orientation : str, optional
|
|
190
|
+
Orientation of the resulting DataFrame, either "wide" or "long", by default "long"
|
|
191
|
+
build_cache : bool, optional
|
|
192
|
+
Whether to build a cache of the results, by default True
|
|
193
|
+
"""
|
|
194
|
+
_dict = self.to_dict(filter, field_types, build_cache)
|
|
195
|
+
|
|
196
|
+
# Check if we can cast to `pd.Series` (no matter the orientation).
|
|
197
|
+
_result_types = set(type(it) for it in _dict.values())
|
|
198
|
+
if len(_result_types) == 1:
|
|
199
|
+
_rt = _result_types.pop()
|
|
200
|
+
if _rt in [int, float]:
|
|
201
|
+
return pd.Series(_dict)
|
|
202
|
+
|
|
203
|
+
if _rt == np.ndarray:
|
|
204
|
+
if len(_dict) == 1:
|
|
205
|
+
k, v = next(iter(_dict.items()))
|
|
206
|
+
|
|
207
|
+
if isinstance(v, int | float):
|
|
208
|
+
return pd.Series(v, index=k)
|
|
209
|
+
|
|
210
|
+
value_shape = v.shape
|
|
211
|
+
if len(value_shape) == 1:
|
|
212
|
+
if value_shape[0] == len(self._snapshots):
|
|
213
|
+
return pd.Series(v, index=self._snapshots, name=k)
|
|
214
|
+
|
|
215
|
+
if orientation == "wide":
|
|
216
|
+
return pd.DataFrame(_dict, index=self._snapshots)
|
|
217
|
+
|
|
218
|
+
if orientation == "wide":
|
|
219
|
+
warnings.warn(
|
|
220
|
+
"Results must be of the same shape (= length) to create a DataFrame, with `orientation='wide'`. "
|
|
221
|
+
"Falling back to `orientation='long'`. This warning can be prevented by calling `results.to_pandas("
|
|
222
|
+
"orientation='long') instead, or by applying filters (using `filter` and/or `field_types`) that only "
|
|
223
|
+
"select results of the same shape (example: objectives are always scalars, while most variables - "
|
|
224
|
+
"except Decisions - are vector valued, indexed over all snapshots)."
|
|
225
|
+
)
|
|
226
|
+
warnings.warn(f"Got the following result types: {_result_types}")
|
|
227
|
+
orientation = "long"
|
|
228
|
+
|
|
229
|
+
if orientation == "long":
|
|
230
|
+
n_snapshots = len(self._snapshots)
|
|
231
|
+
_data = {c: [] for c in ["snapshot", "component", "fieldtype", "field", "value", "mode"]}
|
|
232
|
+
|
|
233
|
+
for (c, t, f), v in _dict.items():
|
|
234
|
+
m = "primal"
|
|
235
|
+
if f.endswith("__dual"):
|
|
236
|
+
f = f[:-6]
|
|
237
|
+
m = "dual"
|
|
238
|
+
|
|
239
|
+
if isinstance(v, (int, float)):
|
|
240
|
+
_data["snapshot"].append(None)
|
|
241
|
+
_data["component"].append(c)
|
|
242
|
+
_data["fieldtype"].append(t)
|
|
243
|
+
_data["field"].append(f)
|
|
244
|
+
_data["value"].append(v)
|
|
245
|
+
_data["mode"].append(m)
|
|
246
|
+
else:
|
|
247
|
+
_data["snapshot"].extend(self._snapshots)
|
|
248
|
+
_data["component"].extend([c] * n_snapshots)
|
|
249
|
+
_data["fieldtype"].extend([t] * n_snapshots)
|
|
250
|
+
_data["field"].extend([f] * n_snapshots)
|
|
251
|
+
_data["value"].extend(v)
|
|
252
|
+
_data["mode"].extend([m] * n_snapshots)
|
|
253
|
+
|
|
254
|
+
return pd.DataFrame(_data)
|
|
255
|
+
|
|
256
|
+
raise ValueError(f"`orientation` can be 'wide' or 'long', got '{orientation}'.")
|
|
257
|
+
|
|
258
|
+
# def __getattr__(self, attr: str):
|
|
259
|
+
# if attr not in Results._valid_attrs:
|
|
260
|
+
# raise Exception(f"Attribute '{attr}' is not accessible, pick one of {Results._valid_attrs}")
|
|
261
|
+
# if not hasattr(self, f"_{attr}"):
|
|
262
|
+
# raise Exception(f"`Results` object has no attribute '{attr}'")
|
|
263
|
+
# if getattr(self, f"_{attr}") is None:
|
|
264
|
+
# raise Exception(f"Attribute '{attr}' not properly loaded, consider checking `results.entries()` first")
|
|
265
|
+
# return getattr(self, f"_{attr}")
|
|
266
|
+
|
|
267
|
+
def _build_cache(self):
|
|
268
|
+
if self._cache is None:
|
|
269
|
+
self._cache = self.to_dict(build_cache=False)
|
|
270
|
+
|
|
271
|
+
def _has_cache(self):
|
|
272
|
+
return self._cache is not None
|
|
273
|
+
|
|
274
|
+
def _get_safe(self, component: str, fieldtype: str, field: str, mode: str = "primal"):
|
|
275
|
+
if mode not in ["primal", "dual"]:
|
|
276
|
+
raise ValueError(f"`mode` must be 'primal' or 'dual', got '{mode}'.")
|
|
277
|
+
|
|
278
|
+
try:
|
|
279
|
+
components = self._model["components"]
|
|
280
|
+
except Exception:
|
|
281
|
+
raise ValueError("Failed to access `components` in model results")
|
|
282
|
+
try:
|
|
283
|
+
all_results = components[component]
|
|
284
|
+
except Exception:
|
|
285
|
+
raise ValueError(f"Failed to access component '{component}' in model results")
|
|
286
|
+
try:
|
|
287
|
+
container = getattr(all_results, fieldtype)
|
|
288
|
+
except Exception:
|
|
289
|
+
raise ValueError(f"Failed to access results for `fieldtype` '{fieldtype}' in component '{component}'")
|
|
290
|
+
try:
|
|
291
|
+
result = getattr(container, field)
|
|
292
|
+
except Exception:
|
|
293
|
+
raise ValueError(f"Failed to access result '{field}' in component '{component}'")
|
|
294
|
+
|
|
295
|
+
return Results._safe_convert(result)
|
|
296
|
+
|
|
297
|
+
def _from_file(self, file: str):
|
|
298
|
+
results = self._IESopt.load_results(file)
|
|
299
|
+
|
|
300
|
+
result_entries = ddict({})
|
|
301
|
+
for key in results.keys():
|
|
302
|
+
_current = result_entries
|
|
303
|
+
_keys = key.split("/")
|
|
304
|
+
for i in range(len(_keys)):
|
|
305
|
+
if i == len(_keys) - 1:
|
|
306
|
+
_current[_keys[i]] = Results._safe_convert(results[key])
|
|
307
|
+
else:
|
|
308
|
+
_current[_keys[i]] = _current.get(_keys[i], ddict({}))
|
|
309
|
+
_current = _current[_keys[i]]
|
|
310
|
+
|
|
311
|
+
for key in result_entries.keys():
|
|
312
|
+
if hasattr(self, f"_{key}"):
|
|
313
|
+
if getattr(self, f"_{key}") is None:
|
|
314
|
+
setattr(self, f"_{key}", result_entries[key])
|
|
315
|
+
else:
|
|
316
|
+
raise Exception(f"Duplicate result entry: {key}")
|
|
317
|
+
else:
|
|
318
|
+
raise Exception(f"Unknown result entry: {key}")
|
|
319
|
+
|
|
320
|
+
snapshots = results["model/snapshots"]
|
|
321
|
+
self._snapshots = [snapshots[t].name for t in sorted(snapshots.keys())]
|
|
322
|
+
self._components = sorted(results["model/components"].keys())
|
|
323
|
+
self._source = file
|
|
324
|
+
|
|
325
|
+
def _from_model(self, model):
|
|
326
|
+
self._source = "an IESopt model"
|
|
327
|
+
self._model = {
|
|
328
|
+
"components": model.data.results.components,
|
|
329
|
+
"objectives": model.data.results.objectives,
|
|
330
|
+
"custom": model.data.results.customs,
|
|
331
|
+
}
|
|
332
|
+
self._snapshots = [model.data.model.snapshots[t].name for t in model.data.model.T]
|
|
333
|
+
self._components = sorted(model.data.results.components.keys())
|
|
334
|
+
|
|
335
|
+
def __repr__(self) -> str:
|
|
336
|
+
_sep = "', '"
|
|
337
|
+
return (
|
|
338
|
+
"An IESopt result object:"
|
|
339
|
+
+ f"\n\tsource: {self._source}"
|
|
340
|
+
+ "\n\tattributes: "
|
|
341
|
+
+ (
|
|
342
|
+
f"'{self.entries('attributes')[0]}', ..., '{self.entries('attributes')[-1]}'"
|
|
343
|
+
if self._attributes is not None
|
|
344
|
+
else "none"
|
|
345
|
+
)
|
|
346
|
+
+ f"\n\tmodel results: {'yes' if self._model is not None else 'no'}"
|
|
347
|
+
+ "\n\tcustom results: "
|
|
348
|
+
+ (f"{len(self._custom)}" if self._custom is not None and len(self._custom) > 0 else "no")
|
|
349
|
+
+ "\n\tinput fields: "
|
|
350
|
+
+ (f"'{_sep.join(self._input)}'" if self._input is not None else "none")
|
|
351
|
+
+ "\n\tinfo fields: "
|
|
352
|
+
+ (f"'{_sep.join(self._info)}'" if self._info is not None else "none")
|
|
353
|
+
)
|
|
354
|
+
|
|
355
|
+
@classmethod
|
|
356
|
+
def _safe_convert(cls, value):
|
|
357
|
+
# TODO: ensure recursive conversion of all multi-element types
|
|
358
|
+
if jl_isa(value, "AbstractVector"):
|
|
359
|
+
return value.to_numpy(copy=False)
|
|
360
|
+
if jl_isa(value, "AbstractDict"):
|
|
361
|
+
return dict(value)
|
|
362
|
+
if jl_isa(value, "AbstractSet"):
|
|
363
|
+
return set(value)
|
|
364
|
+
return value
|
|
File without changes
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def set_iesopt_module_attr(attr: str, value):
|
|
5
|
+
"""Set an internal attribute of the `iesopt` module."""
|
|
6
|
+
sys.modules["iesopt"].__dict__[f"_!_attr_{attr}"] = value
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_iesopt_module_attr(attr: str):
|
|
10
|
+
"""Get an internal attribute of the `iesopt` module."""
|
|
11
|
+
return sys.modules["iesopt"].__dict__[f"_!_attr_{attr}"]
|