Working with Type Parameters can be a bit challenging in Dynamo for beginners and on top of that working with multiple elements and their parameters. Today we are going to look at how to set the multiple type parameters for each of the various families in the project.
Type parameters are specific to a family type, and we need to obtain the family type to access its parameters. Setting parameters for multiple elements can be achieved in a similar manner.
Sorting is a fundamental operation in computer programming that involves arranging a collection of data in a specific order. In Python, sorting can be performed using various built-in functions such as sorted(), sort(), and others.
Alphanumeric or Natural Sorting
Alphanumeric or natural sorting is a type of sorting that orders strings containing numeric characters in a more natural way. For example, consider the following list of strings:
As you can see, the regular sorting method sorts the list in lexicographical order, which is not the natural order we might expect. Alphanumeric sorting, on the other hand, would sort the list in the following order:
['item1', 'item2', 'item3', 'item10', 'item11']
This is the natural order we might expect when sorting a list of strings containing numbers.
Alphanumeric or Natural Sortingin Dynamo
import re
def sorted_alpha_num(lst):
def convert(text):
return int(text) if text.isdigit() else text.lower()
def alphanum_key(key):
return [convert(c) for c in re.split('([0-9]+)', key)]
return sorted(lst, key=alphanum_key)
OUT = sorted_alpha_num(IN[0])
The Python code above is sorting the list in an alphanumeric order using a custom sorting key function. The code uses the re module to split the input string into alphanumeric components and then sorts them according to the natural ordering.
The ‘re’ module is a built-in module in Python that provides support for regular expressions. It provides various functions and methods to work with regular expressions, such as searching, matching, splitting, and substitution. In this code, the ‘re.split()‘ method is used to split the key string into alphanumeric components based on the regular expression pattern ‘[0-9]+‘.
The code defines two nested functions: convert() and alphanum_key(). The convert() function takes a text string and returns an integer if the text contains only digits; otherwise, it returns the lower-case version of the text. The alphanum_key() function takes a key string and splits it into alphanumeric components using the regular expression pattern ‘[0-9]+’. The function then applies the convert() function to each component and returns a list of converted components as the sorting key.
The sorted_alpha_num() function takes a list as input and applies the alphanum_key() function to each element of the list. The function then returns a new list sorted based on the converted keys.
Windows PowerShell is a scripting language and task automation framework for system administration both on-premises and remotely. PS comes preinstalled in every new Windows-based system now.
PS code is generally very short and effective due to the availability of a huge library of cmdlets pertaining to any module.
Some people may find this blue screen similar to Command Prompt, but it is much more powerful than traditional CMD. To put it differently, PowerShell can be seen as an enhanced version of Command Prompt with added features and capabilities. Here are some examples of PowerShell workflows that can automate everyday tasks on Windows.
Managing files and folders: you can use PowerShell to create, copy, move, and delete files and folders in bulk.
System configuration: It can be used to automate the configuration of system settings such as network settings, Windows updates, and user accounts.
Managing processes: It can help you automate the monitoring and management of processes running on your system, such as starting, stopping, and restarting services.
Software deployment: It can be used to automate the deployment of software to multiple computers, making it easier to roll out new software or updates.
Task scheduling: It can be used to create and manage scheduled tasks, allowing you to automate routine tasks such as backups, system maintenance, or running reports.
How to Use PowerShell?
There are many flavors of PowerShell, you may even run it on other IDEs (e.g. VS, VS Code) but for simplicity, Windows PowerShell ISE (Integrated Scripting Environment) works as an editor, debugger and provides ready IntelliSense.
If you have a PowerShell script file (*.ps1) and want to run it, you can simply right-click on it and choose to run it with PowerShell. However, it’s advisable to review the script and modify the inputs if necessary before executing the file. To do this, you can open PowerShell ISE, load the PowerShell file, review and edit the code as needed, and then run it by clicking the “Run Script” button (shortcut: F5). This ensures that you have the opportunity to verify and adjust the script before executing it.
Let’s see some of the everyday workflows where PowerShell can be a great time-saver.
1. Rename Files
Here we are directly renaming files by adding a prefix to the file name and changing the file name text to the title case.
# Set the folder path and custom prefix
$folderPath = "C:\Users\{Username}\Documents\_Docs Temp\_Temp"
$prefix = "RAC_"
# Get all files in the folder
$files = Get-ChildItem $folderPath
# Loop through each file and rename it
foreach ($file in $files) {
# Get the new file name with prefix and title case
$newName = $prefix + ((Get-Culture).TextInfo.ToTitleCase($file.BaseName)) + $file.Extension
# Rename the file
Rename-Item $file.FullName -NewName $newName
}
This PowerShell script renames all files in a folder with a custom prefix and title case. It gets all the files in the folder, loops through each file to generate a new name with the prefix and title case base name, and renames the file with the new name.
2. Rename Multiple Files at Once using Excel / CSV
To rename large numbers of files located somewhere in the local drive at once using an external spreadsheet or CSV (Comma-separated Value) file seems to be the easiest workflow to anyone because of the quick and familiar way of editing text, finding and replacing text or using formulae in Excel.
# Set the folder path and import the CSV file
$folderPath = "C:\Users\{Username}\Documents\_Docs Temp\_Temp"
$csvPath = "C:\Users\{Username}\Documents\_Docs Temp\RenameFilesWithCSV.csv"
$fileNames = Import-Csv $csvPath
# Loop through each file name in the CSV file and rename the file
foreach ($fileName in $fileNames) {
$existingName = $fileName.ExistingNames
$newName = $fileName.NewNames
$filePath = Join-Path $folderPath $existingName
if (Test-Path $filePath) {
Rename-Item $filePath -NewName $newName
Write-Host "File '$existingName' renamed to '$newName'"
}
else {
Write-Host "File '$existingName' not found in folder"
}
}
This script renames files in a folder using a CSV file that contains “ExistingNames” and “NewNames” columns. The script imports the CSV file and loops through each row to extract the existing file name and new file name. It then checks if the file exists in the folder and renames it using the Rename-Item cmdlet if it does. Finally, it outputs a message indicating whether the file was renamed or not.
3. Create Multiple Folders
With PowerShell, you have the capability to create multiple folders simultaneously by importing a CSV or Excel file. These folders can have any number of subfolder levels as desired.
This script creates multiple folders using a CSV file. It starts by setting the current location where the folders are to be created. Then, it imports a CSV file containing a list of folder names to be created.
Using a foreach loop, the script creates each folder in the CSV file by using the New-Item cmdlet with the type parameter set to the directory. The folder names are specified by the column header “FolderNames” in the CSV file.
# Location where your folders are to be created
Set-Location "C:\Users\{Username}\Documents\_Docs Temp\_Temp\Multiple Folder Creation\Folders Created"
# Import CSV file from location
$Folders = Import-Csv "C:\Users\{Username}\Documents\_Docs Temp\_Temp\Multiple Folder Creation\FoldersToBeCreated.csv"
# Create Folders from CSV ensure your have a heading of FolderNames in your CSV file
ForEach ($Folder in $Folders) {
New-Item $Folder.FolderNames -type directory
}
To sum up, PowerShell is a powerful tool that can automate a wide range of tasks and processes in your daily work routine. Whether you need to manage files and folders, configure system settings, or deploy applications, PowerShell can help you save time and streamline your workflow.
Revit is a powerful tool for building design and construction, but with great power comes great responsibility. Keeping your Revit projects tidy and efficient can be a daunting task, especially when it comes to purging unwanted elements. Revit does come with an out-of-the-box feature Purge Unwanted to purge items, but it doesn’t allow bulk deleting of custom-picked elements.
To solve this problem, we can turn to Dynamo, a visual programming platform that allows us to automate tasks in Revit. By creating a Dynamo script or workflow, we can first get all the materials used in the project and then let the user pick the elements or materials that need to be deleted. The script filters out the selected materials and deletes them in bulk.
Delete Unwanted Materials Dynamo Graph
By creating our own Dynamo workflows around this, we can delete other unplaced elements in bulk, such as views, floor plans, sections, legends, schedules, spaces, rooms, scope boxes, imported files, and more.
By using Dynamo to automate the process of purging unwanted elements in Revit, we can save time and improve the efficiency of our workflow. So why not give it a try and see how it can streamline your Revit projects?
Python 1: Get All Materials This piece of code retrieves all the material elements and their names in the project.
# Import the necessary packages
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
clr.AddReference('RevitServices')
from RevitServices.Persistence import DocumentManager
# Get the Revit document
doc = DocumentManager.Instance.CurrentDBDocument
# Get all the materials in the project
materials = FilteredElementCollector(doc).OfClass(Material)
mats = FilteredElementCollector(doc).OfClass(Material).ToElements()
# Create lists to store the material names and IDs
material_names = []
material_ids = []
# Loop through the materials and retrieve their names and IDs
for material in materials:
material_names.append(str(material.Id) + " - " + material.Name)
# Define the outputs
OUT = mats, material_names
Python 2: Filter List
The Python 2: Filter List node is taken from the List.FilterBySelection custom node by spring nodes by Dimitar Venkov. This Python code defines a custom form with checkboxes that allow the user to select elements. The code adds references to the necessary libraries, defines a few functions, and then creates the form using the CheckBoxForm class. The form includes buttons to check or uncheck all the elements, and to save the selected elements. This code can be used in Dynamo scripts to enable user selection of elements for further processing.
Ever wondered how to export data from Revit or any source for that matter to an existing Excel file where you already have some formatting done? It can be a bit winding task to first export your data to an intermediary blank Excel sheet and then copy/paste or link the cells or range to your original Excel template file.
This workflow here does not require any custom node or high-level coding — just a couple of out-of-the-box nodes to get your job done in a few seconds.
This is how you can save precious time to export data to any existing Excel file without making any modifications to the formatting. You can re-run the Dynamo script after changing input data in order to make any further changes.
Many times when you are creating MEP models in Revit using native rfa families, it would be required to split the piping or ducting into some standard lengths based on the project requirement. This could be quite a tedious manual process to measure and split the pipes/ducts especially when it comes to sloped piping the exact standard split length seems to be hard to achieve.
This Dynamo workflow helps you to split Pipe or Duct networks into optimal Manufacturer’s lengths in Revit. Just run the script in Dynamo or Dynamo Player and select the model in a Revit view. It will auto-detect all the piping/ducting and split them into user-specified lengths. You can anytime make adjustments to the selection method.
Supported Versions Revit 2017, 2018, 2019, 2020, 2021 Dynamo 2.0.4 and above
WordPress compresses images, so the above picture might not be legible. Please see the screenshots in two parts below. Right click on the image and select ‘Open image in new tab’.
Revit Python Shell or RPS is a good way to write Python codes in Revit and create plugins. It’s a free script editor integrated into Revit API that gives you the benefit of seeing the result as you code.
Use it in combination with Revit Lookup. It has below three features.
Interactive Python Shell
Non-modal Shell: Not interfering with the Revit model
Deploy RpsAddin: Make plugins for Revit
But first, we will see how to install RPS in Windows.
Go to the RPS GitHub page and download the installer for your respective Revit version.
Run the installer and check if the RPS appears on your Add-ins tab in Revit.
If not, download the whole master code zip from the Github page.
The installer would have created the below directory in your C drive.
Go to the below location and make an ADDIN manifest file by pasting the code. Make sure to give it the right path of the RevitPythonShell.dll file from the previous step.
5. Unzip the downloaded revitpythonshell-master package from step 2 and copy the contents of the folder revitpythonshell-master\revitpythonshell-master\RevitPythonShell\DefaultConfigand make a folder with RevitPythonShell2019 or whatever version the Revit version you want to work with and paste the contents into this folder at the path shown in the image below.
Launch the target Revit version and accept the RevitPythonShell popup with Always Load. The RevitPythonShell ribbon should appear under Add-ins tab.
Making and Deploying RPS Addin
An RpsAddin refers to a Revit Addin that was written using the RevitPythonShell and then bundled for deployment using the “Deploy RpsAddin” feature of the RevitPythonShell.
RpsAddins allow you to easily deploy your scripts without having to install and configure RevitPythonShell on each machine. It does this by creating a Revit DLL that can be used as an Addin. This DLL will use some runtime glue code located in RpsRuntime.dll to provide IronPython integration for the Addin. The DLL also contains your scripts and a manifest for the addin as string resources.
In a future post, we’ll see to create and deploy an RPS addin. Till then, download the guidebook for Python Scripting with RPS from here.
Ever wondered how to filter out elements in Autodesk Navisworks Manage by their Revit worksets?
Worksets in Navisworks can give you greater control over your model data. You can perform various filtering, formatting on the worksets. It is also easier to extract parametric data out of Navisworks when you have clearly defined worksets.
Worksets in Revit
Steps:
Export the 3D model in NWC format. Remember to keep the “Close NWC/NWD files on load” checkbox ticked while saving as *.nwc. Without this checked, the file lock is on and you cannot overwrite the file unless you close the current Navisworks file where it is appended to.
Exporting as *.nwc
2. Append the file in Navisworks Manage. Select any element and right-click and make sure that the Set Selection Resolution is kept as the First Object. It will make the object path start at the highest level of objects below the layer node, if applicable.
Set Selection Resolution setting
3. You can see all the property data of the selected Revit element from the Properties panel in the Home ribbon. This is for our viewing purpose.
Properties in Navisworks
4. Now open Selection Tree panel (Ctrl+F12), and select Properties from the drop down menu.
As worksets are a property of the elements, go to Element > Workset.
Here you can find all the worksets (only those that contain elements) from your Revit project.
Workset Selection
5. You can right-click and tick Hide Unselected to isolate the elements of the specific workset.
Click on Selection Inspector and it will show all the elements of that particular workset. Click Save Selection for all the entities in Workset.
Save Selection for Workset
Now you can find all the worksets under the Sets in the Selection Tree. All the filtering and sorting could be performed on these worksets.
Workset Section Sets
Tip: To sort or filter elements of different categories based on their parametric values Find Items is a pretty handy feature.
Go to View > Windows > Find Items
Find Items for filtering
You can search in the already defined worksets or other selection sets to narrow down the filtering.
So, today we’re going to see a simple yet handy Dynamo workflow to rename a bunch of families in your Revit project using Dynamo player.
Now this Dynamo graph combines two routines — to add prefix and/or suffix to either families (loadable) or family types.
We have set all our 4 input nodes as inputs in Dynamo and it’s ready to go in Dynamo player.
Don’t forget to load the required packages. Browse the script in Dynamo player and edit the inputs.
The prefix or suffix fields could be kept empty in case you don’t want any one of them. The boolean input could toggle between modifying family name or family type name.
STL and OBJ files have become a standard in the 3D printing industry. Many 3D modeling and computer graphics programs such as Autodesk Maya, Blender, Sketchup, Cinema 4D can produce these models in a pretty nifty manner.
For color 3D printing with precise mesh encoding, OBJ files prove to be a useful format while preserving the precise mesh encoding. You may get yourself a free 3D model from Oyonale.
You can see the 3D model in any free 3D object viewer. The 3D Viewer from Microsoft is a great application that comes with Windows 10.