Skip to content
Snippets Groups Projects
Commit 566df372 authored by Zizhe Wang's avatar Zizhe Wang
Browse files

fix load libraries

parent 9d5d068c
Branches
Tags
No related merge requests found
{ {
"DATA_FILE_PATH": "energy_available_and_user_demand_data.txt", "DATA_FILE_PATH": "data/energy_available_and_user_demand.txt",
"CONFIG_PATH": "config.json", "CONFIG_PATH": "config.json",
"MODEL_FILE": "ITSystem.mo", "MODEL_FILE": "ITSystem.mo",
"MODEL_NAME": "ITSystem", "MODEL_NAME": "ITSystem",
...@@ -46,9 +46,9 @@ ...@@ -46,9 +46,9 @@
"ENABLE_PLOT": false "ENABLE_PLOT": false
}, },
"LIBRARY_CONFIG": { "LIBRARY_CONFIG": {
"LOAD_LIBRARIES": true, "LOAD_LIBRARIES": false,
"LIBRARIES": [ "LIBRARIES": [
{"name": "PNlib-3.0.0", "path": "PNlib-3.0.0/PNlib/package.mo"} {"name": "", "path": ""}
] ]
}, },
"N_JOBS": -1 "N_JOBS": -1
......
...@@ -8,10 +8,16 @@ import shutil ...@@ -8,10 +8,16 @@ import shutil
import tempfile import tempfile
from OMPython import OMCSessionZMQ from OMPython import OMCSessionZMQ
def init_omc_session(temp_dir, model_file): def init_omc_session(temp_dir, model_file, library_config):
omc = OMCSessionZMQ() omc = OMCSessionZMQ()
omc.sendExpression(f'cd("{temp_dir}")') omc.sendExpression(f'cd("{temp_dir}")')
if library_config['LOAD_LIBRARIES']:
for lib in library_config['LIBRARIES']:
library_path = os.path.join(os.getcwd(), 'models', lib['path']).replace('\\', '/')
omc.sendExpression(f'loadFile("{library_path}")')
omc.sendExpression(f'loadModel({lib["name"]})')
load_result = omc.sendExpression(f'loadFile("{model_file}")') load_result = omc.sendExpression(f'loadFile("{model_file}")')
print(f"Load model result: {load_result}")
return omc return omc
def build_model(omc, model_name): def build_model(omc, model_name):
...@@ -22,6 +28,7 @@ def simulate_and_evaluate(parameters, simulation_time, simulation_inputs, orches ...@@ -22,6 +28,7 @@ def simulate_and_evaluate(parameters, simulation_time, simulation_inputs, orches
# General setup and configuration # General setup and configuration
model_file = orchestration_config['MODEL_FILE'] model_file = orchestration_config['MODEL_FILE']
model_name = orchestration_config['MODEL_NAME'] model_name = orchestration_config['MODEL_NAME']
model_path = os.path.join(os.getcwd(), 'models', model_file)
param_types = {param: details['type'] for param, details in orchestration_config['TUNABLE_PARAMETERS']['PARAM_BOUNDS'].items()} param_types = {param: details['type'] for param, details in orchestration_config['TUNABLE_PARAMETERS']['PARAM_BOUNDS'].items()}
# Create a temporary directory to avoid GUID mismatch issues # Create a temporary directory to avoid GUID mismatch issues
...@@ -32,7 +39,7 @@ def simulate_and_evaluate(parameters, simulation_time, simulation_inputs, orches ...@@ -32,7 +39,7 @@ def simulate_and_evaluate(parameters, simulation_time, simulation_inputs, orches
goal_expression = orchestration_config['CRITERIA']['GOAL_EXPRESSION'] goal_expression = orchestration_config['CRITERIA']['GOAL_EXPRESSION']
try: try:
omc = init_omc_session(temp_dir, model_file) omc = init_omc_session(temp_dir, model_path, orchestration_config['LIBRARY_CONFIG'])
build_result = build_model(omc, model_name) build_result = build_model(omc, model_name)
print(f"Model build result: {build_result}") print(f"Model build result: {build_result}")
...@@ -43,14 +50,19 @@ def simulate_and_evaluate(parameters, simulation_time, simulation_inputs, orches ...@@ -43,14 +50,19 @@ def simulate_and_evaluate(parameters, simulation_time, simulation_inputs, orches
value = int(value) value = int(value)
response = omc.sendExpression(f'setParameterValue({model_name}, {param}, {value})') response = omc.sendExpression(f'setParameterValue({model_name}, {param}, {value})')
print(f"Set parameter {param} to {value}: {response}") print(f"Set parameter {param} to {value}: {response}")
if response != 'Ok':
raise RuntimeError(f"Error setting parameter {param}: {response}")
# Set input parameters # Set input parameters
for input_param, value in simulation_inputs.items(): for input_param, value in simulation_inputs.items():
omc.sendExpression(f'setParameterValue({model_name}, {input_parameters[input_param]}, {value})') omc.sendExpression(f'setParameterValue({model_name}, {input_parameters[input_param]}, {value})')
print(f"Set input parameter {input_param} to {value}: {response}")
# Run simulation # Run simulation
result = omc.sendExpression(f'simulate({model_name}, stopTime={simulation_time})') result = omc.sendExpression(f'simulate({model_name}, stopTime={simulation_time})')
print(f"Simulation result: {result}")
termination_message = result.get('messages', "") termination_message = result.get('messages', "")
print(f"Simulation termination message: {termination_message}")
# Determine depletion time if simulation terminates early # Determine depletion time if simulation terminates early
match = re.search(r'Simulation call terminate\(\) at time ([\d\.]+)', termination_message) match = re.search(r'Simulation call terminate\(\) at time ([\d\.]+)', termination_message)
...@@ -107,6 +119,7 @@ def adaptive_control_loop(data, moo_wrapper, orchestration_config): ...@@ -107,6 +119,7 @@ def adaptive_control_loop(data, moo_wrapper, orchestration_config):
# Try each parameter set in order until goal is satisfied or options are exhausted # Try each parameter set in order until goal is satisfied or options are exhausted
goal_satisfied = False goal_satisfied = False
for best_parameters in parameter_list: for best_parameters in parameter_list:
try: try:
evaluation_results, goal_satisfied, parameters, depletion_time = simulate_and_evaluate( evaluation_results, goal_satisfied, parameters, depletion_time = simulate_and_evaluate(
......
# Copyright (c) 2024 - Zizhe Wang # Copyright (c) 2024 - Zizhe Wang
# https://zizhe.wang # https://zizhe.wang
import json
import os import os
import json
import shutil
from optimize_main import run_optimization from optimize_main import run_optimization
from OMPython import OMCSessionZMQ from OMPython import OMCSessionZMQ
...@@ -11,6 +12,8 @@ class MOO4ModelicaWrapper: ...@@ -11,6 +12,8 @@ class MOO4ModelicaWrapper:
self.orchestration_config_path = orchestration_config_path self.orchestration_config_path = orchestration_config_path
self.config_path = config_path self.config_path = config_path
self.load_configs() self.load_configs()
self.backup_config_path = self.config_path + ".bak"
self.backup_config_file()
self.update_config_file() self.update_config_file()
self.omc = OMCSessionZMQ() self.omc = OMCSessionZMQ()
self.load_libraries() self.load_libraries()
...@@ -22,6 +25,13 @@ class MOO4ModelicaWrapper: ...@@ -22,6 +25,13 @@ class MOO4ModelicaWrapper:
with open(self.config_path, 'r') as f: with open(self.config_path, 'r') as f:
self.config = json.load(f) self.config = json.load(f)
def backup_config_file(self):
shutil.copy(self.config_path, self.backup_config_path)
def restore_config_file(self):
shutil.copy(self.backup_config_path, self.config_path)
os.remove(self.backup_config_path)
def update_config_file(self): def update_config_file(self):
# Update config with orchestration config # Update config with orchestration config
self.config['MODEL_NAME'] = self.orchestration_config['MODEL_NAME'] self.config['MODEL_NAME'] = self.orchestration_config['MODEL_NAME']
...@@ -77,3 +87,6 @@ class MOO4ModelicaWrapper: ...@@ -77,3 +87,6 @@ class MOO4ModelicaWrapper:
{param: value for param, value in zip(self.config['PARAMETERS'], params)} {param: value for param, value in zip(self.config['PARAMETERS'], params)}
for params in parameters for params in parameters
] ]
def __del__(self):
self.restore_config_file()
\ No newline at end of file
...@@ -2,24 +2,21 @@ ...@@ -2,24 +2,21 @@
# https://zizhe.wang # https://zizhe.wang
import json import json
import os
from orchestration_wrapper import MOO4ModelicaWrapper from orchestration_wrapper import MOO4ModelicaWrapper
from orchestration_configurator import adaptive_control_loop, read_data_from_file from orchestration_configurator import adaptive_control_loop, read_data_from_file
base_path = os.path.dirname(__file__)
orchestration_config_path = os.path.join(base_path, 'orchestration_config.json')
def main(): def main():
# Get paths from the orchestration configuration
orchestration_config_path = 'orchestration_config.json'
config_path = 'config.json'
# Load the orchestration configuration # Load the orchestration configuration
with open(orchestration_config_path, 'r') as f: with open(orchestration_config_path, 'r') as f:
orchestration_config = json.load(f) orchestration_config = json.load(f)
# Get paths from the orchestration configuration
data_file_path = os.path.join(base_path, orchestration_config['DATA_FILE_PATH'])
config_path = os.path.join(base_path, orchestration_config['CONFIG_PATH'])
# Read data from the specified data file # Read data from the specified data file
data = read_data_from_file(data_file_path) data_file = orchestration_config['DATA_FILE_PATH']
data = read_data_from_file(data_file)
# Initialize the MOO4ModelicaWrapper with the path to the MOO4Modelica config and the orchestration configuration # Initialize the MOO4ModelicaWrapper with the path to the MOO4Modelica config and the orchestration configuration
moo_wrapper = MOO4ModelicaWrapper(orchestration_config_path=orchestration_config_path, config_path=config_path) moo_wrapper = MOO4ModelicaWrapper(orchestration_config_path=orchestration_config_path, config_path=config_path)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment