Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Load Flexibility measure #1259

Draft
wants to merge 23 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[flake8]
max-line-length = 120
# module level import not at top of file - we need to import after setting up the path
ignore = E402
1 change: 1 addition & 0 deletions measures/LoadFlexibility/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Insert your license here
Empty file.
171 changes: 171 additions & 0 deletions measures/LoadFlexibility/measure.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
"""insert your copyright here.

# see the URL below for information on how to write OpenStudio measures
# http://nrel.github.io/OpenStudio-user-documentation/reference/measure_writing_guide/
"""

import typing
import openstudio
from pathlib import Path
import os
import json
import subprocess
import dataclasses
import xml.etree.ElementTree as ET
import sys
from typing import List, Dict
from dataclasses import fields

if os.environ.get('DEBUGPY', '') == 'true':
import debugpy
debugpy.listen(5694, in_process_debug_adapter=True)
print("Waiting for debugger attach")
debugpy.wait_for_client()

RESOURCES_DIR = Path(__file__).parent / "resources"
sys.path.insert(0, str(RESOURCES_DIR))
from setpoint import HVACSetpoints
from input_helper import OffsetType, RelativeOffsetData, AbsoluteOffsetData, OffsetTimingData, BuildingInfo, Inputs, Argument, get_input_from_dict
from xml_helper import HPXML
sys.path.pop(0)


class LoadFlexibility(openstudio.measure.ModelMeasure):
"""A Residential Load Flexibility measure."""

def name(self):
"""Returns the human readable name.

Measure name should be the title case of the class name.
The measure name is the first contact a user has with the measure;
it is also shared throughout the measure workflow, visible in the OpenStudio Application,
PAT, Server Management Consoles, and in output reports.
As such, measure names should clearly describe the measure's function,
while remaining general in nature
"""
return "LoadFlexibility"

def description(self):
"""Human readable description.

The measure description is intended for a general audience and should not assume
that the reader is familiar with the design and construction practices suggested by the measure.
"""
return "A measure to apply load shifting / shedding to a building based on various user arguments."

def modeler_description(self):
"""Human readable description of modeling approach.

The modeler description is intended for the energy modeler using the measure.
It should explain the measure's intent, and include any requirements about
how the baseline model must be set up, major assumptions made by the measure,
and relevant citations or references to applicable modeling resources
"""
return "This applies a load shifting / shedding strategy to a building."

def arguments(self, model: typing.Optional[openstudio.model.Model] = None):
"""Prepares user arguments for the measure.
Measure arguments define which -- if any -- input parameters the user may set before running the measure.
"""
args = openstudio.measure.OSArgumentVector()
inputs = Inputs()
args.append(inputs.upgrade_name.getOSArgument())
args.append(inputs.offset_type.getOSArgument())
for arg in inputs.relative_offset.__dict__.values():
args.append(arg.getOSArgument())
for arg in inputs.absolute_offset.__dict__.values():
args.append(arg.getOSArgument())
for arg in inputs.offset_timing.__dict__.values():
args.append(arg.getOSArgument())
return args

def get_hpxml_path(self, runner: openstudio.measure.OSRunner):
workflow_json = json.loads(str(runner.workflow()))
hpxml_path = [step['arguments']['hpxml_path'] for step in workflow_json['steps']
if 'HPXMLtoOpenStudio' in step['measure_dir_name']][0]
return hpxml_path

def get_setpoint_csv(self, setpoint_dict: Dict[str, List[int]]):
header = 'heating_setpoint,cooling_setpoint'
vals = '\n'.join([','.join([str(v) for v in val_pair])
for val_pair in zip(setpoint_dict['heating_setpoints'],
setpoint_dict['cooling_setpoints'])])
return f"{header}\n{vals}"

def process_arguments(self, runner, arg_dict: dict, passed_arg: set):
if arg_dict['offset_type'] == OffsetType.absolute:
relative_offset_fields = set(f.name for f in dataclasses.fields(RelativeOffsetData))
if intersect_args := passed_arg & relative_offset_fields:
runner.registerWarning(f"These inputs are ignored ({intersect_args}) since offset type is absolute.")

if arg_dict['offset_type'] == OffsetType.relative:
absolute_offset_fields = set(f.name for f in dataclasses.fields(AbsoluteOffsetData))
if intersect_args := passed_arg & absolute_offset_fields:
runner.registerError(f"These inputs are ignored ({intersect_args}) since offset type is relative.")

return get_input_from_dict(arg_dict)

def run(
self,
model: openstudio.model.Model,
runner: openstudio.measure.OSRunner,
user_arguments: openstudio.measure.OSArgumentMap,
):
"""Defines what happens when the measure is run."""
super().run(model, runner, user_arguments) # Do **NOT** remove this line

if not (runner.validateUserArguments(self.arguments(model), user_arguments)):
return False

runner.registerInfo("Starting LoadFlexibility")
arg_dict = runner.getArgumentValues(self.arguments(model), user_arguments)
passed_args = {arg_name for arg_name, arg_value in dict(user_arguments).items() if arg_value.hasValue()}
inputs = self.process_arguments(runner, arg_dict, passed_args) # Returns Inputs object
osw_path = str(runner.workflow().oswPath().get())

hpxml_path = self.get_hpxml_path(runner)
result = subprocess.run(["openstudio", f"{RESOURCES_DIR}/create_setpoint_schedules.rb",
hpxml_path, osw_path],
capture_output=True)
building_info = BuildingInfo()

setpoints = [HVACSetpoints(os_runner=runner,
building_info=building_info,
inputs=inputs,
heating_setpoints=setpoint['heating_setpoints'],
cooling_setpoints=setpoint['cooling_setpoints'])
for setpoint in json.loads(result.stdout)
] # [{"heating_setpoint": [], "cooling_setpoint": []}]
if result.returncode != 0:
runner.registerError(f"Failed to run create_setpoint_schedules.rb : {result.stderr}")
return False

new_setpoints: List[Dict[str, List[int]]] = []
for setpoint in setpoints:
new_setpoints.append(setpoint._get_modified_setpoints(inputs=inputs))

hpxml = HPXML(hpxml_path)
doc_buildings = hpxml.findall("Building")
for (indx, building) in enumerate(doc_buildings):
doc_building_id = building.find("ns:BuildingID", hpxml.ns).get('id')
output_csv_name = f"hvac_setpoint_schedule_{doc_building_id}.csv"
output_csv_path = Path(hpxml_path).parent / output_csv_name
setpoint_dict = new_setpoints[indx]
with open(output_csv_path, 'w', newline='') as f:
f.write(self.get_setpoint_csv(setpoint_dict))
extension = hpxml.create_elements_as_needed(building, ['BuildingDetails', 'BuildingSummary', 'extension'])

existing_schedules = hpxml.findall('SchedulesFilePath', extension)
for schedule in existing_schedules:
if schedule.text == str(output_csv_path):
break
else:
schedule_path = ET.SubElement(extension, 'SchedulesFilePath')
schedule_path.text = str(output_csv_path)

hpxml.tree.write(hpxml_path, xml_declaration=True, encoding='utf-8')
return True


# register the measure to be used by the application
LoadFlexibility().registerWithApplication()
78 changes: 78 additions & 0 deletions measures/LoadFlexibility/measure.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?xml version="1.0"?>
<measure>
<schema_version>3.1</schema_version>
<name>load_flexibility</name>
<uid>76047a89-6572-46b1-81a9-6800cff63e48</uid>
<version_id>74b8fa96-1cd8-4853-b83b-4e835e2f1e79</version_id>
<version_modified>2024-04-23T22:54:45Z</version_modified>
<xml_checksum>BCF2C799</xml_checksum>
<class_name>LoadFlexibility</class_name>
<display_name>LoadFlexibility</display_name>
<description>A measure to apply load shifting / shedding to a building</description>
<modeler_description>This applies a load shifting / shedding strategy to a building.</modeler_description>
<arguments>
<argument>
<name>offset</name>
<display_name>Offset amount (deg F)</display_name>
<description>How much offset to apply to the HVAC schedule in degree fahrenheit</description>
<type>Double</type>
<required>true</required>
<model_dependent>false</model_dependent>
<default_value>2</default_value>
</argument>
</arguments>
<outputs />
<provenances />
<tags>
<tag>Envelope.Fenestration</tag>
</tags>
<attributes>
<attribute>
<name>Measure Type</name>
<value>ModelMeasure</value>
<datatype>string</datatype>
</attribute>
<attribute>
<name>Measure Language</name>
<value>Python</value>
<datatype>string</datatype>
</attribute>
</attributes>
<files>
<file>
<filename>LICENSE.md</filename>
<filetype>md</filetype>
<usage_type>license</usage_type>
<checksum>CD7F5672</checksum>
</file>
<file>
<filename>.gitkeep</filename>
<filetype>gitkeep</filetype>
<usage_type>doc</usage_type>
<checksum>00000000</checksum>
</file>
<file>
<version>
<software_program>OpenStudio</software_program>
<identifier>3.8.0</identifier>
<min_compatible>3.8.0</min_compatible>
</version>
<filename>measure.py</filename>
<filetype>py</filetype>
<usage_type>script</usage_type>
<checksum>244DC979</checksum>
</file>
<file>
<filename>example_model.osm</filename>
<filetype>osm</filetype>
<usage_type>test</usage_type>
<checksum>53D14E69</checksum>
</file>
<file>
<filename>test_load_flexibility.py</filename>
<filetype>py</filetype>
<usage_type>test</usage_type>
<checksum>5F37BD52</checksum>
</file>
</files>
</measure>
1 change: 1 addition & 0 deletions measures/LoadFlexibility/resources.pth
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
resources
Empty file.
116 changes: 116 additions & 0 deletions measures/LoadFlexibility/resources/create_setpoint_schedules.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
require 'openstudio'
require_relative '../../../resources/hpxml-measures/HPXMLtoOpenStudio/resources/meta_measure'
require_relative '../../../resources/hpxml-measures/HPXMLtoOpenStudio/resources/constants'
require 'openstudio'
require 'pathname'
require 'oga'
require 'json'

Dir["#{File.dirname(__FILE__)}/../../../resources/hpxml-measures/BuildResidentialScheduleFile/resources/*.rb"].each do |resource_file|
require resource_file
end
Dir["#{File.dirname(__FILE__)}/../../../resources/hpxml-measures/HPXMLtoOpenStudio/resources/*.rb"].each do |resource_file|
next if resource_file.include? 'minitest_helper.rb'
require resource_file
end

class SetpointScheduleGenerator

def initialize(hpxml, hpxml_path, workflow_path, building_index)
@hpxml_path = hpxml_path
@hpxml = hpxml
@hpxml_bldg = @hpxml.buildings[building_index]
@epw_path = Location.get_epw_path(@hpxml_bldg, @hpxml_path)
@workflow_json = OpenStudio::WorkflowJSON.new(workflow_path)
@runner = OpenStudio::Measure::OSRunner.new(@workflow_json)
@weather = WeatherFile.new(epw_path: @epw_path, runner: @runner, hpxml: @hpxml)
@sim_year = Location.get_sim_calendar_year(@hpxml.header.sim_calendar_year, @weather)
@total_days_in_year = Constants.NumDaysInYear(@sim_year)
@sim_start_day = DateTime.new(@sim_year, 1, 1)
@minutes_per_step = @hpxml.header.timestep
@steps_in_day = 24 * 60 / @minutes_per_step
end


def get_heating_cooling_setpoint_schedule()
@runner.registerInfo("Creating heating and cooling setpoint schedules for building #{@hpxml_path}")
clg_weekday_setpoints, clg_weekend_setpoints, htg_weekday_setpoints, htg_weekend_setpoints = get_heating_cooling_weekday_weekend_setpoints

heating_setpoints = []
cooling_setpoints = []

@total_days_in_year.times do |day|
today = @sim_start_day + day
day_of_week = today.wday
if [0, 6].include?(day_of_week)
heating_setpoint_sch = htg_weekend_setpoints
cooling_setpoint_sch = clg_weekend_setpoints
else
heating_setpoint_sch = htg_weekday_setpoints
cooling_setpoint_sch = clg_weekday_setpoints
end
@steps_in_day.times do |step|
hour = (step * @minutes_per_step) / 60
heating_setpoints << heating_setpoint_sch[day][hour]
cooling_setpoints << cooling_setpoint_sch[day][hour]
end
end
return {"heating_setpoints": heating_setpoints, "cooling_setpoints": cooling_setpoints}
end

def c2f(setpoint_sch)
setpoint_sch.map { |i| i.map { |j| UnitConversions.convert(j, 'C', 'F') } }
end

def get_heating_cooling_weekday_weekend_setpoints
hvac_control = @hpxml_bldg.hvac_controls[0]
has_ceiling_fan = (@hpxml_bldg.ceiling_fans.size > 0)
cooling_days, heating_days = get_heating_cooling_days(hvac_control)
hvac_control = @hpxml_bldg.hvac_controls[0]
onoff_thermostat_ddb = @hpxml.header.hvac_onoff_thermostat_deadband.to_f
htg_weekday_setpoints, htg_weekend_setpoints = HVAC.get_heating_setpoints(hvac_control, @sim_year, onoff_thermostat_ddb)
clg_weekday_setpoints, clg_weekend_setpoints = HVAC.get_cooling_setpoints(hvac_control, has_ceiling_fan, @sim_year, @weather, onoff_thermostat_ddb)

htg_weekday_setpoints, htg_weekend_setpoints, clg_weekday_setpoints, clg_weekend_setpoints = HVAC.create_setpoint_schedules(@runner, heating_days, cooling_days, htg_weekday_setpoints, htg_weekend_setpoints, clg_weekday_setpoints, clg_weekend_setpoints, @sim_year)
return c2f(clg_weekday_setpoints), c2f(clg_weekend_setpoints), c2f(htg_weekday_setpoints), c2f(htg_weekend_setpoints)
end

def get_heating_cooling_days(hvac_control)
htg_start_month = hvac_control.seasons_heating_begin_month || 1
htg_start_day = hvac_control.seasons_heating_begin_day || 1
htg_end_month = hvac_control.seasons_heating_end_month || 12
htg_end_day = hvac_control.seasons_heating_end_day || 31
clg_start_month = hvac_control.seasons_cooling_begin_month || 1
clg_start_day = hvac_control.seasons_cooling_begin_day || 1
clg_end_month = hvac_control.seasons_cooling_end_month || 12
clg_end_day = hvac_control.seasons_cooling_end_day || 31
heating_days = Schedule.get_daily_season(@sim_year, htg_start_month, htg_start_day, htg_end_month, htg_end_day)
cooling_days = Schedule.get_daily_season(@sim_year, clg_start_month, clg_start_day, clg_end_month, clg_end_day)
return cooling_days, heating_days
end

def main(hpxml_path)
hpxml = HPXML.new(hpxml_path: hpxml_path)
sf = SchedulesFile.new(schedules_paths: hpxml.buildings[0].header.schedules_filepaths,
year: @year,
output_path: @tmp_schedule_file_path)

end
end

if ARGV.empty?
raise "Usage: ruby create_setpoint_schedules.rb <hpxml_path> <workflow_path>"
exit
end

hpxml_path = ARGV[0]
workflow_path = ARGV[1]
hpxml = HPXML.new(hpxml_path: hpxml_path)
num_buildings = hpxml.buildings.size
setpoint_array = []
num_buildings.times do |building_index|
generator = SetpointScheduleGenerator.new(hpxml, hpxml_path, workflow_path, building_index)
setpoints = generator.get_heating_cooling_setpoint_schedule
setpoint_array << setpoints
end
puts(setpoint_array.to_json)
Loading
Loading