def getLibs(self): """ Looks at the Rhino DocumentUserText to see if there are window libraries, if so, reads them in for use in the comboBox dropdowns """ glazingLib = [] frameLib = [] psiLib = [] variableTypes = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] print "Reading the Rhino Document's Glazing and Frame Types..." if rs.IsDocumentUserText(): for eachKey in rs.GetDocumentUserText(): if 'Glazing' in eachKey: glazingLib.append( json.loads(rs.GetDocumentUserText(eachKey))['Name']) elif 'Frame' in eachKey: frameLib.append( json.loads(rs.GetDocumentUserText(eachKey))['Name']) elif '_PsiInstall_' in eachKey: psiLib.append( json.loads( rs.GetDocumentUserText(eachKey))['Typename']) return frameLib, glazingLib, psiLib, variableTypes
def _get_surface_U_value(self, _srfcGUID): """Takes in a single Surface GUID and returns its U-Value Param Will look at the UserText of the surface to get the EP Construction Name and then the Document UserText library to get the U-Value of tha Construction Type. Returns 0.5 W/m2k as default on any errors. Args: self: _srfcGUID (GUID): A single GUID value Returns: srfcUvalue (float): The Surface's UserText Param for 'U-Value' if found """ srfcConstructionName = rs.GetUserText(_srfcGUID, 'EPConstruction') if srfcConstructionName: constParams = rs.GetDocumentUserText('PHPP_lib_Assmbly_' + srfcConstructionName) for k in rs.GetDocumentUserText(): if 'PHPP_lib_Assmbly' not in k: continue try: d = json.loads(rs.GetDocumentUserText(k)) if d.get('Name', None) == srfcConstructionName: constParams = rs.GetDocumentUserText(k) break except: constParams = None else: constParams = None if constParams: constParams = json.loads(constParams) srfcUvalue = constParams.get('uValue', 1) else: warning = ( 'Warning: Could not find a construction type in the', 'Rhino Document UserText with the name "{}?"'.format( srfcConstructionName.upper()), 'Check your Document UserText library to make sure that you have', 'your most recent assembly library file loaded?', 'For now applying a U-Value of 0.5 w/m2k (R11 hr-sf-F/Btu) for this surface.' ) self.ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, warning) srfcUvalue = 0.5 else: warning = 'Warning: could not find a construction type in the\n'\ 'UserText for one or more surfaces? Are you sure you assigned a\n'\ '"EPConstruction" parameter to the Floor Surface being input?\n'\ 'For now applying a U-Value of 0.5 w/m2k (R11 hr-sf-F/Btu) for this surface.' self.ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, warning) srfcUvalue = 0.5 return srfcUvalue
def test_GetDocumentUserTextWithNoArgsIgnoresDocumentData(self): s,k,v = sec_ent_val() rs.SetDocumentData(s,k,v) rs.SetDocumentUserText(k,v) _,k,v = sec_ent_val() rs.SetDocumentUserText(k,v) self.assertTrue(not any("\\" in k for k in rs.GetDocumentUserText())) self.assertEqual(2, rs.GetDocumentUserText().Count)
def getAssmblyLib(self): assmblyLib = [] print("Reading the Rhino Document's Glazing and Frame Types...") if rs.IsDocumentUserText(): for eachKey in rs.GetDocumentUserText(): if 'PHPP_lib_Assmbly' in eachKey: assmblyLib.append( json.loads(rs.GetDocumentUserText(eachKey))['Name']) return assmblyLib
def getTBLib(self): tb_name_list = [] print "Reading the Rhino Document's Thermal Bridge types..." if rs.IsDocumentUserText(): for eachKey in rs.GetDocumentUserText(): if 'PHPP_lib_TB_' in eachKey: dict = json.loads(rs.GetDocumentUserText(eachKey)) tb_name_list.append( dict.get('Name', '') ) return sorted(tb_name_list)
def runTest(): areas = (createCoverage(objs), createFloors(objs)) sitearea = float(rs.GetDocumentUserText("site area")) legalscr = float(rs.GetDocumentUserText("legal scr")) legalfar = float(rs.GetDocumentUserText("legal far")) designGFA = areas[1] designFAR = designGFA / sitearea designCVA = areas[0] designSCR = designCVA / sitearea rs.SetDocumentUserText("design gfa", str(round(designGFA, 2))) rs.SetDocumentUserText("design far", str(round(designFAR, 2))) rs.SetDocumentUserText("design cva", str(round(designCVA, 2))) rs.SetDocumentUserText("design scr", str(round(designSCR, 2)))
def getDocumentLibraryExgValues(self): assmblyLib = {} if rs.IsDocumentUserText(): for eachKey in rs.GetDocumentUserText(): if self.LibType in eachKey: d = json.loads(rs.GetDocumentUserText(eachKey)) d['ID'] = self.ensureIDisInt(d['ID']) assmblyLib[d['ID']] = d if len(assmblyLib.keys()) == 0: assmblyLib[1] = self.getBlankRow(1) self.Data = assmblyLib return assmblyLib
def setUp(self): rs.DeleteDocumentData() # there's no DeleteDocumentUserText() keys = rs.GetDocumentUserText() if keys: for k in keys: rs.SetDocumentUserText(k)
def test_DeleteDocumentData_not_delete_DocumentUserText(self): s, e, v = sec_ent_val() rs.SetDocumentData(s, e, v) _, k, v = sec_ent_val() rs.SetDocumentUserText(k, v) rs.DeleteDocumentData() self.assertEqual(v, rs.GetDocumentUserText(k))
def get_sisufile_path(): f = rs.GetDocumentUserText(SISUFILE_KEY) if f: return f doc_path = rs.DocumentPath() if not doc_path: return None return os.path.join(doc_path, 'sisufile.json')
def get_constructions_from_rh(_ghdoc): ''' Returns a dict with all the assemblies found in the Rhino UserText''' constructions_ = {} with helpers.context_rh_doc(_ghdoc): if not rs.IsDocumentUserText(): return constructions_ for key in rs.GetDocumentUserText(): if 'PHPP_lib_Assmbly_' in key: value_as_str = rs.GetDocumentUserText(key) value_as_dict = json.loads(value_as_str) assembly_name = value_as_dict.get('Name') constructions_[assembly_name] = value_as_dict return constructions_
def _clearDocumentLibValues(self, _keys): if not rs.IsDocumentUserText(): return for eachKey in rs.GetDocumentUserText(): for k in _keys: if k in eachKey: rs.SetDocumentUserText(eachKey) # no second val = delete
def cPlaneLvl(): userstr = rs.GetDocumentUserText("levels") objdict = ast.literal_eval(userstr) for i in objdict: lvlname = i["level"] elevation = float(i["elevation"]) newplane = rs.CreatePlane((0, 0, elevation)) rs.ViewCPlane(None, newplane) rs.AddNamedCPlane(lvlname)
def set_document_user_text(): document_set_is_successful = rs.SetDocumentUserText('key1', 'value1') if document_set_is_successful: print('Document set is successful') else: print("Couldn't set") value1 = rs.GetDocumentUserText('key1') if value1: print('Document get is successful') print('key1: %s' % (value1))
def checkUserText(): keylist = rs.GetDocumentUserText() # print keylist if keylist is None: startupUserText() elif startupUserTextCheck(keylist) == False: startupUserText() elif startupValueCheck() == False: return else: runTest()
def getTBLibFromDocText(): """ Goes and gets the TB library items from the Document User-Text Will return a dict of dicts, ie: {'TB_Name_01':{'Name':'example', 'fRsi':0.77, 'Psi-Value':0.1},... } """ dict = {} with rhDoc(): if rs.IsDocumentUserText(): keys = rs.GetDocumentUserText() tbKeys = [key for key in keys if 'PHPP_lib_TB_' in key] for key in tbKeys: try: val = json.loads(rs.GetDocumentUserText(key)) name = val.get('Name', 'Name Not Found') dict[name] = val except: msg = "Problem getting Psi-Values for '{}' from the File. Check the\n"\ "DocumentUserText and make sure the TBs are loaded properly".format( name) ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, msg) return dict
def getWindowParamsFromLib(_in, _lib): instDepth = _in.get('InstallDepth', 0.1) varType = _in.get('VariantType', 'a') psiInstallType = _in.get('PsiInstallType', None) frameTypeName = _in['FrameType'] frameTypeObj = _lib['lib_FrameTypes'][ frameTypeName] # the dict is inside a list.... glassTypeName = _in['GlazingType'] glassTypeObj = _lib['lib_GlazingTypes'][glassTypeName] installs = [ 0 if _in['InstallLeft'] == 'False' else 1, 0 if _in['InstallRight'] == 'False' else 1, 0 if _in['InstallBottom'] == 'False' else 1, 0 if _in['InstallTop'] == 'False' else 1 ] # Update the Psi-Installs with UD Values if found in the Library if psiInstallType: sc.doc = Rhino.RhinoDoc.ActiveDoc psiInstalls_UD = json.loads( rs.GetDocumentUserText('PHPP_lib_PsiInstall_' + psiInstallType)) sc.doc = ghdoc if psiInstalls_UD['Left'] != None: installs[0] = psiInstalls_UD['Left'] * installs[0] if psiInstalls_UD['Right'] != None: installs[1] = psiInstalls_UD['Right'] * installs[1] if psiInstalls_UD['Bottom'] != None: installs[2] = psiInstalls_UD['Bottom'] * installs[2] if psiInstalls_UD['Top'] != None: installs[3] = psiInstalls_UD['Top'] * installs[3] return frameTypeObj, glassTypeObj, installs, varType, instDepth
def startupValueCheck(): test = [] for key in siteKeys: try: float(rs.GetDocumentUserText(key)) test.append(True) except: test.append(False) # print test if False in test: return False else: return True
def SetNewLayerStateInLayouts_Init(): # Get it from document user text new_layer_state = rs.GetDocumentUserText("SafeLayout_NewLayerState") if new_layer_state is None: new_layer_state = "off" else: new_layer_state = new_layer_state.lower() if not new_layer_state in ['on', 'off']: new_layer_state = 'off' sc.sticky["SafeLayout_NewLayerState"] = new_layer_state # Set it to document user text rs.SetDocumentUserText("SafeLayout_NewLayerState", new_layer_state)
def RunCommand(is_interactive): # First, get any existing library paths in the Document User Text libPath_compo = rs.GetDocumentUserText('PHPP_Component_Lib') libPath_tb = rs.GetDocumentUserText('PHPP_TB_Lib') libPath_psiInstalls = rs.GetDocumentUserText('PHPP_PsiInstalls_Lib') # Apply defaults if nothing already loaded into the file libPath_compo = libPath_compo if libPath_compo else 'Load Main Library File...' libPath_tb = libPath_tb if libPath_tb else 'Load TB Library File ...' libPath_psiInstalls = libPath_psiInstalls if libPath_psiInstalls else 'Load Window Psi-Installs Library File...' # Call the Dialog Window dialog = Dialog_Libaries(libPath_compo, libPath_tb, libPath_psiInstalls) rc = dialog.ShowModal(Rhino.UI.RhinoEtoApp.MainWindow) # If 'OK' button, then update the DocumentUserText if dialog.Update: if dialog.LibPath_compo: rs.SetDocumentUserText('PHPP_Component_Lib', dialog.LibPath_compo) print 'Setting PHPP Component Library for the Rhino Document to: {}'.format( dialog.LibPath_compo) if dialog.LibPath_tb: rs.SetDocumentUserText('PHPP_TB_Lib', dialog.LibPath_tb) print 'Setting PHPP Thermal Bridge Library for the Rhino Document to: {}'.format( dialog.LibPath_tb) if dialog.LibPath_psiInstalls: rs.SetDocumentUserText('PHPP_PsiInstalls_Lib', dialog.LibPath_psiInstalls) print 'Setting Window Psi-Installs Library for the Rhino Document to: {}'.format( dialog.LibPath_psiInstalls) return 1 # temp for debuggin in editor # RunCommand(True)
def readRoomAttrsFromExcel(self): if rs.IsDocumentUserText(): libpath = rs.GetDocumentUserText('eQ_Spc_Attr_Lib') try: if libpath==None: return [] if not os.path.exists(libPath): return [] #------------------------------- print 'Reading the main Room model attr workbook....beepBoopBeep' with self.readingFromExcel(libPath): try: wsSpaces = self.worksheets['Space']
def readCompoDataFromExcel(self): if rs.IsDocumentUserText(): libPath = rs.GetDocumentUserText('PHPP_Component_Lib') try: if libPath != None: # If a Library File is set in the file... if os.path.exists(libPath): print 'Reading the Main Component Library File....' # Make a Temporary copy saveDir = os.path.split(libPath)[0] tempFile = '{}_temp.xlsx'.format(random.randint(0, 1000)) tempFilePath = os.path.join(saveDir, tempFile) copyfile( libPath, tempFilePath) # create a copy of the file to read from # Open the Excel Instance and File ex = Excel.ApplicationClass() ex.Visible = False # False means excel is hidden as it works ex.DisplayAlerts = False workbook = ex.Workbooks.Open(tempFilePath) worksheets = workbook.Worksheets try: wsComponents = worksheets['Components'] except: print "Could not find the 'Components' Worksheet in the taget file?" # Read in the Components from Excel Worksheet # Come in as 2D Arrays..... grrr..... xlArrayGlazing = wsComponents.Range['IE15:IG113'].Value2 xlArrayFrames = wsComponents.Range['IL15:JC113'].Value2 xlArrayAssemblies = wsComponents.Range['E15:H113'].Value2 workbook.Close() # Close the worbook itself ex.Quit() # Close out the instance of Excel os.remove(tempFilePath) # Remove the temporary read-file # Build the Glazing Library lib_Glazing = [] xlListGlazing = list(xlArrayGlazing) for i in range(0, len(xlListGlazing), 3): if xlListGlazing[i] != None: newGlazing = [ xlListGlazing[i], xlListGlazing[i + 1], xlListGlazing[i + 2] ] lib_Glazing.append(newGlazing) # Build the Frame Library lib_Frames = [] xlListFrames = list(xlArrayFrames) for i in range(0, len(xlListFrames), 18): newFrame = [] if xlListFrames[i] != None: for k in range(i, i + 18): newFrame.append(xlListFrames[k]) lib_Frames.append(newFrame) # Build the Assembly Library lib_Assemblies = [] xlListAssemblies = list(xlArrayAssemblies) for i in range(0, len(xlListAssemblies), 4): newAssembly = [ xlListAssemblies[i], xlListAssemblies[i + 1], xlListAssemblies[i + 2], xlListAssemblies[i + 3] ] lib_Assemblies.append(newAssembly) return lib_Glazing, lib_Frames, lib_Assemblies except: print('Woops... something went wrong reading from the Excel file?') return [], [], []
def getCompoLibAddress(self): if rs.IsDocumentUserText(): return rs.GetDocumentUserText('PHPP_Component_Lib') else: return '...'
def readCompoDataFromExcel(self): if rs.IsDocumentUserText(): libPath = rs.GetDocumentUserText('PHPP_Component_Lib') try: if libPath == None: return [], [], [] if not os.path.exists(libPath): return [], [], [] #------------------------------------------------------------------- print 'Reading the Main Component Library File....' with self.readingFromExcel(libPath): try: wsComponents = self.worksheets['Components'] except: print "ERROR: Could not find the 'Components' Worksheet in the target file?" return [], [], [] #--------------------------------------------------------------- # Read in the Components from Excel Worksheet # Come in as 2D Arrays..... grrr..... xl_glazing = list(wsComponents.Range['IE15:IG113'].Value2) xl_frames = list(wsComponents.Range['IL15:JC113'].Value2) xl_assemblies = list(wsComponents.Range['E15:H113'].Value2) # Read the units headings xl_glazing_units = list(wsComponents.Range['IE14:IG14'].Value2) xl_frames_units = list(wsComponents.Range['IL14:JC14'].Value2) xl_assemblies_units = list( wsComponents.Range['E14:H14'].Value2) #------------------------------------------------------------------- # Figure out the Unit Conversion Factors to use glazing_units = self.determineUnitsFromStr(xl_glazing_units) frames_units = self.determineUnitsFromStr(xl_frames_units) assembls_units = self.determineUnitsFromStr(xl_assemblies_units) glazing_conv_factors = self.determineConversionFactors( glazing_units) frames_conv_factors = self.determineConversionFactors(frames_units) assmbls_conv_factors = self.determineConversionFactors( assembls_units) #------------------------------------------------------------------- # Build the Glazing Library lib_Glazing = [] for i in range(0, len(xl_glazing), 3): if xl_glazing[i] == None: continue tempList = zip(xl_glazing[i:i + 3], glazing_conv_factors) lib_Glazing.append(self.convertInputVal(tempList)) #------------------------------------------------------------------- # Build the Frame Library lib_Frames = [] for i in range(0, len(xl_frames), 18): if xl_frames[i] == None: continue tempList = zip(xl_frames[i:i + 18], frames_conv_factors) lib_Frames.append(self.convertInputVal(tempList)) #------------------------------------------------------------------- lib_Assemblies = [] for i in range(0, len(xl_assemblies), 4): if xl_assemblies[i] == None: continue tempList = zip(xl_assemblies[i:i + 4], assmbls_conv_factors) lib_Assemblies.append(self.convertInputVal(tempList)) return lib_Glazing, lib_Frames, lib_Assemblies except Exception as inst: print('Woops... something went wrong reading from the Excel file?') print('ERROR: ', inst) return [], [], []
import rhinoscriptsyntax as rs import scriptcontext as sc #import Rhino as rc import ast #import json #sc.doc = rc.RhinoDoc.ActiveDoc objdict = sc.sticky["planplanes"] if sticky else ast.literal_eval( rs.GetDocumentUserText("planplanes")) keys = ['level', 'point'] def func(key): val = [d[key] for d in objdict] return val level, point = map(func, keys) x, y, z = map(lambda x: [d[x] for d in point], ['X', 'Y', 'Z']) plane = map(lambda x: rs.CreatePlane(x), zip(x, y, z))
def refresh_DocumentUserText_psi(self): """Reads Psi-Install Excel and adds entries to the file's DocumentUserText Removes all existing Window Pis-Install values from the DocumentUserText dictionary. Reads in all the values from the designated XLSX Libary file and puts into the DocumentUserText dictionary Will look in the self.LibPath_psiInstalls (path) Excel file for: Worksheet named 'Psi-Installs' Reads from Cells B3:F103 (5 columns): Col 1: Type Name (str) Col 2: Left Psi-Install (float) Col 3: Right Psi-Install (float) Col 4: Bottom Psi-Install (float) Col 5: Top Psi-Install (float) """ t1 = datetime.today() succesReading = False ##################################################################################### ################# EXCEL-READ PART ################# ##################################################################################### try: if self.LibPath_psiInstalls != None: # If a Library File is set in the file... if os.path.exists(self.LibPath_psiInstalls): print 'Reading the Window Psi-Installs Library File....' # Make a Temporary copy saveDir = os.path.split(self.LibPath_psiInstalls)[0] tempFile = '{}_tempPsiInst.xlsx'.format( random.randint(0, 1000)) tempFilePath = os.path.join(saveDir, tempFile) copyfile( self.LibPath_psiInstalls, tempFilePath) # create a copy of the file to read from # Open the Excel Instance and File ex = Excel.ApplicationClass() ex.Visible = False # False means excel is hidden as it works ex.DisplayAlerts = False workbook = ex.Workbooks.Open(tempFilePath) # Find the Windows Worksheet worksheets = workbook.Worksheets try: ws_PsiInst = worksheets['Psi-Installs'] except: try: ws_PsiInst = worksheets['Psi-Install'] except: print "Could not find any worksheet names 'Psi-Installs' in the taget file?" # Read in the Thermal Bridges from an Excel Worksheet # Come in as 2D Arrays..... grrr..... xlArray_Psi = ws_PsiInst.Range['B3:F103'].Value2 workbook.Close() # Close the worbook itself ex.Quit() # Close out the instance of Excel os.remove(tempFilePath) # Remove the temporary read-file # Build the Thermal Bridge Library lib_PsiInst = [] xlList_Psi = list(xlArray_Psi) for i in range(0, len(xlList_Psi), 5): if xlList_Psi[i] != None: newPsiInstall = [ xlList_Psi[i], xlList_Psi[i + 1], xlList_Psi[i + 2], xlList_Psi[i + 3], xlList_Psi[i + 4] ] lib_PsiInst.append(newPsiInstall) succesReading = True else: print('No Library filepath set.') succesReading = False except: print('Woops... something went wrong reading from the Excel file?') succesReading = False print lib_PsiInst ##################################################################################### ################# Write the Rhino Doc Library ################# ##################################################################################### if succesReading == True: # If there are any existing 'Document User-Text' Psi-Install objects, remove them print('Clearing out the old values from the Document UserText....') if rs.IsDocumentUserText(): try: for eachKey in rs.GetDocumentUserText(): if 'PHPP_lib_PsiInstall_' in eachKey: print 'Deleting: Key:', eachKey rs.SetDocumentUserText( eachKey ) # If no values are passed, deletes the Key/Value except: print 'Error reading the Library File for some reason.' print('Writing New Library elements to the Document UserText....') # Write the new Psi-Installs to the Document's User-Text if lib_PsiInst: for eachPsiInstall in lib_PsiInst: if eachPsiInstall[0] != None and len( eachPsiInstall[0]) > 0: # Filter our Null values newPsiInstall = { "Typename": eachPsiInstall[0], "Left": eachPsiInstall[1], "Right": eachPsiInstall[2], "Bottom": eachPsiInstall[3], "Top": eachPsiInstall[4], } rs.SetDocumentUserText( "PHPP_lib_PsiInstall_{}".format( newPsiInstall["Typename"]), json.dumps(newPsiInstall)) else: print 'Did not modify the Rhino User-Text Attributes.' print 'This ran in:', datetime.today() - t1, 'seconds' return 1
def refresh_DocumentUserText_TB(self): """ Removes all existing Thermal Bridge values from the DocumentUserText dictionary. Reads in all the values from the designated XLSX Libary file and puts into the DocumentUserText dictionary """ t1 = datetime.today() succesReading = False ##################################################################################### ################# EXCEL-READ PART ################# ##################################################################################### try: if self.LibPath_tb != None: # If a Library File is set in the file... if os.path.exists(self.LibPath_tb): print 'Reading the Thermal Bridge Library File....' # Make a Temporary copy saveDir = os.path.split(self.LibPath_tb)[0] tempFile = '{}_temp.xlsx'.format(random.randint(0, 1000)) tempFilePath = os.path.join(saveDir, tempFile) copyfile( self.LibPath_tb, tempFilePath) # create a copy of the file to read from # Open the Excel Instance and File ex = Excel.ApplicationClass() ex.Visible = False # False means excel is hidden as it works ex.DisplayAlerts = False workbook = ex.Workbooks.Open(tempFilePath) # Find the Windows Worksheet worksheets = workbook.Worksheets try: ws_TBs = worksheets['Thermal Bridges'] except: print "Could not find any worksheet names 'Thermal Bridges' in the taget file?" # Read in the Thermal Bridges from an Excel Worksheet # Come in as 2D Arrays..... grrr..... xlArray_TBs = ws_TBs.Range['A2:C100'].Value2 workbook.Close() # Close the worbook itself ex.Quit() # Close out the instance of Excel os.remove(tempFilePath) # Remove the temporary read-file # Build the Thermal Bridge Library lib_TBs = [] xlList_TBs = list(xlArray_TBs) for i in range(0, len(xlList_TBs), 3): newAssembly = [ xlList_TBs[i], xlList_TBs[i + 1], xlList_TBs[i + 2], ] lib_TBs.append(newAssembly) succesReading = True else: print('No Library filepath set.') succesReading = False except: print('Woops... something went wrong reading from the Excel file?') succesReading = False ##################################################################################### ################# Write the Rhino Doc Library ################# ##################################################################################### if succesReading == True: # If there are any existing 'Document User-Text' Thermal Bridge objects, remove them print('Clearing out the old values from the Document UserText....') if rs.IsDocumentUserText(): try: for eachKey in rs.GetDocumentUserText(): if 'PHPP_lib_TB_' in eachKey: print 'Deleting: Key:', eachKey rs.SetDocumentUserText( eachKey ) # If no values are passed, deletes the Key/Value except: print 'Error reading the Library File for some reason.' print('Writing New Library elements to the Document UserText....') # Write the new Assemblies to the Document's User-Text if lib_TBs: for eachAssembly in lib_TBs: if eachAssembly[0] != None and len( eachAssembly[0]) > 0: # Filter our Null values newAssembly = { "Name": eachAssembly[0], "Psi-Value": eachAssembly[1], "fRsi": eachAssembly[2], } rs.SetDocumentUserText( "PHPP_lib_TB_{}".format(newAssembly["Name"]), json.dumps(newAssembly)) else: print 'Did not modify the Rhino User-Text Attributes.' print 'This ran in:', datetime.today() - t1, 'seconds' return 1
def refresh_DocumentUserText_compo(self): """ Removes all existing Frame, Glazing, and Assmbly values from the DocumentUserText dictionary. Reads in all the values from the designated XLSX Libary file and puts into the DocumentUserText dictionary """ t1 = datetime.today() succesReading = False ##################################################################################### ################# EXCEL-READ PART ################# ##################################################################################### try: if self.LibPath_compo != None: # If a Library File is set in the file... if os.path.exists(self.LibPath_compo): print 'Reading the Main Component Library File....' # Make a Temporary copy saveDir = os.path.split(self.LibPath_compo)[0] tempFile = '{}_temp.xlsx'.format(random.randint(0, 1000)) tempFilePath = os.path.join(saveDir, tempFile) copyfile( self.LibPath_compo, tempFilePath) # create a copy of the file to read from # Open the Excel Instance and File ex = Excel.ApplicationClass() ex.Visible = False # False means excel is hidden as it works ex.DisplayAlerts = False workbook = ex.Workbooks.Open(tempFilePath) # Find the Windows Worksheet worksheets = workbook.Worksheets try: wsComponents = worksheets['Components'] except: print "Could not find the 'Components' Worksheet in the taget file?" # Read in the Components from Excel Worksheet # Come in as 2D Arrays..... grrr..... xlArrayGlazing = wsComponents.Range['IE15:IG113'].Value2 xlArrayFrames = wsComponents.Range['IL15:JC113'].Value2 xlArrayAssemblies = wsComponents.Range['E15:H113'].Value2 workbook.Close() # Close the worbook itself ex.Quit() # Close out the instance of Excel os.remove(tempFilePath) # Remove the temporary read-file # Build the Glazing Library lib_Glazing = [] xlListGlazing = list(xlArrayGlazing) for i in range(0, len(xlListGlazing), 3): if xlListGlazing[i] != None: newGlazing = [ xlListGlazing[i], xlListGlazing[i + 1], xlListGlazing[i + 2] ] lib_Glazing.append(newGlazing) # Build the Frame Library lib_Frames = [] xlListFrames = list(xlArrayFrames) for i in range(0, len(xlListFrames), 18): newFrame = [] if xlListFrames[i] != None: for k in range(i, i + 18): newFrame.append(xlListFrames[k]) lib_Frames.append(newFrame) # Build the Assembly Library lib_Assemblies = [] xlListAssemblies = list(xlArrayAssemblies) for i in range(0, len(xlListAssemblies), 4): newAssembly = [ xlListAssemblies[i], xlListAssemblies[i + 1], xlListAssemblies[i + 2], xlListAssemblies[i + 3] ] lib_Assemblies.append(newAssembly) succesReading = True else: print('No Library filepath set.') succesReading = False except: print('Woops... something went wrong reading from the Excel file?') succesReading = False ##################################################################################### ################# Write the Rhino Doc Library ################# ##################################################################################### if succesReading == True: # If there is any existing 'Document User-Text' Assemblies, Frames or Glazing Types, remove them print('Clearing out the old values from the Document UserText....') if rs.IsDocumentUserText(): try: for eachKey in rs.GetDocumentUserText(): if 'PHPP_lib_Glazing_' in eachKey or 'PHPP_lib_Frame_' in eachKey or 'PHPP_lib_Assmbly_' in eachKey: print 'Deleting: Key:', eachKey rs.SetDocumentUserText( eachKey ) # If no values are passed, deletes the Key/Value except: print 'Error reading the Library File for some reason.' print('Writing New Library elements to the Document UserText....') # Write the new Assemblies to the Document's User-Text if lib_Assemblies: for eachAssembly in lib_Assemblies: if eachAssembly[0] != None and len( eachAssembly[0]) > 0: # Filter our Null values newAssembly = { "Name": eachAssembly[0], "Thickness": eachAssembly[1], "uValue": eachAssembly[2], "intInsulation": eachAssembly[3] } rs.SetDocumentUserText( "PHPP_lib_Assmbly_{}".format(newAssembly["Name"]), json.dumps(newAssembly)) # Write the new Glazings to the Document's User-Text if lib_Glazing: for eachGlazing in lib_Glazing: newGlazingType = { "Name": eachGlazing[0], "gValue": eachGlazing[1], "uValue": eachGlazing[2] } rs.SetDocumentUserText( "PHPP_lib_Glazing_{}".format(newGlazingType["Name"]), json.dumps(newGlazingType)) # Write the new Frames to the Document's User-Text if lib_Frames: for eachFrame in lib_Frames: newFrameType = { "Name": eachFrame[0], "uFrame_L": eachFrame[1], "uFrame_R": eachFrame[2], "uFrame_B": eachFrame[3], "uFrame_T": eachFrame[4], "wFrame_L": eachFrame[5], "wFrame_R": eachFrame[6], "wFrame_B": eachFrame[7], "wFrame_T": eachFrame[8], "psiG_L": eachFrame[9], "psiG_R": eachFrame[10], "psiG_B": eachFrame[11], "psiG_T": eachFrame[12], "psiInst_L": eachFrame[13], "psiInst_R": eachFrame[14], "psiInst_B": eachFrame[15], "psiInst_T": eachFrame[16], "chi": eachFrame[17] } rs.SetDocumentUserText( "PHPP_lib_Frame_{}".format(newFrameType["Name"]), json.dumps(newFrameType)) else: print 'Did not modify the Rhino User-Text Attributes.' print 'This ran in:', datetime.today() - t1, 'seconds' return 1
def _get_curve_psi_value(self, _perimCrvGUID): """Takes in a single Curve GUID and returns its length and Psi*Len Will look at the UserText of the curve to get the Psi Value Type Name and then the Document UserText library to get the Psi-Value of the Type. Returns 0.5 W/mk as default on any errors. Args: self: _perimCrvGUID (GUID): A single GUID Returns: crvPsiValue (float): The Curve's UserText Param for 'Psi-Value' if found. """ warning = None crvPsiValueName = rs.GetUserText(_perimCrvGUID, 'Typename') if crvPsiValueName: for k in rs.GetDocumentUserText(): if 'PHPP_lib_TB' not in k: continue try: d = json.loads(rs.GetDocumentUserText(k)) if d.get('Name', None) == crvPsiValueName: psiValParams = rs.GetDocumentUserText(k) break except: psiValParams = None else: psiValParams = None if psiValParams: psiValParams = json.loads(psiValParams) crvPsiValue = psiValParams.get('psiValue', self.default_perim_psi) if crvPsiValue < 0: warning = 'Warning: Negative Psi-Value found for type: "{}"\nApplying 0.0 W/mk for that edge.'.format( crvPsiValueName) self.ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, warning) crvPsiValue = 0 else: warning = ( 'Warning: Could not find a Psi-Value type in the', 'Rhino Document UserText with the name "{}?"'.format( crvPsiValueName.upper()), 'Check your Document UserText library to make sure that you have', 'your most recent Thermal Bridge library file loaded?', 'For now applying a Psi-Value of {} w/mk for this edge.'. format(self.default_perim_psi)) self.ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, warning) crvPsiValue = self.default_perim_psi else: warning = 'Warning: could not find a Psi-Value type in the\n'\ 'UserText document library for one or more edges?\n'\ 'Check your Document UserText library to make sure that you have\n'\ 'your most recent Thermal Bridge library file loaded?\n'\ 'For now applying a Psi-Value of {} w/mk for this edge.'.format(self.default_perim_psi) self.ghenv.Component.AddRuntimeMessage( ghK.GH_RuntimeMessageLevel.Warning, warning) crvPsiValue = self.default_perim_psi return crvPsiValue, warning
def build_frame_and_glass_objs_from_RH_doc(_ghdoc, _ghenv): """ Loads window-type entries from DocumentUseText library of the Active Rhino doc. Note, it determines if its a 'window-type' entry by looking for the string "PHPP_lib_Glazing", "PHPP_lib_Frame" or "_PsiInstall_" in the key Args: _ghdoc (ghdoc): The 'ghdoc' object from the Grasshopper document. Returns: PHPPLibrary_ (dict): A dictionary of all the window-type entries found with their parameters. """ PHPPLibrary_ = {'lib_GlazingTypes':{}, 'lib_FrameTypes':{}, 'lib_PsiInstalls':{}} lib_GlazingTypes = {} lib_FrameTypes = {} lib_PsiInstalls = {} with LBT2PH.helpers.context_rh_doc(_ghdoc): # First, try and pull in the Rhino Document's PHPP Library # And make new Frame and Glass Objects. Add all of em' to new dictionaries if not rs.IsDocumentUserText(): return PHPPLibrary_ for eachKey in rs.GetDocumentUserText(): if 'PHPP_lib_Glazing' in eachKey: try: tempDict = json.loads(rs.GetDocumentUserText(eachKey)) newGlazingObject = PHPP_Glazing( tempDict['Name'], tempDict['gValue'], tempDict['uValue'] ) lib_GlazingTypes[tempDict['Name']] = newGlazingObject except: msg = 'Something went wrong trying to get the Rhino\n'\ 'information related to the Glazing? Check your\n'\ 'input values there and make sure that it is all filled in\n'\ 'correctly?' _ghenv.Component.AddRuntimeMessage(ghK.GH_RuntimeMessageLevel.Error, msg) elif '_PsiInstall_' in eachKey: try: tempDict = json.loads(rs.GetDocumentUserText(eachKey)) newPsiInstallObject = PHPP_Installs( [ tempDict['Left'], tempDict['Right'], tempDict['Bottom'], tempDict['Top'] ] ) lib_PsiInstalls[tempDict['Typename']] = newPsiInstallObject except Exception as e: msg = 'Something went wrong trying to get the Rhino\n'\ 'information related to the window Psi-Install values? Check your\n'\ 'input values there and make sure that it is all filled in\n'\ 'correctly?' _ghenv.Component.AddRuntimeMessage(ghK.GH_RuntimeMessageLevel.Error, msg) elif 'PHPP_lib_Frame' in eachKey: try: tempDict = json.loads(rs.GetDocumentUserText(eachKey)) newFrameObject = PHPP_Frame() newFrameObject.name = tempDict.get('Name', 'Unnamed Frame') newFrameObject.uValues = [ tempDict.get('uFrame_L', 1.0), tempDict.get('uFrame_R', 1.0), tempDict.get('uFrame_B', 1.0), tempDict.get('uFrame_T', 1.0) ] newFrameObject.frameWidths =[ tempDict.get('wFrame_L', 0.12), tempDict.get('wFrame_R', 0.12), tempDict.get('wFrame_B', 0.12), tempDict.get('wFrame_T', 0.12) ] newFrameObject.PsiGVals = [ tempDict.get('psiG_L', 0.04), tempDict.get('psiG_R', 0.04), tempDict.get('psiG_B', 0.04), tempDict.get('psiG_T', 0.04) ] newFrameObject.Installs = [ tempDict.get('psiInst_L', 0.04), tempDict.get('psiInst_R', 0.04), tempDict.get('psiInst_B', 0.04), tempDict.get('psiInst_T', 0.04) ] lib_FrameTypes[ newFrameObject.name ] = newFrameObject except Exception as e: msg = 'Something went wrong trying to get the Rhino\n'\ 'information related to the window frames? Check your\n'\ 'input values there and make sure that it is all filled in\n'\ 'correctly?' _ghenv.Component.AddRuntimeMessage(ghK.GH_RuntimeMessageLevel.Error, msg) PHPPLibrary_['lib_GlazingTypes'] = lib_GlazingTypes PHPPLibrary_['lib_FrameTypes'] = lib_FrameTypes PHPPLibrary_['lib_PsiInstalls'] = lib_PsiInstalls return PHPPLibrary_