def main(): """Main script - Correct the pipe riser tags tagging vent pipes.""" print("🐍 Running {name} version {ver}:".format(name=__name, ver=__version)) # STEP 0: Setup doc = __revit__.ActiveUIDocument.Document view = doc.ActiveView # STEP 1: Get all available Pipe Tags in the project print("Getting all available pipe tags from the model... ", end="") tag_types = db.FilteredElementCollector(doc)\ .OfCategory(db.BuiltInCategory.OST_PipeTags)\ .WhereElementIsElementType()\ .ToElements() tag_types_mapping = {} # tag_title: tag_type for tag_type in tag_types: tag_family_name = tag_type.get_Parameter( db.BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM).AsString() tag_type_name = tag_type.get_Parameter( db.BuiltInParameter.SYMBOL_NAME_PARAM).AsString() full_tag_name = "{f_name} - {t_name}".format(f_name=tag_family_name, t_name=tag_type_name) tag_types_mapping[full_tag_name] = tag_type print("✔") # STEP 2: Check if setup tags actually exist in project print("Checking if expected tag family (and types) exist(s)... ", end="") all_tags_available = True for tag_name in TAG_TYPE_NAME_MAPPING.values(): if not tag_name in tag_types_mapping: print( "✘ Error: {tag_name} not available!".format(tag_name=tag_name)) all_tags_available = False if not all_tags_available: print( "✘ Error: Not all required tags are available in the project! See above." ) return ui.Result.Failed print("✔") # STEP 3: Get all the tags in the view tags_in_view = db.FilteredElementCollector(doc, view.Id)\ .OfCategory(db.BuiltInCategory.OST_PipeTags)\ .WhereElementIsNotElementType()\ .ToElements() # STEP 4: Change all tags on vent pipes to vent tags print("Changing all pipe riser tags tagging vent pipes.... ", end="") transaction = db.Transaction(doc) transaction.Start("{name} - v{ver}".format(name=__name, ver=__version)) try: for tag in tags_in_view: host = tag.GetTaggedLocalElement() system = host.MEPSystem if system: system_type = doc.GetElement(system.GetTypeId()) system_classification = system_type.SystemClassification if system_classification == db.MEPSystemClassification.Vent: tag_type = doc.GetElement(tag.GetTypeId()) tag_family_name = tag_type.get_Parameter( db.BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM).AsString( ) tag_type_name = tag_type.get_Parameter( db.BuiltInParameter.SYMBOL_NAME_PARAM).AsString() if not tag_family_name == TAG_FAMILY_NAME: # other kind of tag, dont bother continue if tag_type_name not in REMAPPING: # tag type already good or not in remapping continue target = REMAPPING[tag_type_name] target_type_id = tag_types_mapping[ TAG_TYPE_NAME_MAPPING[target]].Id tag.ChangeTypeId(target_type_id) except Exception as ex: print("\n✘ Exception:\n {ex}".format(ex=ex)) transaction.RollBack() return ui.Result.Failed else: transaction.Commit() print("✔\nDone. 😊") return ui.Result.Succeeded
def FindViewType(_doc): view_family_type = DB.FilteredElementCollector(doc) \ .OfClass(DB.ViewFamilyType) \ return next(f for f in view_family_type if f.ViewFamily == DB.ViewFamily.ThreeDimensional)
def main(): """Main script docstring.""" print("🐍 Running {fname} version {ver}...".format(fname=__name, ver=__version)) # STEP 0: Setup app = __revit__.Application doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument view = doc.ActiveView # STEP 1: Find all appropriate schedules print("Getting all available schedules from the model...", end="") all_schedules = db.FilteredElementCollector(doc)\ .OfCategory(db.BuiltInCategory.OST_Schedules)\ .WhereElementIsNotElementType()\ .ToElements() print("✔") print(" ➜ Found {num} schedules in the project.".format( num=len(all_schedules))) #print(all_schedules) # STEP 2: Filtering for quantification schedules (with given prefix) print("Filtering quantification schedules from the found schedules...", end="") quantity_schedules = [ s for s in all_schedules if s.Name.startswith(PREFIX) ] print("✔") print(" ➜ Found {num} schedules with prefix '{prefix}'.".format( num=len(quantity_schedules), prefix=PREFIX)) #print(quantity_schedules) # STEP 3: Ask for export folder location print("Please select an output folder for saving the schedules...", end="") folder_browser = swf.FolderBrowserDialog() folder_browser.Description = "Please select an output folder for saving the schedules." if folder_browser.ShowDialog( ) != swf.DialogResult.OK: # no folder selected print("\n✘ No folder selected. Nothing to do.") return ui.Result.Cancelled print("✔") print("🛈 Selected output folder: {folder}".format( folder=folder_browser.SelectedPath)) # STEP 3: Export all selected schedules # https://www.revitapidocs.com/2018/8ba18e73-6daf-81b6-d15b-e4aa90bc8c22.htm print("Exporting schedules as CSV to selected output folder...", end="") try: export_options = db.ViewScheduleExportOptions() export_options.FieldDelimiter = "," for schedule in quantity_schedules: file_name = "{name}.csv".format(name=schedule.Name) schedule.Export(folder_browser.SelectedPath, file_name, export_options) except Exception as ex: print("\n✘ Exception:\n {ex}".format(ex=ex)) return ui.Result.Failed else: print("✔\nDone. 😊") return ui.Result.Succeeded
clr.AddReference('RevitNodes') import Revit clr.ImportExtensions(Revit.Elements) from System.Collections.Generic import List def tolist(x): if hasattr(x, '__iter__'): return x else: return [x] x = UnwrapElement(tolist(IN[0])) fec = DB.FilteredElementCollector(doc).WhereElementIsElementType() if isinstance(x[0], DB.Category): catId = List[DB.ElementId](c.Id for c in x) filter = DB.ElementMulticategoryFilter(catId) elif isinstance(x[0], DB.ElementType): types = List[System.Type](t.GetType() for t in x) filter = DB.ElementMulticlassFilter(types) else: types = List[System.Type](x) filter = DB.ElementMulticlassFilter(types) fec.WherePasses(filter) OUT = [e.ToDSType(1) for e in fec] fec.Dispose() filter.Dispose()
try: doc.Delete(view.Id) break except: forms.alert( 'Current view was cannot be deleted. Close view and try again.' ) return False return True if forms.check_workshared(doc, 'Model is not workshared.'): viewtype_id = FindViewType(doc).Id worksets = DB.FilteredWorksetCollector(doc).OfKind( DB.WorksetKind.UserWorkset) views = DB.FilteredElementCollector(doc).OfClass(DB.View).ToElements() # Check if the view type found has ViewTemplate associated with it # A ViewTemplate will prevent the assignment of correct Workset settings RemoveViewTemplate(viewtype_id) # Delete all previous Workset views # In case the user has opened one of them, warn them and do not execute if DeleteExistingView(views, worksets): with revit.Transaction("Create 3D Worksets"): for workset in worksets: name = workset.Name view = DB.View3D.CreateIsometric(doc, viewtype_id) view.Name = "WORKSET VIEW - " + name SetWorksetVisibility(view, workset) forms.alert('Successfully created Workset Views')
def CurtainCheck(TypeCheck): if hasattr(TypeCheck,'__iter__'): return TypeCheck else : return [TypeCheck] #VARIABLES doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument #Angle between project north and real north (in radians). #final -1 "undoes" real to project north transformation. angle = doc.ActiveProjectLocation.get_ProjectPosition(XYZ(0,0,0)).Angle * -1 walls = DB.FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElements() #doors = DB.FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Doors).WhereElementIsNotElementType().ToElements() collwindows = DB.FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Windows).WhereElementIsNotElementType().ToElements() CurtainPanels = DB.FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_CurtainWallPanels).WhereElementIsNotElementType().ToElements() windows = [] new_walls = [] ori_x = [] ori_y = [] ExcludedWalls = [] print("Total walls in model: " + str(len(walls))) NWalls = []
clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * clr.AddReference('RevitNodes') import Revit clr.ImportExtensions(Revit.Elements) clr.ImportExtensions(Revit.GeometryConversion) clr.AddReference('RevitServices') import RevitServices from RevitServices.Persistence import DocumentManager from RevitServices.Transactions import TransactionManager rooms = DB.FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms) #Metodos del nodo de dynamo (por si hubiese que usar la segunda) """#method #1 - get boundary segments try: for boundarylist in item.GetBoundarySegments(options): for boundary in boundarylist: blist.append(doc.GetElement(boundary.ElementId)) if version > 2016: clist.append(boundary.GetCurve().ToProtoType()) else: clist.append(boundary.Curve.ToProtoType()) except: pass #method #2 - spatial element geometry calculator try:
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import * #use ElementId from System.Collections.Generic import * #use LIST from pyrevit import revit, DB, HOST_APP from pyrevit import script output = script.get_output() # Close other output when launched several times close_other_output = output.close_others(all_open_outputs=True) # Collect family instances familyinstance_collector = DB.FilteredElementCollector(revit.doc)\ .OfClass(DB.FamilyInstance)\ .WhereElementIsNotElementType()\ .ToElements() # filter inplace families inplace_families = [ x for x in familyinstance_collector if x.Symbol and x.Symbol.Family and x.Symbol.Family.IsInPlace ] # make a iCollection of inplace families inplace_families_toIsolate = List[ElementId](i.Id for i in inplace_families) print('Found {} in-place families'.format(len(inplace_families))) print('\nCATEGORY & FAMILY NAME') report = []
def parameterize(names_dict): for i, row in enumerate(names_dict): #if i == 5: # break logging.debug("{} PROCESSING {} = {}".format(i, row['Family'], row['Type'])) target_family = row['Family'] target_type = row['Type'] #param_dict = names_dict[row] elems = rvt_db.FilteredElementCollector(rvt_doc).OfClass( rvt_db.FamilySymbol).ToElements() raise for i, el in enumerate(elems): this_category = None this_family = el.FamilyName this_type = util_ra.get_parameter_value(el, 'Type Name') change_list = list() if target_family == this_family and target_type == this_type: # ITEM CODE ########### if util_ra.get_parameter_value( el, 'IKEA Item Code') != row['IKEA Item Code NEW']: try: util_ra.change_parameter(rvt_doc, el, 'IKEA Item Code', row['IKEA Item Code NEW'], verbose=False) change_list.append("Item Code") except: print("Couldn't change {}".format('IKEA Item Code')) change_list.append("ERROR in Item Code") raise else: change_list.append("Skipped Item Code") # ifcDescription ########### if util_ra.get_parameter_value( el, 'ifcDescription') != row['ifcDescription NEW']: try: util_ra.change_parameter(rvt_doc, el, 'ifcDescription', row['ifcDescription NEW'], verbose=False) change_list.append("ifcDescription") except: print("Couldn't change {}".format('ifcDescription')) change_list.append("ERROR in ifcDescription") raise else: change_list.append("Skipped ifcDescription") # COST GROUP ########### if util_ra.get_parameter_value( el, 'IKEA Cost Group') != row['IKEA Cost Group NEW']: try: util_ra.change_parameter(rvt_doc, el, 'IKEA Cost Group', row['IKEA Cost Group NEW'], verbose=False) change_list.append("IKEA Cost Group") except: print("Couldn't change {}".format('IKEA Cost Group')) change_list.append("ERROR in IKEA Cost Group") raise else: change_list.append("Skipped IKEA Cost Group") logging.debug("Changes: {}".format(";".join(change_list)))
# # Assigns our filter to the element parameter filter so it fits into the # # '.WherePasses(element_filter)' method # element_filter = DB.ElementParameterFilter(param_filter) # Collect a list of items eligible to get picked by the filter. # I found OST_PipeCurves from a combination of looking over the built in categories and options for the collected elements .WhereElementIsNotElementType(). .OfClass(typeof(FamilyInstance)) collected_elements = [] proj_stairs_railings = [] proj_hand_railings = [] proj_top_railings = [] # print("\n" + "-" * 25 + "Stairs Railings: " + "-" * 25) stairs_railings = DB.FilteredElementCollector(doc) \ .OfCategory(DB.BuiltInCategory.OST_StairsRailing) \ .WhereElementIsNotElementType() \ .ToElements() for rail in stairs_railings: collected_elements.append(rail) proj_stairs_railings.append(rail) # print(rail.Id) # print("\n" + "-" * 25 + "Hand Railings: " + "-" * 25) hand_railings = DB.FilteredElementCollector(doc) \ .OfCategory(DB.BuiltInCategory.OST_RailingHandRail) \ .WhereElementIsNotElementType() \ .ToElements() for rail in hand_railings: collected_elements.append(rail) proj_hand_railings.append(rail)
import pandas as pd df_dict = {'key 1': 1, 'key 2': 2, 'key 3': 3} df = pd.DataFrame([df_dict]) print("\n## pandas DataFrame:") print_html(df.to_html().replace('\n', '')) except Exception as ex: print(f'pandas load error: {ex}') import clr # clr.AddReference('Autodesk.Revit.DB') import Autodesk.Revit.DB as DB print('\n## UIApplication:') __revit__ = sys.host print(__revit__) cl = DB.FilteredElementCollector(__revit__.ActiveUIDocument.Document)\ .OfClass(DB.Wall)\ .WhereElementIsNotElementType()\ .ToElements() print('\n## list of DB.Walls:') for wall in cl: print(f'{wall} id:{wall.Id.IntegerValue}') # test unicode print(""" Кириллица (/ sɪˈrɪlɪk /) - это система письма """)
TESTED REVIT API: 2017 Author: Gui Talarico | github.com/gtalarico This file is shared on www.revitapidocs.com For more information visit http://github.com/gtalarico/revitapidocs License: http://github.com/gtalarico/revitapidocs/blob/master/LICENSE.md """ import clr clr.AddReference('RevitAPI') clr.AddReference('RevitAPIUI') from Autodesk.Revit import DB uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document pts = DB.FilteredElementCollector(doc).OfClass( DB.PointCloudInstance).WhereElementIsNotElementType().ToElements() pt_cloud_settings = DB.PointClouds.PointCloudOverrideSettings() pt_cloud_settings.ColorMode = DB.PointCloudColorMode.Normals for pt in pts: view = uidoc.ActiveView pt_overrides = view.GetPointCloudOverrides() t = DB.Transaction(doc) t.Start('Set Pt Cloud Color Mode') pt_overrides.SetPointCloudOverrideSettings(pt.Id, pt_cloud_settings) t.Commit()
'Planting', 'Plumbing Fixtures', 'RVT Links', 'Railings', 'Ramps', 'Roads', 'Roofs', 'Rooms', 'Security Devices', 'Shaft Openings', 'Site', 'Spaces', 'Specialty Equipment', 'Sprinklers', 'Stairs', 'Structural Area Reinforcement', 'Structural Beam Systems', 'Structural Columns', 'Structural Connections', 'Structural Foundations', 'Structural Framing', 'Structural Path Reinforcement', 'Structural Rebar', 'Structural Rebar Couplers', 'Structural Stiffeners', 'Structural Trusses', 'Switch System', 'Telephone Devices', 'Topography', 'Views', 'Walls', 'Windows', 'Wires' ] choose = forms.CommandSwitchWindow.show(ops, message='Select Option') catlist = { 'Air Terminal': DB.FilteredElementCollector(doc).OfCategory( DB.BuiltInCategory.OST_DuctTerminal), 'Areas': DB.FilteredElementCollector(doc).OfCategory(DB.BuiltInCategory.OST_Areas), 'Assemblies': DB.FilteredElementCollector(doc).OfCategory( DB.BuiltInCategory.OST_Assemblies), 'Cable Tray Fitting': DB.FilteredElementCollector(doc).OfCategory( DB.BuiltInCategory.OST_CableTrayFitting), 'Cable Tray Runs': DB.FilteredElementCollector(doc).OfCategory( DB.BuiltInCategory.OST_CableTrayRun), 'Cable Trays': DB.FilteredElementCollector(doc).OfCategory( DB.BuiltInCategory.OST_CableTray), 'Casework':
# coding: utf8 from Autodesk.Revit import DB # from pyrevit import revit, DB doc = __revit__.ActiveUIDocument.Document # doc = revit.doc.ActiveUIDocument.Document # Creating collector instance and collecting all the walls from the model # wc = DB.FilteredElementCollector(doc)\ # .OfCategory(DB.BuiltInCategory.OST_Walls)\ # .WhereElementIsNotElementType()\ # .ToElements() wc = DB.FilteredElementCollector(revit.doc)\ .OfCategory(DB.BuiltInCategory.OST_Walls)\ .WhereElementIsNotElementType()\ .ToElements() wc = DB.FilteredElementCollector(doc).OfCategory( DB.BuiltInCategory.OST_Walls).WhereElementIsNotElementType().ToElements() wc = DB.FilteredElementCollector(doc).OfCategory( DB.BuiltInCategory.OST_Walls).WhereElementIsElementType().ToElements() # col = [x for x in wall_collector] # w1 = col[0] cws = [] bws = [] # for w in wc: