Skip to content

Commit

Permalink
Merge pull request #86 from jgrguric96/hotfix/ModelConstructor
Browse files Browse the repository at this point in the history
Hotfix collection for ModelConstructor class
  • Loading branch information
manuGil authored Nov 28, 2024
2 parents f2e94f5 + 67d6dfe commit 643ab08
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 18 deletions.
42 changes: 42 additions & 0 deletions examples/adder_copy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
scenario:
name: "AddingNumbers" # in mosaik so called world
start_time: '2012-01-02 00:00:00' # ISO 8601 start time of the simulation
end_time: '2012-01-02 00:00:10' # duration in seconds
time_resolution: 900 # time step in seconds. Defaults to 15 minutes (900 s)
results: './out.csv'
models: # list of models for the energy network
- name: Adder1 # name for the model (must be unique)
type: Adder # most match the class inheriting from IlluminatorConstructor
inputs:
in1: 10 # input-name: initial value, default value will be used if not defined
in2: 20
outputs:
out1: 0
parameters:
param1: "adding tens"
- name: Adder2
type: Adder # models can reuse the same type
inputs:
in1: 100 # input-name: initial value, default value will be used if not defined
in2: 200
outputs:
out1: 0
parameters:
param1: "adding hundreds"
connections:
- from: Adder1.out1 # start model, pattern: model_name.output_name/input_name
to: Adder2.in1n # end model
# TODO: Below is what Illuminator looks for, but is not valid. Needs to be fixed
# - from: Adder1-0.hybrid_0.out1
# to: Adder2-0.hybrid_0.in1

#monitor: # a list of models, its inputs, output and states to be monitored and logged
#- Adder2.out2 # pattern model_name.state_name
monitor:
file: './out.csv'
items:
- Adder2.out2




32 changes: 23 additions & 9 deletions src/illuminator/builder/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from dataclasses import dataclass, field
from enum import Enum
from datetime import datetime
import illuminator.engine as engine

class SimulatorType(Enum):
TIME_BASED = 'time-based'
Expand Down Expand Up @@ -56,7 +57,7 @@ class IlluminatorModel():
simulator_type: SimulatorType = SimulatorType.HYBRID
time_step_size: int = 15 # This is closely related to logic in the step method. Currently, all models have the same time step size (15 minutes). This is a global setting for the simulation, not a model-specific setting.
time: Optional[datetime] = None # Shouldn't be modified by the user.

model_type: Optional[str] = "Model"

def __post_init__(self):
self.validate_states()
Expand All @@ -70,7 +71,7 @@ def simulator_meta(self) -> dict:
meta = {
'type': self.simulator_type.value,
'models': {
'Model': {
self.model_type : {
'public': True,
'params': list(self.parameters.keys()),
'attrs': list(self.outputs.keys())
Expand Down Expand Up @@ -111,7 +112,16 @@ def validate_simulator_type(self):
class ModelConstructor(ABC, Simulator):
"""A common interface for constructing models in the Illuminator"""

def __init__(self, model: IlluminatorModel) -> None:
def __init__(self, **kwargs) -> None:
#model: IlluminatorModel
model_vals = engine.current_model
model = IlluminatorModel(
parameters=model_vals['parameters'],
inputs=model_vals["inputs"],
outputs=model_vals["outputs"],
states={},
model_type=model_vals["type"]
)
super().__init__(meta=model.simulator_meta)
self._model = model
self.model_entities = {}
Expand Down Expand Up @@ -140,12 +150,13 @@ def step(self, time:int, inputs:dict=None, max_advance:int=None) -> int:
"""
pass

def init(self, sid, time_resolution, **sim_params): # can be use to update model parameters set in __init__
def init(self, sid, time_resolution=1, **sim_params): # can be use to update model parameters set in __init__
print(f"running extra init")
# This is the standard Mosaik init method signature
self.sid = sid
self.time_resolution = time_resolution

# This bit of code is unused.
# Assuming sim_params is structured as {'sim_params': {model_name: model_data}}
sim_params = sim_params.get('sim_params', {})
if len(sim_params) != 1:
Expand All @@ -156,12 +167,15 @@ def init(self, sid, time_resolution, **sim_params): # can be use to update mode
# self.model = self.load_model_class(self.model_data['model_path'], self.model_data['model_type'])
return self._model.simulator_meta

def create(self, num: int) -> List:
def create(self, num:int, model:str, **model_params) -> List[dict]: # This change is mandatory. It MUST contain num and model as parameters otherwise it receives an incorrect number of parameters
"""Creates an instance of the model"""
for i in range(num):
eid = f"{self._model.simulator_type.value}_{i}"
self.model_entities[eid] = self._model
return list(self.model_entities.keys())
new_entities = [] # See below why this was created
for i in range(num): # this seems ok
eid = f"{self._model.simulator_type.value}_{i}" # this seems ok
self.model_entities[eid] = self._model # this seems fine
# return list(self.model_entities.keys()) # I removed this bit for now. Create is expected to return a list of dictionaries
new_entities.append({'eid': eid, 'type': model}) # So basically, like this. Later on we can look into other alternatives if needed.
return new_entities

def current_time(self):
"""Returns the current time of the simulation"""
Expand Down
2 changes: 1 addition & 1 deletion src/illuminator/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing_extensions import Annotated
import illuminator.engine as engine
from pathlib import Path
from illuminator.cluster import build_runshfile
# from illuminator.cluster import build_runshfile
from illuminator.schema.simulation import load_config_file
from illuminator.engine import Simulation

Expand Down
35 changes: 27 additions & 8 deletions src/illuminator/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from datetime import datetime
from illuminator.schema.simulation import load_config_file

current_model = {}

def create_world(sim_config: dict, time_resolution: int) -> MosaikWorld:
"""
Expand Down Expand Up @@ -158,6 +159,7 @@ def start_simulators(world: MosaikWorld, models: list) -> dict:
for model in models:
model_name = model['name']
model_type = model['type']
set_current_model(model)


if 'parameters' in model:
Expand All @@ -179,6 +181,8 @@ def start_simulators(world: MosaikWorld, models: list) -> dict:
else:
simulator = world.start(sim_name=model_name,
# **model_parameters
model_name = model_name,
sim_params= {model_name: model} # This value gets picked up in the init() function
# Some items must be passed here, and some other at create()
)

Expand All @@ -194,14 +198,19 @@ def start_simulators(world: MosaikWorld, models: list) -> dict:

# TODO:
# this is a temporary solution to continue developing the CLI
entity = model_factory.create(num=1, sim_start='2012-01-01 00:00:00',
panel_data={'Module_area': 1.26, 'NOCT': 44, 'Module_Efficiency': 0.198, 'Irradiance_at_NOCT': 800,
'Power_output_at_STC': 250,'peak_power':600},
m_tilt=14,
m_az=180,
cap=500,
output_type='power'
)

# TODO: If we wish to use different values here, we must define the parameters used here within the appropriate .yaml file.
# Right now adder.yaml defines the custom parameters as "param1"

# entity = model_factory.create(num=1, sim_start='2012-01-01 00:00:00',
# panel_data={'Module_area': 1.26, 'NOCT': 44, 'Module_Efficiency': 0.198, 'Irradiance_at_NOCT': 800,
# 'Power_output_at_STC': 250,'peak_power':600},
# m_tilt=14,
# m_az=180,
# cap=500,
# output_type='power'
# )
entity = model_factory.create(num=1, param1="Not in use")

model_entities[model_name] = entity
print(model_entities)
Expand Down Expand Up @@ -272,6 +281,16 @@ def compute_mosaik_end_time(start_time:str, end_time:str, time_resolution:int =

return steps

# def get_current_model():
# return current_model

def set_current_model(model):
global current_model
current_model["type"] = model['type']
current_model['parameters']=model['parameters']
current_model['inputs']=model["inputs"]
current_model['outputs']=model["outputs"]


def connect_monitor(world: MosaikWorld, model_entities: dict[MosaikEntity],
monitor:MosaikEntity, monitor_config: dict) -> MosaikWorld:
Expand Down
1 change: 1 addition & 0 deletions src/illuminator/schema/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
# monitor and connections sections enforce a format such as
# <model>.<input/output/state>
valid_model_item_format = r'^\w+\.\w+$'
# valid_model_item_format = r'^([\w-]+\.?)+$' # This is kept here as an alternative. I believe this might be useful later on



Expand Down

0 comments on commit 643ab08

Please sign in to comment.