-
Notifications
You must be signed in to change notification settings - Fork 1
/
app_Jihoon_merged.py
493 lines (369 loc) · 18.4 KB
/
app_Jihoon_merged.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
import pathlib
from uuid import uuid4
import os
import glob
import ladybug_geometry.geometry2d
import ladybug_geometry.geometry3d
import streamlit as st
import honeybee
import ladybug
from ladybug.epw import EPW
from ladybug.wea import Wea
import ladybug_geometry
from honeybee.room import Room
from honeybee.model import Model, Face, Aperture
from honeybee_radiance.properties.model import ModelRadianceProperties
from honeybee_vtk.model import DisplayMode
from honeybee_vtk.model import Model as VTKModel
from honeybee_vtk.vtkjs.schema import SensorGridOptions
from honeybee_radiance.sensorgrid import SensorGrid
from visualize_model import generate_vtk_model
from streamlit_vtkjs import st_vtkjs
from pollination_io.api.client import ApiClient
from pollination_io.interactors import Job, NewJob, Recipe
from queenbee.job.job import JobStatusEnum
from streamlit_autorefresh import st_autorefresh
import dload
# Jihoon: Modules to implement an EnergyPlus simulations
from inputs import initialize
from simulation import run_energy_simulation
from outputs import display_results
#### CONFIGURE PAGE
app_title = 'ROOMBOX - HACKSIMBUILD 2024'
st.set_page_config(
page_title=app_title,
layout='wide',
page_icon='assets/240520_Roombox_Logo_v4.ico',
initial_sidebar_state='collapsed'
)
if 'model_names' not in st.session_state:
st.session_state['model_names'] = []
if 'models' not in st.session_state:
st.session_state['models'] = []
if 'study_inputs' not in st.session_state:
st.session_state['study_inputs'] = []
if 'model_var' not in st.session_state:
st.session_state['model_var'] = []
# Jihoon: initialize the app and load up all of the inputs
initialize()
model_name = []
baseline_model = []
hor_num = 0
hor_depth = 0
run_simulation = []
vert_depth = 0
vert_num = 0
epw_data = 0
epw_filepath = ''
study_name = ''
#### hide sidebar by default
# st.markdown("""
# <style>
# section[data-testid="stSidebar"][aria-expanded="true"]{
# display: none;
# }
# </style>
# """, unsafe_allow_html=True)
#### login
api_key = st.sidebar.text_input(
'Enter Pollination APIKEY', type='password', value='8B8AC8B0.13F7476390ECDE0F50F7ED05',
help=':bulb: You only need an API Key to access private projects. '
'If you do not have a key already go to the settings tab under your profile to '
'generate one.'
) or None
owner = st.sidebar.text_input('Project Owner', value="justinshultz")
project = st.sidebar.text_input('Project Name', value="hacksimbuild-2024")
#### run pollination
api_client = ApiClient(api_token=api_key)
st.image("assets/240520_Roombox_Logo_w.Name_w.PplName.png", width=700)
# if st.button('Clear Session State'):
# st.session_state.clear()
# st.success('Session state cleared!')
tab1, tab2 = st.tabs(['| 1 Model Creation','| 2 Results Visualization'])
with tab1:
##### establish layout
col1, col2, col3= st.columns([1,2,1])
col2_con = col2.container()
with col1:
#### room setup
col1_header, col2_header = st.columns([2,1])
col1_header.subheader('Room Creation')
units = col2_header.selectbox('UNITS', options=['Meter','Feet'], index=1, label_visibility='collapsed')
#### room program
with st.expander('1 - Bldg & Room Program', expanded=False):
bldg_prog = st.selectbox('Bldg Program', options=['Select Bldg Program', 'Office','Lab','Higher Ed'], index=1, label_visibility='collapsed')
room_prog = ''
if bldg_prog != 'Select Bldg Program':
room_prog = st.selectbox('Room Program', options=['Select Room Program', 'Open Office','Conference','Classroom'], index=1, label_visibility='collapsed')
if bldg_prog != 'Select Bldg Program' and room_prog != 'Select Room Program':
st.write(bldg_prog," :: ",room_prog)
else:
st.error('Select Bldg & Room Program')
#### room geometry
with st.expander('2 - Room Geometry', expanded=False):
room_width = st.slider('Room Width', value=30, min_value=5, max_value=5)
room_depth = st.slider('Room Depth', value=30, min_value=5, max_value=5)
room_height = st.slider('Room Height', value=15, min_value=10, max_value=30)
room_orient = st.slider('Room Orientation', value=180, step=5, min_value=0, max_value=355)
st.write('Room Dimensions: ',str(room_width),' x ',str(room_depth),' x ',str(room_height),' @ ',str(room_orient),'°')
# Jihoon: orientation info for EnergyPlus simulation
if room_orient != st.session_state.north:
st.session_state.north = room_orient
st.session_state.sql_results = None # reset to have results recomputed
#### room glazing
with st.expander('3 - Glazing', expanded=False):
wwr = st.slider("WWR", max_value=95, min_value=10, step=5, value=40)/100
vlt = st.slider("VLT", max_value=90, min_value=10, step=5)/100
shgc = st.slider("SHGC", max_value=90, min_value=10, step=5)/100
st.write('WWR: ',str(wwr)," - VLT: ",str(vlt)," - SHGC",str(shgc))
#### room shading
with st.expander('4 - Shading', expanded=False):
horizontal = st.checkbox('Horizontal Shading')
if horizontal:
hor_num = st.slider("Number of Overhangs", max_value=5, min_value=1, value=1)
hor_depth = st.slider("Overhang Depth", max_value=6.0, min_value=0.0, step=.5, value=1.0)
vertical = st.checkbox('Vertical Shading')
if vertical:
vert_num = st.slider("Number of Fins", max_value=5, min_value=1, value=1)
vert_depth = st.slider("Fin Depth", max_value=6.0, min_value=0.0, step=.5, value=1.0)
if horizontal:
st.write(str(hor_num),' x Horizontal Overhang: ',str(hor_depth)," deep")
if vertical:
st.write(str(vert_num),' x Vertical Overhang: ',str(vert_depth)," deep")
save_model = ''
#### save analysis model
if bldg_prog != 'Select Bldg Program' and room_prog != 'Select Room Program':
model_name = st.text_input('model name')
#### create honeybee room
room = Room.from_box(
identifier=str(uuid4()),
width=room_width,
depth=room_depth,
height=room_height)
point_origin = ladybug_geometry.geometry3d.Point3D(x=room_width/2, y=room_depth/2 ,z=0)
room.rotate_xy(-1*room_orient,point_origin)
grid = SensorGrid.from_mesh3d(str(uuid4()), room.generate_grid(x_dim=2, offset=2.5))
faces: Face = room.faces[1]
faces.apertures_by_ratio(wwr)
apertures: Aperture = faces.apertures[0]
aperture_height = (apertures.max - apertures.min).z
aperture_width = (apertures.max.x - apertures.min.x)
if horizontal:
apertures.louvers_by_distance_between(distance=aperture_height/hor_num, depth=hor_depth, base_name='shade_hor',contour_vector=ladybug_geometry.geometry2d.Vector2D(0, 1))
if vertical:
apertures.louvers_by_distance_between(distance=aperture_width/vert_num, depth=vert_depth, contour_vector=ladybug_geometry.geometry2d.Vector2D(1, 0), base_name='shade_vert')
simple_model = Model.from_objects(
identifier=f'model_{room_width}_{room_depth}_{room_height}_{wwr}_{room_orient}_{hor_depth}_{hor_num}_{vert_depth}_{vert_num}',
objects=[room],
units=units)
# st.write(simple_model)
simple_model._properties._radiance = ModelRadianceProperties(simple_model, [grid])
model_path = simple_model.to_hbjson(name=simple_model.identifier, folder='data')
vtk_path = pathlib.Path('data', f'{simple_model.identifier}.vtkjs')
if model_name in st.session_state['model_names']:
if bldg_prog != 'Select Bldg Program' and room_prog != 'Select Room Program':
over_button = st.button("OVERRIDE: {}".format(model_name), key='over_button', type="primary")
if over_button:
if len(model_name) > 0:
st.session_state['model_names'].append(model_name)
# st.write(st.session_state['model_names'])
# st.write(model_path)
# st.session_state['models'].append(model_path)
# st.write(st.session_state['models'])
# st.session_state['models_varialbles'].append({
# 'width': room_width,
# 'depth': room_depth,
# 'height': room_height,
# 'orientation': room_orient,
# 'glazing-ration': wwr,
# 'VLT': vlt,
# 'SHGC': shgc
# })
else:
st.warning("Enter text")
else:
if bldg_prog != 'Select Bldg Program' and room_prog != 'Select Room Program':
add_button = st.button("SAVE ANALYSIS MODEL", key='add_button')
if add_button:
if len(model_name) > 0:
st.session_state['model_names'] += [model_name]
# st.write(st.session_state['model_names'])
# st.write(model_path)
st.session_state['models'].append(model_path)
# st.write(st.session_state['models'])
st.session_state['model_var'].append({
'width': room_width,
'depth': room_depth,
'height': room_height,
'orientation': room_orient,
'glazing-ration': wwr,
'VLT': vlt,
'SHGC': shgc
})
# st.write(st.session_state['model_var'])
else:
st.warning("Enter text")
# Jihoon: get the inputs that only affect the display and do not require re-simulation
in_heat_cop = col1.number_input(
label='Heating COP', min_value=0.0, max_value=6.0, value=1.0, step=0.05)
if in_heat_cop != st.session_state.heat_cop:
st.session_state.heat_cop = in_heat_cop
in_cool_cop = col1.number_input(
label='Cooling COP', min_value=0.0, max_value=6.0, value=1.0, step=0.05)
if in_cool_cop != st.session_state.cool_cop:
st.session_state.cool_cop = in_cool_cop
if not vtk_path.is_file():
VTKModel.from_hbjson(model_path, SensorGridOptions.Sensors).to_vtkjs(
folder='data', name=simple_model.identifier)
with col2_con:
st_vtkjs(
content=vtk_path.read_bytes(),
key=simple_model.identifier, subscribe=False
)
# Jihoon: get the inputs that only affect the display and do not require re-simulation
ip_help = 'Display output units in kBtu and ft2 instead of kWh and m2.'
in_ip_units = col2.checkbox(label='IP Units', value=False, help=ip_help)
if in_ip_units != st.session_state.ip_units:
st.session_state.ip_units = in_ip_units
norm_help = 'Normalize all energy values by the gross floor area.'
in_normalize = col2.checkbox(label='Floor Normalize', value=True, help=norm_help)
if in_normalize != st.session_state.normalize:
st.session_state.normalize = in_normalize
with col3:
st.subheader('({}) Analysis Models'.format(len(st.session_state['model_names'])))
col3_body1, col3_body2 = st.columns([2,1])
if len(st.session_state['model_names']) >0:
clear_models = col3_body2.button('X CLEAR')
if clear_models:
st.session_state['model_names']=[]
baseline_model = col3_body1.radio('Select Baseline Model:', options=st.session_state['model_names'])
st.write(baseline_model)
with st.expander('5 - Project Location', expanded=False):
url = "https://www.ladybug.tools/epwmap/"
st.write("Launch [EPW Map](%s)" % url)
epw_url = st.text_input('EPW URL')
files = glob.glob('data/epw/*')
for f in files:
os.remove(f)
dload.save_unzip(epw_url, 'data/epw/', delete_after=True,)
for file_name in os.listdir('data/epw/'):
if file_name.endswith(".epw"):
epw_urlfile = 'data/epw/' + file_name
epw_filepath = epw_urlfile
st.write(epw_filepath)
st.write('-- or --')
epw_upload = st.file_uploader("EPW File", type=['epw'], key='epw_upload', accept_multiple_files=False)
# st.write(epw_upload)
if epw_upload:
epw_filepath = pathlib.Path(f'./data/{epw_upload.name}')
# st.write(epw_filepath)
epw_filepath.parent.mkdir(parents=True, exist_ok=True)
epw_filepath.write_bytes(epw_data.read())
if epw_filepath:
ddy_file = epw_filepath.as_posix().replace('.epw', '.ddy')
epw_data = EPW(epw_filepath)
epw_data.to_ddy(ddy_file)
ddy_path = pathlib.Path(ddy_file)
st.session_state.epw_path = epw_filepath
st.session_state.ddy_path = ddy_path
# st.write(epw_data)
if epw_data != 0:
st.write('Project Location:',str(epw_data.location).split(',')[1])
study_name = st.text_input('Study Name')
run_simulation = st.button('Run Study')
else:
st.error('Add Project EPW file')
if epw_data:
# epw_file = pathlib.Path(f'./data/{epw_data.name}')
# st.write(epw_file)
# epw_file.parent.mkdir(parents=True, exist_ok=True)
# epw_file.write_bytes(epw_data.read())
# epw_obj = EPW(epw_file)
wea_obj = Wea.from_epw_file(epw_filepath)
wea_file = wea_obj.write(f'./data/weather_file.wea')
# st.write(wea_file)
# .to_wea(file_path=epw_file)
if run_simulation:
job_id = None
recipe = Recipe(
owner = 'ladybug-tools',
name = 'annual-daylight',
tag = 'latest',
client = api_client
)
new_job = NewJob(
owner=owner,
project=project,
recipe=recipe,
name=study_name,
client=api_client)
wea_project_path = new_job.upload_artifact(pathlib.Path(wea_file), 'streamlit-job')
recipe_inputs = {
'wea': wea_project_path
}
index = 0
for mod in st.session_state['models']:
# st.write(mod)
model_project_path = new_job.upload_artifact(
pathlib.Path(mod), 'streamlit-job')
inputs = dict(recipe_inputs)
inputs['model'] = model_project_path
inputs.update(st.session_state['model_var'][index])
index += 1
# st.session_state['inputs']['model'] = model_project_path
# inputs= [
# {'model': model_project_path,
# 'wea': wea_project_path,
# # 'width': room_width,
# # 'depth': room_depth,
# # 'height': room_height,
# # 'glazing-ration': wwr,
# # 'VLT': vlt,
# # 'SHGC': shgc
# }
# ]
# st.session_state['study_inputs'].append(st.session_state['inputs'])
st.session_state['study_inputs'].append(inputs)
st.write(st.session_state['study_inputs'])
new_job.arguments = st.session_state['study_inputs']
job = new_job.create()
job_id = job.id
if job_id is not None and owner is not None and project is not None:
job = Job(owner, project, job_id, client=api_client)
st.write(
f'Checkout your job [here](https://app.pollination.cloud/{owner}/projects/{project}/jobs/{job_id})')
if job.status.status in [
JobStatusEnum.pre_processing,
JobStatusEnum.running,
JobStatusEnum.created,
JobStatusEnum.unknown]:
with st.spinner(text="Simulation in Progres..."):
st.warning(f'Simulation is {job.status.status.value}...')
# st_autorefresh(interval=2000, limit=100)
elif job.status.status in [JobStatusEnum.failed, JobStatusEnum.cancelled]:
st.warning(f'Simulation is {job.status.status.value}')
# else:
# job.runs_dataframe.parameters
# res_model_path = view_results(
# owner, project, job_id, api_key)
# st_vtkjs(
# content=pathlib.Path(res_model_path).read_bytes(), key='results',
# subscribe=False
# )
st.markdown("""---""") # horizontal divider line between input and output
out_container = st.container() # container to eventually hold the results
st.session_state.hb_model = simple_model
run_energy_simulation(
st.session_state.target_folder,
st.session_state.hb_model,
st.session_state.epw_path, st.session_state.ddy_path, st.session_state.north
)
# create the resulting charts
display_results(
out_container, st.session_state.sql_results,
st.session_state.heat_cop, st.session_state.cool_cop,
st.session_state.ip_units, st.session_state.normalize
)
with tab2:
if baseline_model:
st.write(baseline_model)