Difference between revisions of "IfcOpenShell code examples"
(Add Explore IFC schema paragraph) |
|||
Line 1: | Line 1: | ||
− | Before getting started, you may be interested in [[Using the Python console with BlenderBIM Add-on]], to quickly install all the software and development environment you need for writing and running code, without any administrator privileges required. | + | Before getting started, you may be interested in [[Using the Python console with BlenderBIM Add-on]], to quickly install all the software and development environment you need for writing and running code, without any administrator privileges required. You may also find it useful watching [https://www.youtube.com/watch?v=WZPNaAM9ZuQ this video] which is complementary. |
=Crash course= | =Crash course= |
Revision as of 11:08, 17 December 2020
Before getting started, you may be interested in Using the Python console with BlenderBIM Add-on, to quickly install all the software and development environment you need for writing and running code, without any administrator privileges required. You may also find it useful watching this video which is complementary.
Crash course
To load a file, you'll need to import IfcOpenShell and store the IFC file in a variable. We'll use the variable ifc
. The ifc
will be then used throughout.
import ifcopenshell
ifc = ifcopenshell.open('/path/to/your/file.ifc')
Let's see what IFC schema we are using:
print(ifc.schema) # May return IFC2X3 or IFC4
Let's get the first piece of data in our IFC file:
print(ifc.by_id(1))
But getting data from beginning to end isn't too meaningful to humans. What if we knew a GlobalId
value instead?
print(ifc.by_guid('0EI0MSHbX9gg8Fxwar7lL8'))
If we're not looking specifically for a single element, perhaps let's see how many walls are in our file, and count them:
walls = ifc.by_type('IfcWall')
print(len(walls))
Once we have an element, we can see what IFC class it is:
wall = ifc.by_type('IfcWall')[0]
print(wall.is_a()) # Returns 'IfcWall'
You can also test if it is a certain class, as well as check for parent classes too:
print(wall.is_a('IfcWall')) # Returns True
print(wall.is_a('IfcElement')) # Returns True
print(wall.is_a('IfcWindow')) # Returns False
Let's quickly check the STEP ID of our element:
print(wall.id())
Let's get some attributes of an element. IFC attributes have a particular order. We can access it just like a list, so let's get the first and third attribute:
print(wall[0]) # The first attribute is the GlobalId
print(wall[2]) # The third attribute is the Name
Knowing the order of attributes is boring and technical. We can access them by name too:
print(wall.GlobalId)
print(wall.Name)
Getting attributes one by one is tedious. Let's grab them all:
print(wall.get_info()) # Gives us a dictionary of attributes, such as {'id': 8, 'type': 'IfcWall', 'GlobalId': '2_qMTAIHrEYu0vYcqK8cBX', ... }
Let's see all the properties and quantities associated with this wall:
import ifcopenshell.util
import ifcopenshell.util.element
print(ifcopenshell.util.element.get_psets(wall))
Some attributes are special, called "inverse attributes". They happen when another element is referencing our element. They can reference it for many reasons, like to define a relationship, such as if they create a void in our wall, join our wall, or define a quantity take-off value for our wall, among others. Just treat them like regular attributes:
print(wall.IsDefinedBy)
Perhaps we want to see all elements which are referencing our wall?
print(ifc.get_inverse(wall))
Let's do the opposite, let's see all the elements which our wall references instead:
print(ifc.traverse(wall))
print(ifc.traverse(wall, max_levels=1)) # Or, let's just go down one level deep
If you want to modify data, just assign it to the relevant attribute:
wall.Name = 'My new wall name'
You can also generate new GlobalId
s:
wall.GlobalId = ifcopenshell.guid.new()
After modifying some IFC data, you can save it to a new IFC-SPF file:
ifc.write('/path/to/a/new.ifc')
You can generate a new IFC from scratch too, instead of reading an existing one:
ifc = ifcopenshell.file()
# Or if you want a particular schema:
ifc = ifcopenshell.file(schema='IFC4')
You can create new IFC elements, and add it either to an existing or newly created IFC file object:
new_wall = ifc.createIfcWall() # Will return #1=IfcWall($,$,$,$,$,$,$,$,$) - notice all of the attributes are blank!
print(ifc.by_type('IfcWall')) # Will return a list with our wall in it: [#1=IfcWall($,$,$,$,$,$,$,$,$)]
Alternatively, you can also use this way to create new elements:
ifc.create_entity('IfcWall')
Specifying more arguments lets you fill in attributes while creating the element instead of assigning them separately. You specify them in the order of the attributes.
ifc.create_entity('IfcWall', ifcopenshell.guid.new()) # Gives us #1=IfcWall('0EI0MSHbX9gg8Fxwar7lL8',$,$,$,$,$,$,$,$)
Again, knowing the order of attributes is difficult, so you can use keyword arguments instead:
ifc.create_entity('IfcWall', GlobalId=ifcopenshell.guid.new(), Name='Wall Name') # Gives us #1=IfcWall('0EI0MSHbX9gg8Fxwar7lL8',$,'Wall Name',$,$,$,$,$,$)
Sometimes, it's easier to expand a dictionary:
data = {
'GlobalId': ifcopenshell.guid.new(),
'Name': 'Wall Name'
}
ifc.create_entity('IfcWall', **data)
Some attributes of an element aren't just text, they may be a reference to another element. Easy:
wall = ifc.createIfcWall()
wall.OwnerHistory = ifc.createIfcOwnerHistory()
What if we already have an element from one IFC file and want to add it to another?
wall = ifc.by_type('IfcWall')[0]
new_ifc = ifcopenshell.file()
new_ifc.add(wall)
Fed up with an object? Let's delete it:
ifc.remove(wall)
Geometry processing
The usage of IfcOpenShell for geometry processing is currently considered to be moderate to advanced. There are two approaches to processing geometry. One approach is to traverse the Representation
attribute of the IFC element, and parse it yourself. This requires an in-depth understanding of IFC geometric representations, as well as its many caveats with units and transformations, but can be very simple to extract specific types of geometry. The second approach is to use IfcOpenShell's shape processing features, which will convert almost all IFC representations into a triangulated mesh. Regardless of the source format, once it is in a mesh representation, you may use standard mesh geometry processing algorithms to analyse the geometry. This makes it easier to write generic code for any representation, but may be harder to extract certain geometric features.
Note: this article is a work in progress.
TODO: talk about naming in ids.
import multiprocessing
import ifcopenshell
import ifcopenshell.geom
ifc_file = ifcopenshell.open('/path/to/your/file.ifc')
settings = ifcopenshell.geom.settings()
iterator = ifcopenshell.geom.iterator(settings, ifc_file, multiprocessing.cpu_count())
valid_file = iterator.initialize()
if valid_file:
while True:
shape = iterator.get()
element = ifc_file.by_guid(shape.guid)
if not iterator.next():
break
IFC Query Syntax
Sometimes, you'd like to query an IFC file for a series of elements. It is possible to write this out manually, by means of functions like by_type()
and if
statements, and for
loops. However, a shorthand query syntax has been invented that makes this process much easier. This is made available in the ifcopenshell.util.selector
module.
In this simple example below, we use the #
and .
prefix to our query tells it that we want to search by IFC GlobalId
and class type respectively. Whitespace is optional in queries, but is used in these examples for readability.
import ifcopenshell.util
from ifcopenshell.util.selector import Selector
ifc = ifcopenshell.open('/path/to/your/file.ifc')
selector = Selector()
element = selector.parse(ifc, '#2MLFd4X2f0jRq28Dvww1Vm') # Equivalent to ifc.by_guid('2MLFd4X2f0jRq28Dvww1Vm')
walls = selector.parse(ifc, '.IfcWall') # This is equivalent to ifc.by_type('IfcWall')
It is also possible to search by any attribute:
# This is equivalent to searching by GlobalId
elements = selector.parse(ifc, '.IfcSlab[GlobalId = "2MLFd4X2f0jRq28Dvww1Vm"]')
# This finds all slabs with "Precast" (case-sensitive) in the Name
elements = selector.parse(ifc, '.IfcSlab[Name *= "Precast"]')
# This finds all slabs which have a quantified net volume greater than 10 units
elements = selector.parse(ifc, '.IfcSlab[Qto_SlabBaseQuantities.NetVolume > "10"]')
# This finds all walls which have a particular fire rating property
elements = selector.parse(ifc, '.IfcWall[Pset_WallCommon.FireRating = "2HR"]')
You can also search by spatial containment using the @
symbol, for example:
# If 0ehnsYoIDA7wC8yu69IDjv is the GlobalId of an IfcBuildingStorey, this gets all of the elements in that storey.
elements = selector.parse(ifc, '@ #0ehnsYoIDA7wC8yu69IDjv')
Or by type using the *
symbol:
# If 1uVUwUxTX9Jg1NHVw5KZhI is the GlobalId of an IfcTypeElement, this gets all of the elements of that type.
elements = selector.parse(ifc, '* #1uVUwUxTX9Jg1NHVw5KZhI')
You can use AND
and OR
statements, using the &
and |
symbols respectively:
# This gets all the 2HR fire rated walls in a particular building storey:
elements = selector.parse(ifc, '@ #0ehnsYoIDA7wC8yu69IDjv & .IfcWall[Pset_WallCommon.FireRating = "2HR"]')
# This is equivalent to walls = ifc.by_type('IfcWall') + ifc.by_type('IfcSlab'), i.e. all walls and slabs
elements = selector.parse(ifc, '.IfcWall | .IfcSlab')
You can also use parenthesis to group queries and combine them:
# This gets all walls and slabs in a particular building storey
elements = selector.parse(ifc, '@ #0ehnsYoIDA7wC8yu69IDjv & ( .IfcWall | .IfcSlab )')
Exploring IFC schema
Get Schema :
import ifcopenshell
schema = ifcopenshell.ifcopenshell_wrapper.schema_by_name("IFC4")
Explore class attributes :
ifc_pipe = schema.declaration_by_name("IfcPipeSegment")
ifc_pipe.all_attributes()
>>> (<attribute GlobalId: <type IfcGloballyUniqueId: <string>>>,
<attribute OwnerHistory?: <entity IfcOwnerHistory>>,
<attribute Name?: <type IfcLabel: <string>>>,
<attribute Description?: <type IfcText: <string>>>,
<attribute ObjectType?: <type IfcLabel: <string>>>,
<attribute ObjectPlacement?: <entity IfcObjectPlacement>>,
<attribute Representation?: <entity IfcProductRepresentation>>,
<attribute Tag?: <type IfcIdentifier: <string>>>,
<attribute PredefinedType?: <enumeration IfcPipeSegmentTypeEnum: (CULVERT, FLEXIBLESEGMENT, GUTTER, NOTDEFINED, RIGIDSEGMENT, SPOOL, USERDEFINED)>>)
ifc_pipe.attribute_count()
>>> 9
ifc_pipe.attribute_by_index(0)
>>> <attribute GlobalId: <type IfcGloballyUniqueId: <string>>>
ifc_pipe.attribute_index("Description")
>>> 3
predefined_type = ifc_pipe.attribute_by_index(8)
predefined_type.name()
>>> 'PredefinedType'
predefined_type.optional()
>>> True
predefined_type.type_of_attribute()
>>> <enumeration IfcPipeSegmentTypeEnum: (CULVERT, FLEXIBLESEGMENT, GUTTER, NOTDEFINED, RIGIDSEGMENT, SPOOL, USERDEFINED)>
# from name you can then recursively explore how create an entity as described above
predefined_type.type_of_attribute().declared_type().name()
>>> 'IfcPipeSegmentTypeEnum'
Get supertype :
ifc_pipe.supertype()
>>> <entity IfcFlowSegment>
Get subtypes :
super_type = ifc_pipe.supertype()
super_type.subtypes()
>>> (<entity IfcCableCarrierSegment>,
<entity IfcCableSegment>,
<entity IfcDuctSegment>,
<entity IfcPipeSegment>)
Samples from web
Subject | Language | Version | Additional infos |
---|---|---|---|
Understanding placements in IFC using IfcOpenShell and FreeCAD | python | 0.6.0a1 | FreeCAD 0.18 git |
Using IfcOpenShell to parse IFC files with Python | python | ||
Read geometry as Boundary Representation in FreeCAD | python | 0.6.0a1 | FreeCAD 0.18 git |
Read IFC geometry as triangle meshes in FreeCAD | python | 0.6.0a1 | FreeCAD 0.18 git |
Using IfcOpenShell and C++ to generate Alignments through the IFC 4×1 schema | python/C++ | ||
Creating a simple wall with property set and quantity information | python | ||
Using IfcOpenshell and pythonOCC to generate cross sections directly from an IFC file | python | <= 0.6 ? | pythonOCC 0.16.0 ? |
Using the parsing functionality of IfcOpenShell interactively | python | ||
Using IfcOpenShell and pythonOCC to construct new geometry | python | <= 0.6 | pythonOCC 0.16.0 |
Various ifc creation examples (little house, geometry etc…) | C++ |