doc = __revit__.ActiveUIDocument.Document path_param = "Auto_PDF_DWF_Path" sheet_set_name = "Auto_PDF_DWG" fileType = "_DWG\\" if doc.ProjectInformation.BuildingName: building = doc.ProjectInformation.BuildingName base_path = doc.ProjectInformation.LookupParameter(path_param).AsString() today = datetime.now().strftime("%y%m%d") export_path = base_path + today + fileType if not os.path.exists(export_path): os.makedirs(export_path) view_sheet_sets = Fec(doc).OfClass(ViewSheetSet) # "Start" the transaction t = Transaction(doc, sheet_set_name) t.Start() for view_sheet_set in view_sheet_sets: if view_sheet_set.Name == sheet_set_name: views = [] for view in view_sheet_set.Views: views.append(view.Id) view_list = List[ElementId](views) dwg_opt = DWGExportOptions() dwg_opt.ExportingAreas = True doc.Export(export_path, building, view_list, dwg_opt)
from Autodesk.Revit.DB import FilteredElementCollector as Fec from Autodesk.Revit.DB import BuiltInCategory as Bic from Autodesk.Revit.DB import Transaction from Autodesk.Revit.DB import FillPattern from Autodesk.Revit.DB import FillPatternElement from Autodesk.Revit.DB import OverrideGraphicSettings from Autodesk.Revit.DB import View from Autodesk.Revit.DB import ElementId import Autodesk import re # reference the current open revit model to work with: doc = __revit__.ActiveUIDocument.Document # get all fill patterns fill_patterns = Fec(doc).OfClass(FillPatternElement).WhereElementIsNotElementType().ToElements() # get id of solid fill solid_fill = fill_patterns[0].Id # set colors color_ast = Autodesk.Revit.DB.Color(177,199,56) color_ast2 = Autodesk.Revit.DB.Color(126,150,56) color_ist = Autodesk.Revit.DB.Color(3,147,188) color_ist2 = Autodesk.Revit.DB.Color(0,64,128) color_none = Autodesk.Revit.DB.Color(200,0,0) color_none2 = Autodesk.Revit.DB.Color(128,0,0)
"""Lists all linked and imported DWG instances with worksets and creator.""" import clr from collections import defaultdict from scriptutils import this_script from revitutils import doc, uidoc clr.AddReference("RevitAPI") # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import FilteredElementCollector as Fec # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import ImportInstance, WorksharingUtils dwgs = Fec(doc).OfClass( ImportInstance).WhereElementIsNotElementType().ToElements() dwgInst = defaultdict(list) workset_table = doc.GetWorksetTable() for dwg in dwgs: if dwg.IsLinked: dwgInst["LINKED DWGs:"].append(dwg) else: dwgInst["IMPORTED DWGs:"].append(dwg) cview = uidoc.ActiveGraphicalView for link_mode in dwgInst: this_script.output.print_md("####{}".format(link_mode)) for dwg in dwgInst[link_mode]: dwg_id = dwg.Id
# main ----------------------------------------------------------------------- # ask user to select an option options = process_options(selection.elements) if options: selected_switch = \ forms.CommandSwitchWindow.show(sorted(options), message='Sum values of parameter:') if selected_switch: selected_option = options[selected_switch] # connect to revit model elements via FilteredElementCollector # collect all the elements of selected elements category elements = Fec(doc).OfCategoryId(element_cat).WhereElementIsNotElementType().ToElements() # get selected parametervalue of selcted element sel_el_param_val = process_storage_type(selected_element.LookupParameter(selected_option.name)) # output lists element_ids = [] # main check ---------------------------------------- for element in elements: # collect element ids element_id = element.Id other_el_param_val = process_storage_type(element.LookupParameter(selected_option.name)) if other_el_param_val == sel_el_param_val:
def name(self): return str(self) def get_rvt_obj(self): return self._rvt_type def find_linked_elements(self): with DryAction("Search for linked elements", clear_after_rollback=True): linked_element_ids = doc.Delete(self._rvt_type.Id) return linked_element_ids # Collect viewport types ----------------------------------------------------------------------------------------------- all_element_types = Fec(doc).OfClass(clr.GetClrType(ElementType)).ToElements() all_viewport_types = [ ViewPortType(x) for x in all_element_types if x.FamilyName == 'Viewport' ] logger.debug('Viewport types: {}'.format(all_viewport_types)) # Ask user for viewport types to be purged ----------------------------------------------------------------------------- purge_vp_types = SelectFromList.show(sorted(all_viewport_types), title='Select Types to be Converted') if not purge_vp_types: sys.exit() for purged_vp_type in purge_vp_types: logger.debug('Viewport type to be purged: {}'.format(repr(purged_vp_type)))
import clr from collections import defaultdict from scriptutils import this_script from revitutils import doc, uidoc clr.AddReference('RevitAPI') # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import FilteredElementCollector as Fec # noinspection PyUnresolvedReferences from Autodesk.Revit.UI import TaskDialog this_script.output.print_md("####LIST ALL ELEMENTS ON SELECTED LEVEL(S):") this_script.output.print_md('By: [{}]({})'.format(__author__, __contact__)) all_elements = Fec(doc).WhereElementIsNotElementType().ToElements() selection = [doc.GetElement(elId) for elId in uidoc.Selection.GetElementIds()] levels = [] for el in selection: if el.Category.Name == 'Levels': levels.append(el) if not levels: TaskDialog.Show('pyRevit', 'At least one Level element must be selected.') else: all_count = all_elements.Count print('\n' + str(all_count) + ' Elements found in project.') for element in levels: element_categories = defaultdict(list)
from Autodesk.Revit.DB import FilteredElementCollector as Fec from Autodesk.Revit.DB import BuiltInCategory as Bic from Autodesk.Revit.DB import Transaction from Autodesk.Revit.DB import FillPattern from Autodesk.Revit.DB import FillPatternElement from Autodesk.Revit.DB import OverrideGraphicSettings from Autodesk.Revit.DB import View from Autodesk.Revit.DB import ElementId import Autodesk import re # reference the current open revit model to work with: doc = __revit__.ActiveUIDocument.Document # get all fill patterns fill_patterns = Fec(doc).OfClass( FillPatternElement).WhereElementIsNotElementType().ToElements() # get id of solid fill solid_fill = fill_patterns[0].Id # set colors color_gd = Autodesk.Revit.DB.Color(177, 199, 56) color_gd2 = Autodesk.Revit.DB.Color(126, 150, 56) color_ba = Autodesk.Revit.DB.Color(3, 147, 188) color_ba2 = Autodesk.Revit.DB.Color(0, 64, 128) color_gd_ba = Autodesk.Revit.DB.Color(3, 100, 188) color_gd_ba2 = Autodesk.Revit.DB.Color(0, 25, 128) color_none = Autodesk.Revit.DB.Color(200, 0, 0)
from scriptutils import logger from revitutils import doc, Action # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import FilteredElementCollector as Fec # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import BuiltInCategory, LinkElementId, UV, XYZ, ViewSection, ViewPlan views = Fec(doc).OfCategory( BuiltInCategory.OST_Views).WhereElementIsNotElementType().ToElements() spaces = Fec(doc).OfCategory(BuiltInCategory.OST_MEPSpaces).WhereElementIsNotElementType().ToElements() def GetElementCenter(el, v): cen = el.Location.Point z = (el.UpperLimit.Elevation + el.LimitOffset) / 2 cen = cen.Add( XYZ( 0, 0, z ) ) return cen with Action('Tag All Rooms in All Views'): for v in views: for el in spaces: room_center = GetElementCenter(el, v) if type(v) in [ViewSection, ViewPlan]: logger.debug('Working on view: %s' % v.ViewName) roomtag = doc.Create.NewRoomTag(LinkElementId(el.Id), UV(room_center.X, room_center.Y), v.Id) if isinstance(v, ViewSection): roomtag.Location.Move(XYZ(0, 0, room_center.Z))
# fatten data structure and get ids of elements warnings = [] for fail in failing_elems_ids: warnings.append(list_flatten(fail)) # all model elements ------------------------------------------------------ categories = doc.Settings.Categories model_cats = [] for category in categories: if str(category.CategoryType) == "Model": model_cats.append(category.Id) nr_of_elems = 0 for i in model_cats: cat_elems = Fec(doc).OfCategoryId( i).WhereElementIsNotElementType().ToElements() nr_of_elems += len(cat_elems) # Naming Conventions ------------------------------------------------------ # regex to get material and thickness regex_mat = re.compile('_[A-ZÄÖÜ]+\ [0-9]?[,]?[0-9]') # regex to get total thickness regex_total = re.compile('__\d+,?\d?\d?') # regex to get total thickness and suffix regex_total_postfix = re.compile('__\d+,?\d?\d?_') # Walls naming ------------------------------------------------------- # connect to revit model elements via FilteredElementCollector # collect all the elements elements = Fec(doc).OfCategory(
def Count_Bic(built_in_category): bic_name = str(built_in_category).replace("OST_", "") bic_elems = Fec(doc).OfCategory( built_in_category).WhereElementIsNotElementType().ToElements() return [len(bic_elems), bic_name]
offset_raw = elem.get_Parameter(wall_constraint).AsDouble() offset = ToInt(offset_raw) elem_info.append(StructuralElement(id, offset, attached)) elif elem.Category.Name == "Tragwerksstützen": element_ids.append(id) offset_raw = elem.get_Parameter(column_constraint).AsDouble() offset = ToInt(offset_raw) elem_info.append(StructuralElement(id, offset, attached)) else: pass except: pass # collect levels and their names levels = Fec(doc).OfCategory( Bic.OST_Levels).WhereElementIsNotElementType().ToElements() level_info = [] for level in levels: id = level.Id elevation_double = level.get_Parameter(Bip.LEVEL_ELEV).AsDouble() elevation = ToInt(elevation_double) level_info.append(LevelInfo(id, level.Name, elevation)) # get all fill patterns fill_patterns = Fec(doc).OfClass( FillPatternElement).WhereElementIsNotElementType().ToElements() # get id of solid fill solid_fill = fill_patterns[0].Id # connect to revit model elements via FilteredElementCollector # collect all the elements of categories
from Autodesk.Revit.DB import FilteredElementCollector as Fec from Autodesk.Revit.DB import Transaction from Autodesk.Revit.DB import OverrideGraphicSettings from Autodesk.Revit.DB import View from Autodesk.Revit.DB import TemporaryViewMode import Autodesk # reference the current open revit model to work with: doc = __revit__.ActiveUIDocument.Document view = doc.ActiveView # connect to revit model elements via FilteredElementCollector elements = filter(None, Fec(doc, doc.ActiveView.Id).ToElements()) ogs = OverrideGraphicSettings().SetSurfaceTransparency(0) # entering a transaction to modify the revit model database # start transaction tx = Transaction(doc, "clear graphic overrides") tx.Start() doc.ActiveView.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate) for element in elements: doc.ActiveView.SetElementOverrides((element.Id), ogs)
import clr # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import FilteredElementCollector as Fec # noinspection PyUnresolvedReferences from Autodesk.Revit.DB import BuiltInCategory, View, ViewType, \ ScheduleSheetInstance, ViewSchedule # COLELCTING DATA -------------------------------------------------------------- dviews = [] mviews = [] lviews = [] scheduleviews = [] all_sheeted_view_ids = [] # Collecting all the model, drafting, and legend views views = Fec(doc).OfCategory(BuiltInCategory.OST_Views)\ .WhereElementIsNotElementType().ToElements() for v in views: if not v.IsTemplate: if v.ViewType == ViewType.DraftingView: dviews.append(v) elif v.ViewType == ViewType.Legend: lviews.append(v) else: mviews.append(v) # Schedules need to be collected separately schedule_views = Fec(doc).OfClass(clr.GetClrType(ViewSchedule))\ .WhereElementIsNotElementType().ToElements() for sv in schedule_views: scheduleviews.append(sv)
def count_category_elements(category): collector = Fec(doc).OfCategory( category).WhereElementIsNotElementType().ToElements() return str(collector.Count)
__author__ = 'Frederic Beaupere' __contact__ = 'https://github.com/frederic-beaupere' __credits__ = 'http://eirannejad.github.io/pyRevit/credits/' __doc__ = 'Families Quickcheck - '\ 'non-exhaustive quickcheck to detect corrupt families.' import Autodesk from Autodesk.Revit.DB import FilteredElementCollector as Fec from Autodesk.Revit.DB import Family from System.Diagnostics import Stopwatch from rpw import doc stopwatch = Stopwatch() stopwatch.Start() all_families = Fec(doc).OfClass(Family).ToElements() checked_families = 0 for fam in all_families: if fam.IsEditable: checked_families += 1 print("--{}-----".format(str(checked_families).zfill(4))) print("attempt to open family: {}".format(fam.Name)) fam_doc = doc.EditFamily(fam) print("{} seems ok.".format(fam.Name)) print("\nquickchecked: {0} families\n{1} run in: ".format( checked_families, __title__)) stopwatch.Stop() timespan = stopwatch.Elapsed
def count_class_type_elements(cls): collector = Fec(doc).OfClass(cls).WhereElementIsElementType().ToElements() return str(collector.Count)
from Autodesk.Revit.DB import Transaction # TODO micro steps to get the script to work # reference the current open revit model to work with: doc = __revit__.ActiveUIDocument.Document # parameter names to work with: # these are just the parameter names # not the actual parameters or their values # Vorgang = "hinges_side_family" # instance_hinges_side = "hinges_side_instance" # connect to revit model elements via FilteredElementCollector # collect all the doors doors = Fec(doc).OfCategory( Bic.OST_Doors).WhereElementIsNotElementType().ToElements() # entering a transaction to modify the revit model database # start transaction tx = Transaction(doc, "set door hinges side") tx.Start() # create main logic here..: for door in doors: print(15 * "-") print(door.Id) # ask every door for its type door_type = door.Symbol # get the preset door hinge side hinges_default_param = door_type.LookupParameter("Vorgang")
except: pass # this function takes all structural columns and structurals framings # and creates an object of the # StructuralElement class and appends it to the elem_info list. def ElemCnvrt(elem_lst): for elem in elem_lst: id = elem.Id elem_info.append(StructuralElement(id, 1)) element_ids.append(id) # get all fill patterns fill_patterns = Fec(doc).OfClass( FillPatternElement).WhereElementIsNotElementType().ToElements() # get id of solid fill solid_fill = fill_patterns[0].Id # set colors color_true = Autodesk.Revit.DB.Color(78, 199, 190) color_true2 = Autodesk.Revit.DB.Color(0, 77, 71) color_false = Autodesk.Revit.DB.Color(236, 77, 0) color_false2 = Autodesk.Revit.DB.Color(153, 51, 0) # create graphical overrides try: ogs_true = OverrideGraphicSettings().SetProjectionFillColor(color_true) ogs_true.SetProjectionFillPatternId(solid_fill) except: ogs_true = OverrideGraphicSettings().SetSurfaceForegroundPatternColor(
Author: Frederic Beaupere | github.com/hdm-dt-fb 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") from Autodesk.Revit.DB import FilteredElementCollector as Fec from Autodesk.Revit.DB import Transaction from System.Collections.Generic import List doc = __revit__.ActiveUIDocument.Document all_views = Fec(doc).OfClass(View).ToElements() view_templates = [view for view in all_views if view.IsTemplate] first_view_template = view_templates[0] view_template_params = first_view_template.GetTemplateParameterIds() switch_off_param_name = "keep_non_sheet_view" # get the id of the parameter we want to switch off for param_id in view_template_params: param = doc.GetElement(param_id) if "Name" in dir(param): print(param.Name) if param.Name == switch_off_param_name: switch_off_param_id = param_id break # set the switch off parameter to be non controlled
# -*- coding: utf-8 -*- import clr clr.AddReference("RevitAPI") clr.AddReference("System") from Autodesk.Revit.DB import FilteredElementCollector as Fec from Autodesk.Revit.DB import BuiltInCategory as Bic from Autodesk.Revit.DB import BuiltInParameter as Bip from Autodesk.Revit.DB import Transaction tx = Transaction(doc, "check structural level offsets") tx.Start() rooms = Fec(doc).OfCategory( Bic.OST_Rooms).WhereElementIsNotElementType().ToElements() areas = Fec(doc).OfCategory( Bic.OST_Areas).WhereElementIsNotElementType().ToElements() for room in rooms: try: print(room.get_Parameter(Bip.ROOM_NAME).AsString()) value0 = room.LookupParameter("Geschoss").AsString() room.LookupParameter("temp").Set(value0) except: print(room.Id) for area in areas: id = area.get_Parameter(Bip.AREA_SCHEME_ID).AsElementId() if str(id) == "522977": try: print(area.get_Parameter(Bip.ROOM_NAME).AsString())
def dump(doc, typed_categories=None, untyped_categories=None, export_path=None, filters=None): """ Writes element data for chosen categories, ids, location and params to specified csv with the possibility to filter: e.g. {'type':{'Type Name':r"^[X][X]_.+"}} :param optional list of typed_categories: e.g. [BIC_Doors] :param optional list of untyped_categories: e.g. [BIC_Rooms] :param export_path: as path string e.g. "c:/temp/rvt_data_dump" :param filters: dict of {'inst/type': {'param_name': 'regex_str_for_param_for_elems_to_keep'}} :return: """ today_time = datetime.now().strftime("%Y%m%d_%H%M") if not typed_categories and not untyped_categories: typed_categories = typical_typed_categories untyped_categories = typical_untyped_categories categories = { "typed": typed_categories or [], "untyped": untyped_categories or [], } model_title = doc.Title exported_instances = defaultdict(int) category_param_names = defaultdict(list) category_type_param_names = defaultdict(list) for typing in categories: print(40 * "-" + typing) for bic in categories[typing]: cat_name = bic.ToString().split("_")[-1] print("__current category: {}".format(cat_name)) instances = Fec(doc).OfCategory( bic).WhereElementIsNotElementType().ToElements() if not instances: continue category_param_names[cat_name] = compile_category_params(instances) if typing == "typed": types = Fec(doc).OfCategory( bic).WhereElementIsElementType().ToElements() category_type_param_names[cat_name] = compile_category_params( types) csv_name = "{}_{}_{}.csv".format(today_time, model_title, cat_name) csv_path = os.path.join(export_path, csv_name) with open(csv_path, "w") as cat_csv: print(" writing: {}".format(csv_path)) header = ";".join( [name for name in category_param_names[cat_name]]) type_header = "" if typing == "typed": type_header = ";" + ";".join( [name for name in category_type_param_names[cat_name]]) cat_csv.write("rvt_id;GUID;location;" + header + type_header + "\n") for inst in instances: inst_params_vals = collect_param_values( doc, inst, category_param_names[cat_name]) inst_type = doc.GetElement(inst.GetTypeId()) location = get_elem_location(inst) ids_loc = "{};{};{};".format(inst.Id.ToString(), inst.UniqueId, location) info_line = ids_loc + ";".join( [val for val in inst_params_vals.values()]) if typing == "typed": type_params_vals = collect_param_values( doc, inst_type, category_type_param_names[cat_name]) info_line += ";" + ";".join( [val for val in type_params_vals.values()]) match = False if filters: if filters.get('type'): for type_param_name_filter in filters['type']: re_param = re.compile( filters['type'][type_param_name_filter]) param_val = type_params_vals[ type_param_name_filter] if re.match(re_param, param_val): match = True break elif filters.get('inst'): for inst_param_name_filter in filters['inst']: re_param = re.compile( filters['inst'][inst_param_name_filter]) param_val = inst_params_vals[ type_param_name_filter] if re.match(re_param, param_val): match = True break if match: cat_csv.write(info_line + "\n") exported_instances[cat_name] += 1 print(40 * "-") return exported_instances
cleanup_str = cleanup_str.replace(r'ä', 'ae') cleanup_str = cleanup_str.replace(r'Ä', 'Ae') cleanup_str = cleanup_str.replace(r'ß', 'ss') cleanup_str = re.sub(r'[^a-zA-Z0-9_\-]', '_', cleanup_str) cleanup_str = re.sub(r'_+', '_', cleanup_str) cleanup_str = re.sub(r'(-_|_-)', '-', cleanup_str) return cleanup_str stopwatch = Stopwatch() stopwatch.Start() doc = __revit__.ActiveUIDocument.Document # dest_dir = op.expandvars('%userprofile%\\desktop') dest_dir = select_folder() img_types = Fec(doc).OfClass(ImageType).ToElements() with Transaction("rename_img_types"): for img in img_types: # export images image = img.GetImage() image_name = op.basename(img.Path) image_path = op.join(dest_dir, image_name) image.Save(op.join(dest_dir, image_name)) # add info to raster image type name img_size = convert_size(op.getsize(image_path)) prefix = cleanup(image_name.rsplit(".", 1)[0]) suffix = image_name.rsplit(".", 1)[1] new_img_type_name = prefix + img_size + suffix
from Autodesk.Revit.UI.Selection import ObjectType __title__ = 'Copy/Update Selected Viewports To Selected Sheets' __doc__ = 'Open the source sheet. Select other sheets in Project Browser. '\ 'Run this script (Keep focus on Project Browser otherwise the ' \ 'current selection will not show the selected sheets). ' \ 'Select Viewports and push Finish button on the properties bar. ' \ 'The selected views will be added to the selected sheets. ' \ 'If the view or schedule already exists on that sheet, the ' \ 'location and viewport type will be updated.' selSheets = [] selViewports = [] allSheetedSchedules = Fec(doc).OfClass(ScheduleSheetInstance).ToElements() # cleanup list of selected sheets for elId in uidoc.Selection.GetElementIds(): el = doc.GetElement(elId) if isinstance(el, ViewSheet): selSheets.append(el) # get a list of viewports to be copied, updated if len(selSheets) > 0: if int(__revit__.Application.VersionNumber) > 2014: cursheet = uidoc.ActiveGraphicalView for v in selSheets: if cursheet.Id == v.Id: selSheets.remove(v)
# fatten data structure and get ids of elements warnings = [] for fail in failing_elems_ids: warnings.append(list_flatten(fail)) # all model elements ---------------------------------------------------------- categories = doc.Settings.Categories model_cats = [] for category in categories: if str(category.CategoryType) == "Model": model_cats.append(category.Id) nr_of_elems = 0 for i in model_cats: cat_elems = Fec(doc).OfCategoryId( i).WhereElementIsNotElementType().ToElements() nr_of_elems += len(cat_elems) # data lists ------------------------------------------------------------------ # headers headers = [] # data = values data = [] headers.append("Date") data.append(str(today)) headers.append("Document name") data.append(str(doc_name)) headers.append("Warnings") data.append(len(warnings)) headers.append("Model elements")
# Import DocumentManager clr.AddReference('RevitServices') import RevitServices from RevitServices.Persistence import DocumentManager from System.Collections.Generic import List from Autodesk.Revit.DB import FilteredElementCollector as Fec from Autodesk.Revit.DB import BuiltInCategory as Bic from Autodesk.Revit.DB import Transaction, Document, FailureMessage, ElementId, FillPatternElement, OverrideGraphicSettings from Autodesk.Revit.UI import Selection import Autodesk from rpw import doc # get all fill patterns fill_patterns = Fec(doc).OfClass( FillPatternElement).WhereElementIsNotElementType().ToElements() # get id of solid fill solid_fill = fill_patterns[0].Id # set colors color_true = Autodesk.Revit.DB.Color(243, 220, 86) color_true2 = Autodesk.Revit.DB.Color(238, 130, 11) color_none = Autodesk.Revit.DB.Color(200, 200, 200) color_none2 = Autodesk.Revit.DB.Color(123, 123, 123) # create graphical overrides ogs_true = OverrideGraphicSettings().SetProjectionFillColor(color_true) ogs_true.SetProjectionFillPatternId(solid_fill) ogs_true.SetSurfaceTransparency(0)