class ActionGroup(): def __init__(self, name=None, assimilate=True): self._rvt_transaction_group = TransactionGroup( self.doc, name if name else DEFAULT_TRANSACTION_NAME) self.assimilate = assimilate def __enter__(self): self._rvt_transaction_group.Start() return self def __exit__(self, exception, exception_value, traceback): if exception: self._rvt_transaction_group.RollBack() logger.error('Error in TransactionGroup Context: has rolled back.') logger.error('{}:{}'.format(exception, exception_value)) else: try: if self.assimilate: self._rvt_transaction_group.Assimilate() else: self._rvt_transaction_group.Commit() except Exception as errmsg: self._rvt_transaction_group.RollBack() logger.error( 'Error in TransactionGroup Commit: has rolled back.') logger.error('Error: {}'.format(errmsg)) @property def name(self): return self._rvt_transaction_group.GetName() @name.setter def name(self, new_name): return self._rvt_transaction_group.SetName(new_name) @property def status(self): return ActionStatus.from_rvt_trans_stat( self._rvt_transaction_group.GetStatus()) def has_started(self): return self._rvt_transaction_group.HasStarted() def has_ended(self): return self._rvt_transaction_group.HasEnded()
def main(): pipes = FilteredElementCollector(doc)\ .OfCategory(BuiltInCategory.OST_PipeCurves)\ .WhereElementIsNotElementType().ToElements() pipes = [ pipe for pipe in pipes if '{}'.format(pipe.LookupParameter('Длина').AsDouble() * k) != pipe.LookupParameter('Длина старая').AsString() ] tg = TransactionGroup(doc, "Длина петли") tg.Start() t = Transaction(doc, "blabla") t.Start() [ pipe.LookupParameter('Длина старая').Set('{}'.format( pipe.LookupParameter('Длина').AsDouble() * k)) for pipe in pipes ] global handledElems handledElems = [] global tabs global OUT siblingGroups = [] for pipe in pipes: siblings = [] if pipe.Id.ToString() not in handledElems: handledElems.append(pipe.Id.ToString()) tabs = 1 siblings = getSiblings(pipe) siblingGroups.append(siblings) for group in siblingGroups: s = sum([ e.LookupParameter('Длина').AsDouble() * k for e in group if e.LookupParameter('Длина') ]) for el in group: el.LookupParameter('Длина петли').Set('{:.0f}'.format( s / 1000).replace('.', ',')) t.Commit() tg.Assimilate()
def create_floors(self): """Function to loop through selected rooms and create floors from them.""" # >>>>>>>>>> LOOP THROUGH ROOMS with TransactionGroup(doc, __title__) as tg: tg.Start() for r in self.selected_rooms: room = RoomToFloor(room=r, floor_type=self.selected_floor_type, active_view_level=active_view_level) tg.Assimilate()
class ActionGroup: def __init__(self, name=None, assimilate=True): self.transaction_group = TransactionGroup(doc, name if name else DEFAULT_TRANSACTION_NAME) self.assimilate = assimilate def __enter__(self): self.transaction_group.Start() return self.transaction_group def __exit__(self, exception, exception_value, traceback): if exception: self.transaction_group.RollBack() logger.error('Error in TransactionGroup Context: has rolled back.') logger.error('{}:{}'.format(exception, exception_value)) else: try: if self.assimilate: self.transaction_group.Assimilate() else: self.transaction_group.Commit() except Exception as errmsg: self.transaction_group.RollBack() logger.error('Error in TransactionGroup Commit: has rolled back.') logger.error('Error: {}'.format(errmsg))
def create_spaces_by_rooms(self, rooms): # Initiate the transacton group with TransactionGroup(self.doc, "Batch create spaces/Transfer parameters") as tg: tg.Start() Room_UniqueIds = [ room.UniqueId for room in rooms if room.Area > 0 and room.Location != None ] self.counter += 1 self.ReportProgress.emit(self.counter) # Define if there're spaces in a model if self._space_collector.GetElementCount() == 0: # If there are no spaces # Create a space for room in rooms: if room.Area > 0 and room.UniqueId not in self.New_MEPSpaces: self.space_creator(room, self.lvls_dict) self.counter += 1 self.ReportProgress.emit(self.counter) # If there are spaces in the model else: self.space_check(Room_UniqueIds) # For each room in RVT link rooms take room UniqueId and check if there's space with the same Id among the existing MEP spaces for room in rooms: # If there's such space get it if room.UniqueId in self.Exist_MEPSpaces: exst_space = self.Exist_MEPSpaces[room.UniqueId] self.space_updater(room, exst_space) self.counter += 1 self.ReportProgress.emit(self.counter) # If there's no such space else: # Create a space if room.Area > 0 and room.UniqueId not in self.New_MEPSpaces: self.space_creator(room, self.lvls_dict) self.counter += 1 self.ReportProgress.emit(self.counter) tg.Assimilate()
def create_sheets(self, sender, args): self.Close() if self._process_sheet_code(): if self.sheet_cb.IsChecked: create_func = self._create_sheet transaction_msg = 'Batch Create Sheets' if not self._ask_for_titleblock(): this_script.exit() else: create_func = self._create_placeholder transaction_msg = 'Batch Create Placeholders' with TransactionGroup(doc, transaction_msg) as tg: tg.Start() for sheet_num, sheet_name in self._sheet_dict.items(): logger.debug('Creating Sheet: {}:{}'.format( sheet_num, sheet_name)) create_func(sheet_num, sheet_name) tg.Assimilate()
datafile = usertemp + '\\' + prjname + '_pySaveViewportLocation.pym' selected_ids = uidoc.Selection.GetElementIds() if selected_ids.Count == 1: vport_id = selected_ids[0] try: vport = doc.GetElement(vport_id) except: TaskDialog.Show('pyrevit', 'Select at least one viewport. No more, no less!') if isinstance(vport, Viewport): view = doc.GetElement(vport.ViewId) if view is not None and isinstance(view, ViewPlan): with TransactionGroup(doc, 'Paste Viewport Location') as tg: tg.Start() set_tansform_matrix(vport, view) try: with open(datafile, 'rb') as fp: originalviewtype = pickle.load(fp) if originalviewtype == 'ViewPlan': savedcen_pt = pickle.load(fp) savedmdl_pt = pickle.load(fp) else: raise OriginalIsViewDrafting except IOError: TaskDialog.Show( 'pyrevit', 'Could not find saved viewport placement.\nCopy a Viewport Placement first.' )
def set_tansform_matrix(selvp, selview): # making sure the cropbox is active. cboxactive = selview.CropBoxActive cboxvisible = selview.CropBoxVisible cboxannoparam = selview.get_Parameter( BuiltInParameter.VIEWER_ANNOTATION_CROP_ACTIVE) cboxannostate = cboxannoparam.AsInteger() curviewelements = FilteredElementCollector(doc).OwnedByView( selview.Id).WhereElementIsNotElementType().ToElements() viewspecificelements = [] for el in curviewelements: if el.ViewSpecific \ and (not el.IsHidden(selview)) \ and el.CanBeHidden \ and el.Category != None: viewspecificelements.append(el.Id) with TransactionGroup(doc, 'Activate and Read Cropbox Boundary') as tg: tg.Start() with Transaction(doc, 'Hiding all 2d elements') as t: t.Start() if viewspecificelements: for elid in viewspecificelements: try: selview.HideElements(List[ElementId](elid)) except: pass t.Commit() with Transaction(doc, 'Activate and Read Cropbox Boundary') as t: t.Start() selview.CropBoxActive = True selview.CropBoxVisible = False cboxannoparam.Set(0) # get view min max points in modelUCS. modelucsx = [] modelucsy = [] crsm = selview.GetCropRegionShapeManager() cllist = crsm.GetCropShape() if len(cllist) == 1: cl = cllist[0] for l in cl: modelucsx.append(l.GetEndPoint(0).X) modelucsy.append(l.GetEndPoint(0).Y) cropmin = XYZ(min(modelucsx), min(modelucsy), 0.0) cropmax = XYZ(max(modelucsx), max(modelucsy), 0.0) # get vp min max points in sheetUCS ol = selvp.GetBoxOutline() vptempmin = ol.MinimumPoint vpmin = XYZ(vptempmin.X + vpboundaryoffset, vptempmin.Y + vpboundaryoffset, 0.0) vptempmax = ol.MaximumPoint vpmax = XYZ(vptempmax.X - vpboundaryoffset, vptempmax.Y - vpboundaryoffset, 0.0) transmatrix.sourcemin = vpmin transmatrix.sourcemax = vpmax transmatrix.destmin = cropmin transmatrix.destmax = cropmax revtransmatrix.sourcemin = cropmin revtransmatrix.sourcemax = cropmax revtransmatrix.destmin = vpmin revtransmatrix.destmax = vpmax selview.CropBoxActive = cboxactive selview.CropBoxVisible = cboxvisible cboxannoparam.Set(cboxannostate) if viewspecificelements: selview.UnhideElements( List[ElementId](viewspecificelements)) t.Commit() tg.Assimilate()
return len(copied_element) except Exception as err: logger.error( 'Error occured while copying elements from {} | {}'.format( src_view.ViewName, err)) return 0 else: print('No copyable elements where found.') drafting_views = process_selection() dest_view_type = get_modelview_type() successfully_converted = 0 # iterate over drafting views with TransactionGroup(doc, 'Convert View Types') as tg: tg.Start() tg.IsFailureHandlingForcedModal = False view_count = 1 total_view_count = len(drafting_views) for src_view in drafting_views: this_script.output.print_md('-----\n**{} of {}**'.format( view_count, total_view_count)) this_script.output.print_md('**Converting: {}**'.format( src_view.ViewName)) dest_view_successfully_setup = False try: dest_view = create_dest_view(dest_view_type, src_view.ViewName, src_view.Scale) print('View created: {}'.format(dest_view.ViewName))
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 all the elements that are tied to the selected element. For example elements tags or dimensions.' from Autodesk.Revit.DB import Transaction, TransactionGroup uidoc = __revit__.ActiveUIDocument doc = __revit__.ActiveUIDocument.Document selection = __revit__.ActiveUIDocument.Selection.GetElementIds() tg = TransactionGroup(doc, "Search for linked elements") tg.Start() t = Transaction(doc, "Search for linked elements") t.Start() linkedelementslist = [] for elId in selection: print("Searching for all objects tied to ELEMENT ID: {0}...".format(elId)) linkedelementslist = doc.Delete(elId) t.Commit() tg.RollBack() for elId in linkedelementslist: el = doc.GetElement(elId)
viewsheet = forms.select_sheets(button_name='Select Sheet Set') selected_viewtemplates = forms.select_viewtemplates(doc=revit.doc) temp=selected_viewtemplates[0].Id save_tem = [] views = [] count=0 print("View from sheets:") for sheet in viewsheet: print (sheet.Title) print("------------------------------------------------------------------------------") print("Changing view template to: " + str(selected_viewtemplates[0].Name)) tg = TransactionGroup(doc, "Update Template") tg.Start() t=Transaction(doc,"Change Template") t.Start() for vs in viewsheet: for eid in vs.GetAllPlacedViews(): ev=doc.GetElement(eid) if str(ev.ViewType) != "Legend" and str(ev.ViewType) != "DraftingView": tam=ev.ViewTemplateId if str(tam) != ("-1"): ev.ViewTemplateId = temp views.append(ev) save_tem.append(tam) count+=1 else:
See this link for a copy of the GNU General Public License protecting this package. https://github.com/eirannejad/pyRevit/blob/master/LICENSE ''' __doc__ = 'Flips the selected walls along their core axis and changes their location lines to Core Face Exterior.' __window__.Close() from Autodesk.Revit.DB import TransactionGroup, Transaction, Wall doc = __revit__.ActiveUIDocument.Document selection = [ doc.GetElement(elId) for elId in __revit__.ActiveUIDocument.Selection.GetElementIds() ] tg = TransactionGroup(doc, "Search for linked elements") tg.Start() locLineValues = { 'Wall Centerline': 0, 'Core Centerline': 1, 'Finish Face: Exterior': 2, 'Finish Face: Interior': 3, 'Core Face: Exterior': 4, 'Core Face: Interior': 5, } for el in selection: if isinstance(el, Wall): param = el.LookupParameter('Location Line') with Transaction(doc, 'Change Wall Location Line') as t:
datafile = usertemp + '\\' + prjname + '_pySaveViewportLocation.pym' selected_ids = uidoc.Selection.GetElementIds() if selected_ids.Count == 1: vport_id = selected_ids[0] try: vport = doc.GetElement(vport_id) except: TaskDialog.Show('pyRevit', 'Select at least one viewport. No more, no less!') if isinstance(vport, Viewport): view = doc.GetElement(vport.ViewId) if view is not None and isinstance(view, ViewPlan): with TransactionGroup(doc, 'Copy Viewport Location') as tg: tg.Start() set_tansform_matrix(vport, view) center = vport.GetBoxCenter() modelpoint = sheet_to_view_transform(center) center_pt = Point(center.X, center.Y, center.Z) model_pt = Point(modelpoint.X, modelpoint.Y, modelpoint.Z) with open(datafile, 'wb') as fp: originalviewtype = 'ViewPlan' pickle.dump(originalviewtype, fp) pickle.dump(center_pt, fp) pickle.dump(model_pt, fp) tg.Assimilate() elif view is not None and isinstance(view, ViewDrafting): center = vport.GetBoxCenter() center_pt = Point(center.X, center.Y, center.Z)
return len(copied_element) except Exception as err: logger.error( 'Error occured while copying elements from {} | {}'.format( src_view.ViewName, err)) return 0 else: print('No copyable elements where found.') drafting_views = process_selection() dest_view_type = get_modelview_type() successfully_converted = 0 # iterate over drafting views with TransactionGroup(doc, 'Convert Drafting to Model') as tg: tg.Start() tg.IsFailureHandlingForcedModal = False view_count = 1 total_view_count = len(drafting_views) for src_view in drafting_views: this_script.output.print_md( '-----\n**{} of {}**\n**Converting: {}**'.format( view_count, total_view_count, src_view.ViewName)) dest_view_successfully_setup = False try: dest_view = create_dest_view(dest_view_type, src_view.ViewName, src_view.Scale) print('View created: {}'.format(dest_view.ViewName)) dest_view_successfully_setup = True
__doc__ = 'Moves all Filled Regions on the seleced views back-and-forth by a tiny amount to push Revit ' \ 'to regenerate the filled region and update the display. This tool is meant to be used in ' \ 'conjunction with the "Swap Line Styles" tool. The swap tool updates the line styles inside ' \ 'Filled region but does not currently shake the filled regions (Revit crashes on large models.)' def shake_filled_regions(view): vcl = FilteredElementCollector(doc).OwnedByView(view.Id) fregions = vcl.OfClass(clr.GetClrType(FilledRegion)).WhereElementIsNotElementType().ToElements() print('Shaking Filled Regions in: {}'.format(view.ViewName)) for i, fr in enumerate(fregions): with Transaction(doc, 'Shake FilledRegion #{}'.format(i)) as t: t.Start() fr.Location.Move(XYZ(0.01, 0, 0)) fr.Location.Move(XYZ(-0.01, 0, 0)) t.Commit() print('Shaking Filled Regions in {} views'.format(selection.count)) with TransactionGroup(doc, 'Shake Filled Regions') as t: t.Start() for i, view in enumerate(selection.elements): shake_filled_regions(view) this_script.output.update_progress(i+1, selection.count) t.Assimilate() print('All Filled Regions where shaken...')
__title__ = 'First\nTransactions' __author__ = 'Ehsan Iran-Nejad' from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, Transaction, TransactionGroup doc = __revit__.ActiveUIDocument.Document sheets_collector = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Sheets) \ .WhereElementIsNotElementType() \ .ToElements() wall_id_collector = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Walls) \ .WhereElementIsNotElementType() \ .ToElementIds() tg = TransactionGroup(doc, "Update and Delete") tg.Start() t = Transaction(doc, "Update Sheet Parmeters") t.Start() for sheet in sheets_collector: custom_param = sheet.LookupParameter('Comments') if custom_param: custom_param.Set("Example value") t.Commit() t = Transaction(doc, "Deleting All Walls") t.Start()
# GET SELECTED MAIN SHEET selected_sheet_name = None items = self.test_ListBox.Items for item in items: if item.IsChecked: selected_sheet_name = item.Name break # VARIABLES MAIN/OTHER SHEETS self.main_sheet = self.selected_sheets.pop(selected_sheet_name) self.other_sheets = self.selected_sheets.values() # ALIGN VIEWPORTS self.align_other_sheets() # ==================================================================================================== # ╔╦╗╔═╗╦╔╗╔ # ║║║╠═╣║║║║ # ╩ ╩╩ ╩╩╝╚╝ MAIN # ==================================================================================================== if __name__ == '__main__': tg = TransactionGroup(doc, __title__) tg.Start() x = AlignViewports() tg.Assimilate() if x.selected_sheets: print('_' * 120) print('Align Viewports is finished.')
BuiltInCategory.OST_ElectricalCircuit).WhereElementIsNotElementType().ToElements() set_progress(pb, 10) class Cir(): objects = [] def __init__(self, origin): self.__class__.objects.append(self) self.origin = origin self.id = origin.Id self.panel = origin.BaseEquipment self.els = list(origin.Elements) tg = TransactionGroup(doc, 'Расчет MVS 2') tg.Start() t = Transaction(doc, 'Part 1') t.Start() for cir in cirs: cir = Cir(cir) cir.origin.LookupParameter('Имя нагрузки').Set(cir.els[0].LookupParameter('Тип').AsValueString().replace(' значок выкл', '').split('((')[0]) # Используется имя только первого элемента цепи! Могут быть проблемы при разнородных шлейфах cir.origin.LookupParameter('Помещение').Set(cir.els[0].LookupParameter('Помещение').AsString() or '') # –//– cir.origin.LookupParameter('Помещение панели').Set(cir.panel.LookupParameter('Помещение').AsString() or '') if cir.origin.LookupParameter('Помещение панели') else None cir.origin.LookupParameter('Помещение цепи').Set(cir.els[0].LookupParameter('Помещение').AsString().replace('Стойка ', '') or '') if cir.origin.LookupParameter('Помещение цепи') else None cir.panel.LookupParameter('Имя панели').Set(cir.panel.LookupParameter('Тип').AsValueString().split('((')[0]) cir.origin.LookupParameter('Комментарии').Set('Панель "' + cir.panel.LookupParameter('Тип').AsValueString() + '", id цепи ' + str(cir.id)) if cir.origin.LookupParameter('Позиция начала'): param = cir.els[0].LookupParameter('ADSK_Обозначение') designation = param.AsString() if param and param.AsString() else ''
# Collect all elements that are somehow linked to the viewport types to be purged -------------------------------------- TaskDialog.Show('pyRevit', 'Starting Conversion. Hit Cancel if you get any prompts.') purge_dict = {} for purge_vp_type in purge_vp_types: logger.info('Finding all viewports of type: {}'.format(purge_vp_type.name)) logger.debug('Purging: {}'.format(repr(purge_vp_type))) linked_elements = purge_vp_type.find_linked_elements() logger.debug('{} elements are linked to this viewport type.'.format( len(linked_elements))) purge_dict[purge_vp_type.name] = linked_elements # Perform cleanup ------------------------------------------------------------------------------------------------------ tg = TransactionGroup(doc, 'Fixed Unpurgable Viewport Types') tg.Start() # TRANSACTION 1 # Correct all existing viewports that use the viewport types to be purged # Collect viewports and find the ones that use the purging viewport types all_viewports = Fec(doc).OfClass(clr.GetClrType(Viewport)).ToElements() purge_vp_ids = [x.get_rvt_obj().Id for x in purge_vp_types] t1 = Transaction(doc, 'Correct Viewport Types') t1.Start() for vp in all_viewports: if vp.GetTypeId() in purge_vp_ids: try: # change their type to the destination type logger.debug( 'Changing viewport type for viewport with id: {}'.format(
def __init__(self, name=None, assimilate=True): self._rvt_transaction_group = TransactionGroup( self.doc, name if name else DEFAULT_TRANSACTION_NAME) self.assimilate = assimilate
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() # Define function to modify parameter def modParameter(param, checkEmpty, inputParam):