_images/revitron.svg

Revitron

Revitron is a Revit API wrapper written in Python. It helps you to develop clean and powerful Revit plugins in pyRevit.

https://img.shields.io/github/v/tag/revitron/revitron?label=Release&style=flat-square&labelColor=292b2e&color=292b2e

Getting Started

Revitron is a Revit API wrapper written in Python that can help you to develop clean and powerful pyRevit extensions. Check out the developer guide for more information or use the cheat sheet to get started quickly.

Installation

There are three options for installing Revitron and the Revitron UI — using the pyRevit UI, using the pyRevit CLI or installing the full bundle.

Important

Note that in order to use the Revitron package manager or the bundle installer, Git must be installed on your computer.

Using the pyRevit UI

To use the Revit UI to install this extensions, open the pyRevit tab, click on pyRevit > Extensions to open the extensions manager and follow these instructions.

Using the pyRevit CLI

In case you want to use the command line to install Revitron and the Revitron UI, use the following command:

pyrevit extend lib revitron https://github.com/revitron/revitron.git
pyrevit extend ui revitron https://github.com/revitron/revitron-ui.git

Bundled Version

There is also a bundle installer available that will install pyRevit including the Revitron and the Revitron UI packages.

  1. Right-click here to download the Revitron installer. Make sure it keeps the .bat extension.

  2. Move the install.bat to the directory, where you want to install pyRevit.

  3. Double-click the install.bat file to start the installation and wait until it has finished.

  4. Start Revit.

Revitron CLI Setup

In order to be able to run the revitron command from anywhere it has to be added to your path environment variable. You can do that manually or by running the following commands once:

cd path\to\revitron.lib
cli\setup

Developer Guide

The Revitron package is a Revit API wrapper written in Python to help you developing clean and powerful Revit plugins in pyRevit. The package consists of a minimal main module and collection of specific submodules covering certain topics of the Revit API.

Concept

Basically this package is designed to be a generic Revit API toolbox. It doesn’t focus on a single topic, but tries to combine multiple wrapper classes instead to enable you to create plugins using just one single base library. However, there are two topics that are in the main focus of many pyRevit plugins — working with elements and filtering.

Note

Check out the cheat sheet to get you started quickly with the most common tools.

Working with Elements

Revitron elements wrap standard Revit elements and expose additional convenience methods in order to make working with the API a bit less cumbersome:

import revitron
_element = revitron.Element(element)

Alternatively to the default constructor it is also possible to create element instances by using the following shorthand function:

from revitron import _
_element = _(element)

In both cases _element is a proper Revitron element. This comes in handy in many situations where a quick access to an element is needed. The following example demonstrates how it is possible to set a parameter value, even though the parameter itself doesn’t exist yet:

from revitron import _
_(element).set('ParameterName', value)

In that one line we just set a parameter value and also created the parameter if neccessary. In order to get a parameter value of a given element we can use:

from revitron import _
comment = _(element).get('Comments')

You can find the documentation of more available element methods in the revitron.element reference.

Using Filters

Besides element properties, filtering is another core functionality of this package. Working with FiteredElementCollector instances can be quite complex and difficult to debug. Revitron provides a Filter that implements a powerful tool to also filter the database by parameter values using human readable one-liner:

import revitron
filter = revitron.Filter
ids = filter().byStringEquals('param', 'value').noTypes().getElementIds()

Revitron Module

The main Revitron module contains only some global module properties as well as the magic _() function. Specific classes are located in the submodules listed below.

DOC

The currently active document.

UIDOC

The active UI document.

APP

A shortcut for accessing the application object of the active document.

ACTIVE_VIEW

The active view element.

DB

A shortcut for Autodesk.Revit.DB.

LIB_DIR

The path to the Revitron library extension directory.

REVIT_VERSION

The version number string of the running Revit application.

Subpackages

revitron.analyze

The revitron.analyze module helps you to automate analysing the health and status of a model and to extract several types of data and statistics in order to simplifiy BIM quality control. Extracted data is stored as snapshots in a SQLite database to be consumed by other applications or dashboards.

class DataProviderResult(providerClass, providerName, providerConfig)[source]

Bases: object

The DataProviderResult object handles the execution of a data provider by creating a unified results object containing the provider name, the resulting value and its data type.

__init__(providerClass, providerName, providerConfig)[source]

Inits a new provider class instances and runs the provider’s run() method in order to populate the value property.

Parameters
  • providerClass (string) – The class name for the data provider that has to be used

  • providerName (string) – A descriptive name to generate the storage field

  • providerConfig (dict) – The configuration that is passed to the data provider

property dataType

The data type that is used to store the value.

Returns

The data type

Return type

string

property name

The name that is used to create a storage field.

Returns

The field name

Return type

string

property value

The resulting value.

Returns

The value that is returned by the provider’s run() method

Return type

mixed

class ModelAnalyzer(configJson, cliLog)[source]

Bases: object

The ModelAnalyzer class applies a configured set of data providers on a model and creates snapshots with the extracted statistics in a given SQLite database.

__init__(configJson, cliLog)[source]

Init a ModelAnalyzer instance.

Parameters
  • configJson (string) – The configuration JSON file

  • cliLog (CliLog) – The CLI log instance

snapshot()[source]

Create a snapshot and store the given DataProviderResult list along with a timestamp using a given storage driver.

Submodules
revitron.analyze.history

This submodule provides an synchronizer class for mirroring hsitory data to Directus.

Classes:

DirectusHistorySynchronizer(config)

This synchronizer class mirrors sync meta data that is tracked by the Revitron History into a Directus database.

class DirectusHistorySynchronizer(config)[source]

Bases: object

This synchronizer class mirrors sync meta data that is tracked by the Revitron History into a Directus database.

Methods:

__init__(config)

Init the synchronizer.

sync()

Fetch sync meta data from the history SQLite file and push it to the Directus database.

__init__(config)[source]

Init the synchronizer.

Parameters

config (dict) – The configuration dictionary.

sync()[source]

Fetch sync meta data from the history SQLite file and push it to the Directus database.

revitron.analyze.providers

This submodule is a collection of data providers that are used to extract information from a given Revit model.

Classes:

AbstractDataProvider(config)

The abstract data provider.

ElementAreaProvider(config)

This data provider returns the accumulated area of a set of elements after applying all filters that are defined in the provider configuration.

ElementCountProvider(config)

This data provider returns the count of filtered elements after applying all filters that are defined in the provider configuration.

ElementLengthProvider(config)

This data provider returns the accumulated length of a set of elements after applying all filters that are defined in the provider configuration.

ElementVolumeProvider(config)

This data provider returns the accumulated area of a set of elements after applying all filters that are defined in the provider configuration.

WarningCountProvider(config)

This data provider returns the number of warnings in a model.

class AbstractDataProvider(config)[source]

Bases: object

The abstract data provider. A data provider must implement a run() method that actually defines the extracted data.

Methods:

__init__(config)

Init a new data provider with a given configuration.

run()

The abstract method for data extraction.

Attributes:

dataType

The data type property defines the data type of the provided data in the database.

valueType

The value type property defines the type of the provided data in the database, such as length, area, volume or count.

__init__(config)[source]

Init a new data provider with a given configuration.

Parameters

config (dict) – The data provider configuration

property dataType

The data type property defines the data type of the provided data in the database.

Returns

The data type that is used for provided values in the database

Return type

string

abstract run()[source]

The abstract method for data extraction. This method must be implemented by a data provider.

abstract property valueType

The value type property defines the type of the provided data in the database, such as length, area, volume or count.

Returns

The value type

Return type

string

class ElementAreaProvider(config)[source]

Bases: AbstractDataProvider

This data provider returns the accumulated area of a set of elements after applying all filters that are defined in the provider configuration.

Methods:

__init__(config)

Init a new data provider with a given configuration.

run()

Apply filters and accumulate the area of the filtered elements.

Attributes:

dataType

The area data type is real.

valueType

The value type is area.

__init__(config)

Init a new data provider with a given configuration.

Parameters

config (dict) – The data provider configuration

property dataType

The area data type is real.

Returns

The data type

Return type

string

run()[source]

Apply filters and accumulate the area of the filtered elements.

Returns

The accumulated area

Return type

integer

property valueType

The value type is area.

Returns

The value type

Return type

string

class ElementCountProvider(config)[source]

Bases: AbstractDataProvider

This data provider returns the count of filtered elements after applying all filters that are defined in the provider configuration.

Methods:

__init__(config)

Init a new data provider with a given configuration.

run()

Run the data provider and return the number of filtered elements.

Attributes:

dataType

The data type property defines the data type of the provided data in the database.

valueType

The value type for the counter is count.

__init__(config)

Init a new data provider with a given configuration.

Parameters

config (dict) – The data provider configuration

property dataType

The data type property defines the data type of the provided data in the database.

Returns

The data type that is used for provided values in the database

Return type

string

run()[source]

Run the data provider and return the number of filtered elements.

Returns

The number of filtered elements

Return type

integer

property valueType

The value type for the counter is count.

Returns

The value type

Return type

string

class ElementLengthProvider(config)[source]

Bases: AbstractDataProvider

This data provider returns the accumulated length of a set of elements after applying all filters that are defined in the provider configuration.

Methods:

__init__(config)

Init a new data provider with a given configuration.

run()

Apply filters and accumulate the length of the filtered elements.

Attributes:

dataType

The length data type is real.

valueType

The value type is length.

__init__(config)

Init a new data provider with a given configuration.

Parameters

config (dict) – The data provider configuration

property dataType

The length data type is real.

Returns

The data type

Return type

string

run()[source]

Apply filters and accumulate the length of the filtered elements.

Returns

The accumulated length

Return type

integer

property valueType

The value type is length.

Returns

The value type

Return type

string

class ElementVolumeProvider(config)[source]

Bases: AbstractDataProvider

This data provider returns the accumulated area of a set of elements after applying all filters that are defined in the provider configuration.

Methods:

__init__(config)

Init a new data provider with a given configuration.

run()

Apply filters and accumulate the volume of the filtered elements.

Attributes:

dataType

The volume data type is real.

valueType

The value type is volume.

__init__(config)

Init a new data provider with a given configuration.

Parameters

config (dict) – The data provider configuration

property dataType

The volume data type is real.

Returns

The data type

Return type

string

run()[source]

Apply filters and accumulate the volume of the filtered elements.

Returns

The accumulated area

Return type

integer

property valueType

The value type is volume.

Returns

The value type

Return type

string

class WarningCountProvider(config)[source]

Bases: AbstractDataProvider

This data provider returns the number of warnings in a model.

Methods:

__init__(config)

Init a new data provider with a given configuration.

run()

Get the number of warnings.

Attributes:

dataType

The data type property defines the data type of the provided data in the database.

valueType

The value type is count.

__init__(config)

Init a new data provider with a given configuration.

Parameters

config (dict) – The data provider configuration

property dataType

The data type property defines the data type of the provided data in the database.

Returns

The data type that is used for provided values in the database

Return type

string

run()[source]

Get the number of warnings.

Returns

The number of warnings

Return type

integer

property valueType

The value type is count.

Returns

The value type

Return type

string

revitron.analyze.storage

This submodule is a collection of storage drivers that can be used to store extracted model information in different types of formats such as SQLite, JSON or API based databases.

Classes:

AbstractStorageDriver(config)

The abstract storage driver is the base class for all storage driver classes.

DirectusAPI(host, token, collection)

The DirectusAPI class provides the needed tools to interact with the Directus API.

DirectusStorageDriver(config)

This storage driver handles storing snapshots to in Directus using the Directus API.

JSONStorageDriver(config)

This storage driver handles appending snapshots to JSON files.

SQLiteStorageDriver(config)

This storage driver handles the connection to the SQLite database as well as the actual creation of the snapshots.

class AbstractStorageDriver(config)[source]

Bases: object

The abstract storage driver is the base class for all storage driver classes.

Methods:

__init__(config)

Init a new storage driver instance with a givenm configuration.

add(dataProviderResults, modelSize)

Add a new snapshot.

__init__(config)[source]

Init a new storage driver instance with a givenm configuration.

Parameters

config (dict) – The driver configuration

abstract add(dataProviderResults, modelSize)[source]

Add a new snapshot.

Parameters
class DirectusAPI(host, token, collection)[source]

Bases: object

The DirectusAPI class provides the needed tools to interact with the Directus API.

Methods:

__init__(host, token, collection)

Init a new API wrapper instance.

clearCache()

Clear the Directus cache.

collectionExists()

Test whether a collection exists.

createCollection()

Create the collection.

createField(name, dataType)

Create a field in the collection.

get(endpoint[, log])

Get data from a given endpoint.

getFields()

Get the fields list of a collection.

post(endpoint, data)

Post data to a given enpoint.

__init__(host, token, collection)[source]

Init a new API wrapper instance.

Parameters
  • host (string) – The API URL

  • token (string) – The API token that is used for authentication

  • collection (string) – The collection name

clearCache()[source]

Clear the Directus cache.

Returns

The response data

Return type

dict

collectionExists()[source]

Test whether a collection exists.

Returns

True if the collection exists

Return type

bool

createCollection()[source]

Create the collection.

Returns

The response data

Return type

dict

createField(name, dataType)[source]

Create a field in the collection.

Parameters
  • name (string) – The field name

  • dataType (string) – The data type for the field

Returns

The response data

Return type

dict

get(endpoint, log=True)[source]

Get data from a given endpoint.

Parameters
  • endpoint (string) – The Directus API endpoint

  • log (bool, optional) – Enable logging. Defaults to True.

Returns

The reponse dictionary

Return type

dict

getFields()[source]

Get the fields list of a collection.

Returns

The list of fields

Return type

list

post(endpoint, data)[source]

Post data to a given enpoint.

Parameters
  • endpoint (string) – The endpoint

  • data (dict) – The data dict

Returns

The reponse dictionary

Return type

dict

class DirectusStorageDriver(config)[source]

Bases: AbstractStorageDriver

This storage driver handles storing snapshots to in Directus using the Directus API.

Methods:

__init__(config)

Init a new Directus storage driver instance with a givenm configuration.

add(dataProviderResults, modelSize)

Send a POST request to the Directus API in order store a snapshot

__init__(config)[source]

Init a new Directus storage driver instance with a givenm configuration.

Parameters

config (dict) – The driver configuration

add(dataProviderResults, modelSize)[source]

Send a POST request to the Directus API in order store a snapshot

Parameters
class JSONStorageDriver(config)[source]

Bases: AbstractStorageDriver

This storage driver handles appending snapshots to JSON files.

Methods:

__init__(config)

Init a new storage driver instance with a givenm configuration.

add(dataProviderResults, modelSize)

Add a new item to JSON file.

__init__(config)

Init a new storage driver instance with a givenm configuration.

Parameters

config (dict) – The driver configuration

add(dataProviderResults, modelSize)[source]

Add a new item to JSON file.

Parameters
class SQLiteStorageDriver(config)[source]

Bases: AbstractStorageDriver

This storage driver handles the connection to the SQLite database as well as the actual creation of the snapshots.

Methods:

__init__(config)

Init a new storage driver instance with a givenm configuration.

add(dataProviderResults, modelSize)

Add a new row to the snapshots table.

__init__(config)

Init a new storage driver instance with a givenm configuration.

Parameters

config (dict) – The driver configuration

add(dataProviderResults, modelSize)[source]

Add a new row to the snapshots table.

Parameters

revitron.ui

The revitron.ui module provides a set of helpers for creating UI elements in pyRevit.

Submodules
revitron.ui.button

A basic button module that integrates well into Revitron windows.

Classes:

Button(*args, **kwargs)

A simple Ok/Cancel button to be used in Revitron windows.

class Button(*args: Any, **kwargs: Any)[source]

Bases: Button

A simple Ok/Cancel button to be used in Revitron windows.

Methods:

OnClick()

The OnClick handler function.

__init__(text, window[, cancel])

Initialize a new Button instance.

create(window, containerName, text[, cancel])

A helper to easily create a new button instance

OnClick()[source]

The OnClick handler function.

__init__(text, window, cancel=False, **kwargs)[source]

Initialize a new Button instance.

Parameters
  • text (string) – The button label text

  • window (object) – The parent window object

  • cancel (bool, optional) – If true, the window is closed without returning data. Defaults to False.

static create(window, containerName, text, cancel=True)[source]

A helper to easily create a new button instance

Parameters
  • window (object) – The parent window object

  • containerName (string) – The name of the parent container

  • text (strict) – The button label text

  • cancel (bool, optional) – The cancel option for the button. Defaults to True.

revitron.ui.form

This submodule contains a collection of basic form elements.

Classes:

CheckBox()

A simple checkbox component.

Label()

A simple label component.

SelectBox()

A dropdown field.

TextBox()

A text input field

class CheckBox[source]

Bases: object

A simple checkbox component.

Methods:

create(window, containerName, key, input[, ...])

A helper function that creates checkbox form element.

static create(window, containerName, key, input, title=None)[source]

A helper function that creates checkbox form element.

Parameters
  • window (object) – The parent window object

  • containerName (string) – The name of the parent container

  • key (string) – The key that references the value in the window values dictionary

  • input (mixed) – The input value

  • title (string, optional) – The checkbox title. Defaults to the key.

class Label[source]

Bases: object

A simple label component.

Methods:

create(window, containerName, text)

A helper function that creates a label component.

static create(window, containerName, text)[source]

A helper function that creates a label component.

Parameters
  • window (object) – The parent window object

  • containerName (string) – The name of the parent container

  • text (string) – The label text

class SelectBox[source]

Bases: object

A dropdown field.

Methods:

create(window, containerName, key, options, ...)

Create a select dropdown in a specific container of a given window.

static create(window, containerName, key, options, input, title=None)[source]

Create a select dropdown in a specific container of a given window.

Parameters
  • window (Window) – The Revitron Window object

  • containerName (string) – The name of the target container

  • key (string) – The key

  • options (dict|list) – The dict or list of options

  • input (dict|string) – The value for the field - a configuration dict where ‘key’ stores the value, or simply a string

  • title (string, optional) – An optional title. Defaults to None.

class TextBox[source]

Bases: object

A text input field

Methods:

create(window, containerName, key, input[, ...])

Create a text box in a specific container of a given window.

static create(window, containerName, key, input, title=None, default='')[source]

Create a text box in a specific container of a given window.

Parameters
  • window (Window) – The Revitron Window object

  • containerName (string) – The name of the target container

  • key (string) – The key

  • input (dict|string) – The value for the field - a configuration dict where ‘key’ stores the value, or simply a string

  • title (string, optional) – An optional title. Defaults to None.

revitron.ui.window

The window submodule contains classes for generating UI windows.

Classes:

AbstractWindow(*args, **kwargs)

An abstract base window class.

SimpleWindow(*args, **kwargs)

A simple window.

TabWindow(*args, **kwargs)

A window where the content is split into multiple custom tabs.

class AbstractWindow(*args: Any, **kwargs: Any)[source]

Bases: FlexForm

An abstract base window class.

Methods:

__init__(title[, width, height])

Init a new window object.

close()

Close the window

getContainer(name)

Get the container within the window by name.

__init__(title, width=520, height=620, **kwargs)[source]

Init a new window object.

Parameters
  • title (string) – The window title

  • width (int, optional) – The window width. Defaults to 520.

  • height (int, optional) – The window height. Defaults to 620.

close()[source]

Close the window

getContainer(name)[source]

Get the container within the window by name.

Parameters

name (name) – The container name

Returns

The container in the window

Return type

object

class SimpleWindow(*args: Any, **kwargs: Any)[source]

Bases: AbstractWindow

A simple window.

Methods:

__init__(title[, width, height, ...])

Init a new simple window.

close()

Close the window

getContainer(name)

Get the container within the window by name.

getValues()

Get the values of all form elements in the window and store them in the values dictionary.

__init__(title, width=520, height=620, cancelButtonText='Cancel', okButtonText='OK', **kwargs)[source]

Init a new simple window.

Parameters
  • title (string) – The window title

  • width (int, optional) – The window width. Defaults to 520.

  • height (int, optional) – The window height. Defaults to 620.

  • cancelButtonText (str, optional) – The cancel button text. Defaults to ‘Cancel’.

  • okButtonText (str, optional) – The OK button text. Defaults to ‘OK’.

close()

Close the window

getContainer(name)

Get the container within the window by name.

Parameters

name (name) – The container name

Returns

The container in the window

Return type

object

getValues()[source]

Get the values of all form elements in the window and store them in the values dictionary.

class TabWindow(*args: Any, **kwargs: Any)[source]

Bases: AbstractWindow

A window where the content is split into multiple custom tabs.

Methods:

__init__(title, tabs[, width, height, ...])

Init a new tabbed window.

close()

Close the window

getContainer(name)

Get the container within the window by name.

getValues()

Get the values of all form elements in the window and store them in the values dictionary.

__init__(title, tabs, width=520, height=620, cancelButtonText='Cancel', okButtonText='OK', **kwargs)[source]

Init a new tabbed window.

Parameters
  • title (string) – The window title

  • tabs (list) – The list of tab names

  • width (int, optional) – The window width. Defaults to 520.

  • height (int, optional) – The window height. Defaults to 620.

  • cancelButtonText (str, optional) – The cancel button text. Defaults to ‘Cancel’.

  • okButtonText (str, optional) – The OK button text. Defaults to ‘OK’.

close()

Close the window

getContainer(name)

Get the container within the window by name.

Parameters

name (name) – The container name

Returns

The container in the window

Return type

object

getValues()[source]

Get the values of all form elements in the window and store them in the values dictionary.

Submodules

revitron.boundingbox

The boundingbox submodule complements the Revit API bounding box methods by a simple helper class for working with bounding box elements.

Classes:

BoundingBox(element)

A BoundingBox class instance is a wrapper element for Revit bounding box object.

class BoundingBox(element)[source]

Bases: object

A BoundingBox class instance is a wrapper element for Revit bounding box object.

Create a new instance as follows:

bbox = revitron.BoundingBox(element)

Or even:

bbox = _(element).getBbox()

Attributes:

Max

The Max point of the bounding box.

Min

The Min point of the bounding box.

Methods:

__init__(element)

Inits a new BoundingBox instance for an element.

containsXY(bbox2)

Checks whether the bounding box contains another bounding box.

getCenterPoint()

Returns the center point of the bounding box.

hasPointXY(point)

Checks whether a point is inside a bounding box.

property Max

The Max point of the bounding box.

Returns

A Revit XYZ object

Return type

object

property Min

The Min point of the bounding box.

Returns

A Revit XYZ object

Return type

object

__init__(element)[source]

Inits a new BoundingBox instance for an element. In case the element has a scope box applied, the scope box’s bounding box is taken. In case the element has no scope box, but is a view plan, the crop box is used. The default Revit bounding box is used for all other elements.

Parameters

element (object) – A Revit Element

containsXY(bbox2)[source]

Checks whether the bounding box contains another bounding box. Only in X and Y dimensions.

Example:

contains = _(element1).getBbox().containsXY(_(element2).getBbox())
Parameters

bbox2 (object) – A bounding box object

Returns

True if the bounding box entirely contains bbox2

Return type

boolean

getCenterPoint()[source]

Returns the center point of the bounding box.

Returns

A Revit XYZ object.

Return type

object

hasPointXY(point)[source]

Checks whether a point is inside a bounding box. Only in X and Y dimensions.

Parameters

point (object) – A point object

Returns

True if the bounding box has the point inside

Return type

boolean

revitron.category

To simplify the interaction with Revit categories, the category submodule provides the Category and BuiltInCategory classes in order to access Revit category objects as well as builtin categories by name.

Classes:

BuiltInCategory(name)

A wrapper class for builtin category objects which can be instantiated by name.

Category(name)

A wrapper class for category objects which can be instantiated by a category name.

class BuiltInCategory(name)[source]

Bases: object

A wrapper class for builtin category objects which can be instantiated by name.

You can get the Revit BuitlInCategory class object by providing a name as follows:

bic = revitron.BuiltInCategory('OST_Walls').get()

For convenience reasons, it is also valid to skip the OST_ prefix and simply do:

bic = revitron.BuiltInCategory('Walls').get()

In case you only know the natural category name and want to get the BuiltInCategory instead, you can also use that one. For example to get the OST_BeamAnalyticalTags BuiltInCategory, you can do simply:

bic = revitron.BuiltInCategory('Analytical Beam Tags').get()

A full list of category names can be found here.

Methods:

__init__(name)

Get the BuiltInCategory by its name, its name without the OST_ prefix or even its natural category name.

get()

Return the BuiltInCategory class.

__init__(name)[source]

Get the BuiltInCategory by its name, its name without the OST_ prefix or even its natural category name. A full list of category names can be found here.

Example:

bic = revitron.BuiltInCategory('OST_Walls').get()
bic = revitron.BuiltInCategory('Walls').get()

Use the natural name to get for example OST_BeamAnalyticalTags:

bic = revitron.BuiltInCategory('Analytical Beam Tags').get()
Parameters

name (name) – The name, the name without the OST_ prefix or even the natural category name

get()[source]

Return the BuiltInCategory class.

Returns

The BuiltInCategory class

Return type

class

class Category(name)[source]

Bases: object

A wrapper class for category objects which can be instantiated by a category name.

You can get the Revit Category class object by providing a name as follows:

category = revitron.Category('name').get()

Methods:

__init__(name)

Init a new Category by name.

get()

Returns the category object.

getBic()

Returns the built-in category for a given category.

__init__(name)[source]

Init a new Category by name.

Parameters

name (string) – The category name

get()[source]

Returns the category object.

Returns

The category object

Return type

object

getBic()[source]

Returns the built-in category for a given category.

Returns

The built-in category

Return type

object

revitron.create

The create submodule and its Create class contain helpful shorthand methods to create Revit elements and families programatically. For example a centered room tag can be created as follows:

tag = revitron.Create.roomTag(self.element, self.getBboxCenter())

Note that some methods are also directly accessible in element classes such as Room:

tag = _(room).tagCenter()

Classes:

Create()

A collection of shorthand methods to create Revit elements.

class Create[source]

Bases: object

A collection of shorthand methods to create Revit elements.

Methods:

GridLineLinear(start, end, name)

Create a new linear grid line.

familyDoc(template, savePath)

Creates a new familiy document from a given template and saves it.add()

familyExtrusion(familyDoc, curveArrayArray, ...)

Creates an extrusion within a given family document.

familyInstance(familySymbolId, location[, ...])

Creates a new family instance.

roomTag(room, location[, typeId, viewId])

Creates a room tag for a given room element.

view3D()

Create a new 3D view.

static GridLineLinear(start, end, name)[source]

Create a new linear grid line.

Parameters
  • start (object) – A Revit XYZ element

  • end (object) – A Revit XYZ element

  • name (string) – The grid name

Returns

A Revit grid element

Return type

object

static familyDoc(template, savePath)[source]

Creates a new familiy document from a given template and saves it.add()

Parameters
  • template (string) – The template name without the .rft extension.

  • savePath (string) – The full path of the family file to be saved as.

Returns

A reference to the newly created family document.

Return type

object

static familyExtrusion(familyDoc, curveArrayArray, sketchPlane, height=10.0, location=False, isSolid=True)[source]

Creates an extrusion within a given family document.

Parameters
  • familyDoc (object) – A reference to a family document.

  • curveArrayArray (object) – A Revit API CurveArrArray.

  • sketchPlane (object) – A Revit API SketchPlane.

  • height (float, optional) – The extrusion height. Defaults to 10.0.

  • location (object, optional) – A Revit API XYZ point object. Defaults to False.

  • isSolid (bool, optional) – Soild (True) or void (False). Defaults to True.

Returns

The extrusion element.

Return type

object

static familyInstance(familySymbolId, location, structuralType=False, view=None)[source]

Creates a new family instance.

Example:

transaction = revitron.Transaction()
instance = revitron.Create.familyInstance(familySymbolId, location)
transaction.commit()
Parameters
  • familySymbolId (object) – A Revit API family symbol ID.

  • location (object) – A Revit API XYZ point.

  • structuralType (object, optional) – A Revit API structural type of False for NonStructural. Defaults to False.

  • view (object, optional) – A Revit view, Defaults to None. Note that structuralType and view can not be used together.

Returns

The family instance.

Return type

object

static roomTag(room, location, typeId=False, viewId=False)[source]

Creates a room tag for a given room element.

Parameters
  • room (object) – A Revit room element

  • location (object) – A Revit point object

  • typeId (ElementId, optional) – An optional Id of a tag type. Defaults to False.

  • viewId (ElementId, optional) – An optional Id of a view. Defaults to the currently active view.

Returns

The Revit RoomTag element

Return type

object

static view3D()[source]

Create a new 3D view.

Returns

A Revit 3D view element

Return type

object

revitron.document

The document submodule contains classes to interact with the currently active Revit document or store individual project configurations within a model.

Classes:

Document([doc])

A basic wrapper class for Revit documents.

DocumentConfigStorage()

The DocumentConfigStorage allows for easily storing project configuration items.

class Document(doc=None)[source]

Bases: object

A basic wrapper class for Revit documents.

Basic examples are:

path = revitron.Document().getPath()
if revitron.Document().isFamily():
    pass

In case you want to work with any other model than the active one, it is possible to change the context to that model using the with statement. Changing the context to another model will internally redefine the revitron.DOC property within the scope of that with statement. Therefore it is also possible to use a revitron.Filter instance on any model by just using a filter within a with statement:

with revitron.Document(doc):
    fltr = revitron.Filter().noTypes()
    elements = fltr.getElements()

Methods:

__enter__()

Set revitron.DOC to the document of the current Document class instance.

__exit__(execType, execValue, traceback)

Restore the original context.

__init__([doc])

Inits a new Document instance.

getDuplicateInstances([preferOlderElement])

Returns a list of duplicate family instances.

getLinkedDocuments([scope])

Returns a dictionary of all linked documents.

getPath()

Returns the path to the document.

isFamily()

Checks whether the document is a family.

isOpen(path)

Checks whether a document is open by passing its path.

synchronize([compact, comment])

Synchronize the document.

__enter__()[source]

Set revitron.DOC to the document of the current Document class instance.

By default that will just be the active document and therefore revitron.DOC stays unchanged.

__exit__(execType, execValue, traceback)[source]

Restore the original context.

Parameters
  • execType (string) – The execution type

  • execValue (string) – The execution value

  • traceback (mixed) – The traceback

__init__(doc=None)[source]

Inits a new Document instance.

Parameters

doc (object, optional) – Any document instead of the active one. Defaults to None.

getDuplicateInstances(preferOlderElement=False)[source]

Returns a list of duplicate family instances. By default, the list contains always the younger more recently created duplicate instance.

Note

This method requires Revit 2018 or newer!

Parameters

preferOlderElement (bool, optional) – Optionally return the list with the older instances. Defaults to False.

Returns

A list with duplicate instances, either the younger or the older ones.

Return type

list

getLinkedDocuments(scope=None)[source]

Returns a dictionary of all linked documents. The key is the ID of the link and the value is the actual document object.

Parameters

scope (mixed, optional) – List or view ID. Defaults to None.

Returns

A dictionary of all linked documents.

Return type

dict

getPath()[source]

Returns the path to the document.

Returns

The path

Return type

string

isFamily()[source]

Checks whether the document is a family.

Returns

True in case the document is a family

Return type

boolean

static isOpen(path)[source]

Checks whether a document is open by passing its path.

Parameters

path (string) – The path

Returns

True in case the document is open

Return type

boolean

synchronize(compact=True, comment='')[source]

Synchronize the document.

Parameters
  • compact (bool, optional) – Compact while synchronizing. Defaults to True.

  • comment (str, optional) – A comment for the synch that shows up in the log. Defaults to ‘’.

Returns

True on success

Return type

boolean

class DocumentConfigStorage[source]

Bases: object

The DocumentConfigStorage allows for easily storing project configuration items.

Getting configuration items:

config = revitron.DocumentConfigStorage().get('namespace.item')

The returned config item can be a string, a number, a list or a dictionary. It is also possible to define a default value in case the item is not defined in the storage:

from collections import defaultdict
config = revitron.DocumentConfigStorage().get('namespace.item', defaultdict())

Setting configuration items works as follows:

revitron.DocumentConfigStorage().set('namespace.item', value)

Methods:

__init__()

Inits a new DocumentConfigStorage object.

get(key[, default])

Returns storage entry for a given key.

set(key, data)

Updates or creates a config storage entry.

__init__()[source]

Inits a new DocumentConfigStorage object.

get(key, default=None)[source]

Returns storage entry for a given key.

Example:

config = revitron.DocumentConfigStorage()
item = config.get('name')
Parameters
  • key (string) – The key of the storage entry

  • default (mixed, optional) – An optional default value. Defaults to None.

Returns

The stored value

Return type

mixed

set(key, data)[source]

Updates or creates a config storage entry.

Example:

config = revitron.DocumentConfigStorage()
config.set('name', value)
Parameters
  • key (string) – The storage entry key

  • data (mixed) – The value of the entry

revitron.element

This submodule provides convenient wrappers for the interaction with elements. Getting parameter values or other information can be quite complicated using the plain Revit API. Methods like revitron.Element(element).get(parameter) simplify that process.

Note

Note that there is also the _() shortcut function available to be even more efficient in getting properties of Revit elements. More here

For example getting a parameter value or even a bounding box object works as follows:

form revitron import _
value = _(element).get('parameter')
boundingBox = _(element).getBbox()

Or setting parameter values:

_(element).set('parameter', value)

Classes:

Element(element)

A wrapper class for Revit elements.

class Element(element)[source]

Bases: object

A wrapper class for Revit elements.

Example:

value = revitron.Element(element).get('parameter')

Or in short:

from revitron import _
value = _(element).get('parameter')

Methods:

__getattr__(name)

Define default method to be returned on attribute errors.

__init__(element)

Inits a new element instance.

delete()

Delete an element.

get(paramName)

Returns a parameter value.

getBbox()

Returns a bounding box for the element.

getCategoryName()

Returns the category name of the element.

getClassName()

Returns the class name of the element.

getDependent([filterClass])

Returns a list of dependent elements.

getFamilyAndTypeName()

Returns the family name of the element.

getFamilyName()

Returns the family name of the element.

getFromType(paramName)

Returns a parameter value of the element type.

getGeometry()

Return the Revitron Geometry instance for this element.

getParameter(paramName)

Returns a parameter object.

getTags()

Get possibly existing tags of an element.

isNotOwned()

Checks whether an element is owned by another user.

isType()

Checks whether an element is a type or not.

set(paramName, value[, paramType])

Sets a parameter value.

Attributes:

element

The actual Revit element.

__getattr__(name)[source]

Define default method to be returned on attribute errors.

Since this is a generic element class that is extended by other more specialized classes such as the Room class, a default method along with an error message is returned when accidently calling a special methods that only exists in one of the derived classes on an element of another class.

Parameters

name (string) – The name of the called method

Returns

An empty method

Return type

method

__init__(element)[source]

Inits a new element instance.

Parameters

element (object) – The Revit element or an element ID

delete()[source]

Delete an element.

Example:

_(element).delete()
property element

The actual Revit element.

Returns

The Revit element object

Return type

object

get(paramName)[source]

Returns a parameter value.

Example:

value = _(element).get('name')
Parameters

paramName (string) – The name of the parameter

Returns

The parameter value

Return type

mixed

getBbox()[source]

Returns a bounding box for the element.

Returns

The bounding box or false on error

Return type

object

getCategoryName()[source]

Returns the category name of the element.

Returns

The category name

Return type

string

getClassName()[source]

Returns the class name of the element.

Returns

The class name

Return type

string

getDependent(filterClass=None)[source]

Returns a list of dependent elements.

Parameters

filterClass (class, optional) – An optional class to filter the list of dependent elements by. Defaults to None.

Returns

The list with the dependent Revit elements.

Return type

list

getFamilyAndTypeName()[source]

Returns the family name of the element.

Returns

The family name

Return type

string

getFamilyName()[source]

Returns the family name of the element.

Returns

The family name

Return type

string

getFromType(paramName)[source]

Returns a parameter value of the element type.

Example:

value = _(element).getFromType('name')
Parameters

paramName (string) – The name of the parameter

Returns

The parameter value

Return type

mixed

getGeometry()[source]

Return the Revitron Geometry instance for this element.

Returns

A Revitron Geometry object

Return type

object

getParameter(paramName)[source]

Returns a parameter object.

Parameters

paramName (string) – The name of the parameter

Returns

The parameter object

Return type

object

getTags()[source]

Get possibly existing tags of an element.

Returns

A list of Revit tag objects depending on the element class

Return type

list

isNotOwned()[source]

Checks whether an element is owned by another user.

Returns

True if the element is not owned by another user.

Return type

boolean

isType()[source]

Checks whether an element is a type or not.

Returns

True if element is a type.

Return type

bool

set(paramName, value, paramType=False)[source]

Sets a parameter value.

Example:

_(element).set('name', 'value', 'type')

Some possible parameter types are:

  • Text

  • Integer

  • Number

  • Length

  • Angle

  • Material

  • YesNo

  • MultilineText

  • FamilyType

You can find a list of all types here.

Parameters
  • paramName (string) – The parameter name

  • value (mixed) – The value

  • paramType (string, optional) – The parameter type. Defaults to ‘Text’.

Returns

The element instance

Return type

object

revitron.excel

This submodule contains helper classes to access and modify Microsoft Excel files. The following example demonstrates how to write data to table cells in a sheet created from a template:

book = revitron.ExcelWorkbook(xlsx)
sheet = book.newWorksheetFromTemplate('Template', 'Name')
sheet.setCell(5, 1, 'Value')

Classes:

ExcelWorkbook(file)

A wrapper class for Excel workbooks.

ExcelWorksheet(worksheet)

A wrapper class for modifying Excel worksheet cells.

class ExcelWorkbook(file)[source]

Bases: object

A wrapper class for Excel workbooks.

Methods:

__init__(file)

Inits a new ExcelWorkbook instance.

close([save])

Closes and optionally saves a workbook file.

getWorksheet(name)

Returns a Excel worksheet for a given name

newWorksheetFromTemplate(template, name)

Creates a new worksheet as a copy from a given template.

__init__(file)[source]

Inits a new ExcelWorkbook instance.

Parameters

file (string) – The path to the xls file

close(save=True)[source]

Closes and optionally saves a workbook file.

Parameters

save (bool, optional) – If True, the file is saved before closing. Defaults to True.

getWorksheet(name)[source]

Returns a Excel worksheet for a given name

Parameters

name (string) – The worksheet name

Returns

An Excel worksheet object instance

Return type

object

newWorksheetFromTemplate(template, name)[source]

Creates a new worksheet as a copy from a given template.

Parameters
  • template (string) – The template name

  • name (string) – The name of the new copy

Returns

An ExcelWorksheet instance

Return type

object

class ExcelWorksheet(worksheet)[source]

Bases: object

A wrapper class for modifying Excel worksheet cells.

Methods:

__init__(worksheet)

Inits a new ExcelWorksheet instance.

setCell(row, column, value)

Writes data to a cell of the current worksheet.

__init__(worksheet)[source]

Inits a new ExcelWorksheet instance.

Parameters

file (object) – An Excel worksheet object

setCell(row, column, value)[source]

Writes data to a cell of the current worksheet.

Parameters
  • row (integer) – The row

  • column (integer) – The column

  • value (mixed) – The value

Returns

The ExcelWorkbook instance

Return type

object

revitron.export

The export submodule hosts all classes related to sheet export such as DWG and PDF. For example sending the currently active sheet to a PDF printer in the network works as follows:

exporter = revitron.PDFExporter(printerAddress, printerPath)
exporter.printSheet(revitron.ACTIVE_VIEW,
                                   'A0',
                                   'Landscape',
                                   'C:/pdf',
                                   '{Sheet Number}-{Sheet Title}')

Please check out the export tool of the Revitron UI extension to learn how to export a selection of sheets with a felxible configuration stored in a document.

Classes:

CSVExporter()

Export a schedule as CSV named by a file naming template.

DWGExporter(setupName)

Export sheets as DWG named by a file naming template.

PDFExporter(printer, output)

Export sheets as PDF named by a file naming template.

class CSVExporter[source]

Bases: object

Export a schedule as CSV named by a file naming template.

Methods:

__init__()

Inits a new CSVExporter instance.

exportSchedule(schedule, directory[, ...])

Exports a schedule.

__init__()[source]

Inits a new CSVExporter instance.

exportSchedule(schedule, directory, template=False, delimiter=';', hasTitle=False)[source]

Exports a schedule.

Parameters
  • schedule (object) – A Revit schedule

  • directory (string) – A custom output directory. Defaults to False.

  • template (string, optional) – A name template. Defaults to ‘{View Name}’.

  • delimiter (string, optional) – A csv delimiter. Defaults to ‘;’.

  • hasTitle (bool, optional) – Set True to export schedule title. Defaults to False.

Returns

The path of the exported CSV. False on error.

Return type

string

class DWGExporter(setupName)[source]

Bases: object

Export sheets as DWG named by a file naming template.

Methods:

__init__(setupName)

Inits a new DWGExporter instance.

exportSheet(sheet, directory, unit[, template])

Exports a sheet.

__init__(setupName)[source]

Inits a new DWGExporter instance.

Parameters

setupName (string) – The name of a stored export setup

exportSheet(sheet, directory, unit, template=False)[source]

Exports a sheet.

Parameters
  • sheet (object) – A Revit sheet

  • directory (string) – The export directory

  • unit (object) – The export unit

  • template (string, optional) – A name template. Defaults to ‘{Sheet Number}-{Sheet Name}’.

Returns

The path of the exported PDF. False on error.

Return type

string

class PDFExporter(printer, output)[source]

Bases: object

Export sheets as PDF named by a file naming template.

Methods:

__init__(printer, output)

Inits a new PDFExporter instance.

printSheet(sheet, size[, orientation, ...])

Prints a sheet.

tempOutputPattern(sheet)

Create a glob pattern to identify a printed PDF in the system output directory to be able to move it to its correct location and rename it according to the given template.

__init__(printer, output)[source]

Inits a new PDFExporter instance.

Parameters
  • printer (string) – The printer network adress

  • output (string) – The printer output directory

printSheet(sheet, size, orientation='Landscape', colorMode='Color', directory=False, template=False)[source]

Prints a sheet.

Parameters
  • sheet (object) – A Revit sheet

  • size (string) – A size name like A0 or A4

  • orientation (string, optional) – The orientation, ‘Landscape’ or ‘Portrait’. Defaults to ‘Landscape’.

  • colorMode (string, optional) – The color setting for the printed sheets. Defaults to ‘Color’.

  • directory (string, optional) – A custom output directory. Defaults to False.

  • template (string, optional) – A name template. Defaults to ‘{Sheet Number}-{Sheet Name}’.

Returns

The path of the exported PDF. False on error.

Return type

string

tempOutputPattern(sheet)[source]

Create a glob pattern to identify a printed PDF in the system output directory to be able to move it to its correct location and rename it according to the given template.

Please note that the PDF network printer has to be configured to save PDFs following the below naming scheme:

[Revit File] - Sheet - [Sheet Number] - [Sheet Name].pdf

For example:

Project1 - Sheet - A101 - Unnamed.pdf
Parameters

sheet (object) – A Revit sheet objetc

Returns

The generated glob pattern

Return type

string

revitron.externalreference

This submodule contains a wrapper class for external references within a Revit document.

Classes:

ExternalReference(ref)

An external reference wrapper class.

class ExternalReference(ref)[source]

Bases: object

An external reference wrapper class.

Methods:

__init__(ref)

Inits a new ExternalReference instance.

__init__(ref)[source]

Inits a new ExternalReference instance.

Parameters

ref (object) – A Revit external reference instance.

revitron.failure

This is a helper submodule for handling errors and warnings occuring in transactions.

Classes:

ErrorCatcher(*args, **kwargs)

This class implements the IFailurePreprocessor interface and can be used as a preprocessor for rolling back on errors.

FailureHandler()

A basic failure handler.

WarningAndErrorCatcher(*args, **kwargs)

This class implements the IFailurePreprocessor interface and can be used as a preprocessor for rolling back on errors and muting all warnings.

WarningCatcher(*args, **kwargs)

This class implements the IFailurePreprocessor interface and can be used as a preprocessor for muting all warnings.

class ErrorCatcher(*args: Any, **kwargs: Any)[source]

Bases: IFailuresPreprocessor

This class implements the IFailurePreprocessor interface and can be used as a preprocessor for rolling back on errors.

Parameters

IFailuresPreprocessor (interface) – The Revit API IFailuresPreprocessor interface.

Methods:

PreprocessFailures(failuresAccessor)

Preprocess all failures and returns a ProceedWithRollBack result on error.

PreprocessFailures(failuresAccessor)[source]

Preprocess all failures and returns a ProceedWithRollBack result on error.

Parameters

failuresAccessor (object) – The Revit API FailuresAccessor object.

Returns

The FailureProcessingResult.ProceedWithRollBack result on error or FailureProcessingResult.Continue.

Return type

object

class FailureHandler[source]

Bases: object

A basic failure handler.

Methods:

preprocess(failuresAccessor[, ...])

Preprocess failures by optionally suppressing all warnings and rolling back transactions on error.

static preprocess(failuresAccessor, suppressWarnings=False, rollbackOnError=False)[source]

Preprocess failures by optionally suppressing all warnings and rolling back transactions on error.

Parameters
  • failuresAccessor (object) – A Revit failure accessor object.

  • suppressWarnings (bool, optional) – Optionally suppress all warnings. Defaults to False.

  • rollbackOnError (bool, optional) – Optionally roll back on errors. Defaults to False.

Returns

A Revit FailureProcessingResult

Return type

object

class WarningAndErrorCatcher(*args: Any, **kwargs: Any)[source]

Bases: IFailuresPreprocessor

This class implements the IFailurePreprocessor interface and can be used as a preprocessor for rolling back on errors and muting all warnings.

Parameters

IFailuresPreprocessor (interface) – The Revit API IFailuresPreprocessor interface.

Methods:

PreprocessFailures(failuresAccessor)

Preprocess all failures and returns a ProceedWithRollBack result on error.

PreprocessFailures(failuresAccessor)[source]

Preprocess all failures and returns a ProceedWithRollBack result on error.

Parameters

failuresAccessor (object) – The Revit API FailuresAccessor object.

Returns

The FailureProcessingResult.ProceedWithRollBack result on error or FailureProcessingResult.Continue.

Return type

object

class WarningCatcher(*args: Any, **kwargs: Any)[source]

Bases: IFailuresPreprocessor

This class implements the IFailurePreprocessor interface and can be used as a preprocessor for muting all warnings.

Parameters

IFailuresPreprocessor (interface) – The Revit API IFailuresPreprocessor interface.

Methods:

PreprocessFailures(failuresAccessor)

Preprocess all failures and deletes all warnings to suppress dialog boxes.

PreprocessFailures(failuresAccessor)[source]

Preprocess all failures and deletes all warnings to suppress dialog boxes.

Parameters

failuresAccessor (object) – The Revit API FailuresAccessor object.

Returns

The FailureProcessingResult.Continue result

Return type

object

revitron.filter

The filter submodule is one of the most essential one within the Revitron package. Its main purpose is taking over the heavy lifting of filtering elements in the Revit database and complementing the standard Revit API FilteredElementCollector class with the ability to filter collections by parameter values:

elements = (
    revitron.Filter
    .byStringEquals('param', 'value')
    .noTypes()
    .getElements()
)

Note that you can invert a filter by providing a the third argument for a string filter as follows:

elements = (
    revitron.Filter
    .byStringEquals('param', 'value', True)
    .noTypes()
    .getElements()
)

Note

In order to filter elements in another model instead of the active one, it is possible to change the document context using the with statement.

The document context can be changed as follows:

with revitron.Document(anyOtherDoc):
    fltr = revitron.Filter().noTypes()
    elements = fltr.getElements()

Classes:

Filter([scope])

A filter class based on the FilteredElementCollector class.

class Filter(scope=None)[source]

Bases: object

A filter class based on the FilteredElementCollector class.

Methods:

__init__([scope])

Inits a new Filter instance.

byCategory(name)

Filters the collection by a category name or a built-in category name.

byClass(cls)

Filters the collection by class.

byIntersection(element)

Reduces the set of elements to the ones that are intersecting a given element.

byNumberIsEqual(paramName, value[, invert])

Filters the collection by parameter values equal to a given number.

byNumberIsGreater(paramName, value[, invert])

Filters the collection by parameter values greater than a given number.

byNumberIsGreaterOrEqual(paramName, value[, ...])

Filters the collection by parameter values greater than or equal to a given number.

byNumberIsLess(paramName, value[, invert])

Filters the collection by parameter values smaller than a given number.

byNumberIsLessOrEqual(paramName, value[, invert])

Filters the collection by parameter values smaller than or equal to a given number.

byOneInCsv(evaluatorName, paramName, csv[, ...])

Filters the collection by testing whether a string contains at lease one ot the items in a CSV list.

byRegex(paramName, regex[, invert])

Filters a collection by a given regex.

byStringBeginsWith(paramName, value[, invert])

Filters the collection by a string at the beginning of a parameter value.

byStringContains(paramName, value[, invert])

Filters the collection by a string contained in a parameter.

byStringContainsOneInCsv(paramName, csv[, ...])

Filters the collection by testing whether a string contains at lease one ot the items in a CSV list.

byStringEndsWith(paramName, value[, invert])

Filters the collection by a string at the end of a parameter.

byStringEquals(paramName, value[, invert])

Filters the collection by a string that equals a parameter value.

byStringEqualsOneInCsv(paramName, csv[, invert])

Filters the collection by testing whether a string equals at lease one ot the items in a CSV list.

getElementIds()

Get the collection as element IDs.

getElements()

Get the collection as elements.

noTypes()

Removes all types from collection.

onlyTypes()

Reduce to collection to types only.

__init__(scope=None)[source]

Inits a new Filter instance.

Parameters

scope (Element ID or list of elements, optional) – The optional scope. It can be either a view Id or a list of elements. Defaults to None.

byCategory(name)[source]

Filters the collection by a category name or a built-in category name.

Note that there are basically three valid types that can be used as the filter argument. The first two use the name of a built-in category (with or without the OST_ prefix):

fltr = revitron.Filter().byCategory('Walls')
fltr = revitron.Filter().byCategory('OST_Walls')

The third type uses a natural category name to find a corresponding built-in category to filter, here OST_BeamAnalyticalTags:

fltr = revitron.Filter().byCategory('Analytical Beam Tags')
Parameters

name (string) – A category or built-in category name

Returns

The Filter instance

Return type

object

byClass(cls)[source]

Filters the collection by class.

Example:

fltr = revitron.Filter()
cls = Autodesk.Revit.DB.CurveElement
ids = fltr.byClass(cls).noTypes().getElementIds()

Alternatively it is also possible to use a class name as string instead:

fltr = revitron.Filter()
ids = fltr.byClass('CurveElement').noTypes().getElementIds()
Parameters

cls (class) – A class or class name to filter the elements

Returns

The Filter instance

Return type

object

byIntersection(element)[source]

Reduces the set of elements to the ones that are intersecting a given element.

Parameters

element (objetc) – A Revit element

Returns

The Filter instance

Return type

object

byNumberIsEqual(paramName, value, invert=False)[source]

Filters the collection by parameter values equal to a given number.

Example:

fltr = revitron.Filter()
ids = fltr.byNumberIsEqual('Area', 5).noTypes().getElementIds()
Parameters
  • paramName (string) – The parameter name

  • value (number) – The numeric value to compare to

  • invert (boolean) – Inverts the filter

Returns

The collector

Return type

object

byNumberIsGreater(paramName, value, invert=False)[source]

Filters the collection by parameter values greater than a given number.

Example:

fltr = revitron.Filter()
ids = fltr.byNumberIsGreater('Area', 5).noTypes().getElementIds()
Parameters
  • paramName (string) – The parameter name

  • value (number) – The numeric value to compare to

  • invert (boolean) – Inverts the filter

Returns

The collector

Return type

object

byNumberIsGreaterOrEqual(paramName, value, invert=False)[source]

Filters the collection by parameter values greater than or equal to a given number.

Example:

fltr = revitron.Filter()
fltr = fltr.byNumberIsGreaterOrEqual('Area', 5).noTypes()
ids = fltr.getElementIds()
Parameters
  • paramName (string) – The parameter name

  • value (number) – The numeric value to compare to

  • invert (boolean) – Inverts the filter

Returns

The collector

Return type

object

byNumberIsLess(paramName, value, invert=False)[source]

Filters the collection by parameter values smaller than a given number.

Example:

fltr = revitron.Filter()
ids = fltr.byNumberIsLess('Area', 5).noTypes().getElementIds()
Parameters
  • paramName (string) – The parameter name

  • value (number) – The numeric value to compare to

  • invert (boolean) – Inverts the filter

Returns

The collector

Return type

object

byNumberIsLessOrEqual(paramName, value, invert=False)[source]

Filters the collection by parameter values smaller than or equal to a given number.

Example:

fltr = revitron.Filter()
ids = fltr.byNumberIsLessOrEqual('Area', 5).noTypes().getElementIds()
Parameters
  • paramName (string) – The parameter name

  • value (number) – The numeric value to compare to

  • invert (boolean) – Inverts the filter

Returns

The collector

Return type

object

byOneInCsv(evaluatorName, paramName, csv, invert=False)[source]

Filters the collection by testing whether a string contains at lease one ot the items in a CSV list.

This method is the base method for the byStringContainsOneInCsv and byStringEqualsOneInCsv methods.

Note

that by setting invert to True, all elements that match one of the items will be removed from the collection.

Parameters
  • evaluatorName (method) – The filter method to be used to filter

  • paramName (string) – The name of the parameter

  • csv (string) – A comma separated list of items

  • invert (bool, optional) – Inverts the filter. Defaults to False.

Returns

The Filter instance

Return type

object

byRegex(paramName, regex, invert=False)[source]

Filters a collection by a given regex.

Parameters
  • paramName (string) – The name of the parameter to be matched.

  • regex (string) – The regex.

  • invert (bool, optional) – Inverts the filter. Defaults to False.

Returns

The Filter instance

Return type

object

byStringBeginsWith(paramName, value, invert=False)[source]

Filters the collection by a string at the beginning of a parameter value.

Example:

fltr = revitron.Filter()
fltr = fltr.byStringBeginsWith('param', 'value').noTypes()
ids = fltr.getElementIds()
Parameters
  • paramName (string) – The parameter name

  • value (string) – The searched string

  • invert (boolean) – Inverts the filter

Returns

The collector

Return type

object

byStringContains(paramName, value, invert=False)[source]

Filters the collection by a string contained in a parameter.

Example:

fltr = revitron.Filter()
fltr = fltr.byStringContains('param', 'value').noTypes()
ids = fltr.getElementIds()
Parameters
  • paramName (string) – The parameter name

  • value (string) – The searched string

  • invert (boolean) – Inverts the filter

Returns

The collector

Return type

object

byStringContainsOneInCsv(paramName, csv, invert=False)[source]

Filters the collection by testing whether a string contains at lease one ot the items in a CSV list.

Note

that by setting invert to True, all elements that match one of the items will be removed from the collection.

Example:

fltr = revitron.Filter()
fltr = fltr.byStringContainsOneInCsv('Family', 'some, words', False)
fltr = fltr.noTypes()
elements = fltr.getElements()
Parameters
  • paramName (string) – The name of the parameter

  • csv (string) – A comma separated list of items

  • invert (bool, optional) – Inverts the filter. Defaults to False.

Returns

The Filter instance

Return type

object

byStringEndsWith(paramName, value, invert=False)[source]

Filters the collection by a string at the end of a parameter.

Parameters
  • paramName (string) – The parameter name

  • value (string) – The searched string

  • invert (boolean) – Inverts the filter

Returns

The collector

Return type

object

byStringEquals(paramName, value, invert=False)[source]

Filters the collection by a string that equals a parameter value.

Example:

fltr = revitron.Filter()
ids = fltr.byStringEquals('param', 'value').noTypes().getElementIds()
Parameters
  • paramName (string) – The parameter name

  • value (string) – The searched string

  • invert (boolean) – Inverts the filter

Returns

The collector

Return type

object

byStringEqualsOneInCsv(paramName, csv, invert=False)[source]

Filters the collection by testing whether a string equals at lease one ot the items in a CSV list.

Note

that by setting invert to True, all elements that match one of the items will be removed from the collection.

Example:

fltr = revitron.Filter()
fltr = fltr.byStringEqualsOneInCsv('Family', 'some, words', False)
fltr = fltr.noTypes()
elements = fltr.getElements()
Parameters
  • paramName (string) – The name of the parameter

  • csv (string) – A comma separated list of items

  • invert (bool, optional) – Inverts the filter. Defaults to False.

Returns

The Filter instance

Return type

object

getElementIds()[source]

Get the collection as element IDs.

Returns

The list of excluded element IDs

Return type

list

getElements()[source]

Get the collection as elements.

Returns

The list of excluded elements

Return type

list

noTypes()[source]

Removes all types from collection.

Returns

The Filter instance

Return type

object

onlyTypes()[source]

Reduce to collection to types only.

Returns

The Filter instance

Return type

object

revitron.geometry

The Geometry submodule and its Geometry class contain useful helpers for handling Revit element geometries. Note that it is possible to use the _() shorthand to get the geometry of an element as follows:

geometry = _(element).getGeometry()

The full syntax without using the shorthand can also be used:

geometry = revitron.Geometry(element)

Classes:

Geometry(element)

A collection of useful methods for handling Revit element geometries.

GeometryUtils()

The GeometryUtils class contains a collection of static utility methods for dealing with geometry related tasks.

class Geometry(element)[source]

Bases: object

A collection of useful methods for handling Revit element geometries.

Methods:

__init__(element)

Inits a new Geometry instance.

getCurves([curveType])

Get a list of all curves by type of a given element.

getFaces()

Get a list of all faces of a given element.

getSolids()

Get a list of all solids of a given element.

__init__(element)[source]

Inits a new Geometry instance.

Parameters

element (object) – A Revit element

getCurves(curveType='Line')[source]

Get a list of all curves by type of a given element.

Note

Child classes of Autodesk.DB.Curve can be used.

Parameters
  • curveType (str, optional) – The type of curve to return.

  • 'Line'. (Defaults to) –

Returns

A list of curve objects

Return type

list

getFaces()[source]

Get a list of all faces of a given element.

Returns

A list of face objects

Return type

list

getSolids()[source]

Get a list of all solids of a given element.

Returns

A list of solid objects

Return type

list

class GeometryUtils[source]

Bases: object

The GeometryUtils class contains a collection of static utility methods for dealing with geometry related tasks.

Methods:

getAbsoluteAngleXY(base, endpoint)

Get the absolute angle between 0 and 360 degrees of a vector counter clockwise relative to the X-axis.

getAngleXY(base, reference, endpoint)

Get the angle from a vector to a reference.

getBoundaryPoints(boundary)

Get a list of points from a given boundary that is usually returned by methods such as GetBoundarySegments.

polygonContainsPointXY(polygonPoints, point)

Check whether a given polygon that is planar to a horizontal surface contains a given point.

static getAbsoluteAngleXY(base, endpoint)[source]

Get the absolute angle between 0 and 360 degrees of a vector counter clockwise relative to the X-axis.

Parameters
  • base (XYZ) – The base point that represents 0,0 of the coordinate system

  • endpoint (XYZ) – The endpoint of the line starting from the basepoint that represents the vector in question

Returns

The absolute angle between 0 and 360 degrees

Return type

float

static getAngleXY(base, reference, endpoint)[source]

Get the angle from a vector to a reference. Note that the result returns positiv as well as negative angles depending on the relative location of the reference vector.

Parameters
  • base (XYZ) – The base point that represents 0,0 of the coordinate system

  • reference (XYZ) – The endpoint of the reference line starting from the basepoint

  • endpoint (XYZ) – The endpoint of the line starting from the basepoint that represents the vector in question

Returns

The angle

Return type

float

static getBoundaryPoints(boundary)[source]

Get a list of points from a given boundary that is usually returned by methods such as GetBoundarySegments.

Parameters

boundary (list) – A list of boundary segment lists

Returns

The list of points that define a boundary polygon

Return type

list

static polygonContainsPointXY(polygonPoints, point)[source]

Check whether a given polygon that is planar to a horizontal surface contains a given point. Note that both, the polygon as well as the point must share common Z values.

The algorithm accumulates all angles (positive and negative) between neighboring lines that span from a given point to all vertices of the polygon. In case the accumulated absolute value equals 360, the point is located inside the polygon.

Parameters
  • polygonPoints (list) – A list of points

  • point (XYZ) – The point that is tested

Returns

True, if the polygon contains the point

Return type

boolean

revitron.grid

The Grid submodule contains all classes that are related to Revit grids. It helps you to quickly get filtered lists of grid lines or find closests intersections to given points in orthogonal grids.

Classes:

Grid([typeFilterCsv])

The Grid class is the base class for other grid classes such as the OrthoGrid class.

OrthoGrid([typeFilterCsv])

In contrast to the Grid class, the OrthoGrid object only contains grid lines that are orthogonal.

OrthoGridIntersection(lineX, lineY)

An OrthoGridIntersection object contains all relevant information about an intersection of two orthogonal grid lines.

class Grid(typeFilterCsv=False)[source]

Bases: object

The Grid class is the base class for other grid classes such as the OrthoGrid class. A grid object contains a collection of grid lines. That collection can be filtered when creating a grid instance.

The following example will create a grid object based on all grid lines with a type name that either contains “main” or “sub”:

grid = revitron.Grid('main, sub')

Alternatively you can create a OrthoGrid object only including orthogonal grid lines:

ortho = revitron.OrthoGrid('main, sub')

Methods:

__init__([typeFilterCsv])

Creates a new Grid instance.

Attributes:

lines

The dict of grid lines contained in the Grid object where the grid line name serves as key.

__init__(typeFilterCsv=False)[source]

Creates a new Grid instance. A comma separated string can be passed as an argument to filter the grid elements by their type name.

Parameters

typeFilterCsv (string, optional) – A CSV filter. Defaults to False.

property lines

The dict of grid lines contained in the Grid object where the grid line name serves as key.

Returns

A dict of Revit grid line elements where the grid name serves as key

Return type

dict

class OrthoGrid(typeFilterCsv=False)[source]

Bases: Grid

In contrast to the Grid class, the OrthoGrid object only contains grid lines that are orthogonal.

The following example will create a orthogonal grid object based on all grid lines with a type name that either contains “main” or “sub”:

grid = revitron.OrthoGrid('main, sub')

Methods:

__init__([typeFilterCsv])

Creates a new Grid instance.

closestIntersectionToPointBottomRight(point)

Find the grid intersection that is closest to a given point on the bottom right side.

closestIntersectionToPointTopLeft(point)

Find the grid intersection that is closest to a given point on the top left side.

newLineX(X, name)

Create a new grid line that is defined by single X value and therefore is parallel to the Y axis.

newLineY(Y, name)

Create a new grid line that is defined by single Y value and therefore is parallel to the X axis.

Attributes:

lines

An object that contains one X and one Y property, both dicts containing grid line elements where the grid name serves as key.

__init__(typeFilterCsv=False)

Creates a new Grid instance. A comma separated string can be passed as an argument to filter the grid elements by their type name.

Parameters

typeFilterCsv (string, optional) – A CSV filter. Defaults to False.

closestIntersectionToPointBottomRight(point)[source]

Find the grid intersection that is closest to a given point on the bottom right side.

Parameters

point (object) – A Revit XYZ object

Returns

A OrthoGridIntersection object

Return type

object

closestIntersectionToPointTopLeft(point)[source]

Find the grid intersection that is closest to a given point on the top left side.

Parameters

point (object) – A Revit XYZ object

Returns

A OrthoGridIntersection object

Return type

object

property lines

An object that contains one X and one Y property, both dicts containing grid line elements where the grid name serves as key.

The X property contains all grid lines that are defined by a single value on the X axis and the the Y property contains all grid lines that are defined by a single value on the Y axis.

Note

Note that the lines of the X property are by definition always parallel to the Y axis since they are defined by a single X value and vice versa.

Returns

An object containing orthogonal grid elements split into X and Y lines

Return type

object

static newLineX(X, name)[source]

Create a new grid line that is defined by single X value and therefore is parallel to the Y axis.

Note

Note that the grid line created by this methods marks a position on the X axis that is represented by a line that is parallel to the Y axis.

Parameters
  • X (float) – The position on the X axis

  • name (string) – The name of the new grid line

Returns

A Revit grid element

Return type

object

static newLineY(Y, name)[source]

Create a new grid line that is defined by single Y value and therefore is parallel to the X axis.

Note

Note that the grid line created by this methods marks a position on the Y axis that is represented by a line that is parallel to the X axis.

Parameters
  • Y (float) – The position on the Y axis

  • name (string) – The name of the new grid line

Returns

A Revit grid element

Return type

object

class OrthoGridIntersection(lineX, lineY)[source]

Bases: object

An OrthoGridIntersection object contains all relevant information about an intersection of two orthogonal grid lines.

Attributes:

X

The X coordinate of the intersection on plan.

Y

The Y coordinate of the intersection on plan.

lineX

The Revit grid line element that is defined by a single value on the X axis and is parallel to the Y axis.

lineY

The Revit grid line element that is defined by a single value on the Y axis and is parallel to the X axis.

nameX

The name of the grid line element that is defined by a single value on the X axis.

nameY

The name of the grid line element that is defined by a single value on the Y axis.

Methods:

__init__(lineX, lineY)

Create a new intersection object based on two orthogonal grid lines.

property X

The X coordinate of the intersection on plan.

Returns

The X coordinate

Return type

float

property Y

The Y coordinate of the intersection on plan.

Returns

The Y coordinate

Return type

float

__init__(lineX, lineY)[source]

Create a new intersection object based on two orthogonal grid lines.

Parameters
  • gridX (object) – A Revit grid element

  • gridY (object) – A Revit grid element

property lineX

The Revit grid line element that is defined by a single value on the X axis and is parallel to the Y axis.

Returns

A Revit grid element

Return type

object

property lineY

The Revit grid line element that is defined by a single value on the Y axis and is parallel to the X axis.

Returns

A Revit grid element

Return type

object

property nameX

The name of the grid line element that is defined by a single value on the X axis.

Returns

The name of the grid

Return type

string

property nameY

The name of the grid line element that is defined by a single value on the Y axis.

Returns

The name of the grid

Return type

string

revitron.parameter

Besides the element and the filter submodules, this submodule is one of the most elementary submodules of the Revitron package. It contains all classes related to parameters, built-in parameters and value providers.

Classes:

BuiltInParameterNameMap()

A helper class for mapping lists of built-in parameter names to their representation visible to the user.

Parameter(element, name)

A wrapper class for interacting with element parameters.

ParameterNameList()

A helper class for listing all parameter names in the active document.

ParameterTemplate(element, template[, sanitize])

Create a string based on a parameter template where parameter names are wrapped in {...} and get substituted with their value.

ParameterUtils()

A collection of static parameter utilities.

ParameterValueProviders(name)

A wrapper for parameter value providers used for filtering elements.

class BuiltInParameterNameMap[source]

Bases: object

A helper class for mapping lists of built-in parameter names to their representation visible to the user.

Methods:

__init__()

Inits a new BuiltInParameterNameMap instance.

get(name)

Return the list of matching built-in parameters for a given name.

__init__()[source]

Inits a new BuiltInParameterNameMap instance. The map is a dictionary where the key is a parameter name that is visible to the user and the value is a list of built-in parameters represented by that name.

get(name)[source]

Return the list of matching built-in parameters for a given name.

Parameters

name (string) – The parameter name visible to the user

Returns

The list of built-in parameter ids

Return type

list

class Parameter(element, name)[source]

Bases: object

A wrapper class for interacting with element parameters.

Note

In most cases it is not required to actually create a Parameter class instance in order to access paramter values of a given element. The fastest way of getting or setting parameter values is using the _(element).get('parameter') shortcut function or an instance of the revitron.element class.

Methods:

__init__(element, name)

Init a new parameter instance.

exists()

Checks if a parameter exists.

get()

Return the parameter value.

getDouble()

Return the parameter value as double.

getElementId()

Return the parameter value as ElementId.

getInteger()

Return the parameter value as integer.

getString()

Return the parameter value as string.

getValueString()

Return the parameter value as value string.

hasValue()

Checks if parameter has a value.

set(value[, paramType])

Set a parameter value for an element.

Attributes:

definitionType

The definition parameter type.

unit

The displayed unit type of a parameter.

__init__(element, name)[source]

Init a new parameter instance.

Getting a parameter by name visible to the user:

value = revitron.Parameter(element, 'parameterName').get()

Or the short version:

value = _(element).get('parameterName')

To be language independent it is possible to get a parameter value by its built-in parameter name like for example the view scale:

scale = _(view).get('VIEW_SCALE')
Parameters
  • element (object) – Revit element

  • name (string) – The parameter name or the name of a built-Iin parameter

property definitionType

The definition parameter type.

Returns

The definition parameter type name

Return type

string

exists()[source]

Checks if a parameter exists.

Returns

True if existing

Return type

boolean

get()[source]

Return the parameter value.

Note

As mentioned above, the fastest way of getting a parameter value is to use the get method of the revitron.Element class.

Returns

The value

Return type

mixed

getDouble()[source]

Return the parameter value as double.

Returns

The value

Return type

double

getElementId()[source]

Return the parameter value as ElementId.

Returns

The value

Return type

object

getInteger()[source]

Return the parameter value as integer.

Returns

The value

Return type

integer

getString()[source]

Return the parameter value as string.

Returns

The value

Return type

string

getValueString()[source]

Return the parameter value as value string.

Returns

The value

Return type

string

hasValue()[source]

Checks if parameter has a value.

Returns

True if the parameter has a value

Return type

boolean

set(value, paramType=False)[source]

Set a parameter value for an element. The parameter will be automatically created if not existing. The parameter type can be specified. If not type is given, it will be determined automatically in case of text, integer or float values.

Note

As mentioned above, the fastest way of setting a parameter value is to use the set method of the revitron.Element class.

Example:

_(element).set('name', 'value', 'type')

Some possible parameter types are:

  • Text

  • Integer

  • Number

  • Length

  • Angle

  • Material

  • YesNo

  • MultilineText

  • FamilyType

You can find a list of all types here.

Parameters
  • value (string) – The value

  • paramType (string, optional) – The parameter type

property unit

The displayed unit type of a parameter.

Note that since Revit 2021 the preferred return value is of type ForgeTypeId.

Returns

The displayed unit type (ForgeTypeId or DisplayUnitType)

Return type

mixed

class ParameterNameList[source]

Bases: object

A helper class for listing all parameter names in the active document.

Methods:

__init__()

Inits a new ParameterNameList instance including all parameter names in the document.

get()

Returns the parameter list.

__init__()[source]

Inits a new ParameterNameList instance including all parameter names in the document.

get()[source]

Returns the parameter list.

Returns

The list with all parameters in the document.

Return type

list

class ParameterTemplate(element, template, sanitize=True)[source]

Bases: object

Create a string based on a parameter template where parameter names are wrapped in {...} and get substituted with their value:

This sheet has the number {Sheet Number}

It is also possible to get parameter values from the project information instead by wrapping the parameter names in {%...%} instead:

This sheet of the project {%Project Name%} has the number {Sheet Number}

Methods:

__init__(element, template[, sanitize])

Inits a new ParameterTemplate instance.

reCallback(match)

The callback function used by the get() method.

render()

Returns the rendered template string.

__init__(element, template, sanitize=True)[source]

Inits a new ParameterTemplate instance.

Parameters
  • element (object) – A Revit element

  • template (string) – A template string

  • sanitize (bool, optional) – Optionally sanitize the returned string. Defaults to True.

reCallback(match)[source]

The callback function used by the get() method.

Parameters

match (object) – The regex match object

Returns

The processed string

Return type

string

render()[source]

Returns the rendered template string.

Returns

The rendered string

Return type

string

class ParameterUtils[source]

Bases: object

A collection of static parameter utilities.

Methods:

bind(category, paramName[, paramType, ...])

Bind a new parameter to a category.

externalDefinitionCreationOptions(paramName, ...)

Create proper definition creation options based on a given name and type, that is passed as string.

getParameterTypeFromDefinition(definition)

Get the parameter type as string from a definition.

getStorageType(name)

Get the storage type of a parameter definition by name.

static bind(category, paramName, paramType='Text', typeBinding=False)[source]

Bind a new parameter to a category.

Parameters
  • category (string) – The built-in category

  • paramName (string) – The parameter name

  • paramType (string) –

    The parameter type (see here) Defaults to “Text”.

  • typeBinding (bool) – Bind parameter to type instead of instance. Defaults to False.

Returns

Returns True on success and False on error.

Return type

boolean

static externalDefinitionCreationOptions(paramName, paramType)[source]

Create proper definition creation options based on a given name and type, that is passed as string.

Parameters
  • paramName (string) – The name of the parameter definition

  • paramType (string) – The name of the type

Returns

The ExternalDefinitionCreationOptions object

Return type

ExternalDefinitionCreationOptions

static getParameterTypeFromDefinition(definition)[source]

Get the parameter type as string from a definition.

Parameters

definition (object) – The parameter definition

Returns

The name of the type

Return type

string

static getStorageType(name)[source]

Get the storage type of a parameter definition by name.

Parameters

name (string) – The parameter name

Returns

The storage type

Return type

string

class ParameterValueProviders(name)[source]

Bases: object

A wrapper for parameter value providers used for filtering elements.

Methods:

__init__(name)

Inits a new ParameterValueProviders instance by name.

get()

Returns the list of value providers.

__init__(name)[source]

Inits a new ParameterValueProviders instance by name. Such an instance consists of a list of value providers matching a parameters with a name visible to the user. Note that this list can have more than one value provider, since a parameter name possible matches multiple built-in parameters.

Parameters

name (string) – Name

get()[source]

Returns the list of value providers.

Returns

The list of value providers

Return type

list

revitron.raytrace

The raytrace submodule contains helper methods for easily raytracing intersections or similar.

Classes:

Raytracer(point, view3D)

The Raytracer class.

class Raytracer(point, view3D)[source]

Bases: object

The Raytracer class.

Methods:

__init__(point, view3D)

Inits a raytracer instance.

findIntersection(direction[, elementFilter])

Finds and returns an intersection point of a ray in a given direction based on an optional element filter.

__init__(point, view3D)[source]

Inits a raytracer instance.

Parameters
  • point (object) – A Revit XYZ object used as the base point for the raytracing.

  • view3D (object) – A Revit 3D view.

findIntersection(direction, elementFilter=None)[source]

Finds and returns an intersection point of a ray in a given direction based on an optional element filter.

Parameters
  • direction (object) – A Revit XYZ vector.

  • elementFilter (mixed, optional) – Either a list of Revit element IDs or a Revit ElementClassFilter. Defaults to None.

Returns

A Revit XYZ object or False on errors.

Return type

object

revitron.room

This submodule contains a wrapper classes for Revit room elements.

Classes:

Room(element)

A wrapper class for room elements.

class Room(element)[source]

Bases: Element

A wrapper class for room elements.

Methods:

__getattr__(name)

Define default method to be returned on attribute errors.

__init__(element)

Inits a new element instance.

delete()

Delete an element.

get(paramName)

Returns a parameter value.

getBbox()

Returns a bounding box for the element.

getBboxCenter([inRoomOnly])

Get the center point of a room's bounding box.

getBoundary()

Get the boundary of a given room.

getBoundaryInsetPoints([inset])

Get all points along an inset of the room boundary.

getBoundaryPoints()

Get all points along a room boundary.

getCategoryName()

Returns the category name of the element.

getClassName()

Returns the class name of the element.

getDependent([filterClass])

Returns a list of dependent elements.

getFamilyAndTypeName()

Returns the family name of the element.

getFamilyName()

Returns the family name of the element.

getFromType(paramName)

Returns a parameter value of the element type.

getGeometry()

Return the Revitron Geometry instance for this element.

getParameter(paramName)

Returns a parameter object.

getPointBottomLeft([inset])

Get the most bottom left point of a room boundary.

getPointBottomRight([inset])

Get the most bottom right point of a room boundary.

getPointClosest(point[, inset])

Get the point on a room boundary that is the closest to a given point.

getPointGrid([size, inset])

Generates a point grid based on a given size within the room boundary.

getPointTopLeft([inset])

Get the most top left point of a room boundary.

getPointTopRight([inset])

Get the most top right point of a room boundary.

getTags()

Get possibly existing tags of an element.

isNotOwned()

Checks whether an element is owned by another user.

isType()

Checks whether an element is a type or not.

set(paramName, value[, paramType])

Sets a parameter value.

traceHeight(view3D[, elementFilter, ...])

Traces the room heights and returns an object containing the min/max bottom and min/max top points.

Attributes:

element

The actual Revit element.

__getattr__(name)

Define default method to be returned on attribute errors.

Since this is a generic element class that is extended by other more specialized classes such as the Room class, a default method along with an error message is returned when accidently calling a special methods that only exists in one of the derived classes on an element of another class.

Parameters

name (string) – The name of the called method

Returns

An empty method

Return type

method

__init__(element)

Inits a new element instance.

Parameters

element (object) – The Revit element or an element ID

delete()

Delete an element.

Example:

_(element).delete()
property element

The actual Revit element.

Returns

The Revit element object

Return type

object

get(paramName)

Returns a parameter value.

Example:

value = _(element).get('name')
Parameters

paramName (string) – The name of the parameter

Returns

The parameter value

Return type

mixed

getBbox()

Returns a bounding box for the element.

Returns

The bounding box or false on error

Return type

object

getBboxCenter(inRoomOnly=False)[source]

Get the center point of a room’s bounding box.

Parameters

inRoomOnly (boolean) – Optionally only return a point in case the bounding box center is actually in the room

Returns

A Revit point object

Return type

object

getBoundary()[source]

Get the boundary of a given room.

Returns

A list of boundary segment curves

Return type

list

getBoundaryInsetPoints(inset=0.1)[source]

Get all points along an inset of the room boundary.

The inset is useful in cases where a point has to be used as a location for a tag and therefore should be located direktly on the boundary but a little bit more inside instead to avoid issues and warnings.

Parameters

inset (float, optional) – The inset. Defaults to 0.1.

Returns

The list of points

Return type

list

getBoundaryPoints()[source]

Get all points along a room boundary.

Returns

A list of points

Return type

list

getCategoryName()

Returns the category name of the element.

Returns

The category name

Return type

string

getClassName()

Returns the class name of the element.

Returns

The class name

Return type

string

getDependent(filterClass=None)

Returns a list of dependent elements.

Parameters

filterClass (class, optional) – An optional class to filter the list of dependent elements by. Defaults to None.

Returns

The list with the dependent Revit elements.

Return type

list

getFamilyAndTypeName()

Returns the family name of the element.

Returns

The family name

Return type

string

getFamilyName()

Returns the family name of the element.

Returns

The family name

Return type

string

getFromType(paramName)

Returns a parameter value of the element type.

Example:

value = _(element).getFromType('name')
Parameters

paramName (string) – The name of the parameter

Returns

The parameter value

Return type

mixed

getGeometry()

Return the Revitron Geometry instance for this element.

Returns

A Revitron Geometry object

Return type

object

getParameter(paramName)

Returns a parameter object.

Parameters

paramName (string) – The name of the parameter

Returns

The parameter object

Return type

object

getPointBottomLeft(inset=0.1)[source]

Get the most bottom left point of a room boundary.

Parameters

inset (float, optional) – An optional room boundary inset. Defaults to 0.1.

Returns

A Revit XYZ object

Return type

object

getPointBottomRight(inset=0.1)[source]

Get the most bottom right point of a room boundary.

Parameters

inset (float, optional) – An optional room boundary inset. Defaults to 0.1.

Returns

A Revit XYZ object

Return type

object

getPointClosest(point, inset=0.1)[source]

Get the point on a room boundary that is the closest to a given point.

Parameters
  • point (object) – A Revit XYZ object

  • inset (float, optional) – An optional room boundary inset. Defaults to 0.1.

Returns

A Revit XYZ object

Return type

object

getPointGrid(size=5, inset=0.05)[source]

Generates a point grid based on a given size within the room boundary.

Parameters
  • size (float, optional) – The maximum grid field size. Defaults to 5.00.

  • inset (float, optional) – The inset of the room boundary. Defaults to 0.05.

Returns

A list of Revit XYZ objects

Return type

list

getPointTopLeft(inset=0.1)[source]

Get the most top left point of a room boundary.

Parameters

inset (float, optional) – An optional room boundary inset. Defaults to 0.1.

Returns

A Revit XYZ object

Return type

object

getPointTopRight(inset=0.1)[source]

Get the most top right point of a room boundary.

Parameters

inset (float, optional) – An optional room boundary inset. Defaults to 0.1.

Returns

A Revit XYZ object

Return type

object

getTags()

Get possibly existing tags of an element.

Returns

A list of Revit tag objects depending on the element class

Return type

list

isNotOwned()

Checks whether an element is owned by another user.

Returns

True if the element is not owned by another user.

Return type

boolean

isType()

Checks whether an element is a type or not.

Returns

True if element is a type.

Return type

bool

set(paramName, value, paramType=False)

Sets a parameter value.

Example:

_(element).set('name', 'value', 'type')

Some possible parameter types are:

  • Text

  • Integer

  • Number

  • Length

  • Angle

  • Material

  • YesNo

  • MultilineText

  • FamilyType

You can find a list of all types here.

Parameters
  • paramName (string) – The parameter name

  • value (mixed) – The value

  • paramType (string, optional) – The parameter type. Defaults to ‘Text’.

Returns

The element instance

Return type

object

traceHeight(view3D, elementFilter=None, gridSize=5, inset=0.05)[source]

Traces the room heights and returns an object containing the min/max bottom and min/max top points.

Parameters
  • view3D (object) – A Revit 3D view.

  • elementFilter (mixed, optional) – Either a list of Revit element IDs or a Revit ElementClassFilter. Defaults to None.

  • gridSize (float, optional) – The maximum grid field size for the raytracing. Defaults to 5.00.

  • inset (float, optional) – The inset of the room boundary. Defaults to 0.05.

Returns

An object containing a top and bottom property.

Both properties are nested objects containing an Min and a Max value.

Return type

object

revitron.roomtag

A simple helper module for creating room tags.

Classes:

RoomTag()

This class contains methods to create room tags in given locations.

class RoomTag[source]

Bases: object

This class contains methods to create room tags in given locations.

Methods:

bottomLeft(room[, tagTypeId, viewId])

Create a room tag in the bottom left corner.

bottomRight(room[, tagTypeId, viewId])

Create a room tag in the bottom right corner.

center(room[, tagTypeId, viewId])

Create a room tag in the bounding box center.

create(room, location[, tagTypeId, viewId])

Create a room tag in a given location.

topLeft(room[, tagTypeId, viewId])

Create a room tag in the top left corner.

topRight(room[, tagTypeId, viewId])

Create a room tag in the top right corner.

static bottomLeft(room, tagTypeId=False, viewId=False)[source]

Create a room tag in the bottom left corner.

All existing room tags will be removed before automatically.

Parameters
  • room (object) – A Revit room element.

  • tagTypeId (ElementId, optional) – A Revit element Id of a custom tag type. Defaults to False.

  • viewId (ElementId, optional) – A Revit element Id a view. Defaults to False.

Returns

A Revit RoomTag element

Return type

object

static bottomRight(room, tagTypeId=False, viewId=False)[source]

Create a room tag in the bottom right corner.

All existing room tags will be removed before automatically.

Parameters
  • room (object) – A Revit room element.

  • tagTypeId (ElementId, optional) – A Revit element Id of a custom tag type. Defaults to False.

  • viewId (ElementId, optional) – A Revit element Id a view. Defaults to False.

Returns

A Revit RoomTag element

Return type

object

static center(room, tagTypeId=False, viewId=False)[source]

Create a room tag in the bounding box center.

All existing room tags will be removed before automatically.

Parameters
  • room (object) – A Revit room element.

  • tagTypeId (ElementId, optional) – A Revit element Id of a custom tag type. Defaults to False.

  • viewId (ElementId, optional) – A Revit element Id a view. Defaults to False.

Returns

A Revit RoomTag element

Return type

object

static create(room, location, tagTypeId=False, viewId=False)[source]

Create a room tag in a given location.

All existing room tags will be removed before automatically.

Parameters
  • location (object) – A Revit location point object.

  • tagTypeId (ElementId, optional) – A Revit element Id of a custom tag type. Defaults to False.

  • viewId (ElementId, optional) – A Revit element Id a view. Defaults to False.

Returns

A Revit RoomTag element

Return type

object

static topLeft(room, tagTypeId=False, viewId=False)[source]

Create a room tag in the top left corner.

All existing room tags will be removed before automatically.

Parameters
  • room (object) – A Revit room element.

  • tagTypeId (ElementId, optional) – A Revit element Id of a custom tag type. Defaults to False.

  • viewId (ElementId, optional) – A Revit element Id a view. Defaults to False.

Returns

A Revit RoomTag element

Return type

object

static topRight(room, tagTypeId=False, viewId=False)[source]

Create a room tag in the top right corner.

All existing room tags will be removed before automatically.

Parameters
  • room (object) – A Revit room element.

  • tagTypeId (ElementId, optional) – A Revit element Id of a custom tag type. Defaults to False.

  • viewId (ElementId, optional) – A Revit element Id a view. Defaults to False.

Returns

A Revit RoomTag element

Return type

object

revitron.selection

A small helper submodule to simplify accessing the list of selected elements.

Classes:

Selection()

A selection helper class.

class Selection[source]

Bases: object

A selection helper class.

Example:

for element in revitron.Selection.get():
        ...

Methods:

first()

Get the first elements of the list of selected elements.

get()

Get the currently selected elements.

set(ids)

Set the selection to a list of element ids.

static first()[source]

Get the first elements of the list of selected elements.

Returns

The first element in a list of selected elements

Return type

object

static get()[source]

Get the currently selected elements.

Returns

The list of selected elements

Return type

list

static set(ids)[source]

Set the selection to a list of element ids.

Parameters

ids (list) – A list of element ids

revitron.transaction

The transaction submodule contains a wrapper class to simplify the usage of transactions, transaction groups and subtransactions:

t = revitron.Transaction()
...
t.close()

Or alternatively you can also use the following syntax:

with revitron.Transaction():
    ...

A transaction group can be started using:

with revitron.TransactionGroup():
    ...

Classes:

BaseTransaction()

The base class for Revitron transaction classes.

Transaction([doc, suppressWarnings, ...])

A wrapper class for transactions and subtransactions.

TransactionGroup([doc])

The transaction group wrapper.

class BaseTransaction[source]

Bases: object

The base class for Revitron transaction classes. This class should not be used directly.

Methods:

__enter__()

Enter transaction context.

__exit__(execType, execValue, traceback)

Commit the transaction when leaving context.

__init__()

Init a basic transaction wrapper.

commit()

Commits the open transaction.

rollback()

Rolls back the open transaction.

__enter__()[source]

Enter transaction context.

__exit__(execType, execValue, traceback)[source]

Commit the transaction when leaving context.

__init__()[source]

Init a basic transaction wrapper.

commit()[source]

Commits the open transaction.

rollback()[source]

Rolls back the open transaction.

class Transaction(doc=None, suppressWarnings=False, rollbackOnError=False)[source]

Bases: BaseTransaction

A wrapper class for transactions and subtransactions. A subtransaction is started whenever there is already another active transaction in use. In case the transaction is not a subtransaction, it is possible to optionally suppress warnings and automatically roll back on errors.

Methods:

__enter__()

Enter transaction context.

__exit__(execType, execValue, traceback)

Commit the transaction when leaving context.

__init__([doc, suppressWarnings, ...])

Inits a new transaction.

commit()

Commits the open transaction.

rollback()

Rolls back the open transaction.

__enter__()

Enter transaction context.

__exit__(execType, execValue, traceback)

Commit the transaction when leaving context.

__init__(doc=None, suppressWarnings=False, rollbackOnError=False)[source]

Inits a new transaction.

Parameters
  • doc (object, optional) – An optional document to be used instead of the currently active one. Defaults to None.

  • suppressWarnings (bool, optional) – Optionally suppress any warning messages displayed during the transaction. Not available in subtransactions. Defaults to False.

  • rollbackOnError – (bool, optional): Optionally roll back automatically on errors. Not available in subtransactions. Defaults to False.

commit()

Commits the open transaction.

rollback()

Rolls back the open transaction.

class TransactionGroup(doc=False)[source]

Bases: BaseTransaction

The transaction group wrapper.

Methods:

__enter__()

Enter transaction context.

__exit__(execType, execValue, traceback)

Commit the transaction when leaving context.

__init__([doc])

Init a new transaction group.

assimilate()

Assimilates the open transaction group.

commit()

Commits the open transaction.

rollback()

Rolls back the open transaction.

__enter__()

Enter transaction context.

__exit__(execType, execValue, traceback)[source]

Commit the transaction when leaving context.

__init__(doc=False)[source]

Init a new transaction group.

Parameters

doc (bool, optional) – The document for the transaction. Defaults to False.

assimilate()[source]

Assimilates the open transaction group.

commit()

Commits the open transaction.

rollback()

Rolls back the open transaction.

revitron.transmissiondata

This submodule contains the TransmissionData class which allows for editing the paths of linked files without opening a model.

Classes:

TransmissionData(hostPath)

A transmission data wrapper.

class TransmissionData(hostPath)[source]

Bases: object

A transmission data wrapper.

Methods:

__init__(hostPath)

Inits a new TransmissionData instance.

listLinks()

List all links in the host document.

moveLinksOnDisk(source, target)

Moves all external CAD and RVT links on disk and relinks them.

replaceInPath(search, replace)

Search and replace in all link paths of the document.

write()

Writes the TransmissionData back to the model.

__init__(hostPath)[source]

Inits a new TransmissionData instance.

Parameters

hostPath (string) – The path of the host model

List all links in the host document.

moveLinksOnDisk(source, target)[source]

Moves all external CAD and RVT links on disk and relinks them.

Parameters
  • source (string) – The source directory

  • target (string) – The target directory

replaceInPath(search, replace)[source]

Search and replace in all link paths of the document.

Parameters
  • search (string) – The search string

  • replace (string) – The replacement string

write()[source]

Writes the TransmissionData back to the model.

revitron.unit

The unit module and its Unit class provide little helper for handling units in Revit.

Classes:

Unit()

The Unit class contains helpers for handling units.

class Unit[source]

Bases: object

The Unit class contains helpers for handling units.

Methods:

convertToInternalUnit(value, unit)

Convert a given value from a given unit into Revit's internal unit.

static convertToInternalUnit(value, unit)[source]

Convert a given value from a given unit into Revit’s internal unit.

Parameters
  • value (mixed) – A number or string value. Strings are converted to floats automatically.

  • unit (object) – A Revit DisplayUnitType or ForgeTypeId object

Returns

The converted number

Return type

number

revitron.view

This submodule provides helpers related to Revit views.

Classes:

ViewSheetList(sheets)

The ViewSheetList class creates a list of custom view objects based on a list of sheets.

class ViewSheetList(sheets)[source]

Bases: object

The ViewSheetList class creates a list of custom view objects based on a list of sheets.

Methods:

__init__(sheets)

Inits an new ViewSheetList object.

get()

Returns the list of view objects.

__init__(sheets)[source]

Inits an new ViewSheetList object.

Parameters

sheets (list) – A list with sheets or sheet ids

get()[source]

Returns the list of view objects. The view objects have the following properties:

  • id: The ID of the view

  • sheet: The sheet object where the view is placed on

  • view: The actual view object

The returned list can be used as follows:

sheets = revitron.Filter().byCategory('Sheets').getElements()
for view in revitron.ViewSheetList(sheets).get():
        print(view.id, view.sheet, view.view)
Returns

A list with view objects as described above

Return type

list

Command Line

Revitron ships its own little wrapper for the pyRevit CLI that includes some additional features such as the ability to handle cloud models and to pass configuration files.

revitron [command] "path\to\config.json"

Setup

In order to be able to run the revitron command from anywhere it has to be added to your path environment variable. You can do that manually or by running the following commands once:

cd path\to\revitron.lib
cli\setup

Standard Commands

Revitron ships with two default commands.

Command

Description

analyze

Creates analytical snapshots from models. More here.

compact

Compacts a model. The configuration JSON file only has to include model and revit fields.

Compact Example

The configuration for the compact command operating on cloud models looks as follows:

{
    "model": {
        "type": "cloud",
        "projectGUID":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "modelGUID":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "region": "EMEA"
    },
    "revit": "2022"
}

Alternatively local models have a slightly different configuration:

{
    "model": {
        "type": "local",
        "path": "C:\\path\\to\\model.rvt"
    },
    "revit": "2022"
}

The compacting can be started with the following command. Manually or as a command used in a task scheduler.

revitron compact "path\to\config.json"

Custom Commands

Revitron supports custom commands as well to be used with the CLI. In order to be used as a command, a command has to meet the following requirements for its location and its content.

Location

In order to be picked up as a valid command, a custom command file must have the .cli.py extension and be located somewhere subdirectory tree of the main extension directory of pyRevit. It is strongly recommended to ship commands as Revitron packages that will be installed automatically in the correct location by the Revitron package manager.

Anatomy

You can use one of the following example commands below in order to quickly get a custom command up and running:

import revitron
from cli import App, Config, getLogFromEnv

# Get the config dictionary from the JSON file.
config = Config().get()

# Get a log handle to use for logging.
log = getLogFromEnv().write
log('Hello')

# Open the model that is configured in the JSON file.
# Use App.open(True) in order to open and detach the file.
revitron.DOC = App.open(True)

# Implement your functionality here.
# Use the config dict in order to access your configuration stored
# in the JSON file that is passed as CLI argument.

revitron.DOC.Close(False)

In order to sync changes that have been applied by your command, you can use the following boiler plate that includes synching as well.

import revitron
from cli import App, Config, getLogFromEnv

config = Config().get()
log = getLogFromEnv().write
revitron.DOC = App.open(False)

# Implement your functionality here before synching ...

if revitron.Document().synchronize(compact=True, comment='Some comment'):
    log('Synching finished successfully')
else:
    log('Synching failed')

revitron.DOC.Close(False)

You can take a look at the included commands as simple but fully working examples for command files.

Model Analytics

Revitron ships with a small CLI wrapper that uses the pyRevit CLI in the background in order to automatically collect model analytics using a task scheduler such as the Windows Task Scheduler. The CLI analyzer is configured using a JSON file that is passed as argument. The configuration includes the model path, storage configuration, the Revit version and the data providers.

revitron analyze "path\to\config.json"

Introduction

Conceptually the revitron analyze config.json command reads a JSON file, opens the configured Revit version, opens the given model, creates data provider instances as configured and sends the extracted data to a storage driver.

https://github.com/revitron/revitron-charts/raw/master/images/charts.png

Data providers are basically not more than a class that filters elements and aggregates a certain property or counts certain items in a model. Storage drivers are interfaces to data storage formats such as JSON, SQLite or a RESTful API. However, for the time being, only Directus is supported as RESTful API.

Setup

In order to be able to run the revitron command from anywhere it has to be added to your path environment variable. You can do that manually or by running the following commands once:

cd path\to\revitron.lib
cli\setup

Configuration

As mentioned before, analytics jobs are configured using a JSON file. No coding is required at all. A basic configuration consits of four top fields:

Field

Description

model

the Revit model path information

revit

the Revit version to be used to run the analytics

storage

the storage configuration for the extracted data snapshots

providers

the actual configuartion for the data the has to be tracked

Note

You can find a set of example configuration in the official Github repository. Feel free to uses those configuration as template for your own projects.

A typical JSON file that can be used to create snapshots of a model’s accumulated room area looks as follows:

{
    "model": {
        "type": "cloud",
        "projectGUID":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "modelGUID":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "region": "EMEA"
    },
    "storage": {
        "driver": "Directus",
        "config": {
            "token": "YOUR_DIRECTUS_API_KEY",
            "host": "http://domain.com/",
            "collection": "Project Name"
        }
    },
    "revit": "2022",
    "providers": [
       {
            "name": "Room Area",
            "class": "ElementAreaProvider",
            "config": {
                "filters": [
                    {
                        "rule": "byCategory",
                        "args": ["Rooms"]
                    },
                    {
                        "rule": "byStringContains",
                        "args": ["Name", "Room"]
                    }
                ]
            }
        }
    ]
}

Model Path

The model path field contains information about where the source model is loaded from — local or cloud. Local models can be loaded by just providing a local file system path as demonstrated in the snippet below.

{
    "model": {
        "type": "local",
        "path": "C:\\path\\to\\model.rvt"
    }
}

Models that are stored in the BIM360 cloud require a bit more information, such as the project GUID, the model GUID and the region. You can use the Cloud → Cloud Model Info button in the Revitron UI in order to get the required GUIDs and the region information for the currently opened model.

{
    "model": {
        "type": "cloud",
        "projectGUID":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "modelGUID":"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
        "region": "EMEA"
    }
}

Storage Drivers

The storage driver can be configured using the storage field. It field takes a single configuration object that provides the required data for Revitron to write or connect. There are currently multiple options for storing the actual analytics snapshots — SQLite, JSON and Directus

JSON

In order to quickly get up and running and for testing the analytics configuration, the extracted snapshot data can be dumped into a JSON file.

{
    "storage": {
        "driver": "JSON",
        "config": {
            "file": "C:\\path\\to\\snapshots.json"
        }
    }
}
SQLite

Alternatively to JSON files it is also possible to use SQLite databases as local storage.

{
    "storage": {
        "driver": "SQLite",
        "config": {
            "file": "C:\\path\\to\\snapshots.sqlite"
        }
    }
}
Directus

The recommended but by far more complex solution is to send the snapshots data to a Directus instance. Directus is data platform that can be used in the cloud or self-hosted, installed on a local server. The cloud version even provides a free plan. After creating your Directus instance, you will have to create an API key in order to give Revitron write access.

Note

Using Directus for snapshots storage also enables you to make use of automatically generated analytics dashboards.

{
    "storage": {
        "driver": "Directus",
        "config": {
            "token": "YOUR_DIRECTUS_API_KEY",
            "host": "http://domain.com/url/to/directus",
            "collection": "Project Name"
        }
    }
}

Note

Storing the token in plain text in your configuration might not be the best solution. Alternatively it is therefore possible to reference any environment variable instead:

{
    "storage": {
        "driver": "Directus",
        "config": {
            "token": "{{ ENV_VARIABLE }}",
            "host": "http://domain.com/url/to/directus",
            "collection": "Project Name"
        }
    }
}

Data Providers

So far we have configured where the data is taken from and where the snapshots are stored. Now we can define what kind of analytics we want to extract from the model. The data extraction is handled by Data Providers that define how and what data is aggregated and what set of elements is used for the calculation. Therefore a provider configuration consits of the following fields:

{
    "providers": [
       {
            "name": "Room Area",
            "class": "ElementAreaProvider",
            "config": {
                "filters": [
                    {
                        "rule": "byCategory",
                        "args": ["Rooms"]
                    },
                    {
                        "rule": "byStringContains",
                        "args": ["Name", "Room"]
                    }
                ]
            }
        }
    ]
}

Aside from the name field, that has to be unique, the class field and the config.filters field are important here.

Classes

The classes field defines what provider type is used to calculate the extracted value. There are currently five different types of providers available.

Filters

The filters field contains a list of filter objects that have two properties:

Name

Description

rule

The filter method that is used to filter a collection of elements.

args

A list of arguments that is passed to the filter method. Take a look at the documentation for these methods in order get all available parameters.

"filters": [
    {
        "rule": "byCategory",
        "args": ["Rooms"]
    },
    {
        "rule": "byStringContains",
        "args": ["Name", "Room"]
    }
]

Automation

Since we want the snapshots to be taken periodically, like on a daily basis, we can configure the Windows Task Scheduler to run the revitron command, or a .bat file containing multiple calls.

revitron analyze "C:\\path\\to\\config.json"

Visualization

Analytics snapshots that are stored in Directus can automatically visualized in a web based dashboard using Revitron Charts.

https://github.com/revitron/revitron-charts/raw/master/images/dashboard.png

The charts app can easily be deployed on a local webserver using Docker. A working Dockerfile is included in the repository. An installation guide can be found here. After a successfull deployment, there is no further setup needed. All analytically tracked projects are automatically added to the dashboard.

Cheat Sheet

This is a collection of some useful little snippets and examples that can help you getting started quickly.

Imports

To make use of Revitron and the _() function the following items have to be imported:

import revitron
from revitron import _

The revitron module also exposes some useful properties such as the active document and gives you access to the Autodesk.Revit.DB class as well as follows:

doc = revitron.DOC
db = revitron.DB

Selection

Getting all selected elements:

selection = revitron.Selection.get()

Getting the first element in the selection:

elements = revitron.Selection.first()

Elements

Printing the category and class names for of all selected elements:

for el in revitron.Selection.get():
    name = _(el).getClassName()
    cat = _(el).getCategoryName()
    print(name, cat)

Dependent Elements

You can get a list of all dependent elements of a given element as follows:

dependents = _(el).getDependent()

For example the following loop prints the ElementIds of all dependent elements of the selected elements:

for el in revitron.Selection.get():
    for d in _(el).getDependent():
        print(d.Id)

Parameters

Getting a parameter value of all Revit elements in the selection:

for el in revitron.Selection.get():
    name = _(el).get('Name')
    print(name)

Getting the Family and Type parameter as id and string of elements in the selection. Note that here we want actually the value string instead of an ElementId. So the first function will return the ElementId and the second one will give us the actual string.

for el in revitron.Selection.get():
    famTypeId = _(el).get('Family and Type')
    famType = _(el).getParameter('Family and Type').getValueString()
    print(famTypeId)
    print(famType)

Setting a parameter value. Note that a shared parameter will be created and bound to the element’s category in case the parameter doesn’t exist yet. The el variable contains a Revit element.

t = revitron.Transaction()
_(el).set('Cool Parameter', 'Hello there!')
t.commit()

By default the parameter type will be text. It is possible to pass a third argument to the function to set a parameter type:

t = revitron.Transaction()
_(el).set('Cool Integer Parameter', 10, 'Integer')
t.commit()

Filters

Getting all elements of a certain category, specified by a string, for example “Room”:

rooms = revitron.Filter().byCategory('Rooms').getElements()
for room in rooms:
    print(_(room).get('Name'))

Instead of the natural category name, it is also valid to use the string representation of a built-in category as filter argument:

rooms = revitron.Filter().byCategory('OST_Rooms').getElements()

Note

A full list of natural category names and their corresponding built-in categories can be found here.

Filtering those rooms by filtering the Name “beginning with the word Room” can be done as follows. Note the flexible way of breaking down the filtering into multiple line for better readability:

fltr = revitron.Filter()
fltr = fltr.byCategory('Rooms')
fltr = fltr.byStringBeginsWith('Name', 'Room')

for room in fltr.getElements():
    print(_(room).get('Name'))

The filter can be inverted to get only rooms with a Name value “not beginning with Room”:

fltr = revitron.Filter()
fltr = fltr.byCategory('Rooms')
fltr = fltr.byStringBeginsWith('Name', 'Room', True)

for room in fltr.getElements():
    print(_(room).get('Name'))

Getting intersecting elements of one selected element and for example printing their category name:

el = revitron.Selection.first()
for intEl in revitron.Filter().byIntersection(el).getElements():
    print(_(intEl).getCategoryName())

Room Geometry

Printing or getting the boundary points of one (first) selected room:

el = revitron.Selection.first()
points = _(el).getBoundaryPoints()
for p in points:
    print(p)

Or with an inset:

el = revitron.Selection.first()
points = _(el).getBoundaryInsetPoints(0.2)
for p in points:
    print(p)

Get list of all boundary segments of the first selected room:

el = revitron.Selection.first()
boundary = _(el).getBoundary()
for segment in boundary:
    print(segment)

Bounding Boxes

Getting the Revitron bounding box object of the first element in the selection:

el = revitron.Selection.first()
bbox = _(el).getBbox()
print(bbox)

Document Context

In order to filter elements and using revitron.Filter with any other model than the active one, it is possible to temporarily change the document context as follows:

with revitron.Document(anyOtherDoc):
    fltr = revitron.Filter().noTypes()
    elements = fltr.getElements()

Storing Configurations

You can store any kind of easily serializable data such as string, number, list or dict in a config storage container as follows:

data = {'some': 'content'}
revitron.DocumentConfigStorage().set('my.namespace', data)

To get data out of that storage simply do the following. Note that you can pass a default value as a second argument to be returned in case there is no data stored yet and you don’t want to check for existence first:

config = revitron.DocumentConfigStorage().get('my.namespace', dict())
print(config.get('some'))

Index