Read Element's Properties and Methods

You know how to select elements. Now, let's look inside these elements and try to get their properties and methods.

Read Element's Properties and Methods

You know how to select elements. Now, let's look inside these elements and try to get their properties and methods.

Read Element's Properties and Methods

You know how to select elements. Now, let's look inside these elements and try to get their properties and methods.

Summary

Get Element

Let's copy a few lines of code from the previous lesson, so we can pick our elements to read from.

We will also make sure that we only work with rooms, and I will make a simple if statement checking type() of selected elements.

#➡️ Imports
import sys
from Autodesk.Revit.UI.Selection    import ObjectType, Selection
from Autodesk.Revit.DB              import *
from Autodesk.Revit.DB.Architecture import Room

#📦 Variables
doc       = __revit__.ActiveUIDocument.Document
uidoc     = __revit__.ActiveUIDocument
selection = uidoc.Selection #type: Selection

#👉 Pick an Element
ref  = selection.PickObject(ObjectType.Element)
elem = doc.GetElement(ref) 

#🔎 Check if that's a Room
if type(elem) != Room:
    print("This is not a Room selected. Please Try Again.")
    sys.exit()
    
print(elem)

👀 By now we can pick an element, and we know that it will either be a Room or script execution will stop.

Read Room's Properties

Now let's look inside of selected Room using Revit Lookup plugin that we installed in the first module.

When you have a few elements selected you can go to Revit Lookup plugin and click on Snoop Selection.

There are also other option to Snoop Active View, Document, Application, Database

But Snoop Selection is by far the most used one

Once you click on Snoop Selection you will see this menu.

On the left side you have your selected elements sorted by their Classes, and on the right side you get to see element's properties and methods.

💡Regular text means that property or method returns you a value

💡 Bold text means it returns you an Element or List of Elements that you can look even further. When you click no them, it will open separate window with returned Element/s.

Read Element's Properties

Reading properties is very simple once you have your element selected.

We can see all property and method names, and to use properties we just need to write their names after an instance of our element. If you want to use methods then we need to use their name with parenthesis (). Inside we need to provide arguments, that we can find in Revit API Docs.

#🔎 Room variables
level_id = elem.LevelId
level    = doc.GetElement(level_id)
group = "None" if elem.GroupId == ElementId(-1) else elem.GroupId

#📰 Print statements
print("ElementId: {}        ".format(elem.Id))
print("GroupId: {}          ".format(group))
print("Category: {}         ".format(elem.Category.Name))
print("BuiltInCategory: {}  ".format(elem.Category.BuiltInCategory))
print("Level: {}            ".format(level.Name))
print("XYZ: {}              ".format(elem.Location.Point))
print("Area: {}             ".format(elem.Area))
print("Number: {}           ".format(elem.Number))
print("Perimeter: {}        ".format(elem.Perimeter))

💡 Be aware that Revit API uses feet as internal units when we get Numeric values that have units associated with them.

Some properties can't be accessed

There are a few properties that even though we can see them in Revit Lookup, we can't access them like a property with our code. Usually it's going to be a .Name property of ElementTypes and Rooms.

To get it we can either use special class method, or by reading parameter that holds this value.

👇Here is an example for Rooms.

# Get Special Properties like .Name
room_name  = elem.get_Parameter(BuiltInParameter.ROOM_NAME).AsString() # Option A (Just RoomName)
room_name_ = Element.Name.GetValue(elem)                               # Option B (incl. RoomNumber)

💡 We will cover Parameters in its own module soon!

How to Convert Units to Metric?

As I've mentioned, Numeric values that have associated units, use feet internally.

Many of you will be using metric systems when we work in Revit, and therefore we will often need to convert internal feet units into metric units.

There is a class in Revit API called - UnitUtils Class.

It has different methods for converting units. We will use the following ones:
ConvertFromInternalUnits
ConvertToInternalUnits

💡 These methods had updates in Revit API 2022, now there are seperate class for defining Revit API Unit Types. We will tackle it in our function.

Convert Internal Units Function

Since we will need to convert units many times when we work with Revit API, it makes sense to create a reusable function and place it in our lib folder.

💡 Remember:
"Good Programmers Code, But Great Programmers Reuse Code!"

👀 Here is the function that I placed in my lib/Snippets/_convert.py module.

# Imports
from Autodesk.Revit.DB import *

# Variables
uidoc = __revit__.ActiveUIDocument
doc   = __revit__.ActiveUIDocument.Document
app   = __revit__.Application

rvt_year  = int(app.VersionNumber)

# ╔═╗╦ ╦╔╗╔╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
# ╠╣ ║ ║║║║║   ║ ║║ ║║║║╚═╗
# ╚  ╚═╝╝╚╝╚═╝ ╩ ╩╚═╝╝╚╝╚═╝ FUNCTIONS
#==================================================

def convert_internal_units(value, get_internal = True, units='m'):
    #type: (float, bool, str) -> float
    """Function to convert Internal units to meters or vice versa.
    :param value:        Value to convert
    :param get_internal: True to get internal units, False to get Meters
    :param units:        Select desired Units: ['m', 'm2']
    :return:             Length in Internal units or Meters."""

    if rvt_year >= 2021:
        from Autodesk.Revit.DB import UnitTypeId
        if   units == 'm' : units = UnitTypeId.Meters
        elif units == "m2": units = UnitTypeId.SquareMeters
        elif units == 'cm': units = UnitTypeId.Centimeters
    else:
        from Autodesk.Revit.DB import DisplayUnitType
        if   units == 'm' : units = DisplayUnitType.DUT_METERS
        elif units == "m2": units = DisplayUnitType.DUT_SQUARE_METERS
        elif units == "cm": units = DisplayUnitType.DUT_CENTIMETERS

    if get_internal:
        return UnitUtils.ConvertToInternalUnits(value, units)
    return UnitUtils.ConvertFromInternalUnits(value, units)

This function takes in account differences in Revit API versions and provides you an option to select between different units that should be translated To or From InternalUnits.

💡 You can add even more units if necessary.

Simpler Convert Function

It has been a while since I've made this video and I've realized that this function is a bit an overkill if you are not using Revit 2020 anymore...

So we can simplify it like this without even making it a function.

Just choose your units, and decide if you need to convert FromInternal or ToInternal.

units = UnitTypeId.Meters # or .SquareMeters .Centimeters...
value = 10.55

value_to_m  = UnitUtils.ConvertFromInternalUnits(value, units)
value_to_ft = UnitUtils.ConvertToInternalUnits(value, units)
Read Room's Methods

Lastly, let me show you how to use methods. We will look into .GetBoundarySegments().

Since Method often require us to provide arguments, it's good to check this method inside of Revit API Docs. But you could also try to run it, and you will get an error saying that you don't have enough arguments provided.

Once you look at this method in Revit API, you will see that it takes 1 argument - SpatialElementBoundaryOptions.

We can explore this class to learn how to create options, and usually in Revit API we can easily create default set of options with a constructor that takes no arguments.

Here is the constructor method of this Class. It takes 0 arguments, and after we create it, we can modify options by using its Properties or Methods.

But we won't need to do that for our use-case.

👇Here is the Snippet to create Options and get Room's BoundarySegments.

# Boundary Segments
opts              = SpatialElementBoundaryOptions()
boundary_segments = elem.GetBoundarySegments(opts)
print("Boundary Segments: {}".format(boundary_segments))

HomeWork

Choose Element with another category, and try to read as many properties as you can. Also feel free to share with others so you can see more results together.

✅ Select Element with Different Category
✅ Read Properties and Methods

⌨️ Happy Coding!

Questions:

How do you create doc string variables?

How do you create doc string variables?

How to read RoomName?

How to read RoomName?

Discuss the lesson:

P.S. Sometimes this chat might experience connection issues.
Please be patient or join via Discord app so you can get the most out of this community and get access to even more chats.

P.S. Sometimes this chat might experience connection issues.
Please be patient or join via Discord app so you can get the most out of this community and get access to even more chats.

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API