Skip to content

Commit

Permalink
update the log messages and the check for the advance api
Browse files Browse the repository at this point in the history
  • Loading branch information
Huang committed Jun 23, 2022
1 parent 755259d commit 992fe62
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 45 deletions.
2 changes: 1 addition & 1 deletion examples/python/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def control_test(control_module='', start_time=0, warmup_period=0, length=24*360
res = check_response(requests.put('{0}/scenario'.format(url), data=scenario))['time_period']
print(res)
# Record test simulation start time
start_time = res['time']
start_time = int(res['time'])
# Set final time and total time steps to be very large since scenario defines length
final_time = np.inf
total_time_steps = int((365 * 24 * 3600)/step)
Expand Down
6 changes: 3 additions & 3 deletions restapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ def construct(status, message, payload):

# ``initialize`` interface
parser_initialize = reqparse.RequestParser()
parser_initialize.add_argument('start_time', type=float, required=True, help=error_number_input.format('start time'))
parser_initialize.add_argument('warmup_period', type=float, required=True, help=error_number_input.format('warmup period'))
parser_initialize.add_argument('start_time', type=int, required=True, help=error_number_input.format('start time'))
parser_initialize.add_argument('warmup_period', type=int, required=True, help=error_number_input.format('warmup period'))
# ``advance`` interface
parser_advance = reqparse.RequestParser()
for key in case.u.keys():
Expand All @@ -67,7 +67,7 @@ def construct(status, message, payload):
parser_forecast_parameters = reqparse.RequestParser()
forecast_parameters = ['horizon', 'interval']
for arg in forecast_parameters:
parser_forecast_parameters.add_argument(arg, type=float, required=True, help=error_number_input.format(arg))
parser_forecast_parameters.add_argument(arg, type=int, required=True, help=error_number_input.format(arg))
# ``price_scenario`` interface
parser_scenario = reqparse.RequestParser()
parser_scenario.add_argument('electricity_price', type=str, help="electricty price should be a string")
Expand Down
83 changes: 48 additions & 35 deletions testcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def __init__(self, fmupath='models/wrapped.fmu'):
# Set default communication step
self.set_step(int(self.config_json['step']))
# Set default forecast parameters
self.set_forecast_parameters(self.config_json['horizon'], self.config_json['interval'])
self.set_forecast_parameters(int(self.config_json['horizon']), int(self.config_json['interval']))
# Initialize simulation data arrays
self.__initilize_data()
# Set default fmu simulation options
Expand All @@ -73,7 +73,7 @@ def __init__(self, fmupath='models/wrapped.fmu'):
# Instantiate a KPI calculator for the test case
self.cal = KPI_Calculator(testcase=self)
# Initialize test case
self.initialize(self.config_json['start_time'], self.config_json['warmup_period'])
self.initialize(int(self.config_json['start_time']), int(self.config_json['warmup_period']))
# Set default scenario
self.set_scenario(self.config_json['scenario'])

Expand Down Expand Up @@ -207,7 +207,7 @@ def advance(self, u):
----------
u : dict
Defines the control input data to be used for the step.
{<input_name>_activate : bool or int,
{<input_name>_activate : bool,
<input_name>_u : float}
Returns
Expand Down Expand Up @@ -251,20 +251,33 @@ def advance(self, u):
u_list = []
u_trajectory = self.start_time
for key in u.keys():
if key != 'time' and u[key] and key in self.input_names:
try:
value = float(u[key])
except:
status = 400
message = "Invalid value for {} - value must be a float but is {}".format(key, type(u[key]))
logging.error(message)
return status, message, None
# Check min/max if not activation input
if key not in self.input_names and key != 'time':
status = 400
message = "Unexpected input variable: {}".format(key)
logging.error(message)
return status, message, None
if key != 'time' and u[key]:
if '_activate' not in key:
try:
value = float(u[key])
except:
status = 400
message = "Invalid value for {} - value must be a float but is {}".format(key, type(u[key]))
logging.error(message)
return status, message, None
# Check min/max if not activation input
checked_value, message = self._check_value_min_max(key, value)
if message is not None:
logging.warning(message)
alert_message = alert_message +'; '+ message
else:
try:
value = float(u[key])
except:
status = 400
message = "Invalid value for {} - value must be a float but is {}".format(key, type(u[key]))
logging.error(message)
return status, message, None
checked_value = value
u_list.append(key)
u_trajectory = np.vstack((u_trajectory, checked_value))
Expand Down Expand Up @@ -301,9 +314,9 @@ def advance(self, u):
else:
# Errors in the simulation
status = 500
message = "Failed to advance simulation: {}"
message = "Failed to advance simulation: {}".format(res)
payload = res
logging.error(message.format(res))
logging.error(message)
return status, message, payload
else:
# Simulation at end time
Expand All @@ -318,11 +331,11 @@ def initialize(self, start_time, warmup_period, end_time=np.inf):
Parameters
----------
start_time: float
start_time: int
Start time of simulation to initialize to in seconds.
warmup_period: float
warmup_period: int
Length of time before start_time to simulate for warmup in seconds.
end_time: float, optional
end_time: int, optional
Specifies a finite end time to allow the simulation to continue
Default value is infinite.
Expand Down Expand Up @@ -351,24 +364,24 @@ def initialize(self, start_time, warmup_period, end_time=np.inf):
self.__initilize_data()
self.elapsed_control_time_ratio = np.array([])
# Check if the inputs are valid
if not isinstance(start_time, float):
if not isinstance(start_time, int):
status = 400
message = "parameter 'start_time' for initializing the test simulation must be a number but is {}.".format(type(start_time))
message = "Parameter 'start_time' for initializing the test simulation must be an integer but is {}.".format(type(start_time))
logging.error(message)
return status, message, payload
if not isinstance(warmup_period, float):
if not isinstance(warmup_period, int):
status = 400
message = "parameter 'warmup_period' for initializing the test simulation must be a number but is {}.".format(type(warmup_period))
message = "Parameter 'warmup_period' for initializing the test simulation must be an integer but is {}.".format(type(warmup_period))
logging.error(message)
return status, message, payload
if start_time < 0:
status = 400
message = "parameter 'start_time' for initializing the test simulation cannot be negative."
message = "Parameter 'start_time' for initializing the test simulation cannot be negative."
logging.error(message)
return status, message, payload
if warmup_period < 0:
status = 400
message = "parameter 'warmup_period' for initializing the test simulation cannot be negative."
message = "Parameter 'warmup_period' for initializing the test simulation cannot be negative."
logging.error(message)
return status, message, payload
# Record initial testing time
Expand Down Expand Up @@ -465,7 +478,7 @@ def set_step(self, step):
if not isinstance(step, int):
payload = None
status = 400
message = "parameter 'step' must be an integral number but is {}".format(type(step))
message = "Parameter 'step' must be an integer but is {}".format(type(step))
logging.error(message)
return status, message, payload
if step < 0:
Expand Down Expand Up @@ -587,12 +600,12 @@ def get_results(self, var, start_time, final_time):
status = 200
if not isinstance(start_time, float):
status = 400
message = "parameter 'start_time' for getting the results must be a number but is {}.".format(type(start_time))
message = "Parameter 'start_time' for getting the results must be a float but is {}.".format(type(start_time))
logging.error(message)
return status, message, None
if not isinstance(final_time, float):
status = 400
message = "parameter 'final_time' for getting the results must be a number but is {}.".format(type(final_time))
message = "Parameter 'final_time' for getting the results must be a float but is {}.".format(type(final_time))
logging.error(message)
return status, message, None
message = "Queried results data successfully for point {}".format(var)
Expand Down Expand Up @@ -685,9 +698,9 @@ def set_forecast_parameters(self, horizon, interval):
Parameters
----------
horizon: float
horizon: int
Forecast horizon in seconds.
interval: float
interval: int
Forecast interval in seconds.
Returns
Expand All @@ -709,19 +722,19 @@ def set_forecast_parameters(self, horizon, interval):
status = 200
message = "Forecast horizon and interval were set successfully."
payload = dict()
if isinstance(horizon, float):
if isinstance(horizon, int):
self.horizon = horizon
else:
status = 400
message = "parameter 'horizon' for setting the simulation scenario must be a number but is {}.".format(type(horizon))
message = "Parameter 'horizon' for setting the simulation scenario must be an integer but is {}.".format(type(horizon))
logging.error(message)
return status, message, payload
if isinstance(interval, float):
if isinstance(interval, int):
self.interval = interval
else:
payload = None
status = 400
message = "parameter 'interval' for setting the simulation scenario must be a number but is {}.".format(type(interval))
message = "Parameter 'interval' for setting the simulation scenario must be an integer but is {}.".format(type(interval))
logging.error(message)
return status, message, payload
try:
Expand Down Expand Up @@ -876,7 +889,7 @@ def set_scenario(self, scenario):
return status, message, payload
try:
if scenario['time_period']:
initialize_payload = self.initialize(start_time, warmup_period, end_time=end_time)
initialize_payload = self.initialize(int(start_time), int(warmup_period), end_time=end_time)
if initialize_payload[0] != 200:
status = 500
message = initialize_payload[1]
Expand Down Expand Up @@ -1082,10 +1095,10 @@ def _check_value_min_max(self, var, value):
# Check the value and truncate if necessary
if value > maxi:
checked_value = maxi
message = 'Value of {0} for {1} is above maximum of {2}. Using {2}. '.format(value, var, maxi)
message = 'WARNING: value of {0} for {1} is above maximum of {2}. Using {2}. '.format(value, var, maxi)
elif value < mini:
checked_value = mini
message = 'Value of {0} for {1} is below minimum of {2}. Using {2}. '.format(value, var, mini)
message = 'WARNING: value of {0} for {1} is below minimum of {2}. Using {2}. '.format(value, var, mini)
else:
checked_value = value

Expand Down
12 changes: 6 additions & 6 deletions testing/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,9 +353,9 @@ def results_to_df(self, points, start_time, final_time, url='http:https://127.0.0.1:50
----------
points: list of str
List of points to retrieve from boptest api.
start_time: float
start_time: int
Starting time of data to get in seconds.
final_time: float
final_time: int
Ending time of data to get in seconds.
url: str
URL pointing to deployed boptest test case.
Expand Down Expand Up @@ -499,8 +499,8 @@ def test_initialize(self):
# Get current step
step = requests.get('{0}/step'.format(self.url)).json()
# Initialize
start_time = 0.5*24*3600
y = requests.put('{0}/initialize'.format(self.url), data={'start_time':start_time, 'warmup_period':0.5*24*3600}).json()
start_time = int(0.5*24*3600)
y = requests.put('{0}/initialize'.format(self.url), data={'start_time':start_time, 'warmup_period':int(0.5*24*3600)}).json()
# Check that initialize returns the right initial values and results
df = pd.DataFrame.from_dict(y, orient = 'index', columns=['value'])
df.index.name = 'keys'
Expand Down Expand Up @@ -574,7 +574,7 @@ def test_advance_false_overwrite(self):
u = {
'oveTSetSup_activate': 0,
'oveTSetSup_u': 273.15+60,
'ovePum_activate': 0,
'ovePum_activate': 0,
'ovePum_u': 1
}
elif self.name == 'bestest_hydronic_heat_pump':
Expand Down Expand Up @@ -788,7 +788,7 @@ def test_invalid_initialize(self):
# Initialize
start_time = "0.5 * 24 * 3600"
y = requests.put('{0}/initialize'.format(self.url),
data={'start_time': start_time, 'warmup_period': 0.5 * 24 * 3600})
data={'start_time': start_time, 'warmup_period': int(0.5 * 24 * 3600)})
self.compare_error_code(y, "Invalid initialize request did not return 400 message.")

def test_invalid_advance(self):
Expand Down

0 comments on commit 992fe62

Please sign in to comment.