Skip to content

Instantly share code, notes, and snippets.

@giobel
Last active January 18, 2024 20:44
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save giobel/b5ffcb2e04e31d68ad7687ed4fa48f8c to your computer and use it in GitHub Desktop.
Save giobel/b5ffcb2e04e31d68ad7687ed4fa48f8c to your computer and use it in GitHub Desktop.
Dynamo-Python
# collection of Dynamo Python functions.
# credits: archi-lab, MEPover, Bimorph, Clockwork, Rhythm and many more
for i in range(0, len(openings)):
subList = []
conElementsIds.append(subList)
for e in openings[i]:
bb = e.Element.get_BoundingBox(doc.ActiveView)
e.HostedBeamDepth
if e.BeamDirection == "dirX":
newMin = XYZ(bb.Min.X - (e.HostedBeamDepth)/304.8, bb.Min.Y, bb.Min.Z)
newMax = XYZ(bb.Max.X + (e.HostedBeamDepth)/304.8, bb.Max.Y, bb.Max.Z)
else:
newMin = XYZ(bb.Min.X, bb.Min.Y - (e.HostedBeamDepth)/304.8, bb.Min.Z)
newMax = XYZ(bb.Max.X, bb.Max.Y + (e.HostedBeamDepth)/304.8, bb.Max.Z)
outline = Outline( newMin,newMax );
oldline = [bb.Min.ToPoint(), bb.Max.ToPoint()]
bbfilter = BoundingBoxIntersectsFilter( outline );
# Use a view to construct the filter so we get only visible elements. For example, the analytical model will be found otherwise.
collector = FilteredElementCollector(doc, doc.ActiveView.Id).OfCategory(BuiltInCategory.OST_StructuralFraming)
# Lets also exclude the view itself (which often will have an intersecting bounding box), and also the element selected.
idsExclude = List[ElementId]();
idsExclude.Add( e.BeamElement.Id );
idsExclude.Add( e.Element.Id );
# Get the set of elements that pass the
# criteria. Note both filters are quick,
# so order is not so important.
connected = collector.Excluding( idsExclude ).WherePasses( bbfilter );
conElements.append(connected)
newBoundingBox.append([newMin.ToPoint(), newMax.ToPoint()])
for c in connected:
subList.append(e.Element)
subList.append(doc.GetElement(e.BeamElement.Id))
subList.append(doc.GetElement(c.Id))
def Position(duct):
if duct.Shape == "Rectangle":
hCheck = "Pass" if duct.Height < duct.HostedBeamDepth/2 else "Failed"
topFlange = "Pass" if round(duct.ZTop - duct.Centroid[2] - duct.Height/2,0) > (duct.HostedBeamDepth/4) else "Failed"
topFlangeValue = round(duct.ZTop - duct.Centroid[2] - duct.Height/2,0)
botFlange = "Pass" if round(duct.HostedBeamDepth - duct.Height - topFlangeValue,0) > (duct.HostedBeamDepth/4) else "Failed"
botFlangeValue = round(duct.HostedBeamDepth - duct.Height - topFlangeValue, 0)
stDist0 = "Pass" if duct.Distance0 - duct.Width/2 > (2*duct.HostedBeamDepth + 100) else "Failed"
stDist0Value = duct.Distance0 - duct.Width/2
stDist1 = "Pass" if duct.Distance1 - duct.Width/2 > (2*duct.HostedBeamDepth + 100) else "Failed"
stDist1Value = duct.Distance1 - duct.Width/2
return ["Opening Height: " + hCheck + ": " + str(duct.Height), "Distance from Top Flange: " + topFlange + ": " + str(topFlangeValue), "Distance from Bottom Flange: " + botFlange + ": " + str(botFlangeValue), "Distance from Start Point: " + stDist0 + ": " + str(stDist0Value), "Distance from End Point: " + stDist1 + ": " + str(stDist1Value), duct.Element]
else:
hCheck = "Pass" if duct.Width < duct.HostedBeamDepth/2 else "Failed"
topFlange = "Pass" if round(duct.ZTop - duct.Centroid[2] - duct.Width/2,0) > (duct.HostedBeamDepth/4) else "Failed"
topFlangeValue = round(duct.ZTop - duct.Centroid[2] - duct.Width/2,0)
botFlange = "Pass" if round(duct.HostedBeamDepth - duct.Width - topFlangeValue,0) > (duct.HostedBeamDepth/4) else "Failed"
botFlangeValue = round(duct.HostedBeamDepth - duct.Width - topFlangeValue, 0)
stDist0 = "Pass" if duct.Distance0 - duct.Width/2 > (2*duct.HostedBeamDepth + 100) else "Failed"
stDist0Value = duct.Distance0 - duct.Width/2
stDist1 = "Pass" if duct.Distance1 - duct.Width/2 > (2*duct.HostedBeamDepth + 100) else "Failed"
stDist1Value = duct.Distance1 - duct.Width/2
return ["Opening Height: " + hCheck + ": " + str(duct.Width), "Distance from Top Flange: " + topFlange + ": " + str(topFlangeValue), "Distance from Bottom Flange: " + botFlange + ": " + str(botFlangeValue), "Distance from Start Point: " + stDist0 + ": " + str(stDist0Value), "Distance from End Point: " + stDist1 + ": " + str(stDist1Value), duct.Element]
def CheckSpace(duct0, duct1):
allow = max(2*duct0.Width,2*duct1.Width)
distance = math.pow((math.pow((duct0.Centroid[0]-duct1.Centroid[0]),2) + math.pow((duct0.Centroid[1]-duct1.Centroid[1]),2)),0.5)-duct0.Width/2-duct1.Width/2
bool = distance > allow
return ["Required distance: " + str(round(allow,0)), "Actual distance: " + str(round(distance,0)), "Actual>Required? " + str(bool), duct0.Element]
import clr
#The inputs to this node will be stored as a list in the IN variables.
class GridPoint():
def __init__(self):
self.Point = None
self.Name = None
self.vGrid = None
self.hGrid = None
pass
gridObjects= []
for vGrid in IN[1]:
for hGrid in IN[2]:
instance = GridPoint()
instance.Name = vGrid+hGrid
instance.vGrid = vGrid
instance.hGrid = hGrid
gridObjects.append(instance)
for g,p in zip(gridObjects, IN[0]):
g.Point = p
#Assign your output to the OUT variable.
OUT = gridObjects
import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.UI import *
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import Form, Button, Label, TextBox
doc = __revit__.ActiveUIDocument.Document
def createView ( sender, event): # creates drafting view
viewTypes = list(FilteredElementCollector(doc).OfClass(ViewFamilyType))
for vt in viewTypes:
if str(vt.ViewFamily) == 'Drafting':
viewType = vt
break
t = Transaction (doc, 'Make new Drafting view')
t.Start()
newDraftingView = ViewDrafting.Create(doc, viewType.Id)
newDraftingView.Name = textBox.Text
t.Commit()
status.Text = 'Drafting View created!'
# create Windows form
form = Form()
form.Width = 300
form.Height = 145
# Title text
label = Label()
label.Text = "New Drafting View name"
label.Width = 280
label.Parent = form
# User input
textBox = TextBox()
textBox.Text = "Enter View Name here"
textBox.Width = 280
textBox.Top += 25
textBox.Parent = form
# Button to action
button = Button()
button.Text = "Create View"
button.Click += createView
button.Width = 280
button.Top += 50
button.Parent = form
# Title text
status = Label()
status.Text = ""
status.Width = 280
status.Top += 75
status.Parent = form
form.ShowDialog()
#https://forum.dynamobim.com/t/force-run-python/31709/2
import clr
import datetime
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
clr.AddReference('DynamoRevitDS')
import Dynamo
#access to the current Dynamo instance and workspace
dynamoRevit = Dynamo.Applications.DynamoRevit()
currentWorkspace = dynamoRevit.RevitDynamoModel.CurrentWorkspace
#custom definition to mark the node as changed
def nodesAdded(obj):
for i in currentWorkspace.Nodes:
if i.NickName.StartsWith("*Force"):
i.MarkNodeAsModified(True)
#the handlers for a node being added or removed
currentWorkspace.NodeAdded += nodesAdded
currentWorkspace.NodeRemoved += nodesAdded
#usind the current time for the output as an example
OUT = datetime.datetime.now()
area = UnwrapElement(IN[0])
F=IN[1] #Load value
loadtype=UnwrapElement(IN[2])
opt = SpatialElementBoundaryOptions()
opt.StoreFreeBoundaryFaces = False
opt.SpatialElementBoundaryLocation.Center
listLoad = []
TransactionManager.Instance.EnsureInTransaction(doc)
for i in range(0,len(area)):
profileLoops = []
segs = area[i].GetBoundarySegments(opt)
for i in range(0,len(segs)):
pL = CurveLoop()
profileLoops.Add(pL)
for j in range(0,len(segs[i])):
pL.Append(segs[i][j].GetCurve())
listLoad.append(AreaLoad.Create(doc,profileLoops,F.ToXyz(False),loadtype[0]))
TransactionManager.Instance.TransactionTaskDone()
OUT = listLoad
TransactionManager.Instance.EnsureInTransaction(doc)
pts = UnwrapElement(IN[0])
innerPts = UnwrapElement(IN[1])
frt = UnwrapElement(IN[2])
profileLoops = []
outerProfileLoop = CurveLoop()
#innerProfileLoop = CurveLoop()
profileLoops.Add(outerProfileLoop)
#profileLoops.Add(innerProfileLoop)
#create filled region
for i in range(0,len(pts)-1):
outerProfileLoop.Append(
Autodesk.Revit.DB.Line.CreateBound(
XYZ(pts[i].X,pts[i].Y,pts[i].Z),
XYZ(pts[i+1].X,pts[i+1].Y,pts[i+1].Z)
)
)
for j in range(0,len(innerPts)):
innerProfileLoop = CurveLoop()
profileLoops.Add(innerProfileLoop)
for i in range(0,len(innerPts[j])-1):
innerProfileLoop.Append(
Autodesk.Revit.DB.Line.CreateBound(
XYZ(innerPts[j][i].X,innerPts[j][i].Y,innerPts[j][i].Z),
XYZ(innerPts[j][i+1].X,innerPts[j][i+1].Y,innerPts[j][i+1].Z)
)
)
region = FilledRegion.Create(doc,frt[0].Id,activeViewId,profileLoops)
regions.Add(region)
TransactionManager.Instance.TransactionTaskDone()
def dispose_dyna_geom(args):
for arg in args:
arg.Dispose()
# Copy and paste from Bakery "GetElementRotation" node by Lukes Johnson
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
# Import RevitAPI
clr.AddReference('RevitAPI')
import Autodesk
#The inputs to this node will be stored as a list in the IN variable.
elements = UnwrapElement(IN[0])
outlist = [] #export list
templist = [] #temporary list to group attributes by element
for i in elements:
templist.append(i.HandOrientation) #vector XYZ Hand
templist.append(i.FacingFlipped) #is mirrored over X axis?
templist.append(i.HandFlipped) #is mirrored over Y axis?
outlist.append(templist[:])
del templist[:] #clear the templist
#Assign your output to the OUT variable
OUT = outlist
bip = BuiltInParameter.ID_PARAM
provider = ParameterValueProvider(ElementId(bip))
evaluator = FilterNumericEquals();
rule = FilterElementIdRule(provider, evaluator, view[0].Id);
filter = ElementParameterFilter(rule); #True inverts the filter
fec = FilteredElementCollector( view[0].Document ).WherePasses( filter ).ToElementIds()
# Copy and paste from Bakery "GetElementRotation" node by Lukes Johnson
import clr
from math import *
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
#The inputs to this node will be stored as a list in the IN variable.
dataEnteringNode = IN
X=IN[0] #HandOrientation vector.X
Y=IN[1] #HandOrientation vector.Y
outlist = []
templist = []
templist2 = []
count = 0
for e in X:
templist.append((acos(e))) #rotation angle
#if HandOrientation vector.Y >=0 beam angle = rotation angle
#else beam angle = angle + [2*(180-angle)] => reflex angle
while count < len(templist):
#for item in templist:
if Y[count] >= 0:
templist2.append(degrees(templist[count]))
elif Y[count] < 0:
templist2.append((degrees(templist[count])) + (2*(180-(degrees(templist[count])))))
count = count + 1
for e in templist2:
if e == 0:
outlist.append(0)
else:
outlist.append(360 - e)
#Assign your output to the OUT variable
OUT = outlist
# filter selection by category
def BeamsOnly(beam):
return [b for b in inputs if b.Category.Name == "Structural Framing"]
#Filters
finalCollector = FilteredElementCollector(doc);
finalCollector.WherePasses(ElementCategoryFilter(BuiltInCategory.OST_Doors))
elements = finalCollector.ToElements();
# find opening cut host
def FindOpeningCut(beam):
openingCuts = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFramingOpening)
return [o for o in openingCuts if o.Host.Id == beam.Id]
# when the beam does not have cut back applied
def GetEndPoints(beam):
return [beam.Location.Curve.GetEndPoint(0).ToPoint(),
beam.Location.Curve.GetEndPoint(1).ToPoint()]
#use when the beam has a cut back (location curve goes node to node)
def BeamEndPoints_InstaGeom(beam):
opt = Options()
opt.ComputeReferences = True
opt.IncludeNonVisibleObjects = True
#opt.View = doc.ActiveView
opt.DetailLevel = ViewDetailLevel.Medium
geo = beam.get_Geometry(opt)
solids = []
for item in geo:
try:
solids.append(item.GetInstanceGeometry())
except:
""
faces = [solid.Faces for solid in solids[0]]
bb1 = faces[1][0].Origin
bb2 = faces[1][1].Origin
return [bb1, bb2]
#use when the beam has a cut back (location curve goes node to node)
def BeamEndPoints_SolidGeom(beam):
opt = Options()
opt.ComputeReferences = True
opt.IncludeNonVisibleObjects = True
#opt.View = doc.ActiveView
opt.DetailLevel = ViewDetailLevel.Medium
pts = []
geo = beam.get_Geometry(opt)
for g in geo:
try:
pts.append([g.Faces[0].Origin,g.Faces[1].Origin])
except:
""
return pts[0]
for b in beam:
geo = b.get_Geometry(opt)
subList = []
check.append(subList)
for g in geo:
if g.GetType().ToString() == "Autodesk.Revit.DB.Solid":
subList.append("Solid")
else:
subList.append("Instance")
ptsList = []
for c,b in zip(check,beam):
if "Solid" in c:
ptsList.append(BeamEndPoints_SolidGeom(b))
else:
ptsList.append(BeamEndPoints_InstaGeom(b))
# when the beam has cutback applied. Some memory leak crashes Dynamo. Method taken from Marcello Sgambelluri
def BeamZTop(beam)
zOffset = GetBuiltInParam(beam, BuiltInParameter.Z_OFFSET_VALUE) # NEGATIVE VALUE!
return GetEndPoints(beam)[0].Z + zOffset
def beamRealCurve(element):
vertex = element.Geometry()[0].Vertices
pGeom = []
for v in vertex:
pGeom.append(v.PointGeometry)
dispose_dyna_geom(vertex) #DISPOSE
crv = LineBestFit(pGeom)
dispose_dyna_geom(pGeom) #DISPOSE
stPt = crv.PointAtParameter(0)
endPt = crv.PointAtParameter(1)
crv.Dispose() #DISPOSE
return [stPt, endPt]
# Use the element symbol geometry's bounding box to calculate its width
def GetBeamWidth(element):
opt = Options()
opt.ComputeReferences = True
opt.IncludeNonVisibleObjects = False
opt.View = doc.ActiveView
for instance in element.get_Geometry(opt):
try:
geomInst = instance.GetSymbolGeometry()
instTransform = instance.Transform;
width = (geomInst.GetBoundingBox().Max.Y - geomInst.GetBoundingBox().Min.Y)*304.8
except:
continue
return width
def BeamZTop(beam):
zOffset = GetBuiltInParam(beam, BuiltInParameter.Z_OFFSET_VALUE) # NEGATIVE VALUE!
return GetEndPoints(beam)[0].Z + zOffset
def GetBuiltInParam(element, name):
p = element.get_Parameter(name)
if p.StorageType == StorageType.String:
return p.AsString()
elif p.StorageType == StorageType.ElementId:
elem = doc.GetElement(p.AsElementId())
return elem
elif p.StorageType == StorageType.Double:
ProjectUnits = p.DisplayUnitType
newval = UnitUtils.ConvertFromInternalUnits(p.AsDouble(),ProjectUnits)
return newval
else:
return p.AsInteger()
zOffset = GetBuiltInParam(beam, BuiltInParameter.Z_OFFSET_VALUE)
def getLocation(elem):
lc = elem.Location.Curve
return lc.ToProtoType()
#credit teocomi
#Given an element Id or a list or elementIds, return the matching tags/s found
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
# Import RevitAPI
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
def getTagsByElementId(beamIds):
doc = DocumentManager.Instance.CurrentDBDocument
allTags = FilteredElementCollector(doc).OfClass(IndependentTag).ToElements()
return loopSublists(beamIds, allTags)
def loopSublists(data, allTags):
out = []
if type(data) is list:
for d in data:
out.append(loopSublists(d, allTags))
elif data != None:
matches = []
for i in allTags:
if str(i.TaggedElementId.HostElementId) == str(data):
matches.append(i)
# if multiple matches nest them
if len(matches) == 1:
out = matches[0]
elif len(matches) == 0:
out = None
else:
out = matches
return out
OUT = getTagsByElementId(IN[0])
# simplified version
import clr
clr.AddReference("RevitAPI")
import Autodesk
from Autodesk.Revit.DB import *
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
doc = DocumentManager.Instance.CurrentDBDocument
elements = UnwrapElement(IN[0])
thost = []
tags = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_StructuralFramingTags).ToElements()
result = []
for e in elements:
subList = []
result.append(subList)
for t in tags:
try:
tid = t.Id
thost = doc.GetElement(t.TaggedLocalElementId)
if thost.Id == e.Id:
subList.append(t)
except:
""
OUT = result
def GetElemType(e):
try:
elemType = doc.GetElement(e.GetTypeId())
return elemType
except:
pass
return None
#credit MEPover
def GetParam(element, name):
p = element.get_Parameter(name)
if p.StorageType == StorageType.String:
return p.AsString()
elif p.StorageType == StorageType.ElementId:
elem = doc.GetElement(p.AsElementId())
return elem
elif p.StorageType == StorageType.Double:
ProjectUnits = p.DisplayUnitType
newval = UnitUtils.ConvertFromInternalUnits(p.AsDouble(),ProjectUnits)
return newval
else:
return p.AsInteger()
#credit: MEPover
def GetDoubleParVal(element, paramName):
value = []
for e in element:
for p in e.Parameters:
if p.Definition.Name == paramName:
ProjectUnits = p.DisplayUnitType
newVal = UnitUtils.ConvertFromInternalUnits(p.AsDouble(),ProjectUnits)
value.append(newVal)
#credit: MEPover
def GetStringParVal(element, paramName):
value = []
for e in element:
for p in e.Parameters:
if p.Definition.Name == paramName:
value.append(p.AsString())
return value
# Place a family instance on an element's face (i.e. a void in a beam)
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)
clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
uidoc=DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument
#Preparing input from dynamo to revit
beam = UnwrapElement(IN[0])
opt = Options()
opt.ComputeReferences = True
opt.IncludeNonVisibleObjects = False
opt.View = doc.ActiveView
geo = []
for obj in beam.get_Geometry(opt):
if isinstance(obj, Solid):
geo.append(obj)
geo.append(obj.ConvertToMany())
geomInst = None;
instTransform = None;
for instance in beam.get_Geometry(opt):
try:
geomInst = instance.GetSymbolGeometry() # Represented in the CS of the family without regards to the orientation and placement location within the project.
instTransform = instance.Transform;
except:
continue
faces = []
geo = []
for solid in geomInst:
faces.Add(solid.Faces)
geo.append(solid.ConvertToMany()) #THIS GIVES BOTH FACES AND LINES
areas = []
for f in faces[0]:
areas.append(f.Area)
webFace = faces[0][6]
bboxUV = webFace.GetBoundingBox()
center = (bboxUV.Max + bboxUV.Min) * 0.5; #PLACE THE FAMILY IN THE CENTER OF THE SURFACE
start = bboxUV.Min; # PLACE THE FAMILY AT A DISTANCE FROM THE BEAM START POINT
location = webFace.Evaluate(start);
normal = webFace.ComputeNormal(center); #THIS WORKS FOR SOLID/INSTANCE GEOMETRY
refDir = normal.CrossProduct(XYZ.BasisZ); #THIS WORKS FOR SOLID/INSTANCE GEOMETRY
transformedPoint = instTransform.OfPoint(location);
tNormal = instTransform.OfPoint(normal); # THIS DOES NOT GIVE THE CORRECT VECTOR
transformedDir = instTransform.OfPoint(refDir); # THIS DOES NOT GIVE THE CORRECT VECTOR
direction = beam.Location.Curve.GetEndPoint(0) - beam.Location.Curve.GetEndPoint(1) #CALCULATE THE BEAM DIRECTION FROM ITS END POINTS
fs = UnwrapElement(IN[1]) #VOID FAMILY TYPE
TransactionManager.Instance.EnsureInTransaction(doc)
void = doc.Create.NewFamilyInstance.Overloads[Reference, XYZ, XYZ, FamilySymbol](webFace.Reference, transformedPoint, direction, fs);
#void = doc.Create.NewFamilyInstance(location,fs,normal,beam,StructuralType.NonStructural); THIS WOULD WORK FOR WALLS OR FLOORS. IN BEAMS THE VOID APPEARS ON THE XY PLANE (INSTEAD OF ON THE BEAM WEB)
TransactionManager.Instance.TransactionTaskDone()
OUT = transformedPoint.X*304.8, transformedPoint.Y*304.8, tNormal, transformedDir, direction
# find the left most end point of a beam
def LeftMostEnd(beam):
try:
stPt = beam.Location.Curve.GetEndPoint(0).ToPoint()
endPt = beam.Location.Curve.GetEndPoint(1).ToPoint()
leftMostPoint = None
if stPt.X == endPt.X:
if stPt.Y < endPt.Y:
leftMostPoint = stPt
else:
leftMostPoint = endPt
elif stPt.X < endPt.X:
leftMostPoint = stPt
else:
leftMostPoint = endPt
return leftMostPoint
except:
return "Uh-oh something went wrong"
import clr
clr.AddReference("ProtoGeometry")
from Autodesk.DesignScript.Geometry import *
# Import RevitAPI
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
clr.AddReference("RevitAPIUI")
from Autodesk.Revit.UI import TaskDialog
# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
# Import ToProtoType, ToRevitType geometry conversion extension methods
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
doc = DocumentManager.Instance.CurrentDBDocument
my_list = IN[0]
unique = list(set(my_list))
indexes = []
f = lambda my_list, value:filter(lambda x: my_list[x] == value, range(len(my_list)))
for x in unique:
indexes.append(f(my_list, x))
#Assign your output to the OUT variable.
OUT = indexes
# sublist example
V0 = IN[0]
V1 = IN[1]
# Assign your output to the OUT variable.
OUT = [[v+temp for temp in V1] for v in V0]
[s[:-2] for s in IN[0]]
#RhinoInside
import clr
clr.AddReference('System.Core')
from System.Linq import Enumerable
from System.IO import Path, File
clr.AddReference('RhinoInside.Revit')
from Rhino.Geometry import *
from RhinoInside.Revit import Revit, Convert
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib')
import os
doc = Revit.ActiveDBDocument
app = doc.Application
builtInCats = List[ElementId]()
for c in doc.Settings.Categories:
if c.Name in x:
builtInCats.Add(c.Id)
categoryFilter = ElementMulticategoryFilter(builtInCats);
ids = FilteredElementCollector(doc).WherePasses(categoryFilter).WhereElementIsNotElementType().ToElements();
#a = "Walls" in x
Elements = ids
grid = UnwrapElement(IN[0])
OUT = doc.GetElement(grid.GetGridIds()[0]).Curve.ToProtoType()
# Repeat the items in a list of lists according to a list of integers
# main list = [1..5,6..10]
# repeater = Math.Round(Math.RandomList(5)*20)
main = IN[0]
repeater = IN[1]
result = []
for m in main:
sub = []
result.append(sub)
for item,r in zip(m,repeater):
subList = []
sub.append(subList)
for i in range(0,int(r)):
subList.append(item)
OUT = result
class Opening:
def __init__(self, Shape, Width, Height, Centroid, HostedBeamDepth, BeamDirection, Distance0, Distance1, ZTop, Element, BeamElement):
self.Shape = Shape
self.Width = Width
self.Height = Height
self.Centroid = Centroid
self.HostedBeamDepth = HostedBeamDepth
self.BeamDirection = BeamDirection
self.Distance0 = Distance0
self.Distance1 = Distance1
self.ZTop = ZTop
self.Element = Element
self.BeamElement = BeamElement
pass
def printOut(self):
return [self.Shape, self.Width, self.Height, self.Centroid, self.HostedBeamDepth, self.BeamDirection, self.Distance0, self.Distance1, self.ZTop, self.Element, self.BeamElement]
pass
def distance(self, point):
return Geometry.DistanceTo(self.Centroid, point)
pass
def XYDistance(self, Pt1):
distance = math.pow((math.pow((self.Centroid.X-Pt1.X),2) + math.pow((self.Centroid.Y-Pt1.Y),2)),0.5)
return round(distance,0)
pass
def __getitem__(self, item):
return getattr(self, item)
pass
for i in range(0,len(beamList)):
subMEP = []
MEPobjects.append(subMEP)
subKeys = []
keys.append(subKeys)
for j in range(0,len(ductList[i])):
if ductList[i][j].Name == "OpeningDuct":
centroid = ductList[i][j].Location.Point.ToPoint()
stPt = beamEndPts[i][0].ToPoint()
endPt = beamEndPts[i][1].ToPoint()
vct = Vector.ByTwoPoints(stPt, endPt).X
if vct > 0:
beamDir = "dirX"
else:
beamDir = "dirY"
Distance0 = int(PointXYDistance(centroid, stPt))
Distance1 = int(PointXYDistance(centroid, endPt))
instance = Opening ( "Rectangle",
int(GetParamValue(ductList[i][j], "x")),
int(GetParamValue(ductList[i][j], "z")),
[centroid.X, centroid.Y, centroid.Z],
int(GetParamValue(beamList[i], "COBie.Type.NominalHeight")),
beamDir,
Distance0,
Distance1,
BeamZTop(beamList[i]),
ductList[i][j],
beamList[i]
)
subKeys.append(instance.Distance0)
subMEP.append(instance)
centroid.Dispose()
stPt.Dispose()
endPt.Dispose()
else:
centroid = ductList[i][j].Location.Point.ToPoint()
stPt = beamEndPts[i][0].ToPoint()
endPt = beamEndPts[i][1].ToPoint()
vct = Vector.ByTwoPoints(stPt, endPt).X
if vct > 0:
beamDir = "dirX"
else:
beamDir = "dirY"
Distance0 = int(PointXYDistance(centroid, stPt))
Distance1 = int(PointXYDistance(centroid, endPt))
instance = Opening ( "Pipe",
int(GetParamValue(ductList[i][j], "x")),
int(GetParamValue(ductList[i][j], "y")),
[centroid.X, centroid.Y, centroid.Z],
#int(GetParamValue(GetElemType(beamList[i]), "d")),
int(GetParamValue(beamList[i], "COBie.Type.NominalHeight")),
beamDir,
Distance0,
Distance1,
BeamZTop(beamList[i]),
ductList[i][j],
beamList[i]
)
subKeys.append(instance.Distance0)
subMEP.append(instance)
centroid.Dispose()
stPt.Dispose()
endPt.Dispose()
import clr
clr.AddReference("RevitAPIUI")
from Autodesk.Revit.UI import IExternalEventHandler, ExternalEvent, TaskDialog
from Autodesk.Revit.UI.Selection import *
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import Transaction, OverrideGraphicSettings, ElementId, Color
# noinspection PyUnresolvedReferences
from Autodesk.Revit.Exceptions import InvalidOperationException
clr.AddReference('RevitServices')
from RevitServices.Persistence import DocumentManager
global result
doc = DocumentManager.Instance.CurrentDBDocument
uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument
class CustomISelectionFilter(ISelectionFilter):
def __init__(self, category_name):
self.category_name = category_name
def AllowElement(self, e):
if e.Category.Name == self.category_name:
return True
else:
return False
def AllowReference(self, ref, point):
return false
ref = uidoc.Selection.PickObjects(ObjectType.Element, CustomISelectionFilter("Structural Framing"), "Select Multiple Beams")
OUT = [doc.GetElement(r) for r in ref]
#credit Danny Bentley
def PlaceFamInst(point, famtype, x, y, z, angle):
ST = StructuralType.NonStructural
TransactionManager.Instance.EnsureInTransaction(doc)
newobj = doc.Create.NewFamilyInstance(point.ToXyz(),famtype,ST)
p = newobj.LookupParameter("x")
p.Set((x/304.8)/math.sin(math.radians(angle)))
p = newobj.LookupParameter("y")
p.Set(y/304.8)
p = newobj.LookupParameter("z")
p.Set(z/304.8)
p = newobj.LookupParameter("Comments")
#p.Set(Element.Name.__get__(famtype))
p.Set("Cable Trays")
TransactionManager.Instance.TransactionTaskDone()
return newobj
import clr
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
doc = DocumentManager.Instance.CurrentDBDocument
def SignedDistanceTo(plane, p):
v = p - plane.Origin;
return plane.Normal.DotProduct(v)
def ProjectOnto(plane, p):
d = SignedDistanceTo(plane, p )
q = p - d * plane.Normal
return q
points = UnwrapElement(IN[0])
famtype = UnwrapElement(IN[1])
view = doc.ActiveView
version = 2016
elementlist = list()
counter = 0
plane = Plane.CreateByNormalAndOrigin(view.ViewDirection, view.Origin);
TransactionManager.Instance.EnsureInTransaction(doc)
for pt in points:
if version > 2015:
if not(famtype.IsActive): famtype.Activate()
#detline = doc.Create.NewDetailCurve(view, curve.ToRevitType())
#baseLine = detline.GeometryCurve
revitPt = pt.ToRevitType()
projPt = ProjectOnto(plane, revitPt)
pileWidth = 300/304.8
if view.ViewDirection.X == -1:
stPt = XYZ(projPt.X, projPt.Y+pileWidth, projPt.Z)
endPt = XYZ(projPt.X, projPt.Y-pileWidth, projPt.Z)
elif view.ViewDirection.X == 1:
stPt = XYZ(projPt.X, projPt.Y-pileWidth, projPt.Z)
endPt = XYZ(projPt.X, projPt.Y+pileWidth, projPt.Z)
elif view.ViewDirection.Y == 1:
stPt = XYZ(projPt.X+pileWidth, projPt.Y, projPt.Z)
endPt = XYZ(projPt.X-pileWidth, projPt.Y, projPt.Z)
elif view.ViewDirection.Y == -1:
stPt = XYZ(projPt.X-pileWidth, projPt.Y, projPt.Z)
endPt = XYZ(projPt.X+pileWidth, projPt.Y, projPt.Z)
elif view.ViewDirection.X * view.ViewDirection.Y > 0:
stPt = projPt + plane.XVec.Normalize()*pileWidth
endPt = projPt - plane.XVec.Normalize()*pileWidth
else:
stPt = projPt - plane.XVec.Normalize()*pileWidth
endPt = projPt + plane.XVec.Normalize()*pileWidth
baseLine = Line.CreateBound(stPt, endPt);
#elementlist.append(baseLine.ToProtoType())
newobj = doc.Create.NewFamilyInstance.Overloads[Line, FamilySymbol, View](baseLine,famtype,view)
elementlist.append(newobj.ToDSType(False))
#doc.Delete(detline.Id)
TransactionManager.Instance.TransactionTaskDone()
OUT = view, elementlist
def PointXYDistance(Pt0, Pt1):
distance = math.pow((math.pow((Pt0.X-Pt1.X),2) + math.pow((Pt0.Y-Pt1.Y),2)),0.5)
return round(distance,0)
#vbCr = "\r"
#vbLf = "\n"
#vbCrLf = "\r\n"
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)
clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
uidoc=DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument
uiapp = DocumentManager.Instance.CurrentUIApplication
viewSetName = IN[0]
mySheets = UnwrapElement(IN[1])
mySheetNumbers = [m.SheetNumber for m in mySheets]
#mySheetNumbers.extend(["S-11-110","S-11-111","S-70-141"])
myViewSet = ViewSet()
sheetItr = FilteredElementCollector(doc).OfClass(ViewSheet).ToElements()
selectedSheets = list()
for sheet in sheetItr:
if sheet.SheetNumber in mySheetNumbers:
#selectedSheets.append(sheet.SheetNumber)
myViewSet.Insert(sheet)
elemItr = FilteredElementCollector(doc).OfClass(ViewSheetSet).GetElementIterator()
elemItr.Reset()
existingViewSet = None
while (elemItr.MoveNext()):
if (elemItr.Current.Name == viewSetName):
existingViewSet = elemItr.Current
hasBeenDeleted = "No"
TransactionManager.Instance.EnsureInTransaction(doc)
if existingViewSet != None:
doc.Delete(existingViewSet.Id);
hasBeenDeleted = "Yes"
printMan = doc.PrintManager;
printMan.PrintRange = PrintRange.Select;
viewSetting = printMan.ViewSheetSetting;
viewSetting.CurrentViewSheetSet.Views = myViewSet;
viewSetting.SaveAs(viewSetName);
TransactionManager.Instance.TransactionTaskDone()
TaskDialog.Show("Result", "ViewSet: %s \nExisting: %s \nThe view set contains %s sheets." % (viewSetName,hasBeenDeleted, myViewSet.Size))
# From the Journal File: Jrn.RibbonEvent "Execute external command:CustomCtrl_%CustomCtrl_%CADtools%Publish%Batch" & vbCr &
#"Publish:Arup.CADtools.Revit.Commands.RevitPublishCmd"
name = "CustomCtrl_%CustomCtrl_%CADtools%Publish%Batch\rPublish"
id = RevitCommandId.LookupCommandId(name)
uiapp.PostCommand( id )
OUT = "Success"
import clr
clr.AddReference("System.Windows.Forms")
from System.Windows.Forms import Application, Button, Form, Label, TextBox, CheckBox, FolderBrowserDialog, OpenFileDialog, DialogResult, ComboBox, FormBorderStyle, FormStartPosition
clr.AddReference("System.Drawing")
from System.Drawing import *
clr.AddReference("System")
from System import EventHandler
familyName = [1,2,3]
distances = ""
formVoidWidth = 0
formVoidHeight = 0
form = Form()
def Form1Load(sender, e):
for s in familyName:
comboBoxCategory.Items.Add(s);
def Ok_btnClick(sender, e):
global distances
distances = textBox1.Text;
global formVoidWidth
formVoidWidth = int(textBoxWidth.Text);
global formVoidHeight
formVoidHeight = int(textBoxHeight.Text);
if checkBoxStart.Checked:
formPosition = "start";
if checkBoxEnd.Checked:
formPosition = "end";
if checkBoxMidPoint.Checked:
formPosition = "mid";
def ComboBoxCategorySelectedIndexChanged(sender, e):
comboBoxCategory.SelectedItem.ToString()
def CheckBoxStart_Click(sender, e):
checkBoxEnd.Checked = False;
checkBoxMidPoint.Checked = False;
def CheckBoxEnd_Click(sender, e):
checkBoxStart.Checked = False;
checkBoxMidPoint.Checked = False;
ok_btn = Button();
textBox1 = TextBox();
label1 = Label();
comboBoxCategory = ComboBox();
label2 = Label();
btn_cancel = Button();
textBoxWidth = TextBox();
textBoxHeight = TextBox();
label3 = Label();
label4 = Label();
checkBoxStart = CheckBox();
checkBoxEnd = CheckBox();
checkBoxMidPoint = CheckBox();
#SuspendLayout();
#
# ok_btn
#
ok_btn.DialogResult = DialogResult.OK;
ok_btn.Location = Point(38, 207);
ok_btn.Name = "ok_btn";
ok_btn.Size = Size(90, 29);
ok_btn.TabIndex = 0;
ok_btn.Text = "OK";
ok_btn.UseCompatibleTextRendering = True;
ok_btn.UseVisualStyleBackColor = True;
ok_btn.Click += EventHandler(Ok_btnClick);
#
# textBox1
#
textBox1.Location = Point(12, 161);
textBox1.Name = "textBox1";
textBox1.Size = Size(261, 20);
textBox1.TabIndex = 1;
#
# label1
#
label1.Location = Point(12, 141);
label1.Name = "label1";
label1.Size = Size(249, 15);
label1.TabIndex = 2;
label1.Text = "Offset";
label1.UseCompatibleTextRendering = True;
#
# comboBoxCategory
#
comboBoxCategory.FormattingEnabled = True;
comboBoxCategory.Location = Point(13, 29);
comboBoxCategory.Name = "comboBoxCategory";
comboBoxCategory.Size = Size(261, 21);
comboBoxCategory.Sorted = True;
comboBoxCategory.TabIndex = 3;
comboBoxCategory.SelectedIndexChanged += EventHandler(ComboBoxCategorySelectedIndexChanged);
#
# label2
#
label2.Location = Point(13, 11);
label2.Name = "label2";
label2.Size = Size(155, 15);
label2.TabIndex = 5;
label2.Text = "Select Opening Family";
label2.UseCompatibleTextRendering = True;
#
# btn_cancel
#
btn_cancel.DialogResult = DialogResult.Cancel;
btn_cancel.Location = Point(157, 207);
btn_cancel.Name = "btn_cancel";
btn_cancel.Size = Size(86, 29);
btn_cancel.TabIndex = 6;
btn_cancel.Text = "Cancel";
btn_cancel.UseCompatibleTextRendering = True;
btn_cancel.UseVisualStyleBackColor = True;
#
# textBoxWidth
#
textBoxWidth.Location = Point(12, 74);
textBoxWidth.Name = "textBoxWidth";
textBoxWidth.Size = Size(100, 20);
textBoxWidth.TabIndex = 7;
#
# textBoxHeight
#
textBoxHeight.Location = Point(173, 74);
textBoxHeight.Name = "textBoxHeight";
textBoxHeight.Size = Size(100, 20);
textBoxHeight.TabIndex = 8;
#
# label3
#
label3.Location = Point(13, 56);
label3.Name = "label3";
label3.Size = Size(100, 15);
label3.TabIndex = 9;
label3.Text = "Width";
label3.UseCompatibleTextRendering = True;
#
# label4
#
label4.Location = Point(173, 56);
label4.Name = "label4";
label4.Size = Size(100, 15);
label4.TabIndex = 10;
label4.Text = "Height";
label4.UseCompatibleTextRendering = True;
#
# checkBoxStart
#
checkBoxStart.Location = Point(12, 105);
checkBoxStart.Name = "checkBoxStart";
checkBoxStart.Size = Size(104, 24);
checkBoxStart.TabIndex = 11;
checkBoxStart.Text = "Start Point";
checkBoxStart.UseCompatibleTextRendering = True;
checkBoxStart.UseVisualStyleBackColor = True;
checkBoxStart.Click += EventHandler(CheckBoxStart_Click);
#
# checkBoxEnd
#
checkBoxEnd.Location = Point(205, 105);
checkBoxEnd.Name = "checkBoxEnd";
checkBoxEnd.Size = Size(104, 24);
checkBoxEnd.TabIndex = 12;
checkBoxEnd.Text = "End Point";
checkBoxEnd.UseCompatibleTextRendering = True;
checkBoxEnd.UseVisualStyleBackColor = True;
checkBoxEnd.Click += EventHandler(CheckBoxEnd_Click);
#
# checkBoxMidPoint
#
checkBoxMidPoint.Checked = True;
checkBoxMidPoint.Location = Point(105, 105);
checkBoxMidPoint.Name = "checkBoxMidPoint";
checkBoxMidPoint.Size = Size(73, 24);
checkBoxMidPoint.TabIndex = 13;
checkBoxMidPoint.Text = "Mid Point";
checkBoxMidPoint.UseCompatibleTextRendering = True;
checkBoxMidPoint.UseVisualStyleBackColor = True;
#
# Form1
#
form.ClientSize = Size(289, 248);
form.Controls.Add(checkBoxMidPoint);
form.Controls.Add(checkBoxEnd);
form.Controls.Add(checkBoxStart);
form.Controls.Add(label4);
form.Controls.Add(label3);
form.Controls.Add(textBoxHeight);
form.Controls.Add(textBoxWidth);
form.Controls.Add(btn_cancel);
form.Controls.Add(label2);
form.Controls.Add(comboBoxCategory);
form.Controls.Add(label1);
form.Controls.Add(textBox1);
form.Controls.Add(ok_btn);
form.Name = "Form1";
form.Text = "Place Instance By Face";
form.Load += EventHandler(Form1Load);
form.StartPosition = FormStartPosition.CenterScreen
form.ShowDialog()
OUT = textBox1.Text, checkBoxMidPoint.Checked, textBoxWidth.Text, textBoxHeight.Text, distances, formVoidWidth
if isinstance(IN[0], list):
element = UnwrapElement(IN[0])
else:
element = [UnwrapElement(IN[0])]
#credits Clockwork package
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
import Autodesk
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
import math
doc = DocumentManager.Instance.CurrentDBDocument
getDocUnits = doc.GetUnits()
getDisplayUnits = getDocUnits.GetFormatOptions(UnitType.UT_Length).DisplayUnits
projloc = doc.ActiveProjectLocation
position_data = projloc.GetProjectPosition(XYZ.Zero)
location_data = projloc.GetSiteLocation()
elevation = UnitUtils.ConvertFromInternalUnits(position_data.Elevation, getDisplayUnits)
x = UnitUtils.ConvertFromInternalUnits(position_data.EastWest, getDisplayUnits)
y = UnitUtils.ConvertFromInternalUnits(position_data.NorthSouth, getDisplayUnits)
angle = position_data.Angle * 180 / math.pi
OUT = (-angle, elevation, x, y)
#Select all model elements in the Revit model (excluding Element Types, Views, Levels...)
collector = FilteredElementCollector( doc ).WhereElementIsNotElementType()
cat = []
for c in collector:
if (None != c.Category and c.Category.HasMaterialQuantities):
cat.append(c)
#this will not work with MEP objects. To capture them:
for c in collector:
if (None != c.Category and c.Category.CanAddSubcategory):
cat.append(c)
element = UnwrapElement(IN[0])
#analyticalModel = element.GetAnalyticalModel()
TransactionManager.Instance.EnsureInTransaction(doc)
element.SetAlignmentMethod(AnalyticalElementSelector.StartOrBase, AnalyticalAlignmentMethod.Projection)
element.SetProjection(AnalyticalElementSelector.EndOrTop, StickElementProjectionY.Center, StickElementProjectionZ.Center)
TransactionManager.Instance.TransactionTaskDone()
OUT = element
for m in MEPobjects:
sortedDucts = sorted(m, key=lambda instance: instance["Distance0"])
sortedResults.append(sortedDucts)
def SplitString(string, char):
return string.split(char)
from System.Diagnostics import Stopwatch
sw = Stopwatch.StartNew()
a = 0
for i in range(0,IN[0]):
a += 1
#Assign your output to the OUT variable.
OUT = a, sw.Elapsed.TotalMilliseconds
# Transform from Survey coordinates to Dynamo internal coordinates (CS based in the Revit origin acquired using revitOrigin.py).
# PBP has been moved away from the Revit origin!
def transform(x,y,alfa,a,b){
xtransformed = (x-a)*Math.Cos(alfa)-(y-b)*Math.Sin(alfa);
ytransformed = (x-a)*Math.Sin(alfa)+(y-b)*Math.Cos(alfa);
pt = Autodesk.Point.ByCoordinates(xtransformed, ytransformed);
return pt;
};
clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
# if you do not wrap the element, you will get an attribute error when trying to access some of its parameters (i.e. Name)
# https://github.com/DynamoDS/Dynamo/wiki/Python-0.6.3-to-0.7.x-Migration#revitapi
viewNames = []
for vft in FilteredElementCollector(sourceDoc).OfClass(ViewFamilyType):
viewNames.append(vft.ToDSType(True).Name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment