Commit f58c4e1c authored by Daniel Lehmberg's avatar Daniel Lehmberg

Squashed 'Tools/SUQController/' content from commit 422405eb

git-subtree-dir: Tools/SUQController
git-subtree-split: 422405eb5e5af234104f908f1d876303bbc470eb
parents
.idea
__pycache__
*.pyc
*.csv
# Vadere output often generated by console
log.out
# do not track vadere processor outputs and overview files (every computer as different paths, which results in changes for every commit)
vadere_scenarios
parid_lookup.csv
# Vadere jar Models are *not* directly stored in the repo anymore via git lfs
*.jar
# Configuration file (gets generated when importing the project)
suq_config.json
# pickle files
*.p
# folders / files when packaging
build
dist
suqc.egg-info
# tutorial output
/tutorial/example_output/
/tutorial/example_multirun_output/
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
### WORK IN PROGRESS
The suq-controller connects the modules "Surrogate Model" (S) and "Uncertainty Quantification" (UQ) (see other vadere Repos).
The main functionality of the `suq-controller` is to query many differently parametrized VADERE scenarios and
return the result of specified quantity of interests (QoI) in a convenient format ([pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html)).
This git repository uses git large file storage (git-lfs). This allows to ship default VADERE models (larger .jar files.)
with the git repository.
For developers: To install git-lfs follow the instructions [here](https://github.com/git-lfs/git-lfs/wiki/Installation)
In file `.gitattributes` in the repo shows the settings for git-lfs.
### Glossary
Other words were used in this project to not confuse terminology with VADERE (such as `scenario` and `project`).
* **container** is the parent folder of (multiple) environments
* **environment** is folder consisting of a specifed VADERE scenario that is intended to query
* **query** is an user request for a quantity of interest for the specific VADERE setting with the given the scenario
set in the environment. A query can simulate VADERE for multiple scenario settings for the parameter variation
(such as a full grid sampling).
#### Getting started
1. Download and install:
**It is highly recommended to install git-lfs to also download the VADERE models.**
Download source code, pre-set VADERE models and example environments with git:
```
git@gitlab.lrz.de:vadere/suq-controller.git
```
Install package `suqc` by running the following command inside the downloaded folder `suq-contoller`. It is recommended
to use `python>=3.6`.
```
python3 setup.py install
```
Note: In Linux this may have to be executed with `sudo`.
This installs the essential package, but does **not** copy the models or example environments. To set up the
corresponding folders and copy the models to the appropriate position run the following command separately.
```
python3 setup_folders.py TODO
```
Test if the installed package was installed successfully by running:
```
python3 -c "import suqc; print(suqc.__version__)"
```
This command should print the installed version number in the terminal. In case an error was thrown the package is
not installed successfully.
2. Configuration of `suqc`
During the run of `setup_folders.py` two folders are created at the user's home path.
1. `.suqc` consists of the meta configuration of the suq-controller. This includes the path to the
environment-container folder and information about the available models.
2. `suqc_envs` is a container and consists of environments that are set up.
#### Introduction
See [SRC_PATH]/tutorial
sudo -H pip3 uninstall suqc
sudo python3 setup.py install
matplotlib==2.2.3
setuptools==39.1.0
fabric==2.4.0
pandas==0.23.4
numpy==1.15.4
#!/usr/bin/env python3
# TODO: """ << INCLUDE DOCSTRING (one-line or multi-line) >> """
import os
from setuptools import setup, find_packages
from suqc.configuration import SuqcConfig
from suqc import __version__
# --------------------------------------------------
# people who contributed code
__authors__ = "Daniel Lehmberg"
# people who made suggestions or reported bugs but didn't contribute code
__credits__ = ["n/a"]
# --------------------------------------------------
# To generate a new reqirements.txt file run in console (install vis 'pip3 install pipreqs'):
# pipreqs --use-local --force /home/daniel/REPOS/suq-controller
with open('requirements.txt', "r") as f:
requirements = f.read().splitlines()
# Writes a file that gives information about the version such that "suqc.__version__" provides the current version,
# which is a convention in Python:
with open(SuqcConfig.path_package_indicator_file(), "w") as file:
file.write(f"version={__version__}")
assert os.path.exists(SuqcConfig.path_package_indicator_file())
setup(
name="suqc",
version=__version__,
license="LGPL",
url="www.vadere.org",
packages=find_packages(),
install_requires=requirements,
data_files=[('suqc', ["suqc/PACKAGE.txt"])]
)
os.remove(SuqcConfig.path_package_indicator_file())
assert not os.path.exists(SuqcConfig.path_package_indicator_file())
\ No newline at end of file
#!/usr/bin/env python3
# TODO: """ << INCLUDE DOCSTRING (one-line or multi-line) >> """
# include imports after here:
# --------------------------------------------------
# people who contributed code
__authors__ = "Daniel Lehmberg"
# people who made suggestions or reported bugs but didn't contribute code
__credits__ = ["n/a"]
# --------------------------------------------------
from suqc.parameter.sampling import *
from suqc.parameter.postchanges import ScenarioChanges
from suqc.qoi import *
from suqc.request import *
__version__ = "1.0rc1"
#!/usr/bin/env python3
# TODO: """ << INCLUDE DOCSTRING (one-line or multi-line) >> """
import os
import json
import os.path as p
import pathlib
# --------------------------------------------------
# people who contributed code
__authors__ = "Daniel Lehmberg"
# people who made suggestions or reported bugs but didn't contribute code
__credits__ = ["n/a"]
# --------------------------------------------------
# configuration of the suq-controller
DEFAULT_SUQ_CONFIG = {"default_vadere_src_path": "TODO", # TODO Feature: compile Vadere before using the jar file
"server": {
"host": "",
"user": "",
"port": -1
}}
def check_setup(_paths_class):
if not os.path.exists(_paths_class.path_cfg_folder()) and _paths_class.is_package_paths():
print(f"INFO: Setting up configuration folder {_paths_class.path_cfg_folder()}")
os.mkdir(
_paths_class.path_cfg_folder()) # the next two checks will fail automatically too, because the folder is empty
if not os.path.exists(_paths_class.path_models_folder()):
print(f"INFO: Setting up default model lookup folder {_paths_class.path_models_folder()}")
os.mkdir(_paths_class.path_models_folder())
if not os.path.exists(_paths_class.path_suq_config_file()):
print(f"INFO: Setting up default configuration file located at {_paths_class.path_suq_config_file()}")
_paths_class.store_config(DEFAULT_SUQ_CONFIG)
if not os.path.exists(_paths_class.path_container_folder()):
print(f"INFO: Setting up the default container path (which will store output of simulation runs). "
f"Location {_paths_class.path_container_folder()}")
os.mkdir(_paths_class.path_container_folder())
return _paths_class
# class annotation -> everythime the clsas is used, it will be checked if the folders are correctly configured
@check_setup
class SuqcConfig(object):
NAME_PACKAGE = "suqc"
NAME_SUQ_CONFIG_FILE = "suq_config.json"
NAME_MODELS_FOLDER = "models"
NAME_CON_FOLDER = "suqc_envs"
NAME_PACKAGE_FILE = "PACKAGE.txt"
IS_PACKAGE: bool = None
@classmethod
def is_package_paths(cls):
if cls.IS_PACKAGE is None:
return os.path.exists(cls.path_package_indicator_file())
else:
return SuqcConfig.IS_PACKAGE
@classmethod
def set_package_paths(cls, package: bool):
SuqcConfig.IS_PACKAGE = package
@classmethod
def _name_cfg_folder(cls):
if cls.is_package_paths():
return ".suqc"
else:
raise RuntimeError("This should not be called when IS_PACKAGE=False.")
@classmethod
def path_usrhome_folder(cls):
return pathlib.Path.home()
@classmethod
def path_src_folder(cls):
return p.abspath(p.join(p.realpath(__file__), os.pardir))
@classmethod
def path_package_indicator_file(cls):
return p.join(cls.path_src_folder(), cls.NAME_PACKAGE_FILE)
@classmethod
def path_cfg_folder(cls):
if cls.is_package_paths():
return p.join(cls.path_usrhome_folder(), cls._name_cfg_folder())
else:
return cls.path_src_folder()
@classmethod
def path_suq_config_file(cls):
if cls.is_package_paths():
return p.join(cls.path_cfg_folder(), cls.NAME_SUQ_CONFIG_FILE)
else:
return p.join(cls.path_src_folder(), cls.NAME_SUQ_CONFIG_FILE)
@classmethod
def load_cfg_file(cls):
with open(cls.path_suq_config_file(), "r") as f:
cfg = json.load(f)
return cfg
@classmethod
def path_models_folder(cls):
if cls.is_package_paths():
return p.join(cls.path_cfg_folder(), cls.NAME_MODELS_FOLDER)
else:
return p.join(cls.path_src_folder(), cls.NAME_MODELS_FOLDER)
@classmethod
def path_container_folder(cls):
if cls.is_package_paths():
return p.join(cls.path_usrhome_folder(), cls.NAME_CON_FOLDER)
else:
return p.join(cls.path_src_folder(), cls.NAME_CON_FOLDER)
@classmethod
def store_config(cls, cfg):
with open(cls.path_suq_config_file(), "w") as outfile:
json.dump(cfg, outfile, indent=4)
@classmethod
def store_server_config(cls, host: str, user: str, port: int):
cfg_file = cls.load_cfg_file()
cfg_file["server"]["host"] = host
cfg_file["server"]["user"] = user
cfg_file["server"]["port"] = port
cls.store_config(cfg_file)
if __name__ == "__main__":
print(SuqcConfig)
\ No newline at end of file
#!/usr/bin/env python3
# TODO: """ << INCLUDE DOCSTRING (one-line or multi-line) >> """
import json
import glob
import subprocess
import time
import os
from shutil import rmtree
from typing import *
from suqc.configuration import SuqcConfig
from suqc.utils.general import user_query_yes_no, get_current_suqc_state, create_folder
# --------------------------------------------------
# people who contributed code
__authors__ = "Daniel Lehmberg"
# people who made suggestions or reported bugs but didn't contribute code
__credits__ = ["n/a"]
# --------------------------------------------------
# configuration of the suq-controller
DEFAULT_SUQ_CONFIG = {"default_vadere_src_path": "TODO", # TODO Feature: compile Vadere before using the jar file
"server": {
"host": "",
"user": "",
"port": -1
}}
@DeprecationWarning
def get_suq_config():
assert os.path.exists(SuqcConfig.path_suq_config_file()), "Config file does not exist."
with open(SuqcConfig.path_suq_config_file(), "r") as f:
config_file = f.read()
return json.loads(config_file)
class VadereConsoleWrapper(object):
# Current log level choices, requires to manually add, if there are changes
ALLOWED_LOGLVL = ["OFF", "FATAL", "TOPOGRAPHY_ERROR", "TOPOGRAPHY_WARN", "INFO", "DEBUG", "ALL"]
def __init__(self, model_path: str, loglvl="ALL"):
self.jar_path = os.path.abspath(model_path)
assert os.path.exists(self.jar_path)
self.loglvl = loglvl
assert self.loglvl in self.ALLOWED_LOGLVL, f"set loglvl={self.loglvl} not contained in allowed: " \
f"{self.ALLOWED_LOGLVL}"
if not os.path.exists(self.jar_path):
raise FileExistsError(f"Vadere console file {self.jar_path} does not exist.")
def run_simulation(self, scenario_fp, output_path):
start = time.time()
ret_val = subprocess.call(["java", "-jar",
self.jar_path, "--loglevel",
self.loglvl, "suq", "-f", scenario_fp,
"-o", output_path])
return ret_val, time.time() - start
@classmethod
def from_default_models(cls, model):
if not model.endswith(".jar"):
model = ".".join([model, "jar"])
return cls(os.path.join(SuqcConfig.path_models_folder(), model))
@classmethod
def from_model_path(cls, model_path):
return cls(model_path)
@classmethod
def from_new_compiled_package(cls, src_path=None):
pass # TODO: use default src_path
@classmethod
def infer_model(cls, model):
if isinstance(model, str):
if os.path.exists(model):
return VadereConsoleWrapper.from_model_path(os.path.abspath(model))
else:
return VadereConsoleWrapper.from_default_models(model)
elif isinstance(model, VadereConsoleWrapper):
return model
else:
raise ValueError("Failed to infer the Vadere model.")
class EnvironmentManager(object):
output_folder = "vadere_output"
def __init__(self, env_name: str):
self.name = env_name
self.env_path = self.environment_path(self.name)
print(f"INFO: Set environment path to {self.env_path}")
if not os.path.exists(self.env_path):
raise FileNotFoundError(f"Environment {self.env_path} does not exist. Use function "
f"'EnvironmentManager.create_environment' or "
f"'EnvironmentManager.create_if_not_exist'")
self._scenario_basis = None
@property
def basis_scenario(self):
if self._scenario_basis is None:
path_basis_scenario = self.path_basis_scenario
with open(path_basis_scenario, "r") as f:
basis_file = json.load(f)
self._scenario_basis = basis_file
return self._scenario_basis
@property
def path_basis_scenario(self):
sc_files = glob.glob(os.path.join(self.env_path, "*.scenario"))
assert len(sc_files) == 1, "None or too many .scenario files found in environment."
return sc_files[0]
@classmethod
def create_if_not_exist(cls, env_name: str, basis_scenario: Union[str, dict]):
target_path = cls.environment_path(env_name)
if os.path.exists(target_path):
existing = cls(env_name)
# TODO: maybe it is good to compare if the handled file is the same as the existing
#exist_basis_file = existing.get_vadere_scenario_basis_file()
return existing
else:
return cls.create_environment(env_name, basis_scenario)
@classmethod
def create_environment(cls, env_name: str, basis_scenario: Union[str, dict], replace: bool = False):
# Check if environment already exists
target_path = cls.environment_path(env_name)
if replace and os.path.exists(target_path):
if replace:
cls.remove_environment(env_name, force=True)
elif not cls.remove_environment(env_name):
print("Aborting to create a new scenario.")
return
# Create new environment folder
os.mkdir(target_path)
if isinstance(basis_scenario, str): # assume that this is a path