import clr clr.AddReference("RevitAPI") from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, SpatialElementGeometryCalculator, \ BuiltInParameter clr.AddReference("RevitServices") from RevitServices.Persistence import DocumentManager from RevitServices.Transactions import TransactionManager doc = DocumentManager.Instance.CurrentDBDocument room_col = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_Rooms).ToElements() calculator = SpatialElementGeometryCalculator(doc) TransactionManager.Instance.EnsureInTransaction(doc) facelist = [] for room in room_col: room_num = room.get_Parameter(BuiltInParameter.ROOM_NUMBER).AsString() result = calculator.CalculateSpatialElementGeometry(room) room_solid = result.GetGeometry() elems = [] for face in room_solid.Faces: subfaceList = result.GetBoundaryFaceInfo(face) for sub in subfaceList: elem = doc.GetElement(sub.SpatialBoundaryElement.HostElementId) elem.get_Parameter( BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS).Set(room_num) elems.append(elem) facelist.append(elems)
def __init__(self, xaml_file_name): WPFWindow.__init__(self, xaml_file_name) self.levels = FilteredElementCollector(doc).OfClass(Level) self.combobox_levels.DataContext = self.levels
the Free Software Foundation. This program 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. See this link for a copy of the GNU General Public License protecting this package. https://github.com/eirannejad/pyRevit/blob/master/LICENSE ''' import clr from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, Element, Group, GroupType, Transaction, BuiltInParameter, TextNote uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document cl = FilteredElementCollector(doc) grps = list(cl.OfClass(clr.GetClrType(Group)).ToElements()) grpTypes = set() for g in grps: mems = g.GetMemberIds() for el in mems: mem = doc.GetElement(el) if isinstance(mem, TextNote): grpTypes.add(g.GroupType.Id) for gtId in grpTypes: print(Element.Name.GetValue(doc.GetElement(gtId)))
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See this link for a copy of the GNU General Public License protecting this package. https://github.com/eirannejad/pyRevit/blob/master/LICENSE ''' __doc__ = 'Lists keynotes that have not been used in this model.' from Autodesk.Revit.DB import FilteredElementCollector, KeynoteTable, BuiltInCategory from System.Collections.Generic import List uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document usedkeynotes = set() keynotes = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_KeynoteTags).WhereElementIsNotElementType().ToElements( ) for kn in keynotes: usedkeynotes.add(kn.TagText) allkeynotes = set() kt = KeynoteTable.GetKeynoteTable(doc) for kn in kt.GetKeyBasedTreeEntries(): allkeynotes.add(kn.Key) unusedkeynotes = allkeynotes - usedkeynotes for kn in sorted(unusedkeynotes): print(kn)
import clr clr.AddReference('RevitAPI') from Autodesk.Revit.DB import FilteredElementCollector, SharedParameterElement clr.AddReference('RevitServices') from RevitServices.Persistence import DocumentManager from RevitServices.Transactions import TransactionManager doc = DocumentManager.Instance.CurrentDBDocument def DeleteParams(params, name): for p in params: if p.Name == name: doc.Delete(p.Id) name_param = IN[0] params = FilteredElementCollector(doc).OfClass(SharedParameterElement) TransactionManager.Instance.EnsureInTransaction(doc) DeleteParams(params, name_param) TransactionManager.Instance.TransactionTaskDone() OUT = 0
"""Generates a report of all changes for a specific revision.""" import os.path as op from scriptutils import this_script from revitutils import doc, uidoc from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, WorksharingUtils, WorksharingTooltipInfo, ElementId, ViewSheet from Autodesk.Revit.UI import TaskDialog # collect data: revClouds = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_RevisionClouds).WhereElementIsNotElementType() sheetsnotsorted = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_Sheets).WhereElementIsNotElementType().ToElements() sheets = sorted(sheetsnotsorted, key=lambda x: x.SheetNumber) allRevs = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_Revisions).WhereElementIsNotElementType() # fixme: cleanup and re-write OOP # todo: add findDetailNumberAndReferencingSheet() for any clouds that are placed on views # todo: add findUnderlayViewport() for any cloud that is on a sheet over a viewport. # todo: ask for revision number to generate report for: pass # digging into data: descSet = set() noneDescClouds = [] revDict = dict() for revc in revClouds:
"""Lists views that have not been placed on any sheets.""" from scriptutils import this_script from revitutils import doc, uidoc from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, View views = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_Views).WhereElementIsNotElementType().ToElements() mviews = [] dviews = [] for v in views: if 'drafting' in str(v.ViewType).lower() and not v.IsTemplate: dviews.append(v) elif not v.IsTemplate: mviews.append(v) print('DRAFTING VIEWS NOT ON ANY SHEETS'.ljust(100, '-')) for v in dviews: phasep = v.LookupParameter('Phase') sheetnum = v.LookupParameter('Sheet Number') detnum = v.LookupParameter('Detail Number') refsheet = v.LookupParameter('Referencing Sheet') refviewport = v.LookupParameter('Referencing Detail') if sheetnum and detnum and ('-' not in sheetnum.AsString()) and ( '-' not in detnum.AsString()): continue else: print('TYPE: {1} ID: {2} {0}'.format( v.ViewName,
def get_3dview_by_name(view_name, document): view_col = FilteredElementCollector(document).OfClass(View3D) for view in view_col: if view.Name == view_name: return view
def matchPaperSize(viewlist, pdfPrinterName, counterlimit=7): #create dictionary from PaperSizeSet - class doc.PrintManager.SelectNewPrintDriver(pdfPrinterName) #line needed, # when a non-pdf printer is set up. papersizeset = doc.PrintManager.PaperSizes #dic_ps = {i.Name: i for i in papersizeset if i.Name[0].isdigit()} dic_ps = {} # put it in try statement because Foxitpdfprinter hat a form with Blank Name, None -> Error for i in papersizeset: try: if i.Name[0].isdigit( ): #or i.Name in ["119x84.5 A0", "59.5x42 A2", "84.5x59.5 A1" ]: dic_ps[i.Name] = i except: pass bip_shwi = BuiltInParameter.SHEET_WIDTH bip_shhei = BuiltInParameter.SHEET_HEIGHT psmess = [] papersizeobjls = [] try: for i, v in enumerate(viewlist): # Get TitleBlock with Para Sheet_Width > 20 cm # note: FilterDoubleRule(ParameterValueProvider(), FilterNumericEquals), # "ex.10.0", delta_x) filter_double_rule = \ FilterDoubleRule(ParameterValueProvider(ElementId(bip_shwi)), \ FilterNumericGreater(), 0.20 / 0.3048, 1E-2) FECtb = FilteredElementCollector(doc, v.Id) \ .WherePasses(ElementParameterFilter(filter_double_rule)) \ .ToElements() bip_wi = int(FECtb[0].get_Parameter(bip_shwi).AsDouble() * 0.3048 * 1000) # from m to cm bip_hei = int(FECtb[0].get_Parameter(bip_shhei).AsDouble() * 0.3048 * 1000) # print bip_wi, bip_hei , float(bip_wi), float(bip_hei), int(bip_wi), int(bip_hei) # cut of all irelevant 0.750000011 = 750 mm wi_cm = bip_wi / 10 #__future__ division ex: 297 / 10 = 29.7 hei_cm = bip_hei / 10 shsize_str = ''.join([str(wi_cm), "x", str(hei_cm)]) shsize_str_round = ''.join( [str(round_up(wi_cm, 0.5)), "x", str(round_up(hei_cm, 0.5))]) mess = [] mess.append(shsize_str) # Check if original sheetformat or sheetformat roundedUp by 0.5cm is in papersize dic try: if any([ papersizeobjls.append(dic_ps[i]) for i in [shsize_str, shsize_str_round] if i in dic_ps ]): mess.append('match--> worked') mess.append(i) psmess.append(mess) print " any() worked" continue # go back to header of for loop/ continue with for loop except: print "any didn' work" # round to cm values 45.11 --> 50 , 73.0 --> 75 wi = int(round_up(wi_cm, 5)) hei = int(round_up(hei_cm, 5)) shsize_str = ''.join([str(wi), "x", str(hei)]) mess.append(shsize_str) cntr = 0 while shsize_str not in dic_ps and cntr < counterlimit: if cntr % 3 == 0: # 0%3 = 0 1%3 = 1, 2%3 = 2, 3%3=0, 4%3=1, 5%3=2 ... shsize_str = ''.join([str(wi), 'x', str(hei + 5)]) mess.append(shsize_str) cntr += 1 elif cntr % 3 == 1: shsize_str = ''.join([str(wi + 5), "x", str(hei)]) mess.append(shsize_str) cntr += 1 else: # cntr % 3 == 2: wi = wi + 5 hei = hei + 5 shsize_str = ''.join([str(wi), "x", str(hei)]) mess.append(shsize_str) cntr += 1 if shsize_str in dic_ps: mess.append("match-->") mess.append(shsize_str) papersizeobjls.append(dic_ps[shsize_str]) else: #when no papersize found, after while loop, use default = 90x90 papersizeobjls.append(dic_ps["90x90"]) mess.append("no match, ps= 90x90") psmess.append(mess) except: import traceback print(traceback.format_exc()) return (papersizeobjls, psmess)
clr.ImportExtensions(System.Linq) # Import LINQ extension methods (to enable "fluent syntax") import System.Linq from Autodesk.Revit.DB import Transaction, FilteredElementCollector, BuiltInCategory, View, ViewType, ElementId # don't need to import that import sys pyt_path = (r'C:\Program Files (x86)\IronPython 2.7\Lib') sys.path.append(pyt_path) doc = __revit__.ActiveUIDocument.Document # FEC HK section line -> category: Ost_Viewers------------------------------------------- viewers = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Viewers) \ .WhereElementIsNotElementType() \ .ToElements() sectionlines = [] for i in viewers: p = i.LookupParameter("HK") if p and p.AsInteger().Equals(1): sectionlines.append(i) hidelist = sectionlines FECviews= FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Views) \ .WhereElementIsNotElementType() \ .ToElements() viewlist = [i for i in FECviews if i.CanBePrinted]
This program 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. See this link for a copy of the GNU General Public License protecting this package. https://github.com/eirannejad/pyRevit/blob/master/LICENSE ''' import os.path as op from Autodesk.Revit.DB import FilteredElementCollector, Element, ImageType uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document selection = [ doc.GetElement(elId) for elId in __revit__.ActiveUIDocument.Selection.GetElementIds() ] destDir = op.expandvars('%userprofile%\\desktop') cl = FilteredElementCollector(doc) list = cl.OfClass(ImageType).ToElements() for el in list: image = el.GetImage() imageName = op.basename(el.Path) # imageName = Element.Name.GetValue( el ) print('EXPORTING: {0}'.format(imageName)) image.Save(op.join(destDir, imageName))
def draw(panels): els = FilteredElementCollector(doc)\ .OfCategory(BuiltInCategory.OST_GenericAnnotation)\ .WhereElementIsNotElementType()\ .ToElements() # for el in els: # if el.Name == 'Цепь' or el.Name == 'Щит': # doc.Delete(el.Id) anns = FilteredElementCollector(doc)\ .OfCategory(BuiltInCategory.OST_GenericAnnotation)\ .WhereElementIsElementType()\ .ToElements() cirFamily = list( filter( lambda x: x.get_Parameter(BuiltInParameter.SYMBOL_NAME_PARAM). AsString() == 'Цепь', anns))[0] panelFamily = list( filter( lambda x: x.get_Parameter(BuiltInParameter.SYMBOL_NAME_PARAM). AsString() == 'Щит', anns))[0] views = FilteredElementCollector(doc)\ .OfCategory(BuiltInCategory.OST_Views)\ .WhereElementIsNotElementType()\ .ToElements() activeView = 0 for i in views: if i.Name == 'Чертежный вид 1': activeView = i if not activeView: raise Exception('No view to draw') # activeView = doc.ActiveView if doc.ActiveView.Name != 'Чертежный вид 1': return cApps = { 'qf': 'Автоматический выключатель', 'QF': 'Автоматический выключатель 2P', 'QS': 'Выключатель', 'QFD': 'Дифф', 'KM': 'Контактор', 'FU': 'Плавкая вставка', 'QSU': 'Рубильник с плавкой вставкой', 'QD': 'УЗО' } for y, panel in enumerate( natural_sorted(filter( lambda x: doc.GetElement(x).LookupParameter('Имя щита'). AsString(), panels.keys()), key=lambda x: doc.GetElement(x).LookupParameter( 'Имя щита').AsString())): el = doc.Create.NewFamilyInstance(XYZ(0, -y * 250 / k, 0), panelFamily, activeView) el.LookupParameter('Имя щита').Set( doc.GetElement(panel).LookupParameter('Имя щита').AsString()) # headCirs = filter(lambda x: 'Щит' in x.BaseEquipment.Name, natural_sorted(panels[panel], key=lambda x: x.LookupParameter('Номер группы').AsString())) headCirs = [] for cir in natural_sorted( panels[panel], key=lambda x: x.LookupParameter('Номер группы').AsString()): if not cir.BaseEquipment or ( 'Щит' in cir.BaseEquipment.Name and 'Итого' not in cir.LookupParameter('Имя нагрузки группы').AsString()): headCirs.append(cir) # headCirs = filter(lambda x: 'Щит' in x.BaseEquipment.Name, natural_sorted(panels[panel], key=lambda x: x.LookupParameter('Номер группы').AsString())) # print headCirs[0] # print headCirs[0].Id res = headCirs[0].BaseEquipment.LookupParameter('Резерв').AsInteger() # n = len(list(headCirs[0].BaseEquipment.MEPModel.ElectricalSystems)) # Продираемся до щита и считаем количество его цепей n = 0 # print('------------') # print(el.LookupParameter('Имя щита').AsString()) # for cir in list(headCirs[0].BaseEquipment.MEPModel.ElectricalSystems): # print('{} {}'.format(n, cir.LookupParameter('Номер группы').AsString())) # # if cir.LookupParameter('Тип системы').AsValueString() == 'Данные': continue # n += 1 n = len(headCirs) el.LookupParameter('Ширина рамки').Set((n + res) * 16 / k) minNom = 99999999 minChar = 'D' for x, cir in enumerate(headCirs + range(res)): if type(cir) != type(1): el = doc.Create.NewFamilyInstance( XYZ(x * 16 / k, -y * 250 / k, 0), cirFamily, activeView) el.LookupParameter('Номер группы').Set( cir.LookupParameter('Номер группы').AsString()) el.LookupParameter('Расчетная мощность').Set( round( cir.LookupParameter( 'Суммарная мощность группы').AsDouble() / 10763.9104167097, 2)) el.LookupParameter('Cos φ').Set( round(cir.LookupParameter('Cos φ').AsDouble(), 2)) el.LookupParameter('Ток').Set( round(cir.LookupParameter('Ток').AsDouble(), 2)) el.LookupParameter('Падение группы').Set( round(cir.LookupParameter('Падение группы').AsDouble(), 2)) el.LookupParameter('Длина расчетная').Set( round( cir.LookupParameter('Длина расчетная').AsDouble() / 1000, 0)) nom = round( cir.LookupParameter('Номинал аппарата защиты').AsDouble(), 0) if minNom > nom: minNom = nom char = cir.LookupParameter( 'Характеристика аппарата защиты').AsString() if char == 'C': minChar = 'C' el.LookupParameter('Номинал аппарата защиты').Set(nom) # print 909 # print char el.LookupParameter('Характеристика аппарата защиты').Set(char) el.LookupParameter('Напряжение цепи').Set( round( cir.LookupParameter('Напряжение цепи').AsDouble(), 0)) el.LookupParameter('Имя нагрузки').Set( cir.LookupParameter('Имя нагрузки группы').AsString()) el.LookupParameter('Цепи').Set( cir.LookupParameter('Цепи').AsString() if cir. LookupParameter('Цепи').AsString() else str(cir.Id. IntegerValue)) sech = '{:.1f}'.format( cir.LookupParameter('Сечение кабеля').AsDouble()).replace( '.0', '') n = 3 if cir.LookupParameter( 'Напряжение цепи').AsDouble() == 220 else 5 name = cir.LookupParameter('Кабель').AsString() el.LookupParameter('Кабель').Set('{} {}x{}'.format( name, n, sech.replace('.', ','))) # el.LookupParameter('Номер фазы').Set('666') el.LookupParameter('Номер фазы').Set( cir.LookupParameter('Номер фазы').AsString() if cir. LookupParameter('Номер фазы').AsString() else '?') el.LookupParameter('Помещения группы').Set( cir.LookupParameter('Помещения группы').AsString().replace( '; -', '')) el.LookupParameter(cApps[cir.LookupParameter( 'Ком. аппарат').AsString()]).Set(1) el.LookupParameter('Ком. аппарат подпись').Set( cir.LookupParameter('Ком. аппарат').AsString().replace( 'qf', 'QF')) else: el = doc.Create.NewFamilyInstance( XYZ(x * 16 / k, -y * 250 / k, 0), cirFamily, activeView) el.LookupParameter('Имя нагрузки').Set('Резерв') el.LookupParameter('Характеристика аппарата защиты').Set( minChar) el.LookupParameter('Номинал аппарата защиты').Set(minNom) el.LookupParameter('Номер фазы').Set('L1') el.LookupParameter('Основные').Set(0) el.LookupParameter('Автоматический выключатель').Set(1)
for c in list(panel.MEPModel.ElectricalSystems): if list(c.Elements)[0].Id == panel.Id: headCir = c break if headCir: counter.append(headCir.Id.IntegerValue) find_depth(headCir, counter) else: return t = Transaction(doc, 'name') t.Start() elCirs = FilteredElementCollector(doc)\ .OfCategory(BuiltInCategory.OST_ElectricalCircuit)\ .WhereElementIsNotElementType().ToElements() UnpluggedFakeCirs = list( filter(lambda x: not x.BaseEquipment and 'Щит' in list(x.Elements)[0].Name, elCirs)) elCirs = list(filter(lambda x: x.BaseEquipment, elCirs)) global branches branches = [] for cir in [cir for cir in elCirs if 'Щит' in cir.BaseEquipment.Name]: preBranch = [] find_longer_path(cir, preBranch) pCirs = {} # panelsCircuits for branch in branches:
create_dimension_on_view(elem, 'horizontal', right_view[0]) create_dimension_on_view(elem, 'vertical', right_view[0]) create_dimension_on_view(elem, 'horizontal', section_view[0]) create_dimension_on_view(elem, 'vertical', section_view[0]) create_dimension_on_view(elem, 'horizontal', top_view[0]) create_dimension_on_view(elem, 'vertical', top_view[0]) TransactionManager.Instance.TransactionTaskDone() TransactionManager.Instance.ForceCloseTransaction() fam_doc = doc.EditFamily(family) # Семейство----------------------------------------------------------------------------------- if fam_doc: family_manager = fam_doc.FamilyManager sweep_col = FilteredElementCollector(fam_doc).OfClass(Sweep).ToElements() sweep = [s for s in list(sweep_col) if s.IsSolid][0] empty_sweep = [s for s in list(sweep_col) if not s.IsSolid][0] with Transaction(fam_doc, 'Delete empty form') as trans1: trans1.Start() fam_doc.Delete(empty_sweep.Id) param_ARH_l = family_manager.get_Parameter('ARH_l') if param_ARH_l: family_manager.Set(param_ARH_l, UnitUtils.ConvertToInternalUnits(1000, param_ARH_l.DisplayUnitType)) square = get_square_from_solid(sweep)[0] vol1 = get_square_from_solid(sweep)[1] vol2 = get_volume_from_bBox(sweep) export_to_stl(r'{3D}', fam_doc.Title, fam_doc) trans1.RollBack()
import clr clr.AddReference("RevitAPI") from Autodesk.Revit.DB import FilteredElementCollector, RevitLinkInstance, BuiltInCategory, \ Outline, BoundingBoxIntersectsFilter, BuiltInParameter, UnitUtils, DisplayUnitType clr.AddReference("RevitServices") from RevitServices.Persistence import DocumentManager from RevitServices.Transactions import TransactionManager doc = DocumentManager.Instance.CurrentDBDocument rvtlinks = FilteredElementCollector(doc).OfClass(RevitLinkInstance).ToElements() linkdoc = [] for r in rvtlinks: linkdoc.append(r.GetLinkDocument()) lnkdoc = linkdoc[0] transform = rvtlinks[0].GetTotalTransform() rooms = FilteredElementCollector(lnkdoc).OfCategory(BuiltInCategory.OST_Rooms).ToElements() fam_col = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Furniture). \ WhereElementIsNotElementType().ToElements() mlist = [] for room in rooms: llist = [] room_box = room.get_BoundingBox(None) boxMin = transform.OfPoint(room_box.Min) boxMax = transform.OfPoint(room_box.Max) outline = Outline(boxMin, boxMax) bbfilter = BoundingBoxIntersectsFilter(outline)
def select_template_id(name): col = FilteredElementCollector(doc).OfClass(View).ToElements() for tp in col: if tp.IsTemplate: if tp.Name == name: return tp.Id
ele = CreateRoundStrut(name, diameter, position, height, 0) if ele: v1 = doc.GetElement(ele).LookupParameter("Mark").Set(str(name)) try: v2 = doc.GetElement(ele).LookupParameter("Comments").Set(str(struDescription)) except: print("Description cannot be found") else: print("Creation Error") # Error Message else: print(name + " not built") basePoint = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_ProjectBasePoint).ToElements()[0] basePoint.get_Parameter(BuiltInParameter.BASEPOINT_NORTHSOUTH_PARAM).Set(yAdjust*-1) basePoint.get_Parameter(BuiltInParameter.BASEPOINT_EASTWEST_PARAM).Set(xAdjust*-1) basePoint.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM).Set(zAdjust*-1) ''' surveyPoint = FilteredElementCollector(doc).OfClass(BasePoint).ToElements()[1] surveyPoint.get_Parameter(BuiltInParameter.BASEPOINT_NORTHSOUTH_PARAM).Set(ySurveyAdjust*-1) surveyPoint.get_Parameter(BuiltInParameter.BASEPOINT_EASTWEST_PARAM).Set(xSurveyAdjust*-1) surveyPoint.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM).Set(zSurveyAdjust*-1) ''' projectLocation = uidoc.Document.ActiveProjectLocation projectPosition = projectLocation.GetProjectPosition(XYZ(0, 0, 0)) projectPosition.NorthSouth = ySurveyAdjust*-1 projectPosition.EastWest = xSurveyAdjust*-1 projectPosition.Elevation = zSurveyAdjust*-1
def get_title_block(name): col = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_TitleBlocks).WhereElementIsElementType() for f in col: if f.Family.Name == name: return f.Id
__window__.Close() from Autodesk.Revit.DB import FilteredElementCollector, FamilyInstanceFilter, ElementId from System.Collections.Generic import List uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document curview = uidoc.ActiveGraphicalView matchlist = [] for elId in uidoc.Selection.GetElementIds(): try: el = doc.GetElement(elId) family = el.Symbol.Family symbolIdSet = family.GetFamilySymbolIds() for symid in symbolIdSet: cl = FilteredElementCollector(doc).WherePasses( FamilyInstanceFilter(doc, symid)).ToElements() for el in cl: matchlist.append(el.Id) except: continue selSet = [] for elid in matchlist: selSet.append(elid) uidoc.Selection.SetElementIds(List[ElementId](selSet)) uidoc.RefreshActiveView()
def all_elements_of_category(category): return FilteredElementCollector(doc).OfCategory( category).WhereElementIsNotElementType().ToElements()
def walls(doc): families = FilteredElementCollector(doc).OfClass(WallType) for fam in families: print '{}\t{}'.format( fam.get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_NAME).AsString(), fam.Width * MM)
nameDrawer = formDrawer.value # Call the CreateWindow class and create the input for Checker formChecker = CreateWindow("Change Parameter Checked By", "Checked by") Application.Run(formChecker) # Assign the input to variable nameChecker = formChecker.value # Store current document to variable app = __revit__.Application doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument # Collects all sheets in current document sheetsCollector = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets) \ .ToElements() # Create a Transaction group to group all subsequent transactions tg = TransactionGroup(doc, "Update Drawn By and Checked By") # Start the group transaction tg.Start() # Create a individual transaction to change the parameters on sheet t = Transaction(doc, "Change Sheets Name") # Start individual transaction t.Start() # Variable to store modified sheets modSheets = list()
def FamilyNameChange(doc): namesLst = [] ids = [] family = FilteredElementCollector(doc).OfClass(FamilySymbol).ToElements() for i in family: namesLst.append(i.Family.Name) exempt = [ 'Profiles', 'Section Marks', 'Curtain Panels', 'Section Marks', 'Generic Annotations', 'Callout Heads', 'Level Heads', 'View Titles' ] familyRegex = re.compile(r'\S+.*\s?-\s?\S+.*\s?-\s?\S+.*?') for i in family: if not i.Family.FamilyCategory.Name in exempt and not 'Tag' in i.Family.FamilyCategory.Name and not i.Id.IntegerValue in ids: cate = i.Family.FamilyCategory.Name familyName = i.Family.Name if familyName[0:3] == 'SCA': pass elif familyRegex.findall(familyName) == [] and familyName[0:3] != 'SCA' and \ len(re.split('-', familyName)) <=1 and familyName[0:len(cate)] != cate: proposedName = UniqueName( cate + '_Regular_Generic_' + familyName, namesLst) try: i.Family.Name = proposedName except: pass namesLst.append(proposedName) ids.append(i.Id.IntegerValue.ToString()) print('Changed 1 ' + familyName + ' to ' + proposedName) ''' elif len(re.split(' ', familyName)) >= 2: proposedName = UniqueName(cate + '_' + re.split(' ', familyName)[0] + '_Generic_' + familyName, namesLst) try: i.Family.Name = proposedName except: pass namesLst.append(proposedName) ids.append(i.Id.IntegerValue.ToString()) print('Changed 1.5 ' + familyName + ' to ' + proposedName) ''' elif familyRegex.findall( familyName) == [] and familyName[0:2] != 'PA' and len( re.split('-', familyName)) == 2: proposedName = UniqueName( cate + '_' + re.split('-', familyName)[0] + '_Generic_' + familyName.replace( '-', '_')[len(re.split('-', familyName)[0]):], namesLst) try: i.Family.Name = proposedName except: pass namesLst.append(proposedName) ids.append(i.Id.IntegerValue.ToString()) print('Changed 2 ' + familyName + ' to ' + proposedName) elif familyRegex.findall(familyName) != [] and familyName[0:len(cate)] != cate and familyName[0:len(cate)-1] != cate[0: len(cate) -1]\ and familyName[0:3] != 'SCA': proposedName = UniqueName( cate + '_' + re.split('-', familyName)[0] + '_' + 'Generic_' + familyName.replace( '-', '_')[len(re.split('-', familyName)[0]):], namesLst) try: i.Family.Name = proposedName except: pass namesLst.append(proposedName) ids.append(i.Id.IntegerValue.ToString()) print('Changed 3 ' + familyName + ' to ' + proposedName)
from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, Transaction, TransactionGroup, BuiltInParameter, ElementId, XYZ, Structure doc = __revit__.ActiveUIDocument.Document uidoc = __revit__.ActiveUIDocument from pyrevit import script output = script.get_output() k = 304.8 k1 = 35.31466672149 k2 = 1000000 / k**2 # 10.763910416709722 t = Transaction(doc, 'КР') t.Start() els = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFraming).WhereElementIsNotElementType().ToElements() for el in els: dimL = el.LookupParameter('Фактическая длина').AsDouble() * k dimB = el.LookupParameter('ADSK_Размер_Высота').AsDouble() * k dimH = el.LookupParameter('ADSK_Размер_Ширина').AsDouble() * k name = '{:.0f}×{:.0f}'.format(min([dimB, dimH]), max([dimB, dimH])) mark = name is_plita = el.LookupParameter('Семейство').AsValueString() == 'Плита' if is_plita: dimL = doc.GetElement(el.GetTypeId()).LookupParameter('h').AsDouble() * k dimB = el.LookupParameter('Ширина').AsDouble() * k dimH = el.LookupParameter('Фактическая длина').AsDouble() * k # name = ' {:.0f}×{:.0f}'.format(max([dimB, dimH]), min([dimB, dimH])) name = '{:.0f} мм'.format(dimL) mark = '{:.0f}×{:.0f}'.format(max([dimB, dimH]), min([dimB, dimH])) el.LookupParameter('ADSK_Размер_Длина').Set(dimL / k)
This file is part of pyRevit repository at https://github.com/eirannejad/pyRevit pyRevit is a free set of scripts for Autodesk Revit: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. This program 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. See this link for a copy of the GNU General Public License protecting this package. https://github.com/eirannejad/pyRevit/blob/master/LICENSE """ __doc__ = 'Sets the revision visibility parameter to None for all revisions.' __window__.Close() from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, Transaction, RevisionVisibility doc = __revit__.ActiveUIDocument.Document revs = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_Revisions).WhereElementIsNotElementType() with Transaction(doc, 'Turn off Revisions') as t: t.Start() for rev in revs: rev.Visibility = RevisionVisibility.Hidden t.Commit()