Skip to content

Commit

Permalink
feat(simulation): Add handlers for measures and additional strings
Browse files Browse the repository at this point in the history
  • Loading branch information
chriswmackey authored and Chris Mackey committed Sep 22, 2021
1 parent 99ea2f7 commit af2db74
Show file tree
Hide file tree
Showing 3 changed files with 134 additions and 3 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ jobs:
- name: run semantic release
id: new_release
run: |
nextRelease="`npx semantic-release --dryRun | grep -oP 'Published release \K.*? ' || true`"
npx semantic-release
nextRelease="`npx semantic-release@^17.0.0 --dryRun | grep -oP 'Published release \K.*? ' || true`"
npx semantic-release@^17.0.0
echo "::set-output name=tag::$nextRelease"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
Expand Down
10 changes: 10 additions & 0 deletions pollination_handlers/inputs/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ def get_tempfile(extension, file_name=None):
return file_path


def get_tempfolder(folder_name=None):
"""Get full path to a temporary folder with extension."""
folder_name = str(uuid.uuid4())[:6] if folder_name is None \
or folder_name == '-' else folder_name
temp_dir = tempfile.gettempdir()
folder_path = os.path.join(temp_dir, folder_name)
os.mkdir(folder_path)
return folder_path


def write_values_to_csv(file_path, values):
"""Write a list of fractional values to a discrete 0/1 CSV."""
discrete_vals = []
Expand Down
123 changes: 122 additions & 1 deletion pollination_handlers/inputs/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
import os
import json

from ladybug.futil import copy_file_tree, nukedir
from honeybee_energy.simulation.parameter import SimulationParameter
from honeybee_energy.measure import Measure

from .helper import get_tempfile
from .helper import get_tempfile, get_tempfolder


def energy_sim_par_to_json(sim_par_obj):
Expand Down Expand Up @@ -35,3 +37,122 @@ def energy_sim_par_to_json(sim_par_obj):
'Not {}.'.format(type(sim_par_obj))
)
return sp_file


def measures_to_folder(measures_obj):
"""Translate a list of honeybee-energy Measures to a folder.
Args:
measures_obj: Either a list of honeybee-energy Measure objects or
the path to a folder that contains the measures and a .osw with
the measure arguments. In case the measures_obj is a folder, it will be
returned as is. For a list of objects it will be saved to an OSW file
in a temp folder.
Returns:
str -- Path to a measures folder.
"""
if isinstance(measures_obj, Measure):
measures_obj = [measures_obj]
if measures_obj is None:
return ''
elif isinstance(measures_obj, str):
if measures_obj == '':
return ''
if not os.path.isdir(measures_obj):
raise ValueError('Invalid folder path: %s' % measures_obj)
osw_found = False
for f in os.listdir(measures_obj):
f_lower = f.lower()
if f_lower.endswith('.osw'):
osw_found = True
elif f_lower == 'measure.rb':
raise ValueError(
'Measure folder must contain the constituent measures '
'in sub-directories.')
if not osw_found:
raise ValueError('No .osw file was found in: %s' % measures_obj)
mea_folder = measures_obj
elif isinstance(measures_obj, (list, tuple)):
if len(measures_obj) == 0:
return ''
osw_dict = {} # dictionary that will be turned into the OSW JSON
osw_dict['steps'] = []
mea_folder = get_tempfolder() # will become the folder with all the measures
# ensure measures are correctly ordered
m_dict = {'ModelMeasure': [], 'EnergyPlusMeasure': [], 'ReportingMeasure': []}
for measure in measures_obj:
assert isinstance(measure, Measure), 'Expected honeybee-energy Measure. ' \
'Got {}.'.format(type(measure))
m_dict[measure.type].append(measure)
sorted_measures = m_dict['ModelMeasure'] + m_dict['EnergyPlusMeasure'] + \
m_dict['ReportingMeasure']
# add the measures and the measure paths to the OSW
for measure in sorted_measures:
measure.validate() # ensure that all required arguments have values
osw_dict['steps'].append(measure.to_osw_dict()) # add measure to workflow
dest_folder = os.path.join(mea_folder, os.path.basename(measure.folder))
copy_file_tree(measure.folder, dest_folder)
test_dir = os.path.join(dest_folder, 'tests')
if os.path.isdir(test_dir):
nukedir(test_dir, rmdir=True)
# write the dictionary to a workflow.osw
osw_json = os.path.join(mea_folder, 'workflow.osw')
with open(osw_json, 'w') as fp:
json.dump(osw_dict, fp, indent=4)
else:
raise ValueError(
'Measure input should be a list of Measure objects or a path to a folder. '
'Not {}.'.format(type(measures_obj))
)
return mea_folder


def list_to_additional_strings(additional_strings):
"""Translate a list of additional strings into a single string.
Args:
additional_strings: Either a single string or a list of strings to be
joined into one.
Returns:
str -- A single IDF string.
"""
if additional_strings is None:
return ''
elif isinstance(additional_strings, str):
return additional_strings
elif isinstance(additional_strings, (list, tuple)):
return '\n'.join(additional_strings)
else:
raise ValueError(
'Additional strings input should be a list or a single string. '
'Not {}.'.format(type(additional_strings))
)


def viz_variables_to_string(viz_variables):
"""Translate a list of visualization variables into a single string.
Args:
viz_variables: Either a single string or a list of strings to be
joined into one.
Returns:
str -- A single IDF string.
"""
if viz_variables is None:
return ''
elif isinstance(viz_variables, str):
if not viz_variables.startswith('-v') and not \
viz_variables.startswith('--viz-variable'):
viz_variables = '-v "{}"'.format(viz_variables)
return viz_variables
elif isinstance(viz_variables, (list, tuple)):
viz_variables = ['-v "{}"'.format(var) for var in viz_variables]
return ' '.join(viz_variables)
else:
raise ValueError(
'Visualization variables input should be a list or a single string. '
'Not {}.'.format(type(viz_variables))
)

0 comments on commit af2db74

Please sign in to comment.