-
Notifications
You must be signed in to change notification settings - Fork 145
/
Honeybee_Honeybee.py
9800 lines (8094 loc) · 450 KB
/
Honeybee_Honeybee.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This is the heart of the Honeybee
#
# Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari
#
# This file is part of Honeybee.
#
# Copyright (c) 2013-2018, Mostapha Sadeghipour Roudsari <mostapha@ladybug.tools>
# Honeybee is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 3 of the License,
# or (at your option) any later version.
#
# Honeybee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Honeybee; If not, see <http://www.gnu.org/licenses/>.
#
# @license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
"""
This component carries all of Honeybee's main classes. Other components refer to these
classes to run the studies. Therefore, you need to let her fly before running the studies so the
classes will be copied to Rhinos shared space. So let her fly!
-
Honeybee: A Plugin for Environmental Analysis (GPL) started by Mostapha Sadeghipour Roudsari
You should have received a copy of the GNU General Public License
along with Honeybee; If not, see <http://www.gnu.org/licenses/>.
@license GPL-3.0+ <http://spdx.org/licenses/GPL-3.0+>
Source code is available at: https://github.com/mostaphaRoudsari/Honeybee
-
Provided by Honeybee 0.0.63
Args:
defaultFolder_: Optional input for Honeybee default folder.
If empty default folder will be set to C:\ladybug or C:\Users\%USERNAME%\AppData\Roaming\Ladybug\
Returns:
report: Current Honeybee mood!!!
"""
ghenv.Component.Name = "Honeybee_Honeybee"
ghenv.Component.NickName = 'Honeybee'
ghenv.Component.Message = 'VER 0.0.63\nJUN_29_2018'
ghenv.Component.IconDisplayMode = ghenv.Component.IconDisplayMode.icon
ghenv.Component.Category = "Honeybee"
ghenv.Component.SubCategory = "00 | Honeybee"
try: ghenv.Component.AdditionalHelpFromDocStrings = "1"
except: pass
import sys
sys.path = sorted(sys.path, key=lambda p: p.find("Python27"))
import rhinoscriptsyntax as rs
import Rhino as rc
import scriptcontext as sc
import Grasshopper
import Grasshopper.Kernel as gh
from Grasshopper import DataTree
from Grasshopper.Kernel.Data import GH_Path
import math
import shutil
import os
import System.Threading.Tasks as tasks
import System
import time
import itertools
import datetime
import json
import copy
import urllib2 as urllib
import cPickle as pickle
import subprocess
import uuid
import re
import random
import zipfile
try:
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12
except AttributeError:
# TLS 1.2 not provided by MacOS .NET Core; revert to using TLS 1.0
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls
PI = math.pi
rc.Runtime.HostUtils.DisplayOleAlerts(False)
tolerance = sc.doc.ModelAbsoluteTolerance
class CheckIn():
def __init__(self, defaultFolder, folderIsSetByUser = False):
self.folderIsSetByUser = folderIsSetByUser
self.letItFly = True
if defaultFolder:
# user is setting up the folder
defaultFolder = os.path.normpath(defaultFolder) + os.sep
# check if path has white space
if (" " in defaultFolder):
msg = "Default file path can't have white space. Please set the path to another folder." + \
"\nHoneybee failed to fly! :("
print msg
ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, msg)
sc.sticky["Honeybee_DefaultFolder"] = ""
self.letItFly = False
return
else:
# create the folder if it is not created
if not os.path.isdir(defaultFolder):
try: os.mkdir(defaultFolder)
except:
msg = "Cannot create default folder! Try a different filepath" + \
"\nHoneybee failed to fly! :("
print msg
ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, msg)
sc.sticky["Honeybee_DefaultFolder"] = ""
self.letItFly = False
return
# looks fine so let's set it up
sc.sticky["Honeybee_DefaultFolder"] = defaultFolder
self.folderIsSetByUser = True
#set up default pass
if not self.folderIsSetByUser:
if os.path.exists("c:\\ladybug\\") and os.access(os.path.dirname("c:\\ladybug\\"), os.F_OK):
# folder already exists so it is all fine
sc.sticky["Honeybee_DefaultFolder"] = "c:\\ladybug\\"
elif os.access(os.path.dirname("c:\\"), os.F_OK):
#the folder does not exists but write privileges are given so it is fine
sc.sticky["Honeybee_DefaultFolder"] = "c:\\ladybug\\"
else:
# let's use the user folder
appdata = os.getenv("APPDATA")
# make sure username doesn't have space
if (" " in appdata):
msg = "User name on this system: " + appdata + " has white space." + \
" Default fodelr cannot be set.\nUse defaultFolder_ to set the path to another folder and try again!" + \
"\nHoneybee failed to fly! :("
print msg
ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, msg)
sc.sticky["Honeybee_DefaultFolder"] = ""
self.letItFly = False
return
sc.sticky["Honeybee_DefaultFolder"] = os.path.join(appdata, "Ladybug\\")
self.updateCategoryIcon()
@staticmethod
def updateCategoryIcon():
try:
url = "https://raw.githubusercontent.com/mostaphaRoudsari/Honeybee/master/resources/icon_16_16.png"
icon = os.path.join(sc.sticky["Honeybee_DefaultFolder"], "HB_icon_16_16.png")
if not os.path.isfile(icon):
client = System.Net.WebClient()
client.DownloadFile(url, icon)
iconBitmap = System.Drawing.Bitmap(icon)
Grasshopper.Instances.ComponentServer.AddCategoryIcon("Honeybee", iconBitmap)
except:
# download failed
pass
Grasshopper.Instances.ComponentServer.AddCategoryShortName("Honeybee", "HB")
Grasshopper.Instances.ComponentServer.AddCategorySymbolName("Honeybee", "H")
Grasshopper.Kernel.GH_ComponentServer.UpdateRibbonUI() #Reload the Ribbon
def getComponentVersion(self):
monthDict = {'JAN':'01', 'FEB':'02', 'MAR':'03', 'APR':'04', 'MAY':'05', 'JUN':'06',
'JUL':'07', 'AUG':'08', 'SEP':'09', 'OCT':'10', 'NOV':'11', 'DEC':'12'}
# convert component version to standard versioning
ver, verDate = ghenv.Component.Message.split("\n")
ver = ver.split(" ")[1].strip()
month, day, year = verDate.split("_")
month = monthDict[month.upper()]
version = ".".join([year, month, day, ver])
return version
def isNewerVersionAvailable(self, currentVersion, availableVersion):
# print int(availableVersion.replace(".", "")), int(currentVersion.replace(".", ""))
return int(availableVersion.replace(".", "")) > int(currentVersion.replace(".", ""))
def checkForUpdates(self, LB= True, HB= True, OpenStudio = True, template = True, therm = True):
url = "https://github.com/mostaphaRoudsari/ladybug/raw/master/resources/versions.txt"
versionFile = os.path.join(sc.sticky["Honeybee_DefaultFolder"], "versions.txt")
client = System.Net.WebClient()
client.DownloadFile(url, versionFile)
with open("c:/ladybug/versions.txt", "r")as vf:
versions= eval("\n".join(vf.readlines()))
honeybeeDefaultFolder = sc.sticky["Honeybee_DefaultFolder"]
if LB:
ladybugVersion = versions['Ladybug']
currentLadybugVersion = self.getComponentVersion() # I assume that this function will be called inside Ladybug_ladybug Component
if self.isNewerVersionAvailable(currentLadybugVersion, ladybugVersion):
msg = "There is a newer version of Ladybug available to download! " + \
"We strongly recommend you to download the newer version from Food4Rhino: " + \
"http://www.food4rhino.com/project/ladybug-honeybee"
print msg
ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, msg)
if HB:
honeybeeVersion = versions['Honeybee']
currentHoneybeeVersion = self.getComponentVersion() # I assume that this function will be called inside Honeybee_Honeybee Component
if self.isNewerVersionAvailable(currentHoneybeeVersion, honeybeeVersion):
msg = "There is a newer version of Honeybee available to download! " + \
"We strongly recommend you to download the newer version from Food4Rhino: " + \
"http://www.food4rhino.com/project/ladybug-honeybee"
print msg
ghenv.Component.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, msg)
if OpenStudio:
# This should be called inside OpenStudio component which means Honeybee is already flying
# check if the version file exist
openStudioLibFolder = os.path.join(sc.sticky["Honeybee_DefaultFolder"], "OpenStudio")
versionFile = os.path.join(openStudioLibFolder, "osversion.txt")
isNewerOSAvailable= False
if not os.path.isfile(versionFile):
isNewerOSAvailable= True
else:
# read the file
with open(versionFile) as verFile:
currentOSVersion= eval(verFile.read())['version']
OSVersion = versions['OpenStudio']
if isNewerOSAvailable or self.isNewerVersionAvailable(currentOSVersion, OSVersion):
sc.sticky["isNewerOSAvailable"] = True
else:
sc.sticky["isNewerOSAvailable"] = False
if therm:
thermFile = os.path.join(honeybeeDefaultFolder, 'thermMaterial.csv')
# check file doesn't exist then it should be downloaded
isNewerThermAvailable = False
if not os.path.isfile(thermFile):
isNewerThermAvailable = True
else:
# find the version
try:
with open(thermFile) as tempFile:
currentThermVersion = eval(tempFile.readline().split("!")[-1].strip())["version"]
except: isNewerThermAvailable = True
# finally if the file exist and already has a version, compare the versions
thermVersion = versions['THERM']
if isNewerThermAvailable or self.isNewerVersionAvailable(currentThermVersion, thermVersion):
sc.sticky["isNewerTHERMAvailable"] = True
else:
sc.sticky["isNewerTHERMAvailable"] = False
if template:
templateFile = os.path.join(honeybeeDefaultFolder, 'OpenStudioMasterTemplate.idf')
# check file doesn't exist then it should be downloaded
if not os.path.isfile(templateFile):
return True
# find the version
try:
with open(templateFile) as tempFile:
currentTemplateVersion = eval(tempFile.readline().split("!")[-1].strip())["version"]
except Exception, e:
return True
# finally if the file exist and already has a version, compare the versions
templateVersion = versions['Template']
return self.isNewerVersionAvailable(currentTemplateVersion, templateVersion)
class versionCheck(object):
def __init__(self):
self.version = self.getVersion(ghenv.Component.Message)
def getVersion(self, LBComponentMessage):
monthDict = {'JAN':'01', 'FEB':'02', 'MAR':'03', 'APR':'04', 'MAY':'05', 'JUN':'06',
'JUL':'07', 'AUG':'08', 'SEP':'09', 'OCT':'10', 'NOV':'11', 'DEC':'12'}
# convert component version to standard versioning
try: ver, verDate = LBComponentMessage.split("\n")
except: ver, verDate = LBComponentMessage.split("\\n")
ver = ver.split(" ")[1].strip()
month, day, year = verDate.split("_")
month = monthDict[month.upper()]
version = ".".join([year, month, day, ver])
return version
def isCurrentVersionNewer(self, desiredVersion):
return int(self.version.replace(".", "")) >= int(desiredVersion.replace(".", ""))
def isCompatible(self, LBComponent):
code = LBComponent.Code
# find the version that is supposed to be flying
try:
version = code.split("compatibleHBVersion")[1].split("=")[1].split("\n")[0].strip()
except Exception, e:
print e
self.giveWarning(LBComponent)
return False
desiredVersion = self.getVersion(version)
if not self.isCurrentVersionNewer(desiredVersion):
self.giveWarning(LBComponent)
return False
return True
def giveWarning(self, GHComponent):
warningMsg = "You need a newer version of Honeybee to use this compoent." + \
"Use updateHoneybee component to update userObjects.\n" + \
"If you have already updated userObjects drag Honeybee_Honeybee component " + \
"into canvas and try again."
w = gh.GH_RuntimeMessageLevel.Warning
GHComponent.AddRuntimeMessage(w, warningMsg)
def isInputMissing(self, GHComponent):
isInputMissing = False
for param in GHComponent.Params.Input:
if param.NickName.startswith("_") and \
not param.NickName.endswith("_") and \
not param.VolatileDataCount:
warning = "Input parameter %s failed to collect data!"%param.NickName
GHComponent.AddRuntimeMessage(gh.GH_RuntimeMessageLevel.Warning, warning)
isInputMissing = True
return isInputMissing
class hb_findFolders():
def __init__(self):
self.RADPath, self.RADFile = self.which('rad.exe')
self.EPPath, self.EPFile = self.which('EnergyPlus.exe')
self.DSPath, self.DSFile = self.which('gen_dc.exe')
self.THERMPath, self.THERMFile = self.which('Therm7.exe')
def which(self, program):
"""
Check for path. Modified from this link:
http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
"""
def is_exe(fpath):
# Avoid Radiance and Daysim that comes with DIVA as it has a different
# structure which doesn't match the standard Daysim
if fpath.upper().find("DIVA")<0:
# if the user has DIVA installed the component may find DIVA version
# of RADIANCE and DAYISM which can cause issues because of the different
# structure of folders in DIVA
return os.path.isfile(fpath) and os.access(fpath, os.F_OK)
else:
return False
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
# This is a change to catch cases that user has radiance inastalled
# at C:\Program Files\Radiance
if path.strip().find(" ") == -1:
return path, exe_file
return None, None
class PrepareTemplateEPLibFiles(object):
"""
Download Template files and check for available libraries for EnergyPlus
"""
def __init__(self, downloadTemplate = False, workingDir = None):
if not workingDir: workingDir = sc.sticky["Honeybee_DefaultFolder"]
if not sc.sticky.has_key("honeybee_constructionLib"): sc.sticky ["honeybee_constructionLib"] = {}
if not sc.sticky.has_key("honeybee_materialLib"): sc.sticky ["honeybee_materialLib"] = {}
if not sc.sticky.has_key("honeybee_windowMaterialLib"): sc.sticky ["honeybee_windowMaterialLib"] = {}
if not sc.sticky.has_key("honeybee_ScheduleLib"): sc.sticky["honeybee_ScheduleLib"] = {}
if not sc.sticky.has_key("honeybee_ScheduleTypeLimitsLib"): sc.sticky["honeybee_ScheduleTypeLimitsLib"] = {}
if not sc.sticky.has_key("honeybee_WindowPropLib"): sc.sticky["honeybee_WindowPropLib"] = {}
if not sc.sticky.has_key("honeybee_SpectralDataLib"): sc.sticky["honeybee_SpectralDataLib"] = {}
if not sc.sticky.has_key("honeybee_thermMaterialLib"): sc.sticky["honeybee_thermMaterialLib"] = {}
self.downloadTemplate = downloadTemplate
self.workingDir = workingDir
self.failureMsg = ""
def downloadFile(self, url, workingDir):
localFilePath = workingDir + '/' + url.split('/')[-1]
client = System.Net.WebClient()
client.DownloadFile(url, localFilePath)
def cleanHBLib(self):
sc.sticky ["honeybee_constructionLib"] = {}
sc.sticky ["honeybee_materialLib"] = {}
sc.sticky ["honeybee_windowMaterialLib"] = {}
sc.sticky["honeybee_ScheduleLib"] = {}
sc.sticky["honeybee_ScheduleTypeLimitsLib"] = {}
sc.sticky["honeybee_WindowPropLib"] = {}
sc.sticky["honeybee_SpectralDataLib"] = {}
def cleanThermLib(self):
sc.sticky["honeybee_thermMaterialLib"] = {}
def downloadTemplates(self):
workingDir = self.workingDir
# create the folder if it is not there
if not os.path.isdir(workingDir): os.mkdir(workingDir)
# create a backup from the user's library
templateFile = os.path.join(workingDir, 'OpenStudioMasterTemplate.idf')
bckupfile = os.path.join(workingDir, 'OpenStudioMasterTemplate_' + str(int(time.time())) +'.idf')
thermTemplateFile = os.path.join(workingDir, 'thermMaterial.csv')
thermBckupfile = os.path.join(workingDir, 'thermMaterial_' + str(int(time.time())) +'.csv')
# download EP template file
if self.downloadTemplate or not os.path.isfile(templateFile):
# create a backup from users library
try: shutil.copyfile(templateFile, bckupfile)
except: pass
try:
## download File
print 'Downloading OpenStudioMasterTemplate.idf to ', workingDir
updatedLink = "https://github.com/mostaphaRoudsari/Honeybee/raw/master/resources/OpenStudioMasterTemplate.idf"
self.downloadFile(updatedLink, workingDir)
# clean current library
self.cleanHBLib()
except:
print 'Download failed!!! You need OpenStudioMasterTemplate.idf to use honeybee.' + \
'\nPlease check your internet connection, and try again!'
return -1
else:
pass
if not os.path.isfile(workingDir + '\OpenStudioMasterTemplate.idf'):
iplibPath = ghenv.Script.GetStandardLibPath()
print 'Download failed!!! You need OpenStudioMasterTemplate.idf to use honeybee.' + \
'\nPlease check your internet connection, and try again!'
return -1
else:
libFilePaths = [os.path.join(workingDir, 'OpenStudioMasterTemplate.idf')]
# download openstudio standards
if not os.path.isfile(workingDir + '\OpenStudio_Standards.json'):
try:
## download File
print 'Downloading OpenStudio_Standards.json to ', workingDir
self.downloadFile(r'https://github.com/mostaphaRoudsari/Honeybee/raw/master/resources/OpenStudio_Standards.json', workingDir)
except:
print 'Download failed!!! You need OpenStudio_Standards.json to use honeybee.' + \
'\nPlease check your internet connection, and try again!'
return -1
else:
pass
if not os.path.isfile(workingDir + '\OpenStudio_Standards.json'):
print 'Download failed!!! You need OpenStudio_Standards.json to use honeybee.' + \
'\nPlease check your internet connection, and try again!'
return -1
else:
# load the json file
filepath = os.path.join(workingDir, 'OpenStudio_Standards.json')
try:
with open(filepath) as jsondata:
openStudioStandardLib = json.load(jsondata)
sc.sticky ["honeybee_OpenStudioStandardsFile"] = openStudioStandardLib
print "Standard template file is loaded from %s"%filepath
except:
print 'Download failed!!! You need OpenStudio_Standards.json to use honeybee.' + \
'\nPlease check your internet connection, and try again!'
return -1
# add custom library
customEPLib = os.path.join(workingDir,"userCustomEPLibrary.idf")
if not os.path.isfile(customEPLib):
# create an empty file
with open(customEPLib, "w") as outf:
outf.write("!Honeybee custom EnergyPlus library\n")
if os.path.isfile(customEPLib):
libFilePaths.append(customEPLib)
#download THERM template file.
if sc.sticky.has_key("isNewerTHERMAvailable") and sc.sticky["isNewerTHERMAvailable"] or not os.path.isfile(thermTemplateFile):
# create a backup from users library
try: shutil.copyfile(thermTemplateFile, thermBckupfile)
except: pass
try:
## download File
print 'Downloading thermMaterial.csv to ', workingDir
updatedLink = "https://raw.githubusercontent.com/mostaphaRoudsari/Honeybee/master/resources/thermMaterial.csv"
self.downloadFile(updatedLink, workingDir)
# clean current library
self.cleanThermLib()
except:
print 'Download failed!!! You need thermMaterial.csv to use the "export to THERM" capabilties of honeybee.' + \
'\nPlease check your internet connection, and try again!'
return -1
if not os.path.isfile(thermTemplateFile):
print 'Download failed!!! You need thermMaterial.csv to use the "export to THERM" capabilties of honeybee.' + \
'\nPlease check your internet connection, and try again!'
return -1
else:
# load the csv file
csvfilepath = os.path.join(workingDir, 'thermMaterial.csv')
try:
libFilePaths.append(csvfilepath)
except:
print 'Download failed!!! You need thermMaterial.csv to use the "export to THERM" capabilties of honeybee.' + \
'\nPlease check your internet connection, and try again!'
return -1
return libFilePaths
class HB_GetEPLibraries:
def __init__(self):
self.libraries = {
"Material": {},
"WindowMaterial": {},
"Construction": {},
"Schedule" : {},
"ScheduleTypeLimits": {},
"ThermMaterial": {},
"WindowProperty": {},
"MaterialProperty": {}
}
def getEPMaterials(self):
return self.libraries["Material"]
def getEPConstructions(self):
return self.libraries["Construction"]
def getEPWindowMaterial(self):
return self.libraries["WindowMaterial"]
def getEPWindowProp(self):
return self.libraries["WindowProperty"]
def getEPSpectralData(self):
return self.libraries["MaterialProperty"]
def getEPSchedule(self):
return self.libraries["Schedule"]
def getEPScheduleTypeLimits(self):
return self.libraries["ScheduleTypeLimits"]
def getTHERMMaterials(self):
return self.libraries["ThermMaterial"]
def importEPLibrariesFromFile(self, EPfile, isMatFile, cleanCurrentLib = True, report = True):
if not os.path.isfile(EPfile):
raise Exception("Can't find EP library! at %s"%EPfile)
if isMatFile == False:
print "Loading EP materials, constructions, schedules and material properties from %s"%EPfile
EPObjects = self.getEnergyPlusObjectsFromFile(EPfile)
self.loadEPConstructionsMaterialsAndSchedules(EPObjects, cleanCurrentLib)
else:
print "Loading THERM materials from %s"%EPfile
self.getThermObjectsFromFile(EPfile)
if report:
self.report()
def cleanHBLibs(self):
self.libraries = {
"Material": {},
"WindowMaterial": {},
"Construction": {},
"Schedule" : {},
"ScheduleTypeLimits": {},
"ThermMaterial": {},
"WindowProperty": {},
"MaterialProperty": {}
}
# TODO: Support parsing for files with no next line
# TODO: Check if keys can be case insensitive
# TODO: Create EPObjects and not dictionaries
def loadEPConstructionsMaterialsAndSchedules(self, EPObjectsString, cleanCurrentLib = True):
if cleanCurrentLib: self.cleanHBLibs()
for EPObjectStr in EPObjectsString:
rawLines = EPObjectStr.strip().split("\n")
lines = []
for line in rawLines:
if line.strip() == '' or line.startswith('!'): continue
lines.append(line)
if not lines:
continue
if lines[0].startswith('MaterialProperty:GlazingSpectralData'):
key = 'MaterialProperty:GlazingSpectralData'
shortKey = 'MaterialProperty'
name = lines[1].split(",")[0].strip().upper()
self.libraries[shortKey][name] = dict() # create an empty dictonary
self.libraries[shortKey][name][0] = key
# store the data into the dictionary
for lineCount, line in enumerate(lines):
objValue = line.split("!")[0].strip()
try: objDescription = line.split("!")[1].strip()
except: objDescription = ""
if lineCount == 0:
self.libraries[shortKey][name][lineCount] = objValue[:-1]
elif lineCount == 1:
pass # name is already there as the key
elif objValue.endswith(","):
self.libraries[shortKey][name][lineCount-1] = objValue[:-1], objDescription
elif objValue.endswith(";"):
self.libraries[shortKey][name][lineCount-1] = objValue[:-1], objDescription
else:
if len(lines) < 2: continue
if lines[0].split(",")[0].strip().isupper():
key = lines[0].split(",")[0].strip().title()
else:
key = lines[0].split(",")[0].strip()
shortKey = key.split(":")[0]
name = lines[1].split(",")[0].strip().upper()
values = lines[2:]
# it's a two line object such as Any Number scheduleTypeLimit
if values == []:
name = lines[1].split(";")[0].strip().upper() # name is the last input
if shortKey in self.libraries:
self.libraries[shortKey][name] = dict() # create an empty dictonary
self.libraries[shortKey][name][0] = key
count = 1
delimiter = ","
for value in values:
if not len(value.strip()): continue #pass empty lines
if count==len(values): delimiter = ";"
v = value.split(delimiter)[0].strip() # find the value
if value.find("!")!= -1:
c = value.split("!")[-1].rstrip() # find the value
else:
c = ""
self.libraries[shortKey][name][count] = v, c
count += 1
def report(self):
# Report findings
print "%s EPConstructions are loaded available in Honeybee library"%str(len(self.libraries["Construction"]))
print "%s EPMaterials are now loaded in Honeybee library"%str(len(self.libraries["Material"]))
print "%s EPWindowMaterial are loaded in Honeybee library"%str(len(self.libraries["WindowMaterial"]))
print "%s EPShadingControl are loaded in Honeybee library"%str(len(self.libraries["WindowProperty"]))
print "%s EPMaterialProperty are loaded in Honeybee library"%str(len(self.libraries["MaterialProperty"]))
print "%s schedules are loaded available in Honeybee library"%str(len(self.libraries["Schedule"]))
print "%s schedule type limits are now loaded in Honeybee library"%str(len(self.libraries["ScheduleTypeLimits"]))
print "%s THERM materials are now loaded in Honeybee library"%str(len(self.libraries["ThermMaterial"]))
print "\n"
@staticmethod
def getEnergyPlusObjectsFromString(epFileString):
"""
Parse idf file string and return a list of EnergyPlus objects as separate strings
TODO: Create a class for each EnergyPlus object and return Python objects
instead of strings
Args:
epFileString: EnergyPlus data as a single string. The string can be multiline
Returns:
A list of strings. Each string represents a differnt Rdiance Object
"""
#rawEPObjects = re.findall(r'(.[^;]*;.[^\n]*)', epFileString + "\n",re.MULTILINE)
rawEPObjects = re.findall(r'(.[^;]*;)', epFileString + "\n",re.MULTILINE)
return rawEPObjects
def getEnergyPlusObjectsFromFile(self, epFilePath):
"""
Parse EnergyPlus file and return a list of objects as separate strings
TODO: Create a class for each EnergyPlus object and return Python objects
instead of strings
Args:
epFilePath: Path to EnergyPlus file
Returns:
A list of strings. Each string represents a differnt Rdiance Object
Usage:
getEnergyPlusObjectsFromFile(r"C:\ladybug\21MAR900\imageBasedSimulation\21MAR900.rad")
"""
if not os.path.isfile(epFilePath):
raise ValueError("Can't find %s."%epFilePath)
with open(epFilePath, "r") as epFile:
return self.getEnergyPlusObjectsFromString("".join(epFile.readlines()))
def getThermObjectsFromFile(self, matFile):
if not os.path.isfile(matFile):
raise ValueError("Can't find %s."%matFile)
with open(matFile, "r") as mFile:
for rowCount, row in enumerate(mFile):
if rowCount > 1:
try:
matPropLine = row.split(',')
matNameLine = row.split('"')
matName = matNameLine[1].upper()
#Make a sub-dictionary for the material.
self.libraries["ThermMaterial"][matName] = {}
#Create the material with the values from the file.
self.libraries["ThermMaterial"][matName]["Name"] = matName
self.libraries["ThermMaterial"][matName]["Type"] = int(matPropLine[-1])
self.libraries["ThermMaterial"][matName]["Conductivity"] = float(matPropLine[-5])
self.libraries["ThermMaterial"][matName]["Absorptivity"] = float(matPropLine[-4])
if self.libraries["ThermMaterial"][matName]["Type"] == 0:
self.libraries["ThermMaterial"][matName]["Tir"] = "0.0"
else:
self.libraries["ThermMaterial"][matName]["Tir"] = "-1.0"
self.libraries["ThermMaterial"][matName]["Emissivity"] = float(matPropLine[-3])
self.libraries["ThermMaterial"][matName]["WindowDB"] = ""
self.libraries["ThermMaterial"][matName]["WindowID"] = "-1"
self.libraries["ThermMaterial"][matName]["RGBColor"] = System.Drawing.ColorTranslator.FromHtml("#" + matPropLine[-2])
except: pass
def checkUnits():
units = sc.doc.ModelUnitSystem
if `units` == 'Rhino.UnitSystem.Meters': conversionFactor = 1.00
elif `units` == 'Rhino.UnitSystem.Centimeters': conversionFactor = 0.01
elif `units` == 'Rhino.UnitSystem.Millimeters': conversionFactor = 0.001
elif `units` == 'Rhino.UnitSystem.Feet': conversionFactor = 0.305
elif `units` == 'Rhino.UnitSystem.Inches': conversionFactor = 0.0254
else:
print 'Kidding me! Which units are you using?'+ `units`+'?'
print 'Please use Meters, Centimeters, Millimeters, Inches or Feet'
return
print 'Current document units is in', sc.doc.ModelUnitSystem
print 'Conversion to Meters will be applied = ' + "%.3f"%conversionFactor
return conversionFactor
class RADMaterialAux(object):
class RadianceMaterial:
"""
Radiance Material
Attributes:
name: Material name as a string
type: Material type (e.g. glass, plastic, etc)
modifier: Material modifier. Default is void
values: A dictionary of material data. key is line number and item is the list of values
{0: [], 1: [], 2: ['0.500', '0.500', '0.500', '0.000', '0.050']}
"""
def __init__(self, name, type, values = None, modifier = "void"):
self.name = name.rstrip()
self.type = type.rstrip()
self.modifier = modifier.rstrip()
if not values: values = dict()
self.values = values
def toRadString(self):
firstLine = "%s %s %s"%(self.modifier, self.type, self.name)
material = [firstLine]
# order is important and that's why I'm using range
# and not the keys itself
for lineCount in range(len(self.values.keys())):
values = self.values[lineCount]
count = [str(len(values))]
line = " ".join(count + values).rstrip()
material.append(line)
material.append("\n")
return "\n".join(material)
def addValues(self, lineCount, values):
"""Add values to current material
Args:
lineCount: An integer that represnt the line number
values: Values as a list of string
"""
self.values[lineCount] = values
def __repr__(self):
return self.toRadString()
def __init__(self, reloadRADMaterial = False, materialLibrary = {}, HoneybeeFolder = "c:/ladybug"):
self.HoneybeeFolder = HoneybeeFolder
self.radMaterialLibrary = materialLibrary
self.radMatTypes = ["plastic", "glass", "trans", "metal",
"mirror", "texfunc", "mixedfunc", "dielectric", "transdata",
"light", "glow", "BRTDfunc"]
if reloadRADMaterial:
defaultMaterial = {
'Context_Material' : {'type' : 'plastic', 'value': 0.35},
'Interior_Ceiling' : {'type' : 'plastic', 'value': 0.80},
'Interior_Floor' : {'type' : 'plastic', 'value': 0.20},
'Exterior_Floor' : {'type' : 'plastic', 'value': 0.20},
'Exterior_Roof' : {'type' : 'plastic', 'value': 0.80},
'Exterior_Wall' : {'type' : 'plastic', 'value': 0.50},
'Interior_Wall' : {'type' : 'plastic', 'value': 0.50},
'Interior_Window' : {'type' : 'glass' , 'value': 0.60},
'Exterior_Window' : {'type' : 'glass' , 'value': 0.60}
}
for materialName, materialData in defaultMaterial.items():
radMaterial = self.RadianceMaterial(materialName, materialData['type'])
value = materialData['value']
# add values to material
# first two lines are empty
radMaterial.addValues(0, [])
radMaterial.addValues(1, [])
if radMaterial.type == 'glass':
value = self.getTransmissivity(value)
radMaterial.addValues(2, 3 * ['%.3f'%value]) # leave roughness specularity to 0
else:
radMaterial.addValues(2, 3 * ['%.3f'%value] + ['0', '0']) # leave roughness specularity to 0
# add default materials to the library
self.addMaterialToDocumentLibrary(radMaterial)
# import user defined RAD library
RADLibraryFile = self.getUserDefinedRadianceLibraryPath()
if os.path.isfile(RADLibraryFile):
self.importRADMaterialsFromFile(RADLibraryFile)
else:
# This is only happening the first time
# that user lets the Honeybee fly on their system
# or changes the default folder
if not os.path.isdir(self.HoneybeeFolder):
os.mkdir(self.HoneybeeFolder)
with open(RADLibraryFile, "w") as outf:
outf.write("#Honeybee Radiance Material Library\n")
print "Loading RAD default materials..." + \
`len(self.radMaterialLibrary)` + " RAD materials are loaded\n"
def duplicateMaterialWarning(self, materialName, newMaterialString):
returnYN = {'YES': True, 'NO': False}
buttons = System.Windows.Forms.MessageBoxButtons.YesNo
icon = System.Windows.Forms.MessageBoxIcon.Warning
try:
currentMaterialString = self.getRADMaterialString(materialName)
except:
currentMaterialString = materialName
isAdded, materialName = self.analyseRadMaterials(materialName, False)
msg = materialName + " already exists in the library:\n\n" + \
currentMaterialString + "\n" + \
"Do you want to overwrite the current material with this new definition?\n\n" + \
newMaterialString + "\n\n" + \
"Tip: If you are not sure what to do select No and change the material name."
up = System.Windows.Forms.MessageBox.Show(msg, "Duplicate Material Name", buttons, icon)
return returnYN[up.ToString().ToUpper()]
# TODO: Rewite! This method is poorly written and is very hard to understand
# TODO: Should be probably moved to writeRAD. Here is not the right place
def addRADMatToDocumentDict(self, HBSrf, currentMatDict, currentMixedFunctionsDict):
"""Collect Radiance materials for a single run"""
# check if the material is already added
materialName = HBSrf.RadMaterial
if not materialName in currentMatDict.keys():
# find material type
materialType = self.getRADMaterialType(materialName)
materialModifier = self.getRADMaterialModifier(materialName)
# check if this is a mixed function
if materialType == "mixfunc":
# add mixedFunction
currentMixedFunctionsDict[materialName] = materialName
# find the base materials for the mixed function
mixfunMaterial = self.getMaterialFromHBLibrary(materialName)
material1 = mixfunMaterial.values[0][0]
material2 = mixfunMaterial.values[0][1]
for matName in [material1, material2]:
if not matName in currentMatDict.keys():
currentMatDict[matName] = matName
elif materialModifier != "void":
# add material itself
currentMixedFunctionsDict[materialName] = materialName
# check if modifier is in library and add it to dictionary
if not self.isMatrialExistInLibrary(materialModifier):
raise Exception("You're using %s as a modifier which is not added to the library!")%materialModifier
if not materialModifier in currentMatDict.keys():
currentMatDict[materialModifier] = materialModifier
else:
# add to dictionary
currentMatDict[materialName] = materialName
return currentMatDict, currentMixedFunctionsDict
def getUserDefinedRadianceLibraryPath(self):
return os.path.join(self.HoneybeeFolder, "HoneybeeRadMaterials.mat")
@staticmethod
def getTransmissivity(transmittance):
return (math.sqrt(0.8402528435 + 0.0072522239 * (transmittance ** 2)) - 0.9166530661 ) / 0.0036261119 / transmittance
def analyseRadMaterials(self, radMaterialString, addToDocLib = False, overwrite = True):
"""Analyse Radiance Material string
Import a RAD material string, create a Honeybee RadianceMaterial
and add it to Honeybee library if needed.
Always return the a boolean and Radiance name
"""
try:
# get radince material as a single line
cleanedRadMaterialString = self.cleanRadMaterial(radMaterialString)
lineSegments = cleanedRadMaterialString.split(" ")
if len(lineSegments) == 1:
# this is just the name
# to be used for applying material to surfaces
return False, lineSegments[0].rstrip()
else:
materialModifier = lineSegments[0]
materialType = lineSegments[1]
materialName = lineSegments[2].rstrip()
# initiate Rad material
radMaterial = self.RadianceMaterial(materialName, materialType, modifier = materialModifier)
if addToDocLib:
if self.isMatrialExistInLibrary(materialName) and not overwrite:
# ask for user input before overwriting the material
upload = self.duplicateMaterialWarning(materialName, radMaterialString)
if not upload:
return False, materialName
counters = []
materialProp = lineSegments[3:]
#first counter is the first member of the list
counter = 0
counters.append(0)
while counter < len(materialProp):
counter += int(materialProp[counter]) + 1
try:
counters.append(counter)
except:
pass
for counter, count in enumerate(counters[1:]):
values = materialProp[counters[counter] + 1: count]
# add values to material
radMaterial.addValues(counter, values)
# add material to library
self.addMaterialToDocumentLibrary(radMaterial)
return True, materialName